Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
cli: add `ai-memory purge-project` + cascade-delete indexes
AkitaOnRailsc2944a483946
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 262d924f..f90f9d00 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -85,6 +85,10 @@ pub enum Command {/// `is_latest=false` (they were a multi-project mash-up) so the/// next consolidation can regenerate them per-project. Idempotent.Reorg(ReorgArgs),+ /// Permanently delete a project and ALL its data (pages, sessions,+ /// observations, handoffs, embeddings, on-disk wiki files).+ /// This is irreversible — requires `--confirm`.+ PurgeProject(PurgeProjectArgs),}/// Arguments for `reorg`.@@ -95,6 +99,22 @@ pub struct ReorgArgs {pub dry_run: bool,}+/// Arguments for `purge-project`.+#[derive(Debug, Args)]+pub struct PurgeProjectArgs {+ /// Workspace name. Defaults to "default".+ #[arg(long, default_value = "default")]+ pub workspace: String,+ /// Project name. When omitted, auto-derived from the basename of+ /// the current git repo root (or CWD if no git repo).+ #[arg(long)]+ pub project: Option<String>,+ /// REQUIRED for the purge to run. Without this flag the CLI errors+ /// out — purging is destructive and irreversible.+ #[arg(long)]+ pub confirm: bool,+}+/// Arguments for `install-instructions`.#[derive(Debug, Args)]pub struct InstallInstructionsArgs {diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 98c3ac7b..a1a60809 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -15,6 +15,7 @@ pub mod install_instructions;pub mod install_mcp;pub mod lint;pub mod llm_test;+pub mod purge_project;pub mod render_shared;pub mod reorg;pub mod reset;diff --git a/crates/ai-memory-cli/src/commands/purge_project.rs b/crates/ai-memory-cli/src/commands/purge_project.rsnew file mode 100644index 00000000..e88c4e8c--- /dev/null+++ b/crates/ai-memory-cli/src/commands/purge_project.rs@@ -0,0 +1,73 @@+//! `ai-memory purge-project` — thin HTTP client for project purge.++use anyhow::{Result, bail};+use serde::Serialize;++use crate::cli::PurgeProjectArgs;+use crate::config::Config;+use crate::http_client::{ServerEndpoint, post_json};++/// Request sent to `POST /admin/purge-project`.+#[derive(Serialize)]+struct PurgeProjectRequest {+ workspace: String,+ project: String,+ confirm: bool,+}++/// Run the `purge-project` subcommand.+///+/// Resolves the project name (auto-derived from the git repo root when+/// `--project` is omitted), requires `--confirm` before sending the+/// destructive request, then prints the JSON summary.+///+/// # Errors+/// Returns an error when `--confirm` is absent, the server is unreachable,+/// or the server returns a non-2xx response.+pub async fn run(_config: &Config, args: PurgeProjectArgs) -> Result<()> {+ let project = super::resolve_project_name(args.project.as_deref())?;++ if !args.confirm {+ bail!(+ "purge-project is destructive and irreversible.\n\+ Re-run with --confirm to proceed:\n\n \+ ai-memory purge-project --workspace {} --project {} --confirm",+ args.workspace,+ project,+ );+ }++ let endpoint = ServerEndpoint::from_env();+ let report: serde_json::Value = post_json(+ &endpoint,+ "/admin/purge-project",+ &PurgeProjectRequest {+ workspace: args.workspace.clone(),+ project: project.clone(),+ confirm: true,+ },+ )+ .await?;++ // Human-friendly one-liner followed by the raw JSON for scripting.+ let fallback_label = format!("{}/{}", args.workspace, project);+ let label = report["label"].as_str().unwrap_or(&fallback_label);+ let pages = report["pages_deleted"].as_u64().unwrap_or(0);+ let sessions = report["sessions_deleted"].as_u64().unwrap_or(0);+ let observations = report["observations_deleted"].as_u64().unwrap_or(0);+ let handoffs = report["handoffs_deleted"].as_u64().unwrap_or(0);+ let embeddings = report["embeddings_deleted"].as_u64().unwrap_or(0);+ println!(+ "Purged {label}: {pages} pages, {sessions} sessions, \+ {observations} observations, {handoffs} handoffs, {embeddings} embeddings."+ );+ if let Some(failed) = report["files_failed"].as_array()+ && !failed.is_empty()+ {+ println!(+ "Warning: {} wiki file(s) could not be removed from disk (DB rows are gone).",+ failed.len()+ );+ }+ Ok(())+}diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rsindex 1faa6a0e..08a095aa 100644--- a/crates/ai-memory-cli/src/main.rs+++ b/crates/ai-memory-cli/src/main.rs@@ -60,5 +60,6 @@ async fn main() -> Result<()> {Command::Bootstrap(args) => commands::bootstrap::run(&config, args).await,Command::InstallInstructions(args) => commands::install_instructions::run(&config, args),Command::Reorg(args) => commands::reorg::run(&config, args).await,+ Command::PurgeProject(args) => commands::purge_project::run(&config, args).await,}}diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex ddb787d8..ec7c0b18 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -25,7 +25,9 @@ use ai_memory_consolidate::{};use ai_memory_core::{ProjectId, SessionId, WorkspaceId};use ai_memory_llm::{Embedder, LlmProvider};-use ai_memory_store::{DecayParams, ReaderPool, StoreError, WriterHandle, f32_vec_to_bytes};+use ai_memory_store::{+ DecayParams, PurgeSummary, ReaderPool, StoreError, WriterHandle, f32_vec_to_bytes,+};use ai_memory_wiki::Wiki;use axum::Json;use axum::Router;@@ -94,6 +96,7 @@ fn default_max_input_tokens() -> usize {/// - `POST /admin/forget-sweep`/// - `POST /admin/embed`/// - `POST /admin/commit`+/// - `POST /admin/purge-project`pub fn admin_router(state: AdminState) -> Router {Router::new().route("/admin/bootstrap", post(handle_bootstrap))@@ -104,6 +107,7 @@ pub fn admin_router(state: AdminState) -> Router {.route("/admin/forget-sweep", post(handle_forget_sweep)).route("/admin/embed", post(handle_embed)).route("/admin/commit", post(handle_commit))+ .route("/admin/purge-project", post(handle_purge_project)).with_state(Arc::new(state))}@@ -838,3 +842,150 @@ async fn handle_commit(),}}++// ---------------------------------------------------------------------+// purge-project+// ---------------------------------------------------------------------++/// JSON request body for `POST /admin/purge-project`.+#[derive(Deserialize)]+struct PurgeProjectRequest {+ /// Workspace name. The workspace must already exist; we 404 if absent.+ workspace: String,+ /// Project name. The project must already exist; we 404 if absent.+ project: String,+ /// Mandatory confirmation flag. Without `confirm: true` the server+ /// returns 400 — purging is destructive and irreversible.+ confirm: bool,+}++/// Wire-format summary returned by `POST /admin/purge-project`.+#[derive(Debug, Serialize)]+pub struct PurgeProjectReport {+ /// Human-readable `workspace/project` label.+ pub label: String,+ /// Number of `pages` rows deleted (all versions).+ pub pages_deleted: u64,+ /// Number of `sessions` rows deleted.+ pub sessions_deleted: u64,+ /// Number of `observations` rows deleted.+ pub observations_deleted: u64,+ /// Number of `handoffs` rows deleted.+ pub handoffs_deleted: u64,+ /// Number of `page_embeddings` rows deleted.+ pub embeddings_deleted: u64,+ /// Paths of wiki files that were removed from disk.+ pub files_deleted: Vec<String>,+ /// Paths that could not be removed from disk (non-fatal; DB rows are gone).+ pub files_failed: Vec<String>,+}++impl From<&PurgeSummary> for PurgeProjectReport {+ fn from(s: &PurgeSummary) -> Self {+ Self {+ label: s.label.clone(),+ pages_deleted: s.pages_deleted,+ sessions_deleted: s.sessions_deleted,+ observations_deleted: s.observations_deleted,+ handoffs_deleted: s.handoffs_deleted,+ embeddings_deleted: s.embeddings_deleted,+ files_deleted: Vec::new(),+ files_failed: Vec::new(),+ }+ }+}++async fn handle_purge_project(+ State(state): State<Arc<AdminState>>,+ Json(req): Json<PurgeProjectRequest>,+) -> impl IntoResponse {+ if !req.confirm {+ return (+ StatusCode::BAD_REQUEST,+ Json(serde_json::json!({+ "error": "destructive operation requires confirm=true"+ })),+ );+ }++ // Look up workspace and project IDs without auto-creating.+ let ws_id = match state.reader.find_workspace(req.workspace.clone()).await {+ Ok(Some(id)) => id,+ Ok(None) => {+ return (+ StatusCode::NOT_FOUND,+ Json(serde_json::json!({+ "error": format!("workspace '{}' not found", req.workspace)+ })),+ );+ }+ Err(e) => {+ return (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(serde_json::json!({ "error": e.to_string() })),+ );+ }+ };++ let proj_id = match state.reader.find_project(ws_id, req.project.clone()).await {+ Ok(Some(id)) => id,+ Ok(None) => {+ return (+ StatusCode::NOT_FOUND,+ Json(serde_json::json!({+ "error": format!(+ "project '{}' not found in workspace '{}'",+ req.project, req.workspace+ )+ })),+ );+ }+ Err(e) => {+ return (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(serde_json::json!({ "error": e.to_string() })),+ );+ }+ };++ let label = format!("{}/{}", req.workspace, req.project);+ let summary = match state.writer.purge_project(ws_id, proj_id, &label).await {+ Ok(s) => s,+ Err(e) => {+ return (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(serde_json::json!({ "error": e.to_string() })),+ );+ }+ };++ // Remove wiki files. Partial failures are accumulated but never abort+ // the response — the DB rows are already gone; partial file cleanup is+ // better than returning an error and leaving the caller confused.+ let mut files_deleted: Vec<String> = Vec::new();+ let mut files_failed: Vec<String> = Vec::new();+ for raw_path in &summary.page_paths {+ match ai_memory_core::PagePath::new(raw_path.clone()) {+ Ok(pp) => match state.wiki.delete_page(&pp) {+ Ok(()) => files_deleted.push(raw_path.clone()),+ Err(e) => {+ warn!(path = %raw_path, error = %e, "purge-project: failed to delete wiki file");+ files_failed.push(raw_path.clone());+ }+ },+ Err(e) => {+ warn!(path = %raw_path, error = %e, "purge-project: invalid page path skipped");+ files_failed.push(raw_path.clone());+ }+ }+ }++ let mut report = PurgeProjectReport::from(&summary);+ report.files_deleted = files_deleted;+ report.files_failed = files_failed;++ (+ StatusCode::OK,+ Json(serde_json::to_value(&report).unwrap_or_else(|_| serde_json::json!({}))),+ )+}diff --git a/crates/ai-memory-mcp/tests/admin_purge.rs b/crates/ai-memory-mcp/tests/admin_purge.rsnew file mode 100644index 00000000..c9d4f99b--- /dev/null+++ b/crates/ai-memory-mcp/tests/admin_purge.rs@@ -0,0 +1,366 @@+//! Integration tests for `POST /admin/purge-project`.+//!+//! Follows the same pattern as `admin_phase3.rs`: build a real+//! [`AdminState`] over a tmpdir-backed store + wiki, drive the router+//! with `tower::ServiceExt::oneshot`.++use ai_memory_core::{+ AgentKind, NewHandoff, NewObservation, NewSession, ObservationKind, PagePath, SessionId, Tier,+};+use ai_memory_mcp::{AdminState, admin_router};+use ai_memory_store::{DecayParams, Store};+use ai_memory_wiki::{Wiki, WritePageRequest};+use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::json;+use tempfile::TempDir;+use tower::ServiceExt;++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++async fn make_state(tmp: &TempDir) -> (AdminState, Store) {+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let db_path = store.db_path().to_path_buf();+ let state = AdminState {+ writer: store.writer.clone(),+ reader: store.reader.clone(),+ wiki,+ llm: None,+ embedder: None,+ decay_params: DecayParams::default(),+ data_dir: tmp.path().to_path_buf(),+ db_path,+ bind: "127.0.0.1:0".to_string(),+ };+ (state, store)+}++async fn body_json(resp: axum::response::Response) -> serde_json::Value {+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap();+ serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null)+}++async fn post(state: AdminState, uri: &str, body: serde_json::Value) -> axum::response::Response {+ let router = admin_router(state);+ let req = Request::builder()+ .method("POST")+ .uri(uri)+ .header("content-type", "application/json")+ .body(Body::from(serde_json::to_vec(&body).unwrap()))+ .unwrap();+ router.oneshot(req).await.unwrap()+}++/// Seed two projects (`default/keep` and `default/doomed`), each with one+/// page, one session, some observations, and a handoff. Returns the wiki+/// page path seeded for the doomed project.+async fn seed_two_projects(store: &Store, wiki: &Wiki) -> String {+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let keep = store+ .writer+ .get_or_create_project(ws, "keep", None)+ .await+ .unwrap();+ let doomed = store+ .writer+ .get_or_create_project(ws, "doomed", None)+ .await+ .unwrap();++ // Write pages through the wiki so they land on disk.+ wiki.write_page(WritePageRequest {+ workspace_id: ws,+ project_id: keep,+ path: PagePath::new("notes/keep.md").unwrap(),+ frontmatter: serde_json::json!({"title": "Keep page"}),+ body: "This page must survive the purge.".into(),+ tier: Tier::Semantic,+ pinned: false,+ title: Some("Keep page".into()),+ })+ .await+ .unwrap();++ let doomed_path = "notes/doomed.md";+ wiki.write_page(WritePageRequest {+ workspace_id: ws,+ project_id: doomed,+ path: PagePath::new(doomed_path).unwrap(),+ frontmatter: serde_json::json!({"title": "Doomed page"}),+ body: "This page will be destroyed.".into(),+ tier: Tier::Semantic,+ pinned: false,+ title: Some("Doomed page".into()),+ })+ .await+ .unwrap();++ // Sessions + observations for both projects.+ for (proj, label) in [(keep, "keep"), (doomed, "doomed")] {+ let sid = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ id: sid,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::ClaudeCode,+ cwd: None,+ })+ .await+ .unwrap();+ for i in 0..3u8 {+ store+ .writer+ .insert_observation(NewObservation {+ session_id: sid,+ workspace_id: ws,+ project_id: proj,+ kind: ObservationKind::UserPrompt,+ title: format!("{label} obs {i}"),+ body: "body".into(),+ importance: 5,+ })+ .await+ .unwrap();+ }+ // Handoff for the doomed project only.+ if label == "doomed" {+ store+ .writer+ .insert_handoff(NewHandoff {+ workspace_id: ws,+ project_id: proj,+ from_session_id: Some(sid),+ from_agent: AgentKind::ClaudeCode,+ to_agent: None,+ cwd: None,+ summary: "doomed handoff".into(),+ open_questions: vec![],+ next_steps: vec![],+ files_touched: vec![],+ })+ .await+ .unwrap();+ }+ }++ doomed_path.to_string()+}++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++/// Missing `confirm: true` must return 400.+#[tokio::test]+async fn purge_project_without_confirm_returns_400() {+ let tmp = TempDir::new().unwrap();+ let (state, _store) = make_state(&tmp).await;++ let resp = post(+ state,+ "/admin/purge-project",+ json!({ "workspace": "default", "project": "any", "confirm": false }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);++ let body = body_json(resp).await;+ assert!(+ body["error"]+ .as_str()+ .unwrap_or("")+ .contains("confirm=true"),+ "error must mention confirm=true: {body}"+ );+}++/// Non-existent project must return 404.+#[tokio::test]+async fn purge_project_nonexistent_returns_404() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;++ // Ensure the workspace exists so the 404 is about the project.+ store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();++ let resp = post(+ state,+ "/admin/purge-project",+ json!({ "workspace": "default", "project": "nonexistent", "confirm": true }),+ )+ .await;+ assert_eq!(+ resp.status(),+ StatusCode::NOT_FOUND,+ "nonexistent project must 404"+ );++ let body = body_json(resp).await;+ assert!(+ body["error"].as_str().unwrap_or("").contains("not found"),+ "error must say 'not found': {body}"+ );+}++/// Non-existent workspace must also return 404.+#[tokio::test]+async fn purge_project_nonexistent_workspace_returns_404() {+ let tmp = TempDir::new().unwrap();+ let (state, _store) = make_state(&tmp).await;++ let resp = post(+ state,+ "/admin/purge-project",+ json!({ "workspace": "ghost-workspace", "project": "x", "confirm": true }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);+}++/// Happy path: purge the doomed project, verify counts and file removal.+#[tokio::test]+async fn purge_project_deletes_data_and_files() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;++ let doomed_path = seed_two_projects(&store, &state.wiki).await;++ // File must exist before purge.+ let file_on_disk = tmp.path().join("wiki").join(&doomed_path);+ assert!(file_on_disk.exists(), "wiki file must exist before purge");++ let resp = post(+ state,+ "/admin/purge-project",+ json!({ "workspace": "default", "project": "doomed", "confirm": true }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::OK, "purge must succeed");++ let body = body_json(resp).await;+ assert_eq!(+ body["label"].as_str().unwrap_or(""),+ "default/doomed",+ "label must match: {body}"+ );+ assert_eq!(+ body["pages_deleted"].as_u64().unwrap_or(0),+ 1,+ "one page deleted: {body}"+ );+ assert_eq!(+ body["sessions_deleted"].as_u64().unwrap_or(0),+ 1,+ "one session deleted: {body}"+ );+ assert_eq!(+ body["observations_deleted"].as_u64().unwrap_or(0),+ 3,+ "three observations deleted: {body}"+ );+ assert_eq!(+ body["handoffs_deleted"].as_u64().unwrap_or(0),+ 1,+ "one handoff deleted: {body}"+ );++ // On-disk file must be gone.+ assert!(+ !file_on_disk.exists(),+ "wiki file must be removed after purge"+ );+}++/// After purging `doomed`, `keep` must still have all its data intact.+#[tokio::test]+async fn purge_project_preserves_sibling_project() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;++ seed_two_projects(&store, &state.wiki).await;++ let resp = post(+ state,+ "/admin/purge-project",+ json!({ "workspace": "default", "project": "doomed", "confirm": true }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::OK);++ // The `keep` project's data must be untouched.+ let counts = store.reader.status_counts().await.unwrap();+ // 1 page (keep), 1 session (keep), 3 observations (keep).+ assert_eq!(+ counts.pages_latest, 1,+ "keep's page must survive: {counts:?}"+ );+ assert_eq!(+ counts.sessions, 1,+ "keep's session must survive: {counts:?}"+ );+ assert_eq!(+ counts.observations, 3,+ "keep's observations must survive: {counts:?}"+ );++ // keep's wiki file must still exist.+ let keep_file = tmp.path().join("wiki/notes/keep.md");+ assert!(keep_file.exists(), "keep's wiki file must survive");+}++/// Purging the same project twice: second call returns 404 (already gone).+#[tokio::test]+async fn purge_project_idempotent_second_call_is_404() {+ let tmp = TempDir::new().unwrap();+ let (state_a, store) = make_state(&tmp).await;+ let state_b = AdminState {+ writer: store.writer.clone(),+ reader: store.reader.clone(),+ wiki: state_a.wiki.clone(),+ llm: None,+ embedder: None,+ 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(),+ };++ seed_two_projects(&store, &state_a.wiki).await;++ // First purge succeeds.+ let r1 = post(+ state_a,+ "/admin/purge-project",+ json!({ "workspace": "default", "project": "doomed", "confirm": true }),+ )+ .await;+ assert_eq!(r1.status(), StatusCode::OK);++ // Second purge: project is gone → 404.+ let r2 = post(+ state_b,+ "/admin/purge-project",+ json!({ "workspace": "default", "project": "doomed", "confirm": true }),+ )+ .await;+ assert_eq!(+ r2.status(),+ StatusCode::NOT_FOUND,+ "second purge must 404 because project is already gone"+ );+}diff --git a/crates/ai-memory-store/migrations/V05__cascade_indexes.sql b/crates/ai-memory-store/migrations/V05__cascade_indexes.sqlnew file mode 100644index 00000000..cf44f0a1--- /dev/null+++ b/crates/ai-memory-store/migrations/V05__cascade_indexes.sql@@ -0,0 +1,53 @@+-- Cascade-delete performance indexes.+--+-- Schema audit (pre-V05) findings:+--+-- PRAGMA foreign_keys status+-- --------------------------+-- The writer connection has PRAGMA foreign_keys = ON set in Store::open()+-- before the writer thread is spawned — correct. Reader connections are+-- opened read-only and never trigger cascades, so no change needed there.+--+-- Missing indexes identified+-- --------------------------+-- For DELETE FROM projects WHERE id = ?, SQLite walks every dependent table+-- looking for rows with a matching FK column. Without an index on the FK+-- column, each dependent table requires a full-table scan. The tables that+-- REFERENCES projects(id) ON DELETE CASCADE are:+-- pages — project_id (no standalone index; idx_pages_latest_path+-- is on (workspace_id, project_id, path) WHERE is_latest=1+-- and cannot be used for an unfiltered project_id scan)+-- sessions — project_id (idx_sessions_recent covers the prefix+-- only when workspace_id is also known)+-- observations — project_id (idx_observations_session is on session_id+-- only; no project_id index at all)+-- handoffs — project_id (both handoff indexes are partial/filtered;+-- not usable for an unfiltered project_id scan)+--+-- page_embeddings REFERENCES pages(id) ON DELETE CASCADE is covered by the+-- PRIMARY KEY on page_id — no additional index needed.+--+-- links(from_page_id) REFERENCES pages(id) ON DELETE CASCADE is covered by+-- the PRIMARY KEY on from_page_id — no additional index needed.+--+-- Other schema oddities noted (not fixed here — no behaviour change needed):+-- - audit_log has no FK on workspace_id/project_id/page_id (nullable BLOBs+-- with no REFERENCES clause). Intentional: the audit log is an append-only+-- event log; orphan rows are acceptable and expected.+-- - handoffs.from_session_id is nullable (manual handoffs have no session);+-- the SET NULL cascade on sessions(id) is correct.+-- - observations has workspace_id denormalised alongside project_id; both+-- carry REFERENCES … ON DELETE CASCADE so a workspace delete cascades+-- through the workspace FK independently of the project FK. Correct.++CREATE INDEX IF NOT EXISTS idx_pages_project+ ON pages(project_id);++CREATE INDEX IF NOT EXISTS idx_sessions_project+ ON sessions(project_id);++CREATE INDEX IF NOT EXISTS idx_observations_project+ ON observations(project_id);++CREATE INDEX IF NOT EXISTS idx_handoffs_project+ ON handoffs(project_id);diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 5459637a..3ffc0beb 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -21,7 +21,7 @@ mod writer;pub use decay::{DecayParams, retention_score};pub use error::{StoreError, StoreResult};-pub use ops::ReorgSummary;+pub use ops::{PurgeSummary, ReorgSummary};pub use reader::{ActivityWindow, BriefingPage, BriefingSnapshot, DecayCandidate, PageHit, PageMeta, PageSummary,ProjectSummary, ReaderPool, StatusCounts, StoredEmbedding, f32_vec_to_bytes,diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex f5cf42b9..9f52703c 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -6,7 +6,7 @@use ai_memory_core::{AgentKind, HandoffId, NewHandoff, NewObservation, NewPage, NewSession, ObservationId,- ObservationKind, PageId, ProjectId, SessionId,+ ObservationKind, PageId, ProjectId, SessionId, WorkspaceId,};/// Summary returned by [`reorg_sessions`] and exposed via@@ -20,6 +20,29 @@ pub struct ReorgSummary {/// `is_latest=1` pages marked `is_latest=0` (mash-up graveyard).pub pages_graveyarded: usize,}++/// Summary returned by [`purge_project`] and exposed via+/// [`crate::writer::WriterHandle::purge_project`].+#[derive(Debug, Default, Clone)]+pub struct PurgeSummary {+ /// Human-readable `workspace/project` label. Set by the caller (writer+ /// only knows IDs); filled in by [`purge_project`] from its parameters.+ pub label: String,+ /// Distinct page paths that were present before the delete (all versions,+ /// not just `is_latest=1`). The admin handler uses this list to remove+ /// the corresponding files from the wiki directory.+ pub page_paths: Vec<String>,+ /// Number of `pages` rows deleted (all versions, not just latest).+ pub pages_deleted: u64,+ /// Number of `sessions` rows deleted.+ pub sessions_deleted: u64,+ /// Number of `observations` rows deleted.+ pub observations_deleted: u64,+ /// Number of `handoffs` rows deleted.+ pub handoffs_deleted: u64,+ /// Number of `page_embeddings` rows deleted (cascades through pages).+ pub embeddings_deleted: u64,+}use jiff::Timestamp;use rusqlite::{Connection, OptionalExtension, params};use sha2::{Digest, Sha256};@@ -621,6 +644,93 @@ pub fn reorg_sessions(})}+/// Delete a project and all its data inside one transaction.+///+/// Execution order:+/// 1. Count rows in each dependent table (pages/all versions, sessions,+/// observations, handoffs, embeddings) before the delete so we can+/// report how many rows were removed.+/// 2. Collect all distinct page paths stored under the project — these are+/// the on-disk files the caller must clean up after this function returns.+/// 3. DELETE FROM projects WHERE id = ? — the ON DELETE CASCADE clauses in+/// V01 + V02 propagate the delete to pages, sessions, observations,+/// handoffs, and page_embeddings automatically.+/// 4. Commit and return the [`PurgeSummary`].+///+/// The `workspace_project_label` string is passed in by the caller (the+/// admin handler has the human-readable names; the writer only has IDs) and+/// forwarded verbatim into [`PurgeSummary::label`] for logging.+///+/// # Errors+/// Returns [`StoreError`] if any SQL statement fails. The transaction is+/// rolled back automatically on error.+pub fn purge_project(+ conn: &mut Connection,+ workspace_id: &WorkspaceId,+ project_id: &ProjectId,+ workspace_project_label: &str,+) -> StoreResult<PurgeSummary> {+ let tx = conn.transaction()?;++ let count = |sql: &str, id: &[u8]| -> StoreResult<u64> {+ let n: Option<i64> = tx+ .query_row(sql, rusqlite::params![id], |row| row.get(0))+ .optional()?;+ Ok(u64::try_from(n.unwrap_or(0)).unwrap_or(0))+ };++ let pid = project_id.as_bytes();+ let pages_deleted = count("SELECT COUNT(*) FROM pages WHERE project_id = ?1", &pid[..])?;+ let sessions_deleted = count(+ "SELECT COUNT(*) FROM sessions WHERE project_id = ?1",+ &pid[..],+ )?;+ let observations_deleted = count(+ "SELECT COUNT(*) FROM observations WHERE project_id = ?1",+ &pid[..],+ )?;+ let handoffs_deleted = count(+ "SELECT COUNT(*) FROM handoffs WHERE project_id = ?1",+ &pid[..],+ )?;+ // page_embeddings cascade through pages; count pages that have them.+ let embeddings_deleted = count(+ "SELECT COUNT(*) FROM page_embeddings \+ WHERE page_id IN (SELECT id FROM pages WHERE project_id = ?1)",+ &pid[..],+ )?;++ // Collect all distinct on-disk paths for the caller to clean up.+ // We use DISTINCT because multiple versions of the same logical page+ // share a path; the file only exists once. The statement must be+ // dropped before we call tx.commit() to release the borrow on `tx`.+ let page_paths: Vec<String> = {+ let mut path_stmt = tx.prepare("SELECT DISTINCT path FROM pages WHERE project_id = ?1")?;+ path_stmt+ .query_map(rusqlite::params![&pid[..]], |row| row.get(0))?+ .collect::<rusqlite::Result<Vec<String>>>()?+ };++ // Cascade handles pages / sessions / observations / handoffs /+ // page_embeddings. The workspace row is intentionally left intact —+ // other projects may still live there.+ tx.execute(+ "DELETE FROM projects WHERE id = ?1 AND workspace_id = ?2",+ rusqlite::params![&pid[..], workspace_id.as_bytes()],+ )?;++ tx.commit()?;+ Ok(PurgeSummary {+ label: workspace_project_label.to_string(),+ page_paths,+ pages_deleted,+ sessions_deleted,+ observations_deleted,+ handoffs_deleted,+ embeddings_deleted,+ })+}+#[cfg(test)]mod tests {//! Focused unit tests for the load-bearing mutating SQL paths.diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex e0a0b96b..8b3c269d 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -1007,6 +1007,60 @@ impl ReaderPool {.await}+ /// Look up a workspace id by name without creating it.+ ///+ /// Returns `None` when no workspace with the given name exists.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn find_workspace(&self, name: String) -> StoreResult<Option<WorkspaceId>> {+ self.with_conn(move |conn| {+ let row_opt = conn+ .query_row(+ "SELECT id FROM workspaces WHERE name = ?1",+ params![name],+ |row| {+ let bytes: Vec<u8> = row.get(0)?;+ Ok(bytes)+ },+ )+ .optional()?;+ row_opt+ .map(|bytes| WorkspaceId::from_slice(&bytes).map_err(StoreError::from))+ .transpose()+ })+ .await+ }++ /// Look up a project id by `(workspace_id, name)` without creating it.+ ///+ /// Returns `None` when no project with the given name exists in the workspace.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn find_project(+ &self,+ workspace_id: WorkspaceId,+ name: String,+ ) -> StoreResult<Option<ProjectId>> {+ self.with_conn(move |conn| {+ let row_opt = conn+ .query_row(+ "SELECT id FROM projects WHERE workspace_id = ?1 AND name = ?2",+ params![workspace_id.as_bytes(), name],+ |row| {+ let bytes: Vec<u8> = row.get(0)?;+ Ok(bytes)+ },+ )+ .optional()?;+ row_opt+ .map(|bytes| ProjectId::from_slice(&bytes).map_err(StoreError::from))+ .transpose()+ })+ .await+ }+/// Return aggregate counts for the `status` view.////// # Errorsdiff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 808db0cb..edf49bb4 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -18,7 +18,7 @@ use rusqlite::Connection;use tokio::sync::{mpsc, oneshot};use crate::error::{StoreError, StoreResult};-use crate::ops::{self, ReorgSummary};+use crate::ops::{self, PurgeSummary, ReorgSummary};/// Commands accepted by the writer thread.pub(crate) enum WriteCmd {@@ -90,6 +90,16 @@ pub(crate) enum WriteCmd {dim: u32,reply: oneshot::Sender<StoreResult<()>>,},+ /// Delete a project and all its data (pages, sessions, observations,+ /// handoffs, embeddings) in one transaction. Returns the paths of+ /// every page file that must be removed from disk by the caller.+ PurgeProject {+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ /// Human-readable `workspace/project` label forwarded into the summary.+ label: String,+ reply: oneshot::Sender<StoreResult<PurgeSummary>>,+ },Shutdown,}@@ -303,6 +313,33 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Delete a project and all its data in one atomic transaction.+ ///+ /// ON DELETE CASCADE propagates the delete through pages, sessions,+ /// observations, handoffs, and page_embeddings automatically. The+ /// returned [`PurgeSummary`] includes pre-delete row counts and+ /// the distinct page paths that the caller must remove from disk.+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or+ /// propagates the SQL error from the purge transaction.+ pub async fn purge_project(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ label: impl Into<String>,+ ) -> StoreResult<PurgeSummary> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::PurgeProject {+ workspace_id,+ project_id,+ label: label.into(),+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+/// Retro-fit sessions and their observations to per-cwd projects and/// graveyard any mash-up pages. The `plan` slice contains/// `(session_id, new_project_id)` pairs. Everything runs in one@@ -478,6 +515,15 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {);send_or_warn(reply, result, "store_embedding");}+ WriteCmd::PurgeProject {+ workspace_id,+ project_id,+ label,+ reply,+ } => {+ let result = ops::purge_project(&mut conn, &workspace_id, &project_id, &label);+ send_or_warn(reply, result, "purge_project");+ }}}tracing::debug!("writer thread exiting cleanly");diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex 24019d69..25073a1c 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -115,6 +115,24 @@ impl Wiki {parse(&raw)}+ /// Delete the on-disk file for `path`.+ ///+ /// Returns `Ok(())` when the file was removed or did not exist (idempotent).+ /// The file watcher will observe the deletion; the sha256 short-circuit in+ /// the watcher's reindex path means a missing file produces a graceful+ /// no-op rather than an error.+ ///+ /// # Errors+ /// Returns [`WikiError::Io`] for any OS error other than "not found".+ pub fn delete_page(&self, path: &PagePath) -> WikiResult<()> {+ let abs = self.abs_path(path);+ match std::fs::remove_file(&abs) {+ Ok(()) => Ok(()),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(e) => Err(crate::WikiError::Io(e)),+ }+ }+/// Cloneable handle to the underlying store writer.#[must_use]pub fn writer(&self) -> &WriterHandle {