Skip to content

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

Rust

fix(admin): tighten move-project per review (crash-safety, on_conflict, cache, tests)

Djalma Júnior494deb9907f5
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index c86c36b2..e5d5ccd8 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -371,6 +371,13 @@ pub struct MoveProjectArgs {
/// and the schema rejects any stale write).
#[arg(long)]
pub force: bool,
+ /// Merge conflict policy (copy-purge path only): what to do when a source
+ /// page's path already exists in the destination with different content.
+ /// `block` (default) aborts and lists the conflicts; `overwrite` lets the
+ /// source supersede the destination page; `duplicate` keeps both (source
+ /// lands under a de-duplicated path).
+ #[arg(long, value_parser = ["block", "overwrite", "duplicate"], default_value = "block")]
+ pub on_conflict: String,
}
/// 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.rs
index d5ccedfc..ea3d1459 100644
--- a/crates/ai-memory-cli/src/commands/move_project.rs
+++ b/crates/ai-memory-cli/src/commands/move_project.rs
@@ -15,6 +15,7 @@ struct MoveProjectRequest {
to_workspace: String,
confirm: bool,
force: bool,
+ on_conflict: String,
}
/// Run the `move-project` subcommand.
@@ -59,6 +60,7 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {
to_workspace: args.to_workspace.clone(),
confirm: true,
force: args.force,
+ on_conflict: args.on_conflict.clone(),
},
)
.await?;
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index df98cc75..a9e2e7d7 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -190,6 +190,20 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
.with_stateful_mode(args.http_stateful)
.with_json_response(!args.http_stateful),
);
+ // Shared per-cwd project cache: the hook router owns it; the admin
+ // router gets a fire-and-forget eviction hook so a `move-project`
+ // can proactively drop the moved project's stale entries.
+ let project_cache: ai_memory_hooks::ProjectCache =
+ std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()));
+ let on_project_moved: std::sync::Arc<dyn Fn(ProjectId) + Send + Sync> = {
+ let cache = project_cache.clone();
+ std::sync::Arc::new(move |proj: ProjectId| {
+ let cache = cache.clone();
+ tokio::spawn(async move {
+ cache.lock().await.retain(|_, v| v.1 != proj);
+ });
+ })
+ };
let hooks = hook_router(HookState {
workspace_id: ws,
project_id: proj,
@@ -198,9 +212,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
wiki: wiki.clone(),
consolidator: consolidator.clone(),
sanitizer: sanitizer.clone(),
- project_cache: std::sync::Arc::new(tokio::sync::Mutex::new(
- std::collections::HashMap::new(),
- )),
+ project_cache: project_cache.clone(),
active_project: active_project.clone(),
ingest_semaphore: std::sync::Arc::new(tokio::sync::Semaphore::new(
DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,
@@ -226,6 +238,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
.filter(|p| !p.trim().is_empty())
.map(|p| ai_memory_store::TokenPepper::new(p.clone())),
active_project: active_project.clone(),
+ on_project_moved: Some(on_project_moved),
});
// Multi-rung auth assembly:
// - rung 0 (no bearer_token configured) → AuthState::new
diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rs
index 1f9d959f..0a5ec060 100644
--- a/crates/ai-memory-hooks/src/lib.rs
+++ b/crates/ai-memory-hooks/src/lib.rs
@@ -27,5 +27,5 @@ pub mod synth;
// pointing at this crate's `sanitize` module keep working.
pub use ai_memory_core::{SanitizeConfig, Sanitized, Sanitizer};
pub use payload::{HookEnvelope, HookEvent};
-pub use router::{DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, HookState, hook_router};
+pub use router::{DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, HookState, ProjectCache, hook_router};
pub use synth::synthesize_session_page;
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index f81e3bea..ce5f912f 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -1026,6 +1026,95 @@ mod tests {
assert!(counts.sessions >= 1, "recreated session must be persisted");
}
+ /// The move-project hazard the (workspace_id, project_id) pairing trigger
+ /// exists for: when a cached project is MOVED to another workspace out from
+ /// under the router, the same `project_id` now belongs to a new workspace.
+ /// The next event must NOT silently write a split-brain row with the stale
+ /// workspace id — the trigger aborts that write, and the router evicts +
+ /// re-resolves into a consistent pair (exactly like the purge self-heal).
+ #[tokio::test]
+ async fn process_self_heals_when_cached_project_moved_workspaces() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let cwd = "/home/user/move-project";
+
+ // 1) First event creates + caches the project (in the default workspace).
+ let env1 = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "user-prompt".into(),
+ agent: Some("claude-code".into()),
+ cwd: Some(cwd.into()),
+ ..Default::default()
+ },
+ serde_json::json!({ "sessionID": "move-sess-1" }),
+ );
+ process(&state, env1).await.unwrap();
+ let (ws, proj) =
+ resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)
+ .await
+ .unwrap();
+
+ // 2) Move the project to another workspace (re-stamp workspace_id, same
+ // project_id) — the cache still points at (default_ws, proj), now a
+ // cross-workspace stale pair.
+ let dst_ws = state
+ .writer
+ .get_or_create_workspace("archive".to_string())
+ .await
+ .unwrap();
+ state
+ .writer
+ .move_project_workspace(proj, ws, dst_ws)
+ .await
+ .unwrap();
+ assert!(
+ state
+ .project_cache
+ .lock()
+ .await
+ .values()
+ .any(|ids| *ids == (ws, proj)),
+ "cache still holds the moved project's stale (workspace, project) pair"
+ );
+
+ // 3) Next event with the same cwd must NOT create a split-brain row: the
+ // stale (default_ws, proj) write trips the pairing trigger, the router
+ // evicts + re-resolves, and the event lands cleanly.
+ let env2 = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "user-prompt".into(),
+ agent: Some("claude-code".into()),
+ cwd: Some(cwd.into()),
+ ..Default::default()
+ },
+ serde_json::json!({ "sessionID": "move-sess-2" }),
+ );
+ process(&state, env2)
+ .await
+ .expect("self-heal: stale cross-workspace pair must re-resolve, not write split-brain");
+
+ // 4) The moved project stayed in `dst_ws`; the cwd re-resolved to a
+ // FRESH project back in the default workspace (never the stale pair).
+ assert_eq!(
+ state
+ .reader
+ .find_project(dst_ws, "move-project".to_string())
+ .await
+ .unwrap(),
+ Some(proj),
+ "moved project keeps its id in the destination workspace"
+ );
+ let (ws_new, proj_new) =
+ resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)
+ .await
+ .unwrap();
+ assert_eq!(ws_new, ws, "re-resolved back into the default workspace");
+ assert_ne!(
+ proj_new, proj,
+ "a fresh project replaced the moved one for this cwd"
+ );
+ }
+
#[tokio::test]
async fn process_self_heal_evicts_project_strategy_cache_slot() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 1c39bb33..a71ee25f 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -100,6 +100,14 @@ pub struct AdminState {
/// pointer correct after a move. Empty `ActiveProject::new()` when no
/// hook router is attached (admin-only tests).
pub active_project: ActiveProject,
+ /// Optional hook to PROACTIVELY evict the hook router's per-cwd
+ /// `(workspace_id, project_id)` cache for a project that just moved
+ /// workspaces. Called with the moved `project_id` after a successful move
+ /// so the next hook event re-resolves cleanly instead of tripping the
+ /// pairing trigger on a stale cached pair first. Fire-and-forget
+ /// (best-effort); the trigger + router re-resolve are the correctness net.
+ /// `None` when no hook router is attached (stdio / admin-only tests).
+ pub on_project_moved: Option<std::sync::Arc<dyn Fn(ProjectId) + Send + Sync>>,
}
/// JSON request body for `POST /admin/bootstrap`.
@@ -1613,6 +1621,28 @@ struct MoveProjectRequest {
/// stale write fail cleanly rather than corrupt).
#[serde(default)]
force: bool,
+ /// Policy for the copy-purge MERGE path when a source page's path already
+ /// exists in the destination with DIFFERENT content. Ignored by true-move
+ /// (no copy). Default `block` — the safe choice for a destructive op.
+ #[serde(default)]
+ on_conflict: OnConflict,
+}
+
+/// What to do when a merged page path collides with an existing destination
+/// page of different content.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default)]
+#[serde(rename_all = "lowercase")]
+enum OnConflict {
+ /// Abort the whole move (source untouched), listing the conflicting paths.
+ /// The operator resolves them or picks another policy explicitly.
+ #[default]
+ Block,
+ /// The source page supersedes the destination page at the same path (the
+ /// destination's prior version becomes history).
+ Overwrite,
+ /// Keep BOTH: the source page lands under a de-duplicated path
+ /// (`<stem>-from-<src_workspace>.md`), reported in `conflicts`.
+ Duplicate,
}
/// Wire-format report returned by `POST /admin/move-project`.
@@ -1672,17 +1702,20 @@ pub struct PathConflict {
pub moved_to: 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.
+/// Lossless cross-workspace move: rename the project's on-disk dir to the
+/// destination workspace, then re-stamp its `workspace_id` across every domain
+/// table (one transaction, same `project_id`). 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.
+/// Ordering is deliberately rename-FIRST, SQL-commit-LAST so the **DB is never
+/// ahead of disk**: a rename failure touches nothing; a crash between the two
+/// steps leaves at most an orphan dir at the destination with the DB still
+/// wholly pointing at the source (recoverable), never a DB row pointing at a
+/// missing file. On a SQL failure the dir is renamed back (the op is
+/// symmetric), so the move is all-or-nothing. During the brief window between
+/// rename and commit, any watcher reindex of the moved files attempts an INSERT
+/// under `(dst_ws, proj)` that the V18 pairing trigger rejects cleanly (the
+/// project still lives in `src_ws`), so no split-brain row is created.
async fn true_move_project(
state: &Arc<AdminState>,
req: &MoveProjectRequest,
@@ -1702,8 +1735,7 @@ async fn true_move_project(
};
// 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.
+ // exist. Check before the rename so a stale leftover can never be clobbered.
let dst_dir = state.wiki.project_root(dst_ws, src_proj);
if dst_dir.exists() {
return (
@@ -1717,61 +1749,66 @@ async fn true_move_project(
);
}
+ // 1) Rename the dir FIRST — before any DB change. A failure here leaves
+ // everything untouched.
+ if let Err(e) = state.wiki.rename_project_dir(src_proj, src_ws, dst_ws) {
+ warn!(
+ error = %e,
+ "true-move: dir rename failed before any DB change — nothing moved"
+ );
+ return internal_err(format!(
+ "move aborted (nothing changed): on-disk dir rename failed: {e}"
+ ));
+ }
+
+ // 2) Re-stamp the DB LAST. On failure, rename the dir back so the move is
+ // all-or-nothing and the DB never ends up ahead of disk.
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, 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);
- 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()
- ));
+ Err(e) => {
+ let src_dir = state.wiki.project_root(src_ws, src_proj);
+ match state.wiki.rename_project_dir(src_proj, dst_ws, src_ws) {
+ Ok(()) => {
+ warn!(
+ error = %e,
+ "true-move: DB re-stamp failed; renamed the dir back — nothing moved"
+ );
+ return match e {
+ StoreError::NotFound(msg) => (
+ StatusCode::NOT_FOUND,
+ Json(serde_json::json!({ "error": msg })),
+ ),
+ other => internal_err(format!(
+ "move aborted (nothing changed): DB re-stamp failed: {other}"
+ )),
+ };
+ }
+ Err(rollback_err) => {
+ // Double fault: files are at the destination but the DB
+ // re-stamp failed AND the rename-back failed. Surface a
+ // precise manual-repair message.
+ error!(
+ error = %e,
+ rollback_error = %rollback_err,
+ src = %src_dir.display(),
+ dst = %dst_dir.display(),
+ "true-move: DB re-stamp failed AND dir rename-back failed — manual repair required"
+ );
+ return internal_err(format!(
+ "INCONSISTENT STATE: files moved but DB re-stamp failed ({e}) and dir \
+ rename-back also failed ({rollback_err}); manually move {} -> {} or finish \
+ the re-stamp",
+ dst_dir.display(),
+ src_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
@@ -1780,6 +1817,10 @@ async fn true_move_project(
if state.active_project.get().map(|(_, p)| p) == Some(src_proj) {
state.active_project.set(dst_ws, src_proj);
}
+ // Proactively drop any stale per-cwd cache entry for the moved project.
+ if let Some(evict) = &state.on_project_moved {
+ evict(src_proj);
+ }
let report = MoveProjectReport {
from: format!("{}/{}", req.from_workspace, req.project),
@@ -1945,6 +1986,38 @@ async fn handle_move_project(
Err(e) => return internal_err(e.to_string()),
};
+ // Pre-scan for same-path conflicts (destination already holds the path with
+ // DIFFERENT content). Under the default `block` policy, abort the WHOLE move
+ // now — before anything is copied — so the source stays intact and the
+ // operator resolves them or re-runs with an explicit overwrite/duplicate.
+ if req.on_conflict == OnConflict::Block {
+ let mut blocking: Vec<String> = Vec::new();
+ for s in &summaries {
+ let Ok(path) = PagePath::new(s.path.clone()) else {
+ continue;
+ };
+ if let Ok(Some(existing)) = state
+ .reader
+ .page_body_by_ids(dst_ws, dst_proj, s.path.as_str())
+ .await
+ && let Ok(md) = state.wiki.read_page(src_ws, src_proj, &path)
+ && existing.body != md.body
+ {
+ blocking.push(s.path.clone());
+ }
+ }
+ if !blocking.is_empty() {
+ return (
+ StatusCode::CONFLICT,
+ Json(serde_json::json!({
+ "error": "destination already has pages at these paths with different content; \
+ resolve them or re-run with on_conflict=overwrite or on_conflict=duplicate",
+ "conflicts": blocking,
+ })),
+ );
+ }
+ }
+
// Carry the source page embeddings over verbatim instead of recomputing
// them — embedding is the dominant per-page cost of a bulk move. Writes go
// through an embedder-less Wiki so `write_page` never re-embeds; we then
@@ -2010,31 +2083,43 @@ 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.
+ // Same-path conflict (destination holds this path with DIFFERENT
+ // content): apply the on_conflict policy. Identical content always falls
+ // through to a no-op supersession at the same path. `block` was already
+ // handled by the pre-scan above (we never get here with a real conflict).
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
- }
+ Ok(Some(existing)) if existing.body != md.body => match req.on_conflict {
+ OnConflict::Duplicate => {
+ 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
+ }
+ // Overwrite: the source page supersedes the destination page at
+ // the same path (the dest's prior version becomes history).
+ OnConflict::Overwrite => {
+ conflicts.push(PathConflict {
+ path: s.path.clone(),
+ moved_to: s.path.clone(),
+ });
+ path.clone()
+ }
+ OnConflict::Block => path.clone(),
+ },
_ => path.clone(),
};
used_dest_paths.insert(dest_path.as_str().to_string());
@@ -2153,6 +2238,11 @@ async fn handle_move_project(
if state.active_project.get().map(|(_, p)| p) == Some(src_proj) {
state.active_project.clear();
}
+ // Proactively drop any stale per-cwd cache entry for the purged source
+ // project (its project_id no longer exists).
+ if let Some(evict) = &state.on_project_moved {
+ evict(src_proj);
+ }
let report = MoveProjectReport {
from: label,
@@ -2636,6 +2726,7 @@ mod tests {
bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
});
let resp = router
@@ -2673,6 +2764,7 @@ mod tests {
bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
});
(tmp, router)
}
@@ -2853,6 +2945,7 @@ mod tests {
bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
});
post_write_page(&router, "default", "doomed", "notes/x.md", "bye").await;
@@ -2913,6 +3006,7 @@ mod tests {
bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),
token_pepper: Some(pepper),
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
});
// Wrap in a middleware that stamps the AuthLevel ourselves —
// the real auth middleware lives in ai-memory-cli, and this
@@ -3198,6 +3292,7 @@ mod tests {
bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
});
// 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.rs
index eccdfee5..f452a2a3 100644
--- a/crates/ai-memory-mcp/tests/admin_backup.rs
+++ b/crates/ai-memory-mcp/tests/admin_backup.rs
@@ -37,6 +37,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
};
(state, store)
}
diff --git a/crates/ai-memory-mcp/tests/admin_bootstrap.rs b/crates/ai-memory-mcp/tests/admin_bootstrap.rs
index 83724cd4..0b1b05c3 100644
--- a/crates/ai-memory-mcp/tests/admin_bootstrap.rs
+++ b/crates/ai-memory-mcp/tests/admin_bootstrap.rs
@@ -34,6 +34,7 @@ async fn make_admin_state(tmp: &TempDir) -> AdminState {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
}
}
diff --git a/crates/ai-memory-mcp/tests/admin_move.rs b/crates/ai-memory-mcp/tests/admin_move.rs
index de307f18..770933d5 100644
--- a/crates/ai-memory-mcp/tests/admin_move.rs
+++ b/crates/ai-memory-mcp/tests/admin_move.rs
@@ -45,6 +45,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
};
(state, store)
}
@@ -363,6 +364,7 @@ async fn move_project_carries_source_embedding() {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
};
// Seed source page (gets a synthetic embedding on write).
@@ -573,6 +575,7 @@ async fn make_state_with_embedder(tmp: &TempDir) -> (AdminState, Store) {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
};
(state, store)
}
@@ -722,11 +725,12 @@ fn build_state(store: &Store, tmp: &TempDir) -> AdminState {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
}
}
-/// W5: a same-path conflict in a copy-purge merge de-duplicates the source page
-/// so BOTH versions survive, and the remap is reported.
+/// on_conflict=duplicate: a same-path conflict 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();
@@ -737,7 +741,8 @@ async fn copy_purge_conflict_duplicates_keeping_both() {
let resp = post(
state,
"/admin/move-project",
- json!({ "from_workspace": "src", "project": "proj", "to_workspace": "dst", "confirm": true }),
+ json!({ "from_workspace": "src", "project": "proj", "to_workspace": "dst",
+ "confirm": true, "on_conflict": "duplicate" }),
)
.await;
assert_eq!(resp.status(), StatusCode::OK);
@@ -780,6 +785,109 @@ async fn copy_purge_conflict_duplicates_keeping_both() {
);
}
+/// on_conflict=block (the DEFAULT): a same-path conflict aborts the whole move
+/// with 409, lists the conflicting paths, and leaves the source intact —
+/// nothing is copied to the destination.
+#[tokio::test]
+async fn copy_purge_conflict_blocks_by_default() {
+ 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,
+ "src",
+ "proj",
+ "notes/clean.md",
+ "only in src",
+ )
+ .await;
+ seed_page(&store, &state.wiki, "dst", "proj", "notes/a.md", "body DST").await;
+
+ // No on_conflict → defaults to block.
+ 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);
+ let body = body_json(resp).await;
+ let conflicts = body["conflicts"].as_array().unwrap();
+ assert_eq!(conflicts.len(), 1, "{body}");
+ assert_eq!(conflicts[0], "notes/a.md");
+
+ // Source untouched (NOT purged) and the destination got NONE of the pages.
+ let (src_ws, _) = ids(&store, "src", "proj").await;
+ assert!(
+ store
+ .reader
+ .find_project(src_ws, "proj".to_string())
+ .await
+ .unwrap()
+ .is_some(),
+ "block must leave the source intact"
+ );
+ let dst_paths: Vec<String> = store
+ .reader
+ .list_pages("dst", "proj")
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|p| p.path)
+ .collect();
+ assert_eq!(
+ dst_paths,
+ vec!["notes/a.md"],
+ "destination unchanged — nothing copied"
+ );
+}
+
+/// on_conflict=overwrite: the source page supersedes the destination page at the
+/// same path; the destination ends with the source's content and no duplicate.
+#[tokio::test]
+async fn copy_purge_conflict_overwrites() {
+ 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, "on_conflict": "overwrite" }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["source_purged"], true, "{body}");
+ // Conflict reported, mapped to the same path (supersede, not duplicate).
+ 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.md");
+
+ // Destination has exactly ONE page at the path, carrying the SOURCE content.
+ let dst_paths: Vec<String> = store
+ .reader
+ .list_pages("dst", "proj")
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|p| p.path)
+ .collect();
+ assert_eq!(dst_paths, vec!["notes/a.md"], "no duplicate path");
+ let (dw, dp) = ids(&store, "dst", "proj").await;
+ let page = store
+ .reader
+ .page_body_by_ids(dw, dp, "notes/a.md")
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(page.body, "body SRC", "source superseded the destination");
+}
+
/// 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.)
diff --git a/crates/ai-memory-mcp/tests/admin_phase3.rs b/crates/ai-memory-mcp/tests/admin_phase3.rs
index d1313c81..9bf2bc1e 100644
--- a/crates/ai-memory-mcp/tests/admin_phase3.rs
+++ b/crates/ai-memory-mcp/tests/admin_phase3.rs
@@ -45,6 +45,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
};
(state, store)
}
diff --git a/crates/ai-memory-mcp/tests/admin_purge.rs b/crates/ai-memory-mcp/tests/admin_purge.rs
index f3539b47..b772e793 100644
--- a/crates/ai-memory-mcp/tests/admin_purge.rs
+++ b/crates/ai-memory-mcp/tests/admin_purge.rs
@@ -42,6 +42,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
db_path,
};
(state, store)
@@ -346,6 +347,7 @@ async fn purge_project_rejecting_admission_leaves_source_intact() {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
};
let (ws, _keep, doomed) = seed_two_projects(&store, &state.wiki).await;
@@ -443,6 +445,7 @@ async fn purge_project_idempotent_second_call_is_404() {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
};
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.rs
index b44b7f1e..e5302abb 100644
--- a/crates/ai-memory-mcp/tests/admin_read_page.rs
+++ b/crates/ai-memory-mcp/tests/admin_read_page.rs
@@ -30,6 +30,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
};
(state, store)
}
diff --git a/crates/ai-memory-mcp/tests/admin_rename.rs b/crates/ai-memory-mcp/tests/admin_rename.rs
index 38d7a946..8436fe4a 100644
--- a/crates/ai-memory-mcp/tests/admin_rename.rs
+++ b/crates/ai-memory-mcp/tests/admin_rename.rs
@@ -36,6 +36,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
};
(state, store)
}
@@ -320,6 +321,7 @@ async fn rename_project_pages_still_searchable() {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
};
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.rs
index 6f0d2a2a..bd8d2d29 100644
--- a/crates/ai-memory-mcp/tests/admin_status_search.rs
+++ b/crates/ai-memory-mcp/tests/admin_status_search.rs
@@ -31,6 +31,7 @@ async fn make_admin_state(tmp: &TempDir) -> (AdminState, Store) {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
};
(state, store)
}
diff --git a/crates/ai-memory-mcp/tests/admin_write_page.rs b/crates/ai-memory-mcp/tests/admin_write_page.rs
index a93234de..eb3591c3 100644
--- a/crates/ai-memory-mcp/tests/admin_write_page.rs
+++ b/crates/ai-memory-mcp/tests/admin_write_page.rs
@@ -31,6 +31,7 @@ async fn make_state(tmp: &TempDir) -> AdminState {
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
token_pepper: None,
active_project: ai_memory_core::ActiveProject::new(),
+ on_project_moved: None,
}
}
diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.md
index 1b26b410..0d964447 100644
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@ -146,11 +146,15 @@ 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). 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.
+ wiki root). The destination dir is pre-checked to be absent first. Ordering
+ is **rename-FIRST, SQL-commit-LAST**, so the **DB is never ahead of disk**:
+ a rename failure touches nothing; a crash between the two steps leaves at
+ most an orphan dir at the destination with the DB still wholly at the
+ source (recoverable), never a DB row pointing at a missing file. A SQL
+ failure renames the dir back, so the move is all-or-nothing. During the
+ brief window, any watcher reindex of the moved files attempts an INSERT
+ under `(dst_ws, proj)` that the V18 pairing trigger rejects cleanly (the
+ project still lives in `src_ws`), so no split-brain row is created.
This is O(1) (one transaction + one rename), re-embeds nothing, and
**preserves everything** — sessions, observations, handoffs and the full
@@ -177,14 +181,23 @@ 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).
-**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.)
+**Same-path conflicts (`on_conflict`).** When a source page's path already
+exists in the destination with **different** content, the policy decides
+(identical content is always a no-op supersession at the same path):
+
+- **`block`** (default) — abort the whole move with 409, listing the
+ conflicting paths; the source is left intact. The safe default for a
+ destructive op: nothing is overwritten or split silently. The operator
+ resolves the conflicts or re-runs with an explicit policy.
+- **`overwrite`** — the source page supersedes the destination page at the
+ same path (the destination's prior version becomes history).
+- **`duplicate`** — keep both: the source page lands under a de-duplicated
+ path (`<stem>-from-<src_workspace>.md`, then `-2`, …). Note: wikilinks
+ pointing at the original path are not rewritten, so the lossless
+ `true-move` path remains the way to preserve paths and links.
+
+Every conflict (overwrite/duplicate) is listed in the response `conflicts`
+array (`path` → `moved_to`). Set the policy via `--on-conflict` on the CLI.
**What does NOT migrate (merge case only):** in the `copy-purge` path the
source's `sessions`, `observations`, and `handoffs` (the raw episodic