Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
refactor(move-project): typed conflict error + V18 handoff coverage + reject-path tests
AkitaOnRails315ab1d98ee1
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex c665d32f..50233c29 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -1775,10 +1775,7 @@ async fn true_move_project(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") =>- {+ Err(e @ WikiError::DestinationExists(_)) => {return (StatusCode::CONFLICT,Json(serde_json::json!({ "error": e.to_string() })),@@ -1828,10 +1825,27 @@ async fn true_move_project()}+/// Token inserted between the original stem and the source-workspace+/// slug when copy-purge merges conflicting page paths+/// (`<stem>-from-<src_workspace>.md`). The literal also appears in+/// `docs/lifecycle-ops.md`; keep these two in sync.+const DEDUP_FROM_TOKEN: &str = "-from-";++/// Char allowlist for the source-workspace slug embedded in a deduped+/// destination path. ASCII alphanumeric plus `-` / `_` keeps the slug+/// safe inside a filesystem path component on every supported platform+/// (Windows treats `:`, `*`, `?`, `<`, `>`, `|` as illegal; Linux+/// tolerates more but UTF-8 mojibake in filenames is a maintenance+/// hazard). Everything else collapses to a single `-` separator,+/// preserving readability without introducing path-traversal vectors.+fn is_dedup_slug_char(c: char) -> bool {+ c.is_ascii_alphanumeric() || c == '-' || c == '_'+}+/// 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.+/// appends `<DEDUP_FROM_TOKEN><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,@@ -1846,15 +1860,9 @@ async fn dedup_dest_path(};let slug: String = src_workspace.chars()- .map(|c| {- if c.is_ascii_alphanumeric() || c == '-' || c == '_' {- c- } else {- '-'- }- })+ .map(|c| if is_dedup_slug_char(c) { c } else { '-' }).collect();- let base = format!("{stem}-from-{slug}");+ let base = format!("{stem}{DEDUP_FROM_TOKEN}{slug}");let mut n = 0u32;loop {let cand = if n == 0 {diff --git a/crates/ai-memory-mcp/tests/admin_move.rs b/crates/ai-memory-mcp/tests/admin_move.rsindex a21cb554..2c8b9752 100644--- a/crates/ai-memory-mcp/tests/admin_move.rs+++ b/crates/ai-memory-mcp/tests/admin_move.rs@@ -1328,6 +1328,180 @@ async fn copy_purge_partial_skips_and_preserves_source() {);}+/// Reject-policy webhook returning 5xx must abort a true-move (cross-workspace+/// rename) before any DB or filesystem change. The original test only used a+/// 204-returning webhook, which never exercises the reject path.+#[tokio::test]+async fn true_move_aborts_when_admission_rejects() {+ let app = Router::new().route(+ "/hook",+ axum_post(+ |_headers: HeaderMap, Json(_payload): Json<serde_json::Value>| async move {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ "mirror refuses the move".to_string(),+ )+ },+ ),+ );+ 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: "rejecting-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::INTERNAL_SERVER_ERROR,+ "reject-policy webhook returning 5xx must abort the move"+ );++ // Source rows must be intact — admission ran before any destructive work.+ let src_pages = store.reader.list_pages("src", "proj").await.unwrap();+ assert_eq!(+ src_pages.len(),+ 1,+ "source pages must survive when admission rejects the move"+ );+}++/// Audit BLOCKING #2 regression guard: copy-purge merge must run the purge+/// admission BEFORE writer.purge_project so a reject-policy webhook can still+/// abort the source-side destruction. The prior code ordered admit AFTER the+/// SQL purge — by the time admit ran the rows were gone and reject came too+/// late. Reject-on-purge here must leave source rows intact.+#[tokio::test]+async fn copy_purge_purge_admission_runs_before_db_destruction() {+ use std::sync::atomic::{AtomicUsize, Ordering};++ let purge_hits = std::sync::Arc::new(AtomicUsize::new(0));+ let purge_hits_for_route = purge_hits.clone();+ let app = Router::new().route(+ "/hook",+ axum_post(+ move |headers: HeaderMap, Json(_payload): Json<serde_json::Value>| {+ let purge_hits = purge_hits_for_route.clone();+ async move {+ let op = headers+ .get("X-Memory-Op")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("");+ // Accept move_project so the copy leg can land; reject the+ // PurgeProject step so the source SQL purge must not run.+ match op {+ "purge_project" => {+ purge_hits.fetch_add(1, Ordering::SeqCst);+ (StatusCode::INTERNAL_SERVER_ERROR, "no purging".to_string())+ }+ _ => (StatusCode::NO_CONTENT, String::new()),+ }+ }+ },+ ),+ );+ 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, AdmissionOp::PurgeProject],+ 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,+ };+ // Pre-seed BOTH sides so move-project takes the copy-purge path (merge+ // into existing dst/proj), not the lossless true-move path.+ seed_page(&store, &state.wiki, "src", "proj", "notes/a.md", "body a").await;+ seed_page(&store, &state.wiki, "dst", "proj", "notes/keep.md", "keep").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,+ "purge admission rejecting must surface as 500 from the move handler"+ );+ assert!(+ purge_hits.load(Ordering::SeqCst) >= 1,+ "purge admission webhook must have fired (admit runs before the DB purge)"+ );++ // The source rows must still be present: admission ran before the SQL+ // destruction, so the reject prevented `writer.purge_project` from running.+ let src_pages = store.reader.list_pages("src", "proj").await.unwrap();+ assert_eq!(+ src_pages.len(),+ 1,+ "src/proj pages must survive when purge admission rejects: {src_pages:?}"+ );+}+/// 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]diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 12a0d839..3554759f 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -2151,5 +2151,32 @@ mod tests {..mismatched_obs};insert_observation(&mut conn, &good_obs).unwrap();++ // The handoff insert is the fourth INSERT trigger; audit flagged+ // that the original V18 test omitted it, so the only coverage+ // for the handoffs trigger was the temp-table CHECK on migration.+ // Assert the BEFORE INSERT trigger fires on a stale pair, and+ // a corrected pair lands cleanly.+ let mismatched_handoff = NewHandoff {+ workspace_id: other_ws,+ project_id: proj,+ from_session_id: None,+ from_agent: AgentKind::ClaudeCode,+ to_agent: None,+ cwd: None,+ summary: "stale".into(),+ open_questions: vec![],+ next_steps: vec![],+ files_touched: vec![],+ };+ assert!(+ insert_handoff(&mut conn, &mismatched_handoff).is_err(),+ "handoff insert with mismatched workspace must abort"+ );+ let good_handoff = NewHandoff {+ workspace_id: ws,+ ..mismatched_handoff+ };+ insert_handoff(&mut conn, &good_handoff).unwrap();}}diff --git a/crates/ai-memory-wiki/src/admission.rs b/crates/ai-memory-wiki/src/admission.rsindex 24e191b3..220419f2 100644--- a/crates/ai-memory-wiki/src/admission.rs+++ b/crates/ai-memory-wiki/src/admission.rs@@ -545,6 +545,42 @@ mod tests {assert!(matches!(op, AdmissionOp::WritePage));}+ /// `partial_failure` serialises only when `true`, so existing webhook+ /// consumers see no extra key on the happy path. Mirrors that care+ /// about filesystem-vs-DB drift (a git-push mirror) opt in by reading+ /// the field when it appears.+ #[test]+ fn partial_failure_is_omitted_when_false() {+ let ctx = AdmissionContext {+ workspace: "w".into(),+ project: "p".into(),+ op: AdmissionOp::PurgeProject,+ ..Default::default()+ };+ let payload = serde_json::to_value(&ctx).unwrap();+ assert!(+ payload.get("partial_failure").is_none(),+ "partial_failure must be skipped when false: {payload}"+ );+ }++ #[test]+ fn partial_failure_serialises_when_true() {+ let ctx = AdmissionContext {+ workspace: "w".into(),+ project: "p".into(),+ op: AdmissionOp::PurgeProject,+ partial_failure: true,+ ..Default::default()+ };+ let payload = serde_json::to_value(&ctx).unwrap();+ assert_eq!(+ payload.get("partial_failure").and_then(|v| v.as_bool()),+ Some(true),+ "partial_failure must appear on the wire when true: {payload}"+ );+ }+#[test]fn webhook_config_deserialises_with_defaults() {// Using JSON keeps the test free of an extra TOML dep — thediff --git a/crates/ai-memory-wiki/src/error.rs b/crates/ai-memory-wiki/src/error.rsindex d64f86be..31b6b129 100644--- a/crates/ai-memory-wiki/src/error.rs+++ b/crates/ai-memory-wiki/src/error.rs@@ -34,6 +34,14 @@ pub enum WikiError {/// Store-level error.#[error(transparent)]Store(#[from] StoreError),++ /// A move-project / similar operation refused to overwrite an existing+ /// destination directory. Surfaced as `409 Conflict` at the admin layer+ /// without string-matching the `io::Error` message. The wrapped path is+ /// the namespaced project root (`<wiki_root>/<ws>/<proj>/`) that+ /// already exists.+ #[error("destination dir already exists: {0}")]+ DestinationExists(String),}impl From<serde_yaml::Error> for WikiError {diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex 590ab0b3..82dd279b 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -216,13 +216,9 @@ impl Wiki {let dst = self.project_root(to_workspace, project_id);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()- ),- )));+ return Err(crate::WikiError::DestinationExists(+ dst.display().to_string(),+ ));}let renamed = if src.exists() {