Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(purge): delete one session by UUID (#387) (#539)
Fabio Akita05138e29ca28
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e07efeff..4704765e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- `ai-memory purge-session --session-id <uuid> --confirm` and+ `POST /admin/purge-session` delete one session by UUID: its row, its+ observations, the handoffs it authored, its `sessions/<id>.md` page and+ every superseded version, their embeddings, and its auto-improve runs.+ `purge-project` was too broad and `delete-page` removed a single wiki path,+ so an application promising to forget one conversation had nothing to call+ (#387).++ Scope is enforced structurally rather than trusted: every statement filters+ on `workspace_id` and `project_id` alongside `session_id`, a session outside+ the named scope is a `404` with nothing deleted, and derived pages are+ deleted by id rather than by path — two projects can hold the same+ `sessions/<uuid>.md`, and deleting by path would take the other one with it.+ Targets are collected before anything is cut, because+ `auto_improve_runs.session_id`, `handoffs.from_session_id`,+ `handoffs.accepted_by_session` and `pages.supersedes` are all+ `ON DELETE SET NULL`: cutting the session first destroys the pointers needed+ to find what it produced. Handoffs the session only *accepted* are+ deliberately kept — that text belongs to the session that authored them. The+ admission chain runs before any row is touched, so a `reject`-policy webhook+ can still abort the purge.++ The purge is terminal. Events that produced a session can sit undelivered in+ a client hook spool for days, and `begin_session` would otherwise recreate+ the session row when that spool drained — silently undoing a deletion an+ application had already reported to its user. A `purged_sessions` tombstone+ (V52) is written in the same transaction as the delete, and ingest refuses to+ recreate a session that carries one. The tombstone is scoped, so purging an+ id in one project cannot suppress capture for that id elsewhere.++ The purge is a **logical delete** by default: the session is unreachable+ through the API and through search, but its bytes stay in free pages of the+ database file, as with any SQLite delete. `--compact` additionally rebuilds+ the affected FTS5 indexes and `VACUUM`s. The rebuild is the operative step —+ measured, an ordinary delete leaves the tokens inside the index segments and+ `VACUUM` alone does not clear them. `--compact` rewrites the whole database,+ needs free disk space of about its size, and is **not** forensic erasure: the+ wiki git history keeps page content in its objects and commit messages, and+ earlier backups still contain it. `docs/lifecycle-ops.md` states that+ boundary in a table so it is not inferred from the command name.+## [1.38.0] - 2026-08-30### Addeddiff --git a/README.md b/README.mdindex 05b27f66..57b8ee81 100644--- a/README.md+++ b/README.md@@ -181,7 +181,7 @@ priors are at the [bottom](#influences-and-prior-art).session-aware current-project routing; Claude Code has a built-in opt-inbridge via `install-mcp --session-aware`.- **Thin-client CLI.** `ai-memory status`, `bootstrap`, `checkpoints`,- `restore-page`, `purge-project`, `rename-project`, `move-project`,+ `restore-page`, `purge-project`, `purge-session`, `rename-project`, `move-project`,`move-session`,`audit-contamination`, `lint`, `curator`, `auto-improve`,`auto-improve-report`, `pending-writes`, `embed`, `forget-sweep`, `backup`,diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex a6ee88c0..59ee9650 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -149,6 +149,14 @@ pub enum Command {/// observations, handoffs, embeddings, on-disk wiki files)./// This is irreversible — requires `--confirm`.PurgeProject(PurgeProjectArgs),+ /// Permanently delete ONE session and everything derived from it.+ ///+ /// Removes the session row, its observations, the handoffs it authored,+ /// its derived wiki page (every version) and their embeddings — scoped+ /// strictly to the named workspace and project. Handoffs this session+ /// only *accepted* are left alone: their text belongs to the session that+ /// wrote them.+ PurgeSession(PurgeSessionArgs),/// Rename a project within its workspace. No files move on disk —/// the wiki is flat and pages are differentiated by project_id only./// Useful after renaming the project's directory on disk so the hook@@ -603,6 +611,39 @@ pub struct PurgeProjectArgs {pub confirm: bool,}+/// Arguments for `purge-session`.+#[derive(Debug, Args)]+pub struct PurgeSessionArgs {+ /// Full session UUID, exactly as `sessions.id` stores it.+ #[arg(long)]+ pub session_id: String,+ /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's+ /// `workspace`, else `default`.+ #[arg(long)]+ pub workspace: Option<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,+ /// Also reclaim the freed bytes: rebuild the affected FTS indexes and+ /// VACUUM the database after the delete commits.+ ///+ /// Without this the purge is a logical delete — the session is gone from+ /// the API and from search, but its bytes stay in free pages of the+ /// database file until it is next rewritten, as with any SQLite delete.+ ///+ /// This rewrites the WHOLE database and needs free disk space of about+ /// its size, so it takes minutes on a large store. It also does NOT make+ /// the content forensically unrecoverable: the wiki git history and any+ /// backup taken before the purge still contain it.+ #[arg(long)]+ pub compact: bool,+}+/// Arguments for `rename-project`.#[derive(Debug, Args)]pub struct RenameProjectArgs {diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 243cefe0..b3ec6416 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -42,6 +42,7 @@ pub mod path_util;pub mod pending_writes;pub mod project_registry;pub mod purge_project;+pub mod purge_session;pub mod read_page;pub mod reindex;pub mod rename_project;diff --git a/crates/ai-memory-cli/src/commands/purge_session.rs b/crates/ai-memory-cli/src/commands/purge_session.rsnew file mode 100644index 00000000..165ac4ac--- /dev/null+++ b/crates/ai-memory-cli/src/commands/purge_session.rs@@ -0,0 +1,103 @@+//! `ai-memory purge-session` — thin HTTP client for single-session purge.++use anyhow::{Result, bail};+use serde::Serialize;++use crate::cli::PurgeSessionArgs;+use crate::config::Config;+use crate::http_client::{ServerEndpoint, post_json};++/// Request sent to `POST /admin/purge-session`.+#[derive(Serialize)]+struct PurgeSessionRequest {+ workspace: String,+ project: String,+ session_id: String,+ confirm: bool,+ /// Rebuild the FTS indexes and VACUUM after the delete commits.+ compact: bool,+}++/// Run the `purge-session` subcommand.+///+/// Requires the full session UUID and `--confirm`. The scope is resolved the+/// same way as every other project-scoped command, and the server refuses a+/// session that does not belong to it, so a UUID alone is never authority+/// over another workspace or project.+///+/// # Errors+/// Returns an error when `--confirm` is absent, the session id is not a+/// UUID, the server is unreachable, or the server returns a non-2xx+/// response (including `404` for a session outside the named scope).+pub async fn run(config: &Config, args: PurgeSessionArgs) -> Result<()> {+ let (workspace, project) =+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;++ // Validate locally so an obvious typo fails before anything destructive+ // is sent. The server validates again — this is convenience, not the+ // security boundary.+ let session_id = args.session_id.trim();+ if uuid::Uuid::parse_str(session_id).is_err() {+ bail!(+ "`--session-id {session_id}` is not a UUID. Pass the full \+ `sessions.id` value; a prefix or a workstream id will not match."+ );+ }++ if !args.confirm {+ bail!(+ "purge-session is destructive and irreversible.\n\+ Re-run with --confirm to proceed:\n\n \+ ai-memory purge-session --workspace {workspace} --project {project} \+ --session-id {session_id} --confirm",+ );+ }++ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;+ let report: serde_json::Value = post_json(+ &endpoint,+ "/admin/purge-session",+ &PurgeSessionRequest {+ workspace: workspace.clone(),+ project: project.clone(),+ session_id: session_id.to_owned(),+ confirm: true,+ compact: args.compact,+ },+ )+ .await?;++ let n = |key: &str| report[key].as_u64().unwrap_or(0);+ // The session id is deliberately not echoed. The caller passed it, so+ // repeating it adds nothing they do not have, and this command exists to+ // make a session stop existing — writing its id into terminal scrollback+ // and shell history leaves a pointer to the thing just erased. The scope+ // and the counts are what confirm the operation did what was asked.+ println!(+ "Purged session from {workspace}/{project}: \+ {} observations, {} handoffs, {} pages, {} auto-improve runs.",+ n("observations_deleted"),+ n("handoffs_deleted"),+ n("pages_deleted"),+ n("auto_improve_runs_deleted"),+ );+ if let Some(paths) = report["removed_paths"].as_array()+ && !paths.is_empty()+ {+ println!("Wiki pages removed:");+ for path in paths.iter().filter_map(serde_json::Value::as_str) {+ println!(" - {path}");+ }+ }+ if report["compacted"].as_bool().unwrap_or(false) {+ println!("Database compacted: freed bytes reclaimed.");+ } else {+ println!(+ "Note: this was a logical delete. The session is unreachable through \+ the API and search, but its bytes remain in the database file until \+ it is rewritten. Re-run with --compact to reclaim them (slow), and \+ see `docs/` for what that does and does not guarantee."+ );+ }+ Ok(())+}diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rsindex 9b551c21..b48d8756 100644--- a/crates/ai-memory-cli/src/main.rs+++ b/crates/ai-memory-cli/src/main.rs@@ -136,6 +136,7 @@ async fn main() -> Result<()> {Command::InstallSkills(args) => commands::install_skills::run(&config, args),Command::Reorg(args) => commands::reorg::run(&config, args).await,Command::PurgeProject(args) => commands::purge_project::run(&config, args).await,+ Command::PurgeSession(args) => commands::purge_session::run(&config, args).await,Command::RenameProject(args) => commands::rename_project::run(&config, args).await,Command::MoveProject(args) => commands::move_project::run(&config, args).await,Command::MoveSession(args) => commands::move_session::run(&config, args).await,diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex e50ed8cc..91142d0d 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -22,6 +22,7 @@//! - `GET /admin/checkpoints` — list recent wiki git checkpoints.//! - `POST /admin/restore-page` — restore one page from a checkpoint.//! - `POST /admin/purge-project` — delete a project and all its data.+//! - `POST /admin/purge-session` — delete one session and what it derived.//! - `POST /admin/rename-project` — rename a project (column-only; no files move).//! - `POST /admin/rename-workspace` — rename a workspace and refresh scope manifests.//! - `POST /admin/delete-workspace` — delete a workspace and all of its projects.@@ -619,6 +620,7 @@ pub fn admin_router_with_sweep_tuning(.route("/admin/checkpoints", get(handle_checkpoints)).route("/admin/restore-page", post(handle_restore_page)).route("/admin/purge-project", post(handle_purge_project))+ .route("/admin/purge-session", post(handle_purge_session)).route("/admin/rename-project", post(handle_rename_project)).route("/admin/move-project", post(handle_move_project)).route("/admin/move-session", post(handle_move_session))@@ -3260,6 +3262,123 @@ async fn handle_restore_page())}+// ---------------------------------------------------------------------+// purge-session+// ---------------------------------------------------------------------++/// JSON request body for `POST /admin/purge-session`.+#[derive(Deserialize)]+struct PurgeSessionRequest {+ /// Workspace name. Must already exist; 404 otherwise.+ workspace: String,+ /// Project name. Must already exist; 404 otherwise.+ project: String,+ /// Full `sessions.id` UUID. A session that does not belong to the named+ /// workspace/project is a 404 — the id alone is never authority over+ /// another scope.+ session_id: String,+ /// Mandatory confirmation flag. Without `confirm: true` the server+ /// returns 400 — purging is destructive and irreversible.+ confirm: bool,+ /// Reclaim freed bytes: rebuild the FTS indexes and `VACUUM` after the+ /// delete commits. Off by default; see `ai_memory_store::Compaction` for+ /// the cost and for what it does not guarantee.+ #[serde(default)]+ compact: bool,+}++/// `POST /admin/purge-session` — delete one session and everything derived+/// from it, inside a single workspace/project scope.+async fn handle_purge_session(+ State(state): State<Arc<AdminState>>,+ actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,+ author_ext: Option<axum::Extension<ai_memory_core::UserId>>,+ Json(req): Json<PurgeSessionRequest>,+) -> impl IntoResponse {+ let author_id = author_ext.map(|axum::Extension(u)| u);+ if !req.confirm {+ return (+ StatusCode::BAD_REQUEST,+ Json(serde_json::json!({+ "error": "destructive operation requires confirm=true"+ })),+ );+ }++ let session_id = match req.session_id.trim().parse::<SessionId>() {+ Ok(id) => id,+ Err(_) => {+ return (+ StatusCode::BAD_REQUEST,+ Json(serde_json::json!({ "error": "session_id must be a full UUID" })),+ );+ }+ };++ let (ws_id, proj_id) =+ match lookup_ws_proj_no_create(&state, &req.workspace, &req.project).await {+ Ok(ids) => ids,+ Err(e) => return e,+ };++ // Admission runs before anything is deleted so a reject-policy webhook can+ // refuse while every row is still intact — same order as purge-project.+ let actor = actor_ext+ .map(|axum::Extension(a)| a)+ .unwrap_or_else(ai_memory_core::ActorContext::anonymous);+ let ctx = AdmissionContext {+ workspace: req.workspace.clone(),+ project: req.project.clone(),+ op: AdmissionOp::PurgeSession,+ actor,+ ..Default::default()+ };+ if let Err(e) = state+ .wiki+ .admit_purge_session(ws_id, proj_id, Some(ctx))+ .await+ {+ return internal_err(e.to_string());+ }++ let compaction = if req.compact {+ ai_memory_store::Compaction::Reclaim+ } else {+ ai_memory_store::Compaction::Skip+ };++ let summary = match state+ .writer+ .purge_session(ws_id, proj_id, session_id, author_id, compaction)+ .await+ {+ Ok(s) => s,+ // Absent from this scope (or already purged) is a 404, not a fault.+ Err(e @ StoreError::NotFound(_)) => {+ return (+ StatusCode::NOT_FOUND,+ Json(serde_json::json!({ "error": e.to_string() })),+ );+ }+ Err(e) => return internal_err(e.to_string()),+ };++ (+ StatusCode::OK,+ Json(serde_json::json!({+ "session_id": session_id.to_string(),+ "workspace": req.workspace,+ "project": req.project,+ "observations_deleted": summary.observations_deleted,+ "handoffs_deleted": summary.handoffs_deleted,+ "pages_deleted": summary.pages_deleted,+ "auto_improve_runs_deleted": summary.auto_improve_runs_deleted,+ "removed_paths": summary.removed_paths,+ "compacted": summary.compacted,+ })),+ )+}+// ---------------------------------------------------------------------// purge-project// ---------------------------------------------------------------------diff --git a/crates/ai-memory-store/migrations/V52__purged_sessions_tombstones.sql b/crates/ai-memory-store/migrations/V52__purged_sessions_tombstones.sqlnew file mode 100644index 00000000..3aad7f47--- /dev/null+++ b/crates/ai-memory-store/migrations/V52__purged_sessions_tombstones.sql@@ -0,0 +1,25 @@+-- Tombstones for sessions removed by `purge_session` (#387).+--+-- A purge deletes the session's rows, but the events that produced them may+-- still be sitting in a client hook spool, undelivered. When that spool+-- eventually drains, `begin_session` recreates the session row and the+-- observations land again — the purge is silently undone, and an application+-- that promised to forget the conversation has not.+--+-- The tombstone makes the deletion terminal: ingest checks it and refuses to+-- recreate a session that was purged. Keyed by session id, with the scope kept+-- so a purge in one project cannot suppress a same-id session elsewhere (ids+-- are UUIDv7 and collisions are not expected, but the check costs nothing and+-- the alternative is a cross-scope denial of ingest).+--+-- `purged_at` exists so the ledger can be pruned. A tombstone only has to+-- outlive the spool that might replay the session, and `MAX_AGE_MS` in the+-- drain caps that at 7 days.+CREATE TABLE purged_sessions (+ session_id BLOB PRIMARY KEY NOT NULL,+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,+ purged_at INTEGER NOT NULL+);++CREATE INDEX idx_purged_sessions_at ON purged_sessions(purged_at);diff --git a/crates/ai-memory-store/src/error.rs b/crates/ai-memory-store/src/error.rsindex 24b07577..cee483d7 100644--- a/crates/ai-memory-store/src/error.rs+++ b/crates/ai-memory-store/src/error.rs@@ -80,6 +80,12 @@ pub enum StoreError {/// caller-invariant violation).#[error("not found: {0}")]NotFound(String),+ /// A late-arriving event named a session that `purge_session` removed.+ /// Recreating it would silently undo a deletion the operator already+ /// performed and an application may already have reported to a user, so+ /// ingest refuses instead (#387).+ #[error("session {0} was purged and cannot be recreated")]+ SessionPurged(String),/// A workspace delete was refused because it still holds projects and the/// caller did not pass `force`. Carries the project count so the admindiff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex dea405b4..61cfb91a 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -45,9 +45,10 @@ pub use decay::{pub use error::{StoreError, StoreResult};pub use maintenance::MaintenanceJob;pub use ops::{- AdmittedSession, DeleteWorkspaceSummary, EmbeddingWrite, HookSessionAdmission,+ AdmittedSession, Compaction, DeleteWorkspaceSummary, EmbeddingWrite, HookSessionAdmission,IngestObservationOutcome, LifecycleOnlyEndOutcome, MoveSessionSummary, MoveSummary,- ObservationPruneOutcome, PagesMode, PurgeSummary, ReorgSummary,+ ObservationPruneOutcome, PagesMode, PurgeSessionSummary, PurgeSummary, ReorgSummary,+ purge_session,};pub use reader::{ActivityWindow, AgentSessionCount, AuditEvent, AuditLogFilter, AutoImproveCandidateSession,diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 9cb690f4..09e24ebe 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -964,8 +964,35 @@ pub(crate) fn begin_session_in_transaction(Ok(())}+/// Whether this session was purged and must not be recreated by late-arriving+/// events. Scoped: a purge in one project does not suppress ingest for a+/// session id in another.+fn session_is_purged(conn: &Connection, session: &NewSession) -> StoreResult<bool> {+ Ok(conn.query_row(+ "SELECT EXISTS( \+ SELECT 1 FROM purged_sessions \+ WHERE session_id = ?1 AND workspace_id = ?2 AND project_id = ?3 \+ )",+ params![+ session.id.as_bytes(),+ session.workspace_id.as_bytes(),+ session.project_id.as_bytes(),+ ],+ |row| row.get::<_, i64>(0),+ )? == 1)+}+fn begin_session_row(conn: &Connection, session: &NewSession) -> StoreResult<()> {validate_identity_storage_key(session.actor_user.as_deref(), "session owner")?;+ // A purge must be terminal. The events that produced a session can still+ // be sitting undelivered in a client hook spool; without this check the+ // next drain recreates the session row and the observations land again,+ // silently undoing a deletion an application already promised its user+ // (#387). Every ingest path funnels through here, so this is the one+ // place the guard has to live.+ if session_is_purged(conn, session)? {+ return Err(StoreError::SessionPurged(session.id.to_string()));+ }let now = Timestamp::now().as_microsecond();let agent = session.agent_kind.as_str();let cwd: Option<String> = session@@ -2799,6 +2826,266 @@ pub fn insert_wiki_migration(/// Returns [`StoreError::ManagedRunActive`] when a managed run's lease is/// still live and `force` is false, or [`StoreError`] if any SQL statement/// fails. The transaction is rolled back automatically on error.+/// Whether [`purge_session`] should reclaim the freed bytes afterwards.+///+/// A purge is a logical delete: the rows are gone and nothing can reach them+/// through the API or through search, but their bytes remain in free pages of+/// the database file until the file is rewritten — exactly as for any other+/// SQLite delete.+///+/// [`Compaction::Reclaim`] additionally rebuilds the affected FTS5 indexes+/// (the tokens survive an ordinary delete inside the index segments) and runs+/// `VACUUM`, after the deletion has committed.+///+/// # Cost and limits+///+/// `VACUUM` rewrites the entire database and needs free disk space of roughly+/// the database's own size. On a multi-gigabyte store this is minutes, not+/// milliseconds, so it is opt-in rather than the default.+///+/// It also does **not** make the content forensically unrecoverable. The wiki+/// git repository keeps page text in its objects and commit messages, and any+/// backup taken before the purge still contains it. Reclaiming bytes from the+/// live SQLite file is worth doing on its own terms; it is not a guarantee of+/// erasure everywhere, and must not be described as one.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Compaction {+ /// Leave the freed pages alone. The default, and what #387 promises.+ Skip,+ /// Rebuild the affected FTS indexes and `VACUUM` after committing.+ Reclaim,+}++/// What [`purge_session`] removed. All counts are rows actually deleted.+#[derive(Debug, Default, Clone, PartialEq, Eq)]+pub struct PurgeSessionSummary {+ /// `observations` rows removed.+ pub observations_deleted: u64,+ /// `handoffs` rows removed — only those this session *authored*.+ pub handoffs_deleted: u64,+ /// `pages` rows removed, counting every version in the supersession chain.+ pub pages_deleted: u64,+ /// `auto_improve_runs` rows removed.+ pub auto_improve_runs_deleted: u64,+ /// On-disk wiki paths whose rows are gone, for the caller to unlink.+ pub removed_paths: Vec<String>,+ /// Whether the freed bytes were reclaimed (`VACUUM` ran).+ pub compacted: bool,+}++/// Delete one session and everything addressable from it, within one scope.+///+/// # Scope containment+///+/// This is a destructive operation driven by a caller-supplied id, so the+/// scope is enforced structurally rather than trusted:+///+/// - the session must exist **and** belong to `(workspace_id, project_id)`;+/// a session id from another scope is [`StoreError::NotFound`] and nothing+/// is deleted;+/// - every statement is additionally filtered on `workspace_id` and+/// `project_id` wherever the table carries them, so even a mismatched id+/// cannot reach a row in another workspace or project;+/// - derived pages are deleted by **id**, from a set collected and+/// scope-checked first — never by path. Two projects may hold the same+/// `sessions/<uuid>.md` path, and a hand-written page can occupy the path a+/// session later claims; deleting by path would take those with it.+///+/// # Ordering+///+/// `auto_improve_runs.session_id`, `handoffs.from_session_id`,+/// `handoffs.accepted_by_session` and `pages.supersedes` are all+/// `ON DELETE SET NULL`. Cutting the session first nulls the pointers needed+/// to find what it produced, so every target is collected before anything is+/// deleted.+///+/// # What is deliberately *not* deleted+///+/// Handoffs this session **accepted** but did not author. Their summary text+/// belongs to the authoring session; accepting one does not transfer+/// ownership, and removing it would destroy another session's record. Those+/// rows keep their content and lose only the `accepted_by_session` pointer,+/// via the existing `ON DELETE SET NULL`.+pub fn purge_session(+ conn: &mut Connection,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ session_id: SessionId,+ author_id: Option<ai_memory_core::UserId>,+ compaction: Compaction,+) -> StoreResult<PurgeSessionSummary> {+ let wid = workspace_id.as_bytes();+ let pid = project_id.as_bytes();+ let sid = session_id.as_bytes();+ let tx = conn.transaction()?;++ // The session must live in this scope. A mismatch is NotFound, not a+ // silent no-op: the caller asked to delete something and must learn that+ // it did not happen.+ let in_scope: i64 = tx.query_row(+ "SELECT COUNT(*) FROM sessions \+ WHERE id = ?1 AND workspace_id = ?2 AND project_id = ?3",+ rusqlite::params![&sid[..], &wid[..], &pid[..]],+ |row| row.get(0),+ )?;+ if in_scope == 0 {+ return Err(StoreError::NotFound(format!(+ "session {session_id} not found in this workspace/project"+ )));+ }++ // ---- collect, before anything is cut ----++ // The derived page and every version of it. Walk from the recorded+ // summary page across the supersession chain, staying inside the scope.+ let page_ids: Vec<Vec<u8>> = {+ let mut stmt = tx.prepare(+ "WITH RECURSIVE chain(id) AS ( \+ SELECT summary_page_id FROM sessions \+ WHERE id = ?1 AND summary_page_id IS NOT NULL \+ UNION \+ SELECT p.id FROM pages p JOIN chain c ON p.supersedes = c.id \+ ) \+ SELECT p.id FROM pages p JOIN chain c ON p.id = c.id \+ WHERE p.workspace_id = ?2 AND p.project_id = ?3",+ )?;+ stmt.query_map(rusqlite::params![&sid[..], &wid[..], &pid[..]], |row| {+ row.get::<_, Vec<u8>>(0)+ })?+ .collect::<rusqlite::Result<Vec<_>>>()?+ };++ let removed_paths: Vec<String> = if page_ids.is_empty() {+ Vec::new()+ } else {+ let mut stmt = tx.prepare(+ "SELECT DISTINCT path FROM pages \+ WHERE id = ?1 AND workspace_id = ?2 AND project_id = ?3",+ )?;+ let mut paths = Vec::new();+ for id in &page_ids {+ let found: Option<String> = stmt+ .query_row(rusqlite::params![&id[..], &wid[..], &pid[..]], |row| {+ row.get(0)+ })+ .optional()?;+ if let Some(path) = found+ && !paths.contains(&path)+ {+ paths.push(path);+ }+ }+ paths+ };++ let run_ids: Vec<Vec<u8>> = {+ let mut stmt = tx.prepare(+ "SELECT id FROM auto_improve_runs \+ WHERE session_id = ?1 AND workspace_id = ?2 AND project_id = ?3",+ )?;+ stmt.query_map(rusqlite::params![&sid[..], &wid[..], &pid[..]], |row| {+ row.get::<_, Vec<u8>>(0)+ })?+ .collect::<rusqlite::Result<Vec<_>>>()?+ };++ // ---- delete, innermost first ----++ for run in &run_ids {+ tx.execute(+ "DELETE FROM auto_improve_rejections \+ WHERE source_run_id = ?1 AND workspace_id = ?2 AND project_id = ?3",+ rusqlite::params![&run[..], &wid[..], &pid[..]],+ )?;+ }+ let auto_improve_runs_deleted = tx.execute(+ "DELETE FROM auto_improve_runs \+ WHERE session_id = ?1 AND workspace_id = ?2 AND project_id = ?3",+ rusqlite::params![&sid[..], &wid[..], &pid[..]],+ )? as u64;++ // Authored only. See the note above about accepted handoffs.+ let handoffs_deleted = tx.execute(+ "DELETE FROM handoffs \+ WHERE from_session_id = ?1 AND workspace_id = ?2 AND project_id = ?3",+ rusqlite::params![&sid[..], &wid[..], &pid[..]],+ )? as u64;++ // Pages by id, scoped. Cascades `page_embeddings` and fires `pages_fts_ad`.+ let mut pages_deleted = 0u64;+ for id in &page_ids {+ pages_deleted += tx.execute(+ "DELETE FROM pages WHERE id = ?1 AND workspace_id = ?2 AND project_id = ?3",+ rusqlite::params![&id[..], &wid[..], &pid[..]],+ )? as u64;+ }++ // Deleted explicitly rather than left to the cascade so the row count is+ // known and can be reported. Measured: this does *not* change what the+ // FTS index retains — with an external-content table the cascade already+ // makes the text unsearchable, and the tokens stay in the FTS5 segments+ // either way until a `rebuild`. See the scope note on this function.+ let observations_deleted = tx.execute(+ "DELETE FROM observations \+ WHERE session_id = ?1 AND workspace_id = ?2 AND project_id = ?3",+ rusqlite::params![&sid[..], &wid[..], &pid[..]],+ )? as u64;++ // Tombstone before the row goes, in the same transaction: a purge that+ // committed the deletion but not the tombstone would be undone by the+ // next spool drain (#387).+ tx.execute(+ "INSERT INTO purged_sessions (session_id, workspace_id, project_id, purged_at) \+ VALUES (?1, ?2, ?3, ?4) \+ ON CONFLICT(session_id) DO UPDATE SET purged_at = excluded.purged_at",+ rusqlite::params![+ &sid[..],+ &wid[..],+ &pid[..],+ Timestamp::now().as_microsecond()+ ],+ )?;++ // Finally the session itself; cascades scheduler claims and+ // consolidation jobs, which hold no content of their own.+ tx.execute(+ "DELETE FROM sessions WHERE id = ?1 AND workspace_id = ?2 AND project_id = ?3",+ rusqlite::params![&sid[..], &wid[..], &pid[..]],+ )?;++ audit(+ &tx,+ "purge_session",+ Some(wid),+ Some(pid),+ None,+ author_id.as_ref().map(ai_memory_core::UserId::as_bytes),+ Timestamp::now().as_microsecond(),+ )?;++ tx.commit()?;++ // Outside the transaction: `VACUUM` cannot run inside one, and a rebuild+ // is a whole-index operation we do not want holding the write lock for+ // the duration of the delete.+ if compaction == Compaction::Reclaim {+ conn.execute_batch(+ "INSERT INTO observations_fts(observations_fts) VALUES('rebuild'); \+ INSERT INTO pages_fts(pages_fts) VALUES('rebuild'); \+ VACUUM;",+ )?;+ }++ Ok(PurgeSessionSummary {+ observations_deleted,+ handoffs_deleted,+ pages_deleted,+ auto_improve_runs_deleted,+ removed_paths,+ compacted: compaction == Compaction::Reclaim,+ })+}+pub fn purge_project(conn: &mut Connection,workspace_id: &WorkspaceId,@@ -3978,6 +4265,326 @@ pub(crate) mod tests {}}+ /// Seed a session with one observation and a derived page, return the ids.+ fn seed_session(+ conn: &mut Connection,+ ws: WorkspaceId,+ proj: ProjectId,+ marker: &str,+ ) -> (SessionId, PageId) {+ let sid = SessionId::new();+ let session = hook_session(sid, ws, proj, None);+ begin_session(conn, &session).unwrap();+ let mut obs = hook_observation(&session);+ obs.body = format!("obs-{marker}");+ insert_observation(conn, &obs).unwrap();+ let page_id = upsert_page(+ conn,+ &page(+ ws,+ proj,+ &format!("sessions/{marker}.md"),+ &format!("page-{marker}"),+ ),+ )+ .unwrap();+ end_session(conn, &sid, Some(&page_id)).unwrap();+ (sid, page_id)+ }++ fn count(conn: &Connection, sql: &str) -> i64 {+ conn.query_row(sql, [], |r| r.get(0)).unwrap()+ }++ /// #387, the reporter's reproduction: after purging one session by UUID,+ /// its rows are gone from every table that held them.+ #[test]+ fn purge_session_removes_the_session_and_everything_derived_from_it() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let (sid, _page) = seed_session(&mut conn, ws, proj, "target");++ let summary = purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();++ assert_eq!(+ count(&conn, "SELECT COUNT(*) FROM sessions"),+ 0,+ "sessions=0"+ );+ assert_eq!(+ count(&conn, "SELECT COUNT(*) FROM observations"),+ 0,+ "observations=0"+ );+ assert_eq!(count(&conn, "SELECT COUNT(*) FROM pages"), 0, "pages=0");+ assert_eq!(summary.observations_deleted, 1);+ assert_eq!(summary.pages_deleted, 1);+ assert_eq!(+ summary.removed_paths,+ vec!["sessions/target.md".to_string()]+ );+ }++ /// The blast radius must stop at the session. A sibling session in the+ /// same project keeps every row it owns.+ #[test]+ fn purge_session_leaves_a_sibling_session_in_the_same_project_intact() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let (target, _) = seed_session(&mut conn, ws, proj, "target");+ let (keep, keep_page) = seed_session(&mut conn, ws, proj, "keep");++ purge_session(&mut conn, ws, proj, target, None, Compaction::Skip).unwrap();++ assert_eq!(count(&conn, "SELECT COUNT(*) FROM sessions"), 1);+ let survivor: Vec<u8> = conn+ .query_row("SELECT id FROM sessions", [], |r| r.get(0))+ .unwrap();+ assert_eq!(survivor, keep.as_bytes().to_vec(), "the sibling survived");+ assert_eq!(count(&conn, "SELECT COUNT(*) FROM observations"), 1);+ let body: String = conn+ .query_row("SELECT body FROM observations", [], |r| r.get(0))+ .unwrap();+ assert_eq!(body, "obs-keep");+ let page_rows: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM pages WHERE id = ?1",+ [keep_page.as_bytes()],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(page_rows, 1, "the sibling's page survived");+ }++ /// A session id is not authority over another scope. Naming the wrong+ /// project must fail closed and delete nothing.+ #[test]+ fn purge_session_refuses_a_session_from_another_project_and_deletes_nothing() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let other = get_or_create_project(&mut conn, &ws, "other", None).unwrap();+ let (sid, _) = seed_session(&mut conn, ws, proj, "target");++ let err = purge_session(&mut conn, ws, other, sid, None, Compaction::Skip)+ .expect_err("a session outside the named project must not be purgeable");+ assert!(matches!(err, StoreError::NotFound(_)), "got {err:?}");++ assert_eq!(+ count(&conn, "SELECT COUNT(*) FROM sessions"),+ 1,+ "nothing deleted"+ );+ assert_eq!(count(&conn, "SELECT COUNT(*) FROM observations"), 1);+ assert_eq!(count(&conn, "SELECT COUNT(*) FROM pages"), 1);+ }++ /// Same containment across workspaces.+ #[test]+ fn purge_session_refuses_a_session_from_another_workspace() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let ws2 = get_or_create_workspace(&mut conn, "second").unwrap();+ let proj2 = get_or_create_project(&mut conn, &ws2, "scratch", None).unwrap();+ let (sid, _) = seed_session(&mut conn, ws, proj, "target");++ let err = purge_session(&mut conn, ws2, proj2, sid, None, Compaction::Skip)+ .expect_err("cross-workspace purge must be refused");+ assert!(matches!(err, StoreError::NotFound(_)));+ assert_eq!(count(&conn, "SELECT COUNT(*) FROM sessions"), 1);+ }++ /// Two projects can hold the same `sessions/<uuid>.md` path. Deleting by+ /// path would take the other one; deleting by id must not.+ #[test]+ fn purge_session_does_not_delete_an_identically_pathed_page_in_another_project() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let other = get_or_create_project(&mut conn, &ws, "other", None).unwrap();+ let (sid, _) = seed_session(&mut conn, ws, proj, "shared");+ let twin = upsert_page(+ &mut conn,+ &page(ws, other, "sessions/shared.md", "page-elsewhere"),+ )+ .unwrap();++ purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();++ let survived: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM pages WHERE id = ?1",+ [twin.as_bytes()],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(+ survived, 1,+ "a same-path page in another project must survive a purge by id"+ );+ }++ /// Accepting a handoff does not make its text yours. Purging the+ /// accepting session must not destroy the authoring session's record.+ #[test]+ fn purge_session_deletes_authored_handoffs_but_not_accepted_ones() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let (author, _) = seed_session(&mut conn, ws, proj, "author");+ let (accepter, _) = seed_session(&mut conn, ws, proj, "accepter");+ conn.execute(+ "INSERT INTO handoffs (id, workspace_id, project_id, from_session_id, from_agent, \+ summary, state, created_at, accepted_by_session) \+ VALUES (?1, ?2, ?3, ?4, 'codex', 'authored-by-author', 'accepted', 1, ?5)",+ rusqlite::params![+ &uuid::Uuid::now_v7().as_bytes()[..],+ ws.as_bytes(),+ proj.as_bytes(),+ author.as_bytes(),+ accepter.as_bytes()+ ],+ )+ .unwrap();++ let summary = purge_session(&mut conn, ws, proj, accepter, None, Compaction::Skip).unwrap();+ assert_eq!(summary.handoffs_deleted, 0, "accepting is not authorship");+ assert_eq!(+ count(&conn, "SELECT COUNT(*) FROM handoffs"),+ 1,+ "the authoring session's handoff survives"+ );++ let summary = purge_session(&mut conn, ws, proj, author, None, Compaction::Skip).unwrap();+ assert_eq!(+ summary.handoffs_deleted, 1,+ "the author's handoff is removed"+ );+ assert_eq!(count(&conn, "SELECT COUNT(*) FROM handoffs"), 0);+ }++ /// Purging a session that is already gone is NotFound, not a partial+ /// delete of whatever happens to match.+ #[test]+ fn purge_session_is_not_found_when_run_twice() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let (sid, _) = seed_session(&mut conn, ws, proj, "target");+ let (keep, _) = seed_session(&mut conn, ws, proj, "keep");++ purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();+ let err = purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip)+ .expect_err("already gone");+ assert!(matches!(err, StoreError::NotFound(_)));+ assert_eq!(+ count(&conn, "SELECT COUNT(*) FROM sessions"),+ 1,+ "the second call left the surviving session alone"+ );+ let _ = keep;+ }++ /// Pins the advertised boundary. A purged session is unreachable through+ /// the API and through search, but its bytes are still in the database+ /// file until a `rebuild` + `VACUUM` — exactly as they are for any other+ /// SQLite delete. #387 promises the former and explicitly not the latter,+ /// and this test fails if someone changes that without revisiting the+ /// claim we make to operators.+ #[test]+ fn purge_session_is_unsearchable_but_does_not_claim_byte_level_removal() {+ let (tmp, mut conn, ws, proj) = fresh_db();+ let db_path = tmp.path().join("test.sqlite");+ let (sid, _) = seed_session(&mut conn, ws, proj, "target");+ let (_keep, _) = seed_session(&mut conn, ws, proj, "keep");++ purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();++ let gone: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM observations_fts WHERE observations_fts MATCH '\"obs-target\"'",+ [],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(gone, 0, "the purged session is not searchable");+ let kept: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM observations_fts WHERE observations_fts MATCH '\"obs-keep\"'",+ [],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(kept, 1, "the sibling session is still searchable");++ conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);").ok();+ let bytes = std::fs::read(&db_path).unwrap();+ let still_on_disk = bytes.windows(10).any(|w| w == b"obs-target");+ assert!(+ still_on_disk,+ "documented boundary: purge is a logical delete. If this now fails, \+ byte-level removal was added and the #387 scope note, the CLI help \+ and the operator-facing docs all need updating to match."+ );+ }++ /// The opt-in half: `Compaction::Reclaim` must actually remove the bytes+ /// the default leaves behind. Paired with+ /// `purge_session_is_unsearchable_but_does_not_claim_byte_level_removal`,+ /// which asserts the opposite for the default, so the two together pin+ /// the difference between what we promise and what we offer.+ #[test]+ fn purge_session_with_reclaim_removes_the_bytes_from_the_file() {+ let (tmp, mut conn, ws, proj) = fresh_db();+ let db_path = tmp.path().join("test.sqlite");+ let (sid, _) = seed_session(&mut conn, ws, proj, "target");+ let (_keep, _) = seed_session(&mut conn, ws, proj, "keep");++ let summary = purge_session(&mut conn, ws, proj, sid, None, Compaction::Reclaim).unwrap();+ assert!(summary.compacted, "the summary reports that VACUUM ran");++ conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);").ok();+ let bytes = std::fs::read(&db_path).unwrap();+ assert!(+ !bytes.windows(10).any(|w| w == b"obs-target"),+ "Reclaim must remove the purged text from the database file"+ );+ assert!(+ bytes.windows(8).any(|w| w == b"obs-keep"),+ "the surviving session's text is untouched by the compaction"+ );+ }++ /// A purge must be terminal. The events that produced a session can sit+ /// undelivered in a client hook spool for days (#493 measured spools with+ /// thousands), so without a tombstone the next drain recreates the session+ /// row and the observations land again — silently undoing a deletion an+ /// application already reported to its user.+ #[test]+ fn a_purged_session_is_not_recreated_by_late_arriving_events() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let (sid, _) = seed_session(&mut conn, ws, proj, "target");+ purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();++ // Exactly what a spool drain delivers after the purge.+ let session = hook_session(sid, ws, proj, None);+ let err =+ begin_session(&mut conn, &session).expect_err("a purged session must not be recreated");+ assert!(matches!(err, StoreError::SessionPurged(_)), "got {err:?}");++ assert_eq!(+ count(&conn, "SELECT COUNT(*) FROM sessions"),+ 0,+ "still gone"+ );+ assert_eq!(count(&conn, "SELECT COUNT(*) FROM observations"), 0);+ }++ /// The tombstone is scoped: purging a session id in one project must not+ /// block ingest for the same id in another, or one purge could deny+ /// capture across the whole store.+ #[test]+ fn a_tombstone_does_not_block_the_same_session_id_in_another_project() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let other = get_or_create_project(&mut conn, &ws, "other", None).unwrap();+ let (sid, _) = seed_session(&mut conn, ws, proj, "target");+ purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();++ let elsewhere = hook_session(sid, ws, other, None);+ begin_session(&mut conn, &elsewhere)+ .expect("a purge in one project must not suppress ingest in another");+ assert_eq!(count(&conn, "SELECT COUNT(*) FROM sessions"), 1);+ }+fn session_end_observation(session: &NewSession) -> NewObservation {let mut observation = hook_observation(session);observation.kind = ObservationKind::SessionEnd;diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 3d778629..e2796f35 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -292,6 +292,18 @@ pub(crate) enum WriteCmd {force: bool,reply: oneshot::Sender<StoreResult<PurgeSummary>>,},+ /// Delete one session and everything derived from it, inside a single+ /// `(workspace, project)` scope. See [`ops::purge_session`].+ PurgeSession {+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ session_id: SessionId,+ /// Authenticated operator recorded in the `audit_log` row.+ author_id: Option<ai_memory_core::UserId>,+ /// Whether to reclaim the freed bytes afterwards (`VACUUM`).+ compaction: crate::ops::Compaction,+ reply: oneshot::Sender<StoreResult<crate::ops::PurgeSessionSummary>>,+ },/// Delete a workspace row (its `workspace_id` FKs cascade projects/pages//// sessions/…). Refused when non-empty unless `force`.DeleteWorkspace {@@ -1217,6 +1229,38 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Delete one session by id, with everything derived from it, inside a+ /// single `(workspace, project)` scope.+ ///+ /// Scope is enforced in the store: a session that does not belong to the+ /// named workspace and project is [`StoreError::NotFound`] and nothing is+ /// deleted. See [`ops::purge_session`] for what is and is not removed —+ /// in particular, handoffs this session *accepted* are left alone.+ ///+ /// # Errors+ /// [`StoreError::NotFound`] when the session is absent from that scope,+ /// [`StoreError::WriterClosed`], or a propagated SQL error.+ pub async fn purge_session(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ session_id: SessionId,+ author_id: Option<ai_memory_core::UserId>,+ compaction: crate::ops::Compaction,+ ) -> StoreResult<crate::ops::PurgeSessionSummary> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::PurgeSession {+ workspace_id,+ project_id,+ session_id,+ author_id,+ compaction,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+/// Delete a workspace and, via the `workspace_id` cascade, every project //// page / session under it. Refuses a non-empty workspace unless `force`.///@@ -2211,6 +2255,24 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {);send_or_warn(reply, result, "purge_project");}+ WriteCmd::PurgeSession {+ workspace_id,+ project_id,+ session_id,+ author_id,+ compaction,+ reply,+ } => {+ let result = ops::purge_session(+ &mut conn,+ workspace_id,+ project_id,+ session_id,+ author_id,+ compaction,+ );+ send_or_warn(reply, result, "purge_session");+ }WriteCmd::DeleteWorkspace {workspace_id,force,diff --git a/crates/ai-memory-wiki/src/admission.rs b/crates/ai-memory-wiki/src/admission.rsindex 3adf11ac..45e1ef0f 100644--- a/crates/ai-memory-wiki/src/admission.rs+++ b/crates/ai-memory-wiki/src/admission.rs@@ -56,6 +56,13 @@ pub enum AdmissionOp {/// `remove_dir_all`). Carries the project (ctx), no page path. Lets a/// mirror remove the project's directory.PurgeProject,+ /// One session is being purged (`purge_session`): its rows, the handoffs+ /// it authored, and its `sessions/<id>.md` page and every version of it.+ /// Carries the workspace/project; no page path, since the operation is+ /// driven by session id rather than by path. Lets a mirror drop the+ /// session page file, and lets a scope-guard webhook refuse the delete+ /// before any row is touched.+ PurgeSession,/// A whole workspace is being purged. Carries the workspace (ctx), no page/// path, and an empty project. Lets a mirror remove the workspace tree.PurgeWorkspace,@@ -92,6 +99,7 @@ impl AdmissionOp {AdmissionOp::Consolidate => "consolidate",AdmissionOp::Delete => "delete",AdmissionOp::PurgeProject => "purge_project",+ AdmissionOp::PurgeSession => "purge_session",AdmissionOp::PurgeWorkspace => "purge_workspace",AdmissionOp::MoveProject => "move_project",AdmissionOp::MoveSession => "move_session",diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex be46fc0c..3a03aa80 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -893,6 +893,30 @@ impl Wiki {}}+ /// Run the admission chain for a single-session purge, before any row is+ /// deleted, so a scope-guard webhook can refuse it while the data is+ /// still intact.+ ///+ /// # Errors+ /// Propagates a webhook rejection as [`WikiError`].+ pub async fn admit_purge_session(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ admission_ctx: Option<AdmissionContext>,+ ) -> WikiResult<Option<AdmissionContext>> {+ if let Some(chain) = &self.admission_chain {+ let mut ctx = admission_ctx.unwrap_or_default();+ ctx.op = AdmissionOp::PurgeSession;+ self.resolve_admission_names(workspace_id, project_id, &mut ctx)+ .await;+ chain.notify(None, &ctx).await?;+ Ok(Some(ctx))+ } else {+ Ok(None)+ }+ }+/// Run the blocking admission notification for a workspace purge without/// removing files. Admin callers use this before the DB purge so a/// `failure_policy = reject` webhook can still abort all destructive work.diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex cd997219..364f5daf 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -456,7 +456,7 @@ setup-agent bootstrap install-instructionsinstall-skills reorg purge-projectrename-project move-project move-sessionuninstall auth user-completions handoffs+completions handoffs purge-session```Run `ai-memory --help` for the full tree.diff --git a/docs/admission-webhooks.md b/docs/admission-webhooks.mdindex 51e77d29..a2e1cd27 100644--- a/docs/admission-webhooks.md+++ b/docs/admission-webhooks.md@@ -61,6 +61,11 @@ Webhooks fire on these `op` values today (extensible enum):`remove_dir_all`, routed from `/admin/purge-project`). Carries theproject in `ctx`, **no** page path; fired before the directory isremoved so a mirror can drop the project.+- `purge_session` — one session is purged (routed from+ `/admin/purge-session`). Carries the workspace/project in `ctx`, **no** page+ path — the operation is driven by session id rather than by path. Fired+ before any row is deleted, so a `reject`-policy webhook can refuse the purge+ while the session's data is still intact.- `purge_workspace` — a whole workspace is purged (routed from`/admin/delete-workspace`). Carries the workspace in `ctx.workspace`, leaves`ctx.project` empty, and has **no** page path; fired before SQL/filediff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex 71d4b15e..0b1f7b7f 100644--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@ -9,6 +9,7 @@ on a homelab box where mistakes are harder to undo.| Command | Safe with server **running**? | Wipes data? | Reversible? | Notes ||---|---|---|---|---|| `purge-project --confirm` | ✅ yes | the one project's data | no | Deletes the UUID-namespaced wiki root and raw workstream segments; sibling projects remain untouched. Refuses with `409` while a managed workstream under the project holds a live run lease — `--force` overrides. |+| `purge-session --session-id --confirm` | ✅ yes | the one session's data | no | Deletes one session by UUID: its row, its observations, the handoffs it **authored**, its `sessions/<id>.md` page and every superseded version, their embeddings, and its auto-improve runs. Strictly scoped — a session that does not belong to the named workspace/project is a `404` and nothing is deleted. Handoffs the session only *accepted* are kept: that text belongs to the session that wrote it. Logical delete by default; `--compact` additionally rebuilds the FTS indexes and `VACUUM`s (see below). || `rename-project --from --to` | ✅ yes | no | yes (rename back) | Column-only update on `projects.name`. The on-disk dir is keyed by `project_id` (UUID), so the rename never moves a file. || `/admin/rename-workspace` | ✅ yes | no | yes (rename back) | Column-only update on `workspaces.name`; refreshes `_meta.md` scope manifests and checkpoints the wiki tree. || `/admin/delete-workspace` | ✅ yes | the workspace and every child project | no | Runs `purge_workspace` admission first, deletes SQLite rows in one cascade, removes the UUID-keyed workspace directory and managed-workstream raw segments, reports filesystem partial failures, and dispatches mirror notification after durable work. |@@ -26,6 +27,55 @@ State-touching commands route through the HTTP admin API except `reset`,fundamentally cannot run while another process holds the SQLite WAL writer. See[CLAUDE.md §16](../CLAUDE.md) for the invariant.++## `purge-session` and what "deleted" means++`purge-session` answers *"forget this conversation"*: after it runs, the+session is gone from the API, from `status` counts and from search.++```bash+ai-memory purge-session \+ --workspace default --project my-app \+ --session-id 0199f3d2-1c4e-7a10-9f3b-2b0c5d8e7a11 \+ --confirm+```++It is a **logical delete**, and the distinction matters if you are answering a+regulatory erasure request rather than tidying up:++| | default | `--compact` |+|---|---|---|+| Reachable through the API / MCP tools | no | no |+| Returned by search (FTS) | no | no |+| Bytes still present in `memory.sqlite` | **yes**, in free pages | no |+| Text still in the wiki git history | **yes** | **yes** |+| Present in backups taken before the purge | **yes** | **yes** |+| Cost | one transaction | rewrites the whole database |++`--compact` rebuilds the affected FTS5 indexes — an ordinary delete leaves the+tokens inside the index segments, which is why a rebuild rather than a+`VACUUM` alone is what clears them — and then `VACUUM`s to release the freed+pages. It needs free disk space of roughly the database's own size and takes+minutes on a large store, which is why it is opt-in.++**`--compact` is not forensic erasure.** The wiki git repository stores page+content in its objects *and its commit messages*, and any backup taken before+the purge still contains everything. Removing the bytes from the live SQLite+file is worth doing on its own terms; do not describe it to a user as a+guarantee that the content is unrecoverable, because it is not.++### Scope containment++The session id is never authority on its own. Every statement is filtered on+`workspace_id` and `project_id` as well as `session_id`, the session must+belong to the named scope or the call is a `404` with nothing deleted, and the+derived pages are deleted by **id** rather than by path — two projects can+hold the same `sessions/<uuid>.md`, and deleting by path would take the other+one with it. `/admin/purge-session` runs the admission chain before any row is+touched, so a `failure_policy = reject` webhook can still abort the whole+operation while the data is intact.++## What "project isolation" means hereEvery project's data lives under an isolated, UUID-keyed root on disk: