Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(admin): harden move-project (safe failure model, live-session guard, conflicts)
Djalma Júnior46d5a524f365
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 0548de93..c86c36b2 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -365,6 +365,12 @@ pub struct MoveProjectArgs {/// source, both irreversible. Without this flag the CLI errors out.#[arg(long)]pub confirm: bool,+ /// Override the live-session guard. By default the server refuses (409) to+ /// move the project a hook session is actively writing to; `--force`+ /// proceeds anyway (still safe — the move keeps the active pointer correct+ /// and the schema rejects any stale write).+ #[arg(long)]+ pub force: bool,}/// Arguments for `install-instructions`.diff --git a/crates/ai-memory-cli/src/commands/move_project.rs b/crates/ai-memory-cli/src/commands/move_project.rsindex f53d78ef..d5ccedfc 100644--- a/crates/ai-memory-cli/src/commands/move_project.rs+++ b/crates/ai-memory-cli/src/commands/move_project.rs@@ -14,6 +14,7 @@ struct MoveProjectRequest {project: String,to_workspace: String,confirm: bool,+ force: bool,}/// Run the `move-project` subcommand.@@ -31,14 +32,20 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {if !args.confirm {bail!(- "move-project copies the project's pages into the destination \- workspace, then PURGES the source.\n\+ "move-project moves {}/{} to workspace {}. If the destination has \+ no same-named project it is a lossless true-move (re-stamp in \+ place — sessions, observations and history preserved). If it \+ already has one, the pages are copied in and merged, then the \+ source is PURGED. Both are irreversible.\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,+ args.from_workspace,+ project,+ args.to_workspace,);}@@ -51,6 +58,7 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {project: project.clone(),to_workspace: args.to_workspace.clone(),confirm: true,+ force: args.force,},).await?;@@ -87,6 +95,20 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {source and were skipped; the source was NOT purged. Fix and re-run.",);}+ if let Some(conflicts) = report["conflicts"].as_array().filter(|c| !c.is_empty()) {+ println!(+ "{} path conflict(s) — source page kept under a de-duplicated path \+ (both versions preserved):",+ conflicts.len()+ );+ for c in conflicts {+ println!(+ " {} → {}",+ c["path"].as_str().unwrap_or("?"),+ c["moved_to"].as_str().unwrap_or("?"),+ );+ }+ }}Ok(())}diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 73e821e8..df98cc75 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -225,6 +225,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {.as_ref().filter(|p| !p.trim().is_empty()).map(|p| ai_memory_store::TokenPepper::new(p.clone())),+ active_project: active_project.clone(),});// Multi-rung auth assembly:// - rung 0 (no bearer_token configured) → AuthState::newdiff --git a/crates/ai-memory-core/src/active_project.rs b/crates/ai-memory-core/src/active_project.rsindex 21a22ae2..4bd24906 100644--- a/crates/ai-memory-core/src/active_project.rs+++ b/crates/ai-memory-core/src/active_project.rs@@ -62,6 +62,14 @@ impl ActiveProject {let guard = self.inner.read().unwrap_or_else(|e| e.into_inner());*guard}++ /// Forget the active project. Called after an admin operation invalidates+ /// the published pointer (e.g. a `move-project` whose copy-purge path gives+ /// the project a NEW id, so the old pointer no longer resolves).+ pub fn clear(&self) {+ let mut guard = self.inner.write().unwrap_or_else(|e| e.into_inner());+ *guard = None;+ }}#[cfg(test)]diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex b6c99bb7..1c39bb33 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -32,7 +32,8 @@ use ai_memory_consolidate::{prune_sources_to_budget, run_lint, run_sweep,};use ai_memory_core::{- DEFAULT_PROJECT_NAME, DEFAULT_WORKSPACE_NAME, PagePath, ProjectId, SessionId, Tier, WorkspaceId,+ ActiveProject, DEFAULT_PROJECT_NAME, DEFAULT_WORKSPACE_NAME, PagePath, ProjectId, SessionId,+ Tier, WorkspaceId,};use ai_memory_llm::{Embedder, LlmProvider, ProviderHealth, ProviderHealthSnapshot};use ai_memory_store::{@@ -50,7 +51,7 @@ use flate2::Compression;use flate2::write::GzEncoder;use serde::{Deserialize, Serialize};use tokio_util::io::ReaderStream;-use tracing::{info, warn};+use tracing::{error, info, warn};const EMBEDDING_WRITE_BATCH: usize = 100;@@ -93,6 +94,12 @@ pub struct AdminState {/// installs that predate v0.8); user-management endpoints then/// return 503 `multi-user not enabled`.pub token_pepper: Option<ai_memory_store::TokenPepper>,+ /// Shared in-process pointer to the project the agent is currently+ /// active in (published by the hook router). Read by `move-project` to+ /// refuse moving the live project (unless `force`) and to keep the+ /// pointer correct after a move. Empty `ActiveProject::new()` when no+ /// hook router is attached (admin-only tests).+ pub active_project: ActiveProject,}/// JSON request body for `POST /admin/bootstrap`.@@ -1598,6 +1605,14 @@ struct MoveProjectRequest {/// Mandatory confirmation flag. The move PURGES the source after/// copying, so without `confirm: true` the server returns 400.confirm: bool,+ /// Override the live-session guard. By default the server refuses (409)+ /// to move the project the hook router is currently writing to, since a+ /// live session's next observation would carry a stale workspace id.+ /// `force: true` proceeds anyway (still safe: the move republishes the+ /// active pointer and the (workspace_id, project_id) trigger makes any+ /// stale write fail cleanly rather than corrupt).+ #[serde(default)]+ force: bool,}/// Wire-format report returned by `POST /admin/move-project`.@@ -1641,6 +1656,20 @@ pub struct MoveProjectReport {pub files_deleted: Vec<String>,/// Source on-disk dirs that could not be removed (non-fatal).pub files_failed: Vec<String>,+ /// Same-path conflicts in the copy-purge merge: a source page whose path+ /// already existed in the destination (with different content) was landed+ /// under a de-duplicated path so BOTH survive. Each entry is the original+ /// source path and the de-duplicated destination path it was written to.+ pub conflicts: Vec<PathConflict>,+}++/// One same-path collision resolved by de-duplicating the source page's path.+#[derive(Debug, Serialize)]+pub struct PathConflict {+ /// The source page's original path (also the destination's existing path).+ pub path: String,+ /// The de-duplicated path the source page was written to instead.+ pub moved_to: String,}/// Lossless cross-workspace move: re-stamp the source project's@@ -1672,6 +1701,22 @@ async fn true_move_project(Err(e) => return internal_err(e.to_string()),};+ // A true move targets a FRESH destination, so its dir must not already+ // exist. Check BEFORE touching the DB so a stale leftover can never lead to+ // a DB-ahead-of-disk split-brain or a clobbered directory.+ let dst_dir = state.wiki.project_root(dst_ws, src_proj);+ if dst_dir.exists() {+ return (+ StatusCode::CONFLICT,+ Json(serde_json::json!({+ "error": format!(+ "destination dir already exists: {}; refusing true-move",+ dst_dir.display()+ )+ })),+ );+ }+let summary = match state.writer.move_project_workspace(src_proj, src_ws, dst_ws)@@ -1688,24 +1733,52 @@ async fn true_move_project(};// 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.+ // committed, so a rename failure would leave the DB ahead of disk. Make the+ // move all-or-nothing: on failure, roll the DB re-stamp back (the op is+ // symmetric) so either both rows AND files move, or neither does.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()- ));+ match state+ .writer+ .move_project_workspace(src_proj, dst_ws, src_ws)+ .await+ {+ Ok(_) => {+ warn!(+ error = %e,+ "true-move: dir rename failed; rolled the DB re-stamp back — nothing moved"+ );+ return internal_err(format!(+ "move aborted (nothing changed): on-disk dir rename failed: {e}"+ ));+ }+ Err(rollback_err) => {+ // Double fault: rows are in the destination workspace but files+ // remain at the source AND the revert failed. Surface a precise+ // manual-repair message.+ error!(+ error = %e,+ rollback_error = %rollback_err,+ src = %src_dir.display(),+ dst = %dst_dir.display(),+ "true-move: dir rename failed AND DB rollback failed — manual repair required"+ );+ return internal_err(format!(+ "INCONSISTENT STATE: rows moved but dir rename failed ({e}) and DB rollback \+ also failed ({rollback_err}); manually move {} -> {} or re-stamp the project back",+ src_dir.display(),+ dst_dir.display()+ ));+ }+ }+ }++ // Keep the in-process active-project pointer correct: the project_id is+ // unchanged, only its workspace moved. If a hook had published this project+ // as active, republish it under the destination workspace so the next event+ // resolves cleanly (rather than tripping the pairing trigger first).+ if state.active_project.get().map(|(_, p)| p) == Some(src_proj) {+ state.active_project.set(dst_ws, src_proj);}let report = MoveProjectReport {@@ -1725,6 +1798,8 @@ async fn true_move_project(source_embeddings_deleted: 0,files_deleted: Vec::new(),files_failed: Vec::new(),+ // A true move never copies pages, so it never has a path conflict.+ conflicts: Vec::new(),};(StatusCode::OK,@@ -1732,6 +1807,52 @@ async fn true_move_project()}+/// Pick a destination path that collides with neither an existing destination+/// page nor one already claimed in this run. Keeps the source page's stem and+/// appends `-from-<src_workspace>` (then `-2`, `-3`, …). Used by the copy-purge+/// merge to keep BOTH pages when a path conflicts.+async fn dedup_dest_path(+ state: &AdminState,+ dst_ws: WorkspaceId,+ dst_proj: ProjectId,+ src_path: &str,+ src_workspace: &str,+ used: &std::collections::HashSet<String>,+) -> PagePath {+ let (stem, ext) = match src_path.rsplit_once('.') {+ Some((s, e)) => (s.to_string(), format!(".{e}")),+ None => (src_path.to_string(), String::new()),+ };+ let slug: String = src_workspace+ .chars()+ .map(|c| {+ if c.is_ascii_alphanumeric() || c == '-' || c == '_' {+ c+ } else {+ '-'+ }+ })+ .collect();+ let base = format!("{stem}-from-{slug}");+ let mut n = 0u32;+ loop {+ let cand = if n == 0 {+ format!("{base}{ext}")+ } else {+ format!("{base}-{n}{ext}")+ };+ let collides = used.contains(&cand)+ || matches!(+ state.reader.page_body_by_ids(dst_ws, dst_proj, &cand).await,+ Ok(Some(_))+ );+ if !collides && let Ok(p) = PagePath::new(cand) {+ return p;+ }+ n += 1;+ }+}+async fn handle_move_project(State(state): State<Arc<AdminState>>,Json(req): Json<MoveProjectRequest>,@@ -1765,6 +1886,24 @@ async fn handle_move_project(Err(e) => return e,};+ // Live-session guard: refuse to move the project the hook router is+ // currently writing to. A live session's next observation/log would carry+ // the now-stale workspace id (the (workspace_id, project_id) trigger would+ // make it fail, but the operator should consciously opt in). `force: true`+ // proceeds — safe because the move republishes the active pointer below.+ if !req.force && state.active_project.get().map(|(_, p)| p) == Some(src_proj) {+ return (+ StatusCode::CONFLICT,+ Json(serde_json::json!({+ "error": format!(+ "{}/{} is the active session's project; a live move risks stale-cache writes. \+ Re-run with force=true to proceed.",+ req.from_workspace, req.project+ )+ })),+ );+ }+// 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 {@@ -1848,6 +1987,8 @@ async fn handle_move_project(// fire — minus the per-page embed, which we carry over below.let mut pages_copied = 0u64;let mut pages_skipped: Vec<String> = Vec::new();+ let mut conflicts: Vec<PathConflict> = Vec::new();+ let mut used_dest_paths: std::collections::HashSet<String> = std::collections::HashSet::new();for s in &summaries {let path = match PagePath::new(s.path.clone()) {Ok(p) => p,@@ -1869,11 +2010,39 @@ async fn handle_move_project(continue;}};+ // Same-path conflict → duplicate (keep both): if the destination already+ // holds this path with DIFFERENT content, land the source page under a+ // de-duplicated path so neither version is lost. Identical content falls+ // through to a no-op supersession at the same path.+ let dest_path = match state+ .reader+ .page_body_by_ids(dst_ws, dst_proj, s.path.as_str())+ .await+ {+ Ok(Some(existing)) if existing.body != md.body => {+ let deduped = dedup_dest_path(+ &state,+ dst_ws,+ dst_proj,+ &s.path,+ &req.from_workspace,+ &used_dest_paths,+ )+ .await;+ conflicts.push(PathConflict {+ path: s.path.clone(),+ moved_to: deduped.as_str().to_string(),+ });+ deduped+ }+ _ => path.clone(),+ };+ used_dest_paths.insert(dest_path.as_str().to_string());let new_page_id = match copy_wiki.write_page(WritePageRequest {workspace_id: dst_ws,project_id: dst_proj,- path: path.clone(),+ path: dest_path.clone(),frontmatter: md.frontmatter,body: md.body,tier,@@ -1933,6 +2102,7 @@ async fn handle_move_project(source_embeddings_deleted: 0,files_deleted: Vec::new(),files_failed: Vec::new(),+ conflicts,};return (StatusCode::OK,@@ -1977,6 +2147,13 @@ async fn handle_move_project(}}+ // The source project_id was just purged; if it was the published active+ // project, the pointer now dangles — clear it so the next hook re-resolves+ // to the (new) project rather than the deleted id.+ if state.active_project.get().map(|(_, p)| p) == Some(src_proj) {+ state.active_project.clear();+ }+let report = MoveProjectReport {from: label,to: format!("{}/{}", req.to_workspace, req.project),@@ -1992,6 +2169,7 @@ async fn handle_move_project(source_embeddings_deleted: summary.embeddings_deleted,files_deleted,files_failed,+ conflicts,};(StatusCode::OK,@@ -2457,6 +2635,7 @@ mod tests {bind: "127.0.0.1:49374".to_string(),bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),});let resp = router@@ -2493,6 +2672,7 @@ mod tests {bind: "127.0.0.1:49374".to_string(),bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),});(tmp, router)}@@ -2672,6 +2852,7 @@ mod tests {bind: "127.0.0.1:49374".to_string(),bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),});post_write_page(&router, "default", "doomed", "notes/x.md", "bye").await;@@ -2731,6 +2912,7 @@ mod tests {bind: "127.0.0.1:49374".to_string(),bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),token_pepper: Some(pepper),+ active_project: ai_memory_core::ActiveProject::new(),});// Wrap in a middleware that stamps the AuthLevel ourselves —// the real auth middleware lives in ai-memory-cli, and this@@ -3015,6 +3197,7 @@ mod tests {bind: "127.0.0.1:49374".to_string(),bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),});// Inject a Root level so we're past the require_root gate;// the 503 must come from require_pepper.diff --git a/crates/ai-memory-mcp/tests/admin_backup.rs b/crates/ai-memory-mcp/tests/admin_backup.rsindex aa3a15a9..eccdfee5 100644--- a/crates/ai-memory-mcp/tests/admin_backup.rs+++ b/crates/ai-memory-mcp/tests/admin_backup.rs@@ -36,6 +36,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),};(state, store)}diff --git a/crates/ai-memory-mcp/tests/admin_bootstrap.rs b/crates/ai-memory-mcp/tests/admin_bootstrap.rsindex 22edfbbf..83724cd4 100644--- a/crates/ai-memory-mcp/tests/admin_bootstrap.rs+++ b/crates/ai-memory-mcp/tests/admin_bootstrap.rs@@ -33,6 +33,7 @@ async fn make_admin_state(tmp: &TempDir) -> AdminState {bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),}}diff --git a/crates/ai-memory-mcp/tests/admin_move.rs b/crates/ai-memory-mcp/tests/admin_move.rsindex 5630b608..de307f18 100644--- a/crates/ai-memory-mcp/tests/admin_move.rs+++ b/crates/ai-memory-mcp/tests/admin_move.rs@@ -4,9 +4,14 @@//! 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).+//! move-project has two paths. To a FRESH destination (no same-named project)+//! it does a lossless TRUE-MOVE: re-stamp the project's workspace_id in place,+//! keeping the same project_id, sessions, observations, handoffs, page history+//! and embeddings. To an EXISTING same-named project it does a COPY-PURGE+//! merge: copy the source's latest pages in through the normal write path+//! (carrying embeddings over verbatim, de-duplicating any conflicting path so+//! both versions survive), then purge the source — there the episodic rows+//! (sessions/observations/handoffs) are dropped by the purge.use ai_memory_core::{PagePath, Tier};use ai_memory_mcp::{AdminState, admin_router};@@ -39,6 +44,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),};(state, store)}@@ -356,6 +362,7 @@ async fn move_project_carries_source_embedding() {bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),};// Seed source page (gets a synthetic embedding on write).@@ -536,3 +543,417 @@ async fn move_project_true_move_preserves_sessions_and_observations() {assert_eq!(obs.len(), 1, "observation must survive the move");assert_eq!(obs[0].workspace_id, dst_ws, "observation re-stamped to dst");}++// ---------------------------------------------------------------------------+// Rework (PR #60 review): failure model, live-session guard, copy-purge+// conflict/partial/idempotency, copy-purge embedding carry-over.+// ---------------------------------------------------------------------------++/// Build an AdminState with a synthetic embedder (for copy-purge embedding+/// carry-over) and a published active project pointer.+async fn make_state_with_embedder(tmp: &TempDir) -> (AdminState, Store) {+ let store = Store::open(tmp.path()).unwrap();+ let embedder: std::sync::Arc<dyn ai_memory_llm::Embedder> =+ std::sync::Arc::new(ai_memory_llm::SyntheticEmbedder::new(8));+ let wiki = Wiki::new(tmp.path(), store.writer.clone())+ .unwrap()+ .with_embedder(embedder.clone());+ let db_path = store.db_path().to_path_buf();+ let state = AdminState {+ writer: store.writer.clone(),+ reader: store.reader.clone(),+ wiki,+ llm: None,+ embedder: Some(embedder),+ 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,+ active_project: ai_memory_core::ActiveProject::new(),+ };+ (state, store)+}++async fn ids(+ store: &Store,+ ws: &str,+ proj: &str,+) -> (ai_memory_core::WorkspaceId, ai_memory_core::ProjectId) {+ let ws_id = store+ .reader+ .find_workspace(ws.to_string())+ .await+ .unwrap()+ .unwrap();+ let proj_id = store+ .reader+ .find_project(ws_id, proj.to_string())+ .await+ .unwrap()+ .unwrap();+ (ws_id, proj_id)+}++/// W1: when the on-disk dir rename fails mid true-move, the SQL re-stamp is+/// rolled back so NOTHING moves (no DB-ahead-of-disk split-brain). We force the+/// rename to fail by planting a FILE where the destination workspace dir would+/// be created.+#[tokio::test]+async fn true_move_rolls_back_when_dir_rename_fails() {+ 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;++ // Pre-create the destination workspace, then plant a FILE at its wiki dir+ // so `create_dir_all` during the rename fails. The pre-check passes because+ // the project subdir cannot exist under a file.+ let dst_ws = store+ .writer+ .get_or_create_workspace("dst".to_string())+ .await+ .unwrap();+ let dst_ws_dir = tmp.path().join("wiki").join(dst_ws.to_string());+ std::fs::write(&dst_ws_dir, b"not a dir").unwrap();++ let (src_ws, src_proj) = ids(&store, "src", "proj").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::INTERNAL_SERVER_ERROR);+ let body = body_json(resp).await;+ assert!(+ body["error"]+ .as_str()+ .unwrap_or("")+ .contains("nothing changed"),+ "{body}"+ );++ // The project must still live in the SOURCE workspace (rollback worked).+ let still_src = store+ .reader+ .find_project(src_ws, "proj".to_string())+ .await+ .unwrap();+ assert_eq!(+ still_src,+ Some(src_proj),+ "project rolled back to source ws"+ );+ assert!(+ store+ .reader+ .find_project(dst_ws, "proj".to_string())+ .await+ .unwrap()+ .is_none(),+ "destination must hold no project after rollback"+ );+}++/// W3: moving the project the hook router has published as ACTIVE is refused+/// (409) without `force`.+#[tokio::test]+async fn move_refuses_active_project_without_force() {+ 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, src_proj) = ids(&store, "src", "proj").await;+ state.active_project.set(src_ws, src_proj);++ let resp = post(+ state,+ "/admin/move-project",+ json!({ "from_workspace": "src", "project": "proj", "to_workspace": "dst", "confirm": true }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::CONFLICT);+}++/// W3: `force: true` overrides the active-project guard, and the move+/// republishes the active pointer under the destination workspace.+#[tokio::test]+async fn move_active_project_with_force_succeeds_and_republishes() {+ 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, src_proj) = ids(&store, "src", "proj").await;+ let active = state.active_project.clone();+ active.set(src_ws, src_proj);++ let resp = post(+ state,+ "/admin/move-project",+ json!({ "from_workspace": "src", "project": "proj", "to_workspace": "dst",+ "confirm": true, "force": true }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::OK);++ // The active pointer now points at the SAME project in the destination ws.+ let (dst_ws, _) = ids(&store, "dst", "proj").await;+ assert_eq!(+ active.get(),+ Some((dst_ws, src_proj)),+ "active republished to dst"+ );+}++/// Build an AdminState over an already-open store (lets one test drive two+/// routers — e.g. a move then a re-run — against the same SQLite file).+fn build_state(store: &Store, tmp: &TempDir) -> AdminState {+ AdminState {+ writer: store.writer.clone(),+ reader: store.reader.clone(),+ wiki: Wiki::new(tmp.path(), store.writer.clone()).unwrap(),+ llm: None,+ embedder: None,+ provider_health: ai_memory_llm::ProviderHealth::default(),+ decay_params: DecayParams::default(),+ data_dir: tmp.path().to_path_buf(),+ db_path: store.db_path().to_path_buf(),+ bind: "127.0.0.1:0".to_string(),+ bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),+ }+}++/// W5: a same-path conflict in a copy-purge merge de-duplicates the source page+/// so BOTH versions survive, and the remap is reported.+#[tokio::test]+async fn copy_purge_conflict_duplicates_keeping_both() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ seed_page(&store, &state.wiki, "src", "proj", "notes/a.md", "body SRC").await;+ seed_page(&store, &state.wiki, "dst", "proj", "notes/a.md", "body DST").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["moved_via"], "copy-purge", "{body}");++ let conflicts = body["conflicts"].as_array().unwrap();+ assert_eq!(conflicts.len(), 1, "{body}");+ assert_eq!(conflicts[0]["path"], "notes/a.md");+ assert_eq!(conflicts[0]["moved_to"], "notes/a-from-src.md");++ let mut paths: Vec<String> = store+ .reader+ .list_pages("dst", "proj")+ .await+ .unwrap()+ .into_iter()+ .map(|p| p.path)+ .collect();+ paths.sort();+ assert_eq!(paths, vec!["notes/a-from-src.md", "notes/a.md"]);++ let (dw, dp) = ids(&store, "dst", "proj").await;+ let kept = store+ .reader+ .page_body_by_ids(dw, dp, "notes/a.md")+ .await+ .unwrap()+ .unwrap();+ let moved = store+ .reader+ .page_body_by_ids(dw, dp, "notes/a-from-src.md")+ .await+ .unwrap()+ .unwrap();+ assert_eq!(kept.body, "body DST", "destination's original page is kept");+ assert_eq!(+ moved.body, "body SRC",+ "source page lands under the de-duped path"+ );+}++/// W6: the copy-purge (merge) path carries the source embedding verbatim onto+/// the new destination page id — not a recompute. (The existing embedding test+/// exercised only the true-move path.)+#[tokio::test]+async fn copy_purge_carries_source_embedding() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state_with_embedder(&tmp).await;+ seed_page(+ &store,+ &state.wiki,+ "src",+ "proj",+ "notes/a.md",+ "hello world embed",+ )+ .await;+ // A pre-existing same-named dst project forces the copy-purge path.+ seed_page(&store, &state.wiki, "dst", "proj", "notes/keep.md", "keep").await;++ let (src_ws, src_proj) = ids(&store, "src", "proj").await;+ let src = store+ .reader+ .load_embeddings(+ src_ws,+ src_proj,+ "synthetic".to_string(),+ "bag-of-words-v1".to_string(),+ 8,+ )+ .await+ .unwrap();+ assert_eq!(src.len(), 1);+ let marker: Vec<f32> = vec![9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0];+ store+ .writer+ .store_embedding(+ src[0].id,+ ai_memory_store::f32_vec_to_bytes(&marker),+ "synthetic".to_string(),+ "bag-of-words-v1".to_string(),+ 8,+ )+ .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"], "copy-purge", "{body}");++ let (dst_ws, dst_proj) = ids(&store, "dst", "proj").await;+ let dst = store+ .reader+ .load_embeddings(+ dst_ws,+ dst_proj,+ "synthetic".to_string(),+ "bag-of-words-v1".to_string(),+ 8,+ )+ .await+ .unwrap();+ let moved = dst+ .iter()+ .find(|e| e.path.as_str() == "notes/a.md")+ .expect("moved page embedding");+ for (got, want) in moved.vector.iter().zip(marker.iter()) {+ assert!(+ (got - want).abs() < 1e-4,+ "carried marker, got {:?}",+ moved.vector+ );+ }+}++/// W6: an unreadable source page is skipped and the source is NOT purged, so a+/// fixed re-run is safe; the readable pages still land at the destination.+#[tokio::test]+async fn copy_purge_partial_skips_and_preserves_source() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ seed_page(&store, &state.wiki, "src", "proj", "notes/ok.md", "ok").await;+ seed_page(&store, &state.wiki, "src", "proj", "notes/bad.md", "bad").await;+ seed_page(&store, &state.wiki, "dst", "proj", "notes/keep.md", "keep").await;++ let (src_ws, src_proj) = ids(&store, "src", "proj").await;+ let bad = tmp+ .path()+ .join("wiki")+ .join(src_ws.to_string())+ .join(src_proj.to_string())+ .join("notes/bad.md");+ std::fs::remove_file(&bad).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["source_purged"], false, "{body}");+ let skipped = body["pages_skipped"].as_array().unwrap();+ assert_eq!(skipped.len(), 1, "{body}");+ assert_eq!(skipped[0], "notes/bad.md");++ assert!(+ store+ .reader+ .find_project(src_ws, "proj".to_string())+ .await+ .unwrap()+ .is_some(),+ "source must NOT be purged when a page was skipped"+ );+ let dst_paths: Vec<String> = store+ .reader+ .list_pages("dst", "proj")+ .await+ .unwrap()+ .into_iter()+ .map(|p| p.path)+ .collect();+ assert!(+ dst_paths.contains(&"notes/ok.md".to_string()),+ "readable page copied"+ );+}++/// W6: re-running a copy-purge merge is idempotent — re-copying an+/// already-present page is a no-op supersession, leaving no duplicates.+#[tokio::test]+async fn copy_purge_rerun_is_idempotent() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();++ // First move: src/proj (a.md) into existing dst/proj (keep.md), purges src.+ let s1 = build_state(&store, &tmp);+ seed_page(&store, &s1.wiki, "src", "proj", "notes/a.md", "body a").await;+ seed_page(&store, &s1.wiki, "dst", "proj", "notes/keep.md", "keep").await;+ let r1 = post(+ s1,+ "/admin/move-project",+ json!({ "from_workspace": "src", "project": "proj", "to_workspace": "dst", "confirm": true }),+ )+ .await;+ assert_eq!(r1.status(), StatusCode::OK);++ // Re-create the source identically and run the merge again.+ let s2 = build_state(&store, &tmp);+ seed_page(&store, &s2.wiki, "src", "proj", "notes/a.md", "body a").await;+ let r2 = post(+ s2,+ "/admin/move-project",+ json!({ "from_workspace": "src", "project": "proj", "to_workspace": "dst", "confirm": true }),+ )+ .await;+ assert_eq!(r2.status(), StatusCode::OK);++ // Destination still holds exactly one of each path — no duplicates.+ let mut paths: Vec<String> = store+ .reader+ .list_pages("dst", "proj")+ .await+ .unwrap()+ .into_iter()+ .map(|p| p.path)+ .collect();+ paths.sort();+ assert_eq!(paths, vec!["notes/a.md", "notes/keep.md"]);+}diff --git a/crates/ai-memory-mcp/tests/admin_phase3.rs b/crates/ai-memory-mcp/tests/admin_phase3.rsindex 004c9505..d1313c81 100644--- a/crates/ai-memory-mcp/tests/admin_phase3.rs+++ b/crates/ai-memory-mcp/tests/admin_phase3.rs@@ -44,6 +44,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),};(state, store)}diff --git a/crates/ai-memory-mcp/tests/admin_purge.rs b/crates/ai-memory-mcp/tests/admin_purge.rsindex c3dc5634..f3539b47 100644--- a/crates/ai-memory-mcp/tests/admin_purge.rs+++ b/crates/ai-memory-mcp/tests/admin_purge.rs@@ -41,6 +41,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),db_path,};(state, store)@@ -344,6 +345,7 @@ async fn purge_project_rejecting_admission_leaves_source_intact() {bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),};let (ws, _keep, doomed) = seed_two_projects(&store, &state.wiki).await;@@ -440,6 +442,7 @@ async fn purge_project_idempotent_second_call_is_404() {bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),};seed_two_projects(&store, &state_a.wiki).await;diff --git a/crates/ai-memory-mcp/tests/admin_read_page.rs b/crates/ai-memory-mcp/tests/admin_read_page.rsindex 79f7f845..b44b7f1e 100644--- a/crates/ai-memory-mcp/tests/admin_read_page.rs+++ b/crates/ai-memory-mcp/tests/admin_read_page.rs@@ -29,6 +29,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {bind: "127.0.0.1:49374".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),};(state, store)}diff --git a/crates/ai-memory-mcp/tests/admin_rename.rs b/crates/ai-memory-mcp/tests/admin_rename.rsindex 3303837a..38d7a946 100644--- a/crates/ai-memory-mcp/tests/admin_rename.rs+++ b/crates/ai-memory-mcp/tests/admin_rename.rs@@ -35,6 +35,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),};(state, store)}@@ -318,6 +319,7 @@ async fn rename_project_pages_still_searchable() {bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),};let rename_resp = post(diff --git a/crates/ai-memory-mcp/tests/admin_status_search.rs b/crates/ai-memory-mcp/tests/admin_status_search.rsindex 2b04577f..6f0d2a2a 100644--- a/crates/ai-memory-mcp/tests/admin_status_search.rs+++ b/crates/ai-memory-mcp/tests/admin_status_search.rs@@ -30,6 +30,7 @@ async fn make_admin_state(tmp: &TempDir) -> (AdminState, Store) {bind: "127.0.0.1:49374".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),};(state, store)}diff --git a/crates/ai-memory-mcp/tests/admin_write_page.rs b/crates/ai-memory-mcp/tests/admin_write_page.rsindex 6b36ce79..a93234de 100644--- a/crates/ai-memory-mcp/tests/admin_write_page.rs+++ b/crates/ai-memory-mcp/tests/admin_write_page.rs@@ -30,6 +30,7 @@ async fn make_state(tmp: &TempDir) -> AdminState {bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),}}diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex 8d88dc71..1b26b410 100644--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@ -146,14 +146,23 @@ a low-level re-stamp: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.+ wiki root). The destination dir is pre-checked to be absent first. The+ SQL commits before the rename, but the move is **all-or-nothing**: if the+ rename fails, the SQL re-stamp is rolled back (the op is symmetric) and+ the call returns `move aborted (nothing changed)` — never a+ DB-ahead-of-disk split-brain.This is O(1) (one transaction + one rename), re-embeds nothing, and**preserves everything** — sessions, observations, handoffs and the fullsupersession history all travel with the project.+**Live-session guard.** The server refuses (409) to move the project the+hook router has published as the *active* project (a live session's next+observation would carry a now-stale `workspace_id`). Pass `--force` /+`force: true` to override — still safe: the move republishes the active+pointer, and the `(workspace_id, project_id)` insert trigger (V18) rejects+any stale write cleanly, so the router re-resolves instead of corrupting.+**2. Destination already has a same-named project → `"copy-purge"`(merge).** Two distinct `project_id`s can't be re-stamped into one (itwould collide on `UNIQUE (workspace_id, name)`), so the source's latest@@ -168,6 +177,15 @@ leaving the source intact. An unreadable source file is skipped and alsoblocks the purge (`source_purged: false`) so a fixed re-run is safe(re-running is idempotent — copied pages just supersede).+**Same-path conflicts → duplicate (keep both).** When a source page's path+already exists in the destination with **different** content, the source+page is landed under a de-duplicated path+(`<stem>-from-<src_workspace>.md`, then `-2`, `-3`, …) so neither version is+lost; each remap is listed in the response `conflicts` array. Identical+content is a no-op supersession at the same path. (Wikilinks pointing at the+old path are not rewritten — the lossless `true-move` path is the way to+preserve paths and links.)+**What does NOT migrate (merge case only):** in the `copy-purge` path thesource's `sessions`, `observations`, and `handoffs` (the raw episodiccapture log) are dropped by the purge, and the moved pages start a fresh