Skip to content

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

Rust

fix(admin): harden move-project true-move

AkitaOnRailsf7374bf3775f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 18e7e0f1..78ee6301 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- `ai-memory move-project` can move projects across workspaces via the admin
+ API. Fresh destinations use a lossless true move that keeps the same
+ `project_id`, sessions, observations, handoffs, embeddings, and page history;
+ existing same-named destination projects use copy-purge merge with explicit
+ `on_conflict` handling. Admission webhooks can subscribe to the new
+ `move_project` event and receive destination names in the context ([#60]).
- Page FTS now indexes normalized page paths, so searches can find pages by
filename or slug even when the slug does not appear in the title/body ([#62]).
- Admission webhooks can now observe, mutate, or reject engine write/delete/
@@ -18,6 +24,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
before removal ([#55]).
### Fixed
+- `move-project` true moves now run through a wiki mutation gate: normal
+ page writes/reindexes validate the `(workspace_id, project_id)` pair before
+ touching disk, while true moves hold the exclusive side across the directory
+ rename and DB re-stamp. Stale old-workspace writes now fail without creating
+ orphan files, and V18 aborts if existing split-brain rows are present ([#60]).
+- `move-project` copy-purge conflict detection now treats body, frontmatter,
+ title, tier, and pinned status as the page identity under `on_conflict=block`,
+ preventing metadata-only overwrites from slipping through ([#60]).
- `memory_write_page` calls that specify `project` without `workspace` now
default to the active workspace published by hooks, and project-only reads use
the same active-workspace resolution so the write can be read back without an
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index b6223dae..2a2cbbee 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -39,7 +39,7 @@ use ai_memory_llm::{Embedder, LlmProvider, ProviderHealth, ProviderHealthSnapsho
use ai_memory_store::{
DecayParams, EmbeddingWrite, ReaderPool, StoreError, WriterHandle, f32_vec_to_bytes,
};
-use ai_memory_wiki::{AdmissionContext, AdmissionOp, Wiki, WikiError, WritePageRequest};
+use ai_memory_wiki::{AdmissionContext, AdmissionOp, Markdown, Wiki, WikiError, WritePageRequest};
use axum::Json;
use axum::Router;
use axum::body::Body;
@@ -51,7 +51,7 @@ use flate2::Compression;
use flate2::write::GzEncoder;
use serde::{Deserialize, Serialize};
use tokio_util::io::ReaderStream;
-use tracing::{error, info, warn};
+use tracing::{info, warn};
const EMBEDDING_WRITE_BATCH: usize = 100;
@@ -1702,20 +1702,11 @@ pub struct PathConflict {
pub moved_to: String,
}
-/// 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 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.
+/// Lossless cross-workspace move: under the wiki mutation gate, 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.
async fn true_move_project(
state: &Arc<AdminState>,
req: &MoveProjectRequest,
@@ -1735,7 +1726,8 @@ async fn true_move_project(
};
// A true move targets a FRESH destination, so its dir must not already
- // exist. Check before the rename so a stale leftover can never be clobbered.
+ // exist. Wiki::move_project_workspace repeats this check under the
+ // exclusive mutation guard before it renames anything.
let dst_dir = state.wiki.project_root(dst_ws, src_proj);
if dst_dir.exists() {
return (
@@ -1749,64 +1741,42 @@ 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}"
- ));
- }
+ let move_ctx = AdmissionContext {
+ workspace: req.from_workspace.clone(),
+ project: req.project.clone(),
+ destination_workspace: Some(req.to_workspace.clone()),
+ destination_project: Some(req.project.clone()),
+ op: AdmissionOp::MoveProject,
+ ..Default::default()
+ };
- // 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.
+ // Wiki owns the critical section: it runs move admission, renames the dir,
+ // re-stamps SQLite, and rolls the dir back on SQL failure while normal page
+ // writes/reindexes are blocked by the same process-local gate.
let summary = match state
- .writer
- .move_project_workspace(src_proj, src_ws, dst_ws)
+ .wiki
+ .move_project_workspace(src_proj, src_ws, dst_ws, Some(move_ctx))
.await
{
Ok(s) => s,
+ Err(WikiError::Store(StoreError::NotFound(msg))) => {
+ return (
+ StatusCode::NOT_FOUND,
+ Json(serde_json::json!({ "error": msg })),
+ );
+ }
+ Err(WikiError::Io(e))
+ if e.kind() == std::io::ErrorKind::AlreadyExists
+ && e.to_string().contains("destination dir already exists") =>
+ {
+ return (
+ StatusCode::CONFLICT,
+ Json(serde_json::json!({ "error": e.to_string() })),
+ );
+ }
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()
- ));
- }
- }
+ warn!(error = %e, "true-move: move aborted before completion");
+ return internal_err(format!("move aborted (nothing changed): {e}"));
}
};
@@ -1894,6 +1864,24 @@ async fn dedup_dest_path(
}
}
+fn page_copy_differs(
+ existing: &ai_memory_store::StoredPageBody,
+ source: &Markdown,
+ source_title: &str,
+ source_tier: Tier,
+ source_pinned: bool,
+) -> bool {
+ let source_frontmatter = match serde_json::to_string(&source.frontmatter) {
+ Ok(value) => value,
+ Err(_) => return true,
+ };
+ existing.body != source.body
+ || existing.frontmatter_json != source_frontmatter
+ || existing.title != source_title
+ || existing.tier != source_tier.as_str()
+ || existing.pinned != source_pinned
+}
+
async fn handle_move_project(
State(state): State<Arc<AdminState>>,
Json(req): Json<MoveProjectRequest>,
@@ -1987,21 +1975,27 @@ async fn handle_move_project(
};
// 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.
+ // a different body, frontmatter, title, tier, or pinned bit). 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;
};
+ let tier: Tier = s.tier.parse().unwrap_or(Tier::Semantic);
+ let pinned = matches!(
+ state.reader.page_meta(&req.from_workspace, &req.project, &s.path).await,
+ Ok(Some(ref m)) if m.pinned
+ );
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
+ && page_copy_differs(&existing, &md, &s.title, tier, pinned)
{
blocking.push(s.path.clone());
}
@@ -2083,43 +2077,46 @@ async fn handle_move_project(
continue;
}
};
- // 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).
+ // Same-path conflict (destination holds this path with DIFFERENT page
+ // body/metadata): apply the on_conflict policy. Identical pages always
+ // fall 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 => 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()
+ Ok(Some(existing)) if page_copy_differs(&existing, &md, &s.title, tier, pinned) => {
+ 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(),
}
- OnConflict::Block => path.clone(),
- },
+ }
// No content conflict — but the natural path may already have been
// CLAIMED by an earlier page's de-duplication (duplicate mode). If
// so, de-duplicate this one too rather than clobbering the page that
diff --git a/crates/ai-memory-mcp/tests/admin_move.rs b/crates/ai-memory-mcp/tests/admin_move.rs
index d634260e..a21cb554 100644
--- a/crates/ai-memory-mcp/tests/admin_move.rs
+++ b/crates/ai-memory-mcp/tests/admin_move.rs
@@ -16,10 +16,15 @@
use ai_memory_core::{PagePath, Tier};
use ai_memory_mcp::{AdminState, admin_router};
use ai_memory_store::{DecayParams, Store};
-use ai_memory_wiki::{Wiki, WritePageRequest};
+use ai_memory_wiki::{
+ AdmissionChain, AdmissionOp, FailurePolicy, WebhookConfig, Wiki, WritePageRequest,
+};
use axum::body::Body;
-use axum::http::{Request, StatusCode};
+use axum::http::{HeaderMap, Request, StatusCode};
+use axum::routing::post as axum_post;
+use axum::{Json, Router};
use serde_json::json;
+use std::sync::{Arc, Mutex};
use tempfile::TempDir;
use tower::ServiceExt;
@@ -70,6 +75,39 @@ async fn post(state: AdminState, uri: &str, body: serde_json::Value) -> axum::re
/// Seed `<ws>/<project>/<path>` with one page carrying `body`.
async fn seed_page(store: &Store, wiki: &Wiki, ws: &str, project: &str, path: &str, body: &str) {
+ seed_page_with_metadata(
+ store,
+ wiki,
+ ws,
+ project,
+ path,
+ body,
+ SeedPageOptions {
+ frontmatter: serde_json::json!({"title": path}),
+ title: Some(path.into()),
+ tier: Tier::Semantic,
+ pinned: false,
+ },
+ )
+ .await;
+}
+
+struct SeedPageOptions {
+ frontmatter: serde_json::Value,
+ title: Option<String>,
+ tier: Tier,
+ pinned: bool,
+}
+
+async fn seed_page_with_metadata(
+ store: &Store,
+ wiki: &Wiki,
+ ws: &str,
+ project: &str,
+ path: &str,
+ body: &str,
+ options: SeedPageOptions,
+) {
let ws_id = store.writer.get_or_create_workspace(ws).await.unwrap();
let proj = store
.writer
@@ -80,11 +118,11 @@ async fn seed_page(store: &Store, wiki: &Wiki, ws: &str, project: &str, path: &s
workspace_id: ws_id,
project_id: proj,
path: PagePath::new(path.to_string()).unwrap(),
- frontmatter: serde_json::json!({"title": path}),
+ frontmatter: options.frontmatter,
body: body.to_string(),
- tier: Tier::Semantic,
- pinned: false,
- title: Some(path.into()),
+ tier: options.tier,
+ pinned: options.pinned,
+ title: options.title,
admission_ctx: None,
author_id: None,
actor: ai_memory_core::ActorContext::anonymous(),
@@ -546,6 +584,127 @@ async fn move_project_true_move_preserves_sessions_and_observations() {
assert_eq!(obs[0].workspace_id, dst_ws, "observation re-stamped to dst");
}
+#[tokio::test]
+async fn true_move_stale_source_write_fails_before_creating_file() {
+ 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 stale_wiki = state.wiki.clone();
+
+ 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 stale_path = PagePath::new("notes/stale.md".to_string()).unwrap();
+ let err = stale_wiki
+ .write_page(WritePageRequest {
+ workspace_id: src_ws,
+ project_id: src_proj,
+ path: stale_path.clone(),
+ frontmatter: serde_json::json!({"title": "stale"}),
+ body: "must not land".to_string(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: Some("stale".into()),
+ admission_ctx: None,
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ })
+ .await
+ .unwrap_err();
+ assert!(
+ err.to_string().contains("does not belong to workspace"),
+ "stale write should fail at the pair validator: {err}"
+ );
+ assert!(
+ !stale_wiki.abs_path(src_ws, src_proj, &stale_path).exists(),
+ "stale write must not create an orphan file under the old workspace"
+ );
+}
+
+#[tokio::test]
+async fn true_move_notifies_admission_with_destination_names() {
+ let seen: Arc<Mutex<Vec<serde_json::Value>>> = Arc::new(Mutex::new(Vec::new()));
+ let seen_for_route = seen.clone();
+ let app = Router::new().route(
+ "/hook",
+ axum_post(
+ move |headers: HeaderMap, Json(payload): Json<serde_json::Value>| {
+ let seen = seen_for_route.clone();
+ async move {
+ let mut payload = payload;
+ payload["op_header"] = headers
+ .get("X-Memory-Op")
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("")
+ .into();
+ seen.lock().unwrap().push(payload);
+ StatusCode::NO_CONTENT
+ }
+ },
+ ),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}/hook", listener.local_addr().unwrap());
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let chain = AdmissionChain::new(vec![WebhookConfig {
+ name: "mirror".into(),
+ url,
+ timeout_ms: 2_000,
+ failure_policy: FailurePolicy::Reject,
+ events: vec![AdmissionOp::MoveProject],
+ blocking: true,
+ }])
+ .unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_admission_chain(chain)
+ .with_store_reader(store.reader.clone());
+ let state = AdminState {
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki,
+ llm: None,
+ embedder: None,
+ provider_health: ai_memory_llm::ProviderHealth::default(),
+ decay_params: DecayParams::default(),
+ data_dir: tmp.path().to_path_buf(),
+ db_path: 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(),
+ on_project_moved: None,
+ };
+ seed_page(&store, &state.wiki, "src", "proj", "notes/a.md", "body a").await;
+
+ let resp = post(
+ state,
+ "/admin/move-project",
+ json!({ "from_workspace": "src", "project": "proj", "to_workspace": "dst", "confirm": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let rec = seen.lock().unwrap();
+ assert_eq!(rec.len(), 1, "move_project admission must fire once");
+ assert_eq!(rec[0]["op_header"], "move_project");
+ assert_eq!(rec[0]["ctx"]["workspace"], "src");
+ assert_eq!(rec[0]["ctx"]["project"], "proj");
+ assert_eq!(rec[0]["ctx"]["destination_workspace"], "dst");
+ assert_eq!(rec[0]["ctx"]["destination_project"], "proj");
+ assert_eq!(rec[0]["page"]["path"], "");
+}
+
// ---------------------------------------------------------------------------
// Rework (PR #60 review): failure model, live-session guard, copy-purge
// conflict/partial/idempotency, copy-purge embedding carry-over.
@@ -843,6 +1002,67 @@ async fn copy_purge_conflict_blocks_by_default() {
);
}
+/// `on_conflict=block` must treat metadata differences as conflicts too. A
+/// same body/title/frontmatter with a different pinned bit would otherwise be
+/// silently overwritten by the copy path.
+#[tokio::test]
+async fn copy_purge_conflict_blocks_metadata_difference_by_default() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let fm = serde_json::json!({"title": "same"});
+ seed_page_with_metadata(
+ &store,
+ &state.wiki,
+ "src",
+ "proj",
+ "notes/a.md",
+ "same body",
+ SeedPageOptions {
+ frontmatter: fm.clone(),
+ title: Some("same".into()),
+ tier: Tier::Semantic,
+ pinned: false,
+ },
+ )
+ .await;
+ seed_page_with_metadata(
+ &store,
+ &state.wiki,
+ "dst",
+ "proj",
+ "notes/a.md",
+ "same body",
+ SeedPageOptions {
+ frontmatter: fm,
+ title: Some("same".into()),
+ tier: Tier::Semantic,
+ pinned: true,
+ },
+ )
+ .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::CONFLICT);
+ let body = body_json(resp).await;
+ assert_eq!(body["conflicts"], json!(["notes/a.md"]), "{body}");
+
+ let (src_ws, _) = ids(&store, "src", "proj").await;
+ assert!(
+ store
+ .reader
+ .find_project(src_ws, "proj".to_string())
+ .await
+ .unwrap()
+ .is_some(),
+ "metadata conflict must leave the source intact"
+ );
+}
+
/// 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]
diff --git a/crates/ai-memory-store/migrations/V18__enforce_project_workspace_pairing.sql b/crates/ai-memory-store/migrations/V18__enforce_project_workspace_pairing.sql
index 95ce3eef..785dd541 100644
--- a/crates/ai-memory-store/migrations/V18__enforce_project_workspace_pairing.sql
+++ b/crates/ai-memory-store/migrations/V18__enforce_project_workspace_pairing.sql
@@ -13,6 +13,40 @@
-- evicts its cache and re-resolves on a write error, so a clean abort turns the
-- worst case (silent corruption) into self-healing.
--
+-- Existing split-brain rows must be repaired before the triggers are installed.
+-- SQLite's RAISE() is trigger-only, so this temporary CHECK table gives the
+-- migration a deterministic abort with the table-specific mismatch count.
+CREATE TEMP TABLE _v18_pairing_guard (
+ label TEXT NOT NULL,
+ mismatch_count INTEGER NOT NULL CHECK (mismatch_count = 0)
+);
+
+INSERT INTO _v18_pairing_guard(label, mismatch_count)
+SELECT 'pages', COUNT(*)
+FROM pages pg
+JOIN projects p ON p.id = pg.project_id
+WHERE pg.workspace_id IS NOT p.workspace_id;
+
+INSERT INTO _v18_pairing_guard(label, mismatch_count)
+SELECT 'sessions', COUNT(*)
+FROM sessions s
+JOIN projects p ON p.id = s.project_id
+WHERE s.workspace_id IS NOT p.workspace_id;
+
+INSERT INTO _v18_pairing_guard(label, mismatch_count)
+SELECT 'observations', COUNT(*)
+FROM observations o
+JOIN projects p ON p.id = o.project_id
+WHERE o.workspace_id IS NOT p.workspace_id;
+
+INSERT INTO _v18_pairing_guard(label, mismatch_count)
+SELECT 'handoffs', COUNT(*)
+FROM handoffs h
+JOIN projects p ON p.id = h.project_id
+WHERE h.workspace_id IS NOT p.workspace_id;
+
+DROP TABLE _v18_pairing_guard;
+
-- INSERT only — never UPDATE — so the move-project re-stamp (which UPDATEs
-- workspace_id across these tables in one transaction) is unaffected.
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index d3d139ec..c93bf828 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -25,7 +25,7 @@ pub use fts_query::prepare_fts5_query;
pub use decay::{DecayParams, retention_score};
pub use error::{StoreError, StoreResult};
-pub use ops::{EmbeddingWrite, PurgeSummary, ReorgSummary};
+pub use ops::{EmbeddingWrite, MoveSummary, PurgeSummary, ReorgSummary};
pub use reader::{
ActivityWindow, BriefingPage, BriefingSnapshot, DecayCandidate, DerivedIndexStatus,
EmbeddingTripleCount, HealthDetail, HealthPage, ObservationHit, PageAuthor, PageHit,
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 7d23d9e6..12a0d839 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -142,6 +142,32 @@ pub fn get_or_create_project(
Ok(id)
}
+/// Assert that `project_id` currently belongs to `workspace_id`.
+///
+/// Wiki writes call this before touching the filesystem so a stale hook/cache
+/// carrying the old workspace for a moved project fails before it can create an
+/// orphan file. The pairing INSERT triggers are still the final SQL backstop.
+pub fn ensure_project_workspace(
+ conn: &Connection,
+ workspace_id: &WorkspaceId,
+ project_id: &ProjectId,
+) -> StoreResult<()> {
+ let found = conn
+ .query_row(
+ "SELECT 1 FROM projects WHERE id = ?1 AND workspace_id = ?2",
+ params![project_id.as_bytes(), workspace_id.as_bytes()],
+ |_| Ok(()),
+ )
+ .optional()?;
+ if found.is_some() {
+ Ok(())
+ } else {
+ Err(StoreError::NotFound(format!(
+ "project {project_id} does not belong to workspace {workspace_id}"
+ )))
+ }
+}
+
/// Upsert a batch of pages inside one transaction. Either *all* pages
/// land (each becoming the new `is_latest=true` version) or none do.
///
@@ -1156,7 +1182,9 @@ mod tests {
//! deserve direct coverage so a regression surfaces with a
//! one-line diff instead of a cascading e2e failure.
use super::*;
- use ai_memory_core::{LinkTarget, NewHandoff, NewPage, NewSession, PagePath, Tier};
+ use ai_memory_core::{
+ LinkTarget, NewHandoff, NewPage, NewSession, PagePath, Tier, WorkspaceId,
+ };
use rusqlite::Connection;
use tempfile::TempDir;
@@ -2012,6 +2040,42 @@ mod tests {
assert_eq!(src_pages, 1, "rollback must preserve source pages");
}
+ #[test]
+ fn ensure_project_workspace_rejects_stale_pair_before_disk_write() {
+ let (_tmp, conn, ws, proj) = fresh_db();
+ let other_ws = WorkspaceId::new();
+
+ ensure_project_workspace(&conn, &ws, &proj).unwrap();
+ assert!(
+ matches!(
+ ensure_project_workspace(&conn, &other_ws, &proj),
+ Err(StoreError::NotFound(_))
+ ),
+ "a stale workspace/project pair must fail before wiki writes touch disk"
+ );
+ }
+
+ #[test]
+ fn v18_migration_refuses_existing_split_brain_rows() {
+ let tmp = TempDir::new().unwrap();
+ let db_path = tmp.path().join("test.sqlite");
+ let mut conn = Connection::open(&db_path).unwrap();
+ crate::migrations::run_to(&mut conn, 17).unwrap();
+
+ let src_ws = get_or_create_workspace(&mut conn, "src").unwrap();
+ let stale_ws = get_or_create_workspace(&mut conn, "stale").unwrap();
+ let proj = get_or_create_project(&mut conn, &src_ws, "scratch", None).unwrap();
+ let mut bad_page = page(src_ws, proj, "notes/split.md", "body");
+ bad_page.workspace_id = stale_ws;
+ upsert_page(&mut conn, &bad_page).unwrap();
+
+ let err = crate::migrations::run_to(&mut conn, 18).unwrap_err();
+ assert!(
+ err.to_string().contains("CHECK constraint failed"),
+ "V18 must abort instead of preserving split-brain rows: {err}"
+ );
+ }
+
/// V18 integrity triggers: an INSERT whose `workspace_id` disagrees with
/// the project's actual workspace ABORTs (the split-brain a stale hook
/// cache would otherwise create), while the consistent pair inserts fine.
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 6662c87a..4ee96a71 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -53,6 +53,10 @@ pub struct StoredPageBody {
pub body: String,
/// Raw `frontmatter_json` TEXT column (parse at the call site).
pub frontmatter_json: String,
+ /// Memory tier stored on the latest page row.
+ pub tier: String,
+ /// Whether the latest page row is pinned.
+ pub pinned: bool,
}
/// Search hit with workspace/project names, used by the web UI to avoid
@@ -2630,7 +2634,7 @@ impl ReaderPool {
self.with_conn(move |conn| {
let row = conn
.query_row(
- "SELECT title, body, frontmatter_json FROM pages \
+ "SELECT title, body, frontmatter_json, tier, pinned FROM pages \
WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3 \
AND is_latest = 1",
params![workspace_id.as_bytes(), project_id.as_bytes(), path],
@@ -2639,6 +2643,8 @@ impl ReaderPool {
title: row.get(0)?,
body: row.get(1)?,
frontmatter_json: row.get(2)?,
+ tier: row.get(3)?,
+ pinned: row.get::<_, i64>(4)? != 0,
})
},
)
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index e36b6b7c..8abde6d8 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -33,6 +33,11 @@ pub(crate) enum WriteCmd {
repo_path: Option<String>,
reply: oneshot::Sender<StoreResult<ProjectId>>,
},
+ EnsureProjectWorkspace {
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ reply: oneshot::Sender<StoreResult<()>>,
+ },
UpsertPage {
page: NewPage,
reply: oneshot::Sender<StoreResult<PageId>>,
@@ -239,6 +244,27 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ /// Assert that a project still belongs to the supplied workspace.
+ ///
+ /// # Errors
+ /// Returns [`StoreError::NotFound`] when the `(workspace_id, project_id)`
+ /// pair is stale, [`StoreError::WriterClosed`] if the actor has shut down,
+ /// or propagates the SQL error.
+ pub async fn ensure_project_workspace(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ ) -> StoreResult<()> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::EnsureProjectWorkspace {
+ workspace_id,
+ project_id,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
/// Begin a session (idempotent on the supplied id).
///
/// # Errors
@@ -731,6 +757,14 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
);
send_or_warn(reply, result, "get_or_create_project");
}
+ WriteCmd::EnsureProjectWorkspace {
+ workspace_id,
+ project_id,
+ reply,
+ } => {
+ let result = ops::ensure_project_workspace(&conn, &workspace_id, &project_id);
+ send_or_warn(reply, result, "ensure_project_workspace");
+ }
WriteCmd::UpsertPage { page, reply } => {
let result = ops::upsert_page(&mut conn, &page);
send_or_warn(reply, result, "upsert_page");
diff --git a/crates/ai-memory-wiki/src/admission.rs b/crates/ai-memory-wiki/src/admission.rs
index facf6457..d0bacfc7 100644
--- a/crates/ai-memory-wiki/src/admission.rs
+++ b/crates/ai-memory-wiki/src/admission.rs
@@ -56,6 +56,10 @@ pub enum AdmissionOp {
/// `remove_dir_all`). Carries the project (ctx), no page path. Lets a
/// mirror remove the project's directory.
PurgeProject,
+ /// A whole project is being moved between workspaces without changing its
+ /// project id. Carries source names in `workspace`/`project` and
+ /// destination names in `destination_workspace`/`destination_project`.
+ MoveProject,
}
impl AdmissionOp {
@@ -67,6 +71,7 @@ impl AdmissionOp {
AdmissionOp::Consolidate => "consolidate",
AdmissionOp::Delete => "delete",
AdmissionOp::PurgeProject => "purge_project",
+ AdmissionOp::MoveProject => "move_project",
}
}
}
@@ -136,6 +141,12 @@ pub struct AdmissionContext {
/// (auto-filled from `project_id` when the wiki has a store reader).
#[serde(default)]
pub project: String,
+ /// Destination workspace name for project-level moves.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub destination_workspace: Option<String>,
+ /// Destination project name for project-level moves.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub destination_project: Option<String>,
/// Identity of the actor that triggered the write. The canonical
/// multi-user [`ai_memory_core::ActorContext`] (since the v0.8 merge);
/// `Wiki::write_page` fills it from `WritePageRequest::actor` so the
@@ -354,11 +365,11 @@ impl AdmissionChain {
Ok(())
}
- /// Notify webhooks of a delete / purge (`ctx.op` = `Delete` /
- /// `PurgeProject`). Unlike [`Self::run`], there is no body to send or
- /// mutate — the webhook acts on `ctx.op` + the (optional) page path, e.g.
- /// a mirror `git rm`s the file or removes the project directory. Honours
- /// the same skip-list, op-subscription, timeout, and failure policy.
+ /// Notify webhooks of a delete / purge / project move. Unlike
+ /// [`Self::run`], there is no body to send or mutate — the webhook acts on
+ /// `ctx.op` + the (optional) page path, e.g. a mirror `git rm`s the file,
+ /// removes a project directory, or renames it. Honours the same skip-list,
+ /// op-subscription, timeout, and failure policy.
///
/// # Errors
/// Returns an error only when a `Reject`-policy webhook fails.
@@ -538,6 +549,7 @@ mod tests {
fn op_header_values() {
assert_eq!(AdmissionOp::WritePage.as_header_value(), "write_page");
assert_eq!(AdmissionOp::Consolidate.as_header_value(), "consolidate");
+ assert_eq!(AdmissionOp::MoveProject.as_header_value(), "move_project");
}
#[tokio::test]
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index 3a29a9ce..590ab0b3 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -5,7 +5,8 @@ use std::sync::Arc;
use ai_memory_core::{NewPage, PageId, PagePath, ProjectId, Sanitizer, Tier, WorkspaceId};
use ai_memory_llm::Embedder;
-use ai_memory_store::{ReaderPool, WriterHandle, f32_vec_to_bytes};
+use ai_memory_store::{MoveSummary, ReaderPool, WriterHandle, f32_vec_to_bytes};
+use tokio::sync::RwLock;
use crate::admission::{AdmissionChain, AdmissionContext, AdmissionOp};
use crate::atomic;
@@ -50,6 +51,11 @@ pub struct Wiki {
/// empty `workspace`/`project` strings and must fall back to
/// IDs/headers/`_unscoped` paths.
store_reader: Option<ReaderPool>,
+ /// Process-local gate around filesystem mutations. Page writes/reindexes
+ /// take a shared guard; project true-move takes the exclusive guard across
+ /// the directory rename and SQLite re-stamp so stale writes cannot land
+ /// files under the old workspace while the project is in flight.
+ mutation_lock: Arc<RwLock<()>>,
}
impl Wiki {
@@ -71,6 +77,7 @@ impl Wiki {
sanitizer: Sanitizer::builtin(),
admission_chain: None,
store_reader: None,
+ mutation_lock: Arc::new(RwLock::new(())),
})
}
@@ -170,38 +177,102 @@ 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>`.
+ /// Losslessly move a project to another workspace: rename its on-disk
+ /// directory and re-stamp every store row that carries `workspace_id`, while
+ /// keeping the same `project_id`.
///
- /// 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.
+ /// The exclusive mutation guard is held across both filesystem and store
+ /// phases. That keeps in-process page writes/reindexes from observing the
+ /// project half-moved; stale callers that still carry `(from_workspace,
+ /// project_id)` only resume after the DB re-stamp and then fail the pair
+ /// validator before touching disk.
+ ///
+ /// Ordering is rename-first, SQL-last so the DB is never ahead of disk. If
+ /// the SQL re-stamp fails after a rename, the directory is renamed back.
///
/// # 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(
+ /// Returns [`WikiError`] if the destination directory already exists, the
+ /// rename fails, the SQL re-stamp fails, or rollback fails.
+ pub async fn move_project_workspace(
&self,
project_id: ProjectId,
from_workspace: WorkspaceId,
to_workspace: WorkspaceId,
- ) -> WikiResult<()> {
+ admission_ctx: Option<AdmissionContext>,
+ ) -> WikiResult<MoveSummary> {
+ let _guard = self.mutation_lock.write().await;
+ let resolved_ctx = if let Some(chain) = &self.admission_chain {
+ let mut ctx = admission_ctx.unwrap_or_default();
+ ctx.op = AdmissionOp::MoveProject;
+ self.resolve_admission_names(from_workspace, project_id, &mut ctx)
+ .await;
+ chain.notify(None, &ctx).await?;
+ Some(ctx)
+ } else {
+ None
+ };
+
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)?;
+
+ if dst.exists() {
+ return Err(crate::WikiError::Io(std::io::Error::new(
+ std::io::ErrorKind::AlreadyExists,
+ format!(
+ "destination dir already exists: {}; refusing true-move",
+ dst.display()
+ ),
+ )));
}
- std::fs::rename(&src, &dst)?;
+
+ let renamed = if src.exists() {
+ if let Some(parent) = dst.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ std::fs::rename(&src, &dst)?;
+ true
+ } else {
+ // Nothing on disk to move (a project with zero written pages).
+ false
+ };
+
+ match self
+ .writer
+ .move_project_workspace(project_id, from_workspace, to_workspace)
+ .await
+ {
+ Ok(summary) => {
+ if let (Some(chain), Some(ctx)) = (&self.admission_chain, &resolved_ctx) {
+ chain.dispatch_async(None, &serde_json::Value::Null, "", ctx);
+ }
+ Ok(summary)
+ }
+ Err(e) => {
+ if renamed {
+ if let Some(parent) = src.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ if let Err(rollback_err) = std::fs::rename(&dst, &src) {
+ return Err(crate::WikiError::Io(std::io::Error::other(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.display(),
+ src.display()
+ ))));
+ }
+ }
+ Err(e.into())
+ }
+ }
+ }
+
+ async fn ensure_project_workspace(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ ) -> WikiResult<()> {
+ self.writer
+ .ensure_project_workspace(workspace_id, project_id)
+ .await?;
Ok(())
}
@@ -278,6 +349,10 @@ impl Wiki {
path: &PagePath,
admission_ctx: Option<AdmissionContext>,
) -> WikiResult<()> {
+ let _guard = self.mutation_lock.read().await;
+ self.ensure_project_workspace(workspace_id, project_id)
+ .await?;
+
let mut resolved_ctx = None;
if let Some(chain) = &self.admission_chain {
let mut ctx = admission_ctx.unwrap_or_default();
@@ -415,6 +490,10 @@ impl Wiki {
project_id: ProjectId,
path: PagePath,
) -> WikiResult<PageId> {
+ let _guard = self.mutation_lock.read().await;
+ self.ensure_project_workspace(workspace_id, project_id)
+ .await?;
+
let md = self.read_page(workspace_id, project_id, &path)?;
let title = derive_title(&md.frontmatter, &md.body, &path);
let links = extract_links(&md.body, &path);
@@ -449,10 +528,11 @@ impl Wiki {
if requests.is_empty() {
return Ok(Vec::new());
}
- // Pre-compute markdown + tempfile for each request.
+ // Pre-compute markdown for each request. Filesystem work happens only
+ // after the mutation guard + project/workspace validation below.
let mut staged: Vec<(
WritePageRequest,
- tempfile::NamedTempFile,
+ String,
std::path::PathBuf,
Option<AdmissionContext>,
)> = Vec::with_capacity(requests.len());
@@ -489,51 +569,67 @@ impl Wiki {
.unwrap_or_else(|| derive_title(&markdown.frontmatter, &markdown.body, &req.path));
let emitted = emit(&markdown)?;
let abs = self.abs_path(req.workspace_id, req.project_id, &req.path);
- let parent = abs.parent().ok_or_else(|| {
- ai_memory_wiki_error("page path has no parent (cannot stage tempfile)")
- })?;
- std::fs::create_dir_all(parent)?;
- let mut tmp = tempfile::Builder::new()
- .prefix(".ai-memory-tmp.")
- .tempfile_in(parent)?;
- use std::io::Write as _;
- tmp.write_all(emitted.as_bytes())?;
- tmp.as_file().sync_data()?;
req.frontmatter = markdown.frontmatter;
req.body = markdown.body;
let req_with_title = WritePageRequest {
title: Some(title),
..req
};
- staged.push((req_with_title, tmp, abs, resolved_ctx));
+ staged.push((req_with_title, emitted, abs, resolved_ctx));
}
- // Build NewPage batch with the precomputed titles.
- let pages: Vec<ai_memory_core::NewPage> = staged
- .iter()
- .map(|(req, _, _, _)| ai_memory_core::NewPage {
- workspace_id: req.workspace_id,
- project_id: req.project_id,
- path: req.path.clone(),
- title: req.title.clone().unwrap_or_default(),
- body: req.body.clone(),
- tier: req.tier,
- frontmatter_json: req.frontmatter.clone(),
- pinned: req.pinned || is_slot_path(&req.path),
- links: extract_links(&req.body, &req.path),
- author_id: req.author_id,
- })
- .collect();
-
- let ids = self.writer.upsert_pages_batch(pages).await?;
+ let (ids, dispatches) = {
+ let _guard = self.mutation_lock.read().await;
+ let mut staged_files: Vec<(
+ WritePageRequest,
+ tempfile::NamedTempFile,
+ std::path::PathBuf,
+ Option<AdmissionContext>,
+ )> = Vec::with_capacity(staged.len());
+ for (req, emitted, abs, ctx) in staged {
+ self.ensure_project_workspace(req.workspace_id, req.project_id)
+ .await?;
+ let parent = abs.parent().ok_or_else(|| {
+ ai_memory_wiki_error("page path has no parent (cannot stage tempfile)")
+ })?;
+ std::fs::create_dir_all(parent)?;
+ let mut tmp = tempfile::Builder::new()
+ .prefix(".ai-memory-tmp.")
+ .tempfile_in(parent)?;
+ use std::io::Write as _;
+ tmp.write_all(emitted.as_bytes())?;
+ tmp.as_file().sync_data()?;
+ staged_files.push((req, tmp, abs, ctx));
+ }
- // SQL succeeded; rename tempfiles into place.
- let mut dispatches = Vec::with_capacity(staged.len());
- for (req, tmp, abs, ctx) in staged {
- let persisted = tmp.persist(&abs)?;
- persisted.sync_data()?;
- dispatches.push((req.path, req.frontmatter, req.body, ctx));
- }
+ // Build NewPage batch with the precomputed titles.
+ let pages: Vec<ai_memory_core::NewPage> = staged_files
+ .iter()
+ .map(|(req, _, _, _)| ai_memory_core::NewPage {
+ workspace_id: req.workspace_id,
+ project_id: req.project_id,
+ path: req.path.clone(),
+ title: req.title.clone().unwrap_or_default(),
+ body: req.body.clone(),
+ tier: req.tier,
+ frontmatter_json: req.frontmatter.clone(),
+ pinned: req.pinned || is_slot_path(&req.path),
+ links: extract_links(&req.body, &req.path),
+ author_id: req.author_id,
+ })
+ .collect();
+
+ let ids = self.writer.upsert_pages_batch(pages).await?;
+
+ // SQL succeeded; rename tempfiles into place.
+ let mut dispatches = Vec::with_capacity(staged_files.len());
+ for (req, tmp, abs, ctx) in staged_files {
+ let persisted = tmp.persist(&abs)?;
+ persisted.sync_data()?;
+ dispatches.push((req.path, req.frontmatter, req.body, ctx));
+ }
+ (ids, dispatches)
+ };
if let Some(chain) = &self.admission_chain {
for (path, frontmatter, body, ctx) in &dispatches {
@@ -620,34 +716,42 @@ impl Wiki {
.unwrap_or_else(|| derive_title(&markdown.frontmatter, &markdown.body, &path));
let links = extract_links(&markdown.body, &path);
- let emitted = emit(&markdown)?;
- let abs = self.abs_path(workspace_id, project_id, &path);
- if let Some(parent) = abs.parent() {
- std::fs::create_dir_all(parent)?;
- }
- atomic::write_atomic(&abs, emitted.as_bytes())?;
-
let Markdown {
frontmatter: final_frontmatter,
body: final_body,
} = markdown;
let path_for_dispatch = path.clone();
let frontmatter_for_dispatch = final_frontmatter.clone();
- let page_id = self
- .writer
- .upsert_page(NewPage {
- workspace_id,
- project_id,
- path,
- title,
- body: final_body.clone(),
- tier,
- frontmatter_json: final_frontmatter,
- pinned,
- links,
- author_id,
- })
- .await?;
+ let emitted = emit(&Markdown {
+ frontmatter: final_frontmatter.clone(),
+ body: final_body.clone(),
+ })?;
+
+ let page_id = {
+ let _guard = self.mutation_lock.read().await;
+ self.ensure_project_workspace(workspace_id, project_id)
+ .await?;
+ let abs = self.abs_path(workspace_id, project_id, &path);
+ if let Some(parent) = abs.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ atomic::write_atomic(&abs, emitted.as_bytes())?;
+
+ self.writer
+ .upsert_page(NewPage {
+ workspace_id,
+ project_id,
+ path,
+ title,
+ body: final_body.clone(),
+ tier,
+ frontmatter_json: final_frontmatter,
+ pinned,
+ links,
+ author_id,
+ })
+ .await?
+ };
// Embed if configured. We do this on the caller's task so the
// tool reply still happens "indexes commit in the same
// transaction" (basic-memory #763 lesson): no fire-and-forget
diff --git a/docs/admission-webhooks.md b/docs/admission-webhooks.md
index d8b70b39..8377a88e 100644
--- a/docs/admission-webhooks.md
+++ b/docs/admission-webhooks.md
@@ -1,10 +1,10 @@
# Admission webhooks: pre-persistence HTTP hooks
> Operator-configured HTTP hooks invoked on the engine's write path
-> (`Wiki::write_page`, `delete_page`, `purge_project`)
-> just before the page hits disk. Each hook can mutate the
-> page (return a new frontmatter / body) or just observe and side-effect
-> (return `204 No Content`). Sourced from
+> (`Wiki::write_page`, `delete_page`, `purge_project`, `move_project`)
+> just before the durable mutation commits. Write hooks can mutate the page
+> (return a new frontmatter / body); delete/purge/move hooks are notifications
+> that can observe, mirror, or reject. Sourced from
> `crates/ai-memory-wiki/src/admission.rs` and the wiring in
> `crates/ai-memory-cli/src/commands/serve.rs` — keep both as the
> canonical reference if anything here drifts.
@@ -50,9 +50,15 @@ Webhooks fire on these `op` values today (extensible enum):
`remove_dir_all`, routed from `/admin/purge-project`). Carries the
project in `ctx`, **no** page path; fired before the directory is
removed so a mirror can drop the project.
-
-`delete` / `purge_project` are notifications — there is no body to mutate;
-a `Reject`-policy webhook still aborts the operation. Each webhook opts
+- `move_project` — a whole project is moved between workspaces without
+ changing `project_id` (fresh-destination true move). Carries the source
+ project in `ctx.workspace` / `ctx.project`, destination names in
+ `ctx.destination_workspace` / `ctx.destination_project`, and no page path;
+ fired before the directory rename + DB re-stamp so a mirror can rename or
+ reject the project move.
+
+`delete` / `purge_project` / `move_project` are notifications — there is no
+body to mutate; a `Reject`-policy webhook still aborts the operation. Each webhook opts
into the ops it cares about via `events`; the chain checks the op against
`WebhookConfig::events` before dispatching.
@@ -79,7 +85,7 @@ into the ops it cares about via `events`; the chain checks the op against
```http
POST <webhook.url>
Content-Type: application/json
-X-Memory-Op: write_page | consolidate | delete | purge_project
+X-Memory-Op: write_page | consolidate | delete | purge_project | move_project
```
```jsonc
@@ -92,6 +98,8 @@ X-Memory-Op: write_page | consolidate | delete | purge_project
"ctx": {
"workspace": "default", // resolved name (see §5)
"project": "ai-memory-ops", // resolved name
+ "destination_workspace": "archive", // move_project only; omitted otherwise
+ "destination_project": "ai-memory-ops", // move_project only; omitted otherwise
"actor": { // request-layer identity
"agent": "claude-code", // claude-code | codex | opencode | hook | cli | …
"user": "djalmajr", // null when unauthenticated
@@ -99,7 +107,7 @@ X-Memory-Op: write_page | consolidate | delete | purge_project
"client": "72836f52-...", // DCR client UUID
"session_id": "019e6d-..."
},
- "op": "write_page" // write_page | consolidate | delete | purge_project
+ "op": "write_page" // write_page | consolidate | delete | purge_project | move_project
}
}
```
@@ -198,7 +206,7 @@ name = "git-mirror"
url = "http://git-mirror.memory.svc.cluster.local:8080/sync"
timeout_ms = 2000
failure_policy = "ignore"
-events = ["write_page", "consolidate", "delete", "purge_project"]
+events = ["write_page", "consolidate", "delete", "purge_project", "move_project"]
blocking = false # fire-and-forget after the write; never blocks it
```
@@ -214,11 +222,12 @@ A webhook is either **blocking** or **non-blocking**:
operation has completed. For writes that means the final page is on disk and
indexed in SQLite; for deletes that means the file and index row are gone;
for project purges that means the DB purge has completed and filesystem
- removal has been attempted. The engine does not wait for it and ignores its
- response, so it **cannot mutate or reject** — it only observes/mirrors the
- final state. Use for pure backups/mirrors (e.g. `git-mirror`) so a slow or
- down sink never adds latency to writes. Still honours `events` and the skip
- list.
+ removal has been attempted; for project moves it means the directory and DB
+ rows now point at the destination workspace. The engine does not wait for it
+ and ignores its response, so it **cannot mutate or reject** — it only
+ observes/mirrors the final state. Use for pure backups/mirrors (e.g.
+ `git-mirror`) so a slow or down sink never adds latency to writes. Still
+ honours `events` and the skip list.
Since the blocking chain is sequential, total worst-case write latency is
`Σ timeout_ms` over the **blocking** webhooks only; non-blocking ones add none.
diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.md
index 0d964447..c9dfd5c6 100644
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@ -139,22 +139,30 @@ 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 the destination **workspace** row (not a new project).
-4. Re-stamp `workspace_id` across every domain table for the project in
+4. Take the wiki's exclusive mutation gate and run `op=move_project` admission
+ webhooks with source names in `ctx.workspace` / `ctx.project` and
+ destination names in `ctx.destination_workspace` /
+ `ctx.destination_project`. A reject-policy webhook aborts before files or DB
+ rows move.
+5. While still holding that gate, check that the destination dir is still
+ absent, then `fs::rename` the project dir
+ `<wiki>/<from_ws>/<proj>` → `<wiki>/<to_ws>/<proj>` (atomic within one
+ wiki root).
+6. 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). 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.
+
+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 unless the filesystem also refuses
+the rollback, in which case the error names the manual repair. In-process page
+writes/reindexes take the shared side of the same mutation gate and validate the
+`(workspace_id, project_id)` pair before touching disk, so stale source writes
+fail without creating orphan files after the move.
This is O(1) (one transaction + one rename), re-embeds nothing, and
**preserves everything** — sessions, observations, handoffs and the full
@@ -164,8 +172,9 @@ supersession history all travel with the project.
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.
+pointer, and the wiki pair validator plus `(workspace_id, project_id)` insert
+trigger (V18) reject stale writes cleanly, so the router re-resolves instead of
+corrupting or creating old-workspace files.
**2. Destination already has a same-named project → `"copy-purge"`
(merge).** Two distinct `project_id`s can't be re-stamped into one (it
@@ -182,8 +191,9 @@ blocks the purge (`source_purged: false`) so a fixed re-run is safe
(re-running is idempotent — copied pages just supersede).
**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):
+exists in the destination with a different body, frontmatter, title, tier, or
+pinned bit, the policy decides (identical pages are 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
@@ -218,8 +228,9 @@ 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.
+- **True-move admission, rename, or SQL re-stamp failure** → 500 and no
+ committed move. If a rare rollback double-fault happens after the directory
+ moved but before SQL committed, the error includes the exact manual repair.
### `backup`