Skip to content

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

Rust

fix(purge-session): remove the session's wiki page file after the DB purge (#653)

gba720a5316b37
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a050f732..cc834fdf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
28s to 19s on a 32-thread Windows box.
### Fixed
+- Fixed `purge-session` leaving the live `sessions/<id>.md` wiki file behind
+ after deleting the session's SQLite rows. The admin endpoint now removes the
+ scoped page file after the DB purge commits, reports actual cleanup through
+ `files_deleted` / `files_failed`, and marks `purge_session` observer webhooks
+ with `partial_failure: true` when file cleanup fails, so a later wiki reindex
+ cannot resurrect the purged session. (#653)
- Authentication-disabled HTTP servers now ignore stale or unexpected Bearer
headers and preserve anonymous access. Previously, a client retaining an old
`AI_MEMORY_AUTH_TOKEN` received `401 Unauthorized` even though the server
diff --git a/crates/ai-memory-cli/src/commands/purge_session.rs b/crates/ai-memory-cli/src/commands/purge_session.rs
index 165ac4ac..8517031b 100644
--- a/crates/ai-memory-cli/src/commands/purge_session.rs
+++ b/crates/ai-memory-cli/src/commands/purge_session.rs
@@ -81,7 +81,7 @@ pub async fn run(config: &Config, args: PurgeSessionArgs) -> Result<()> {
n("pages_deleted"),
n("auto_improve_runs_deleted"),
);
- if let Some(paths) = report["removed_paths"].as_array()
+ if let Some(paths) = report["files_deleted"].as_array()
&& !paths.is_empty()
{
println!("Wiki pages removed:");
@@ -89,6 +89,17 @@ pub async fn run(config: &Config, args: PurgeSessionArgs) -> Result<()> {
println!(" - {path}");
}
}
+ if let Some(failed) = report["files_failed"].as_array()
+ && !failed.is_empty()
+ {
+ println!(
+ "Warning: {} wiki page file(s) could not be removed from disk (DB rows are gone).",
+ failed.len()
+ );
+ for path in failed.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 {
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index c7e8b116..5099509e 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -3559,6 +3559,71 @@ struct PurgeSessionRequest {
compact: bool,
}
+/// Wire-format summary returned by `POST /admin/purge-session`.
+#[derive(Debug, Serialize)]
+pub struct PurgeSessionReport {
+ /// Session id that was purged.
+ pub session_id: String,
+ /// Human workspace name.
+ pub workspace: String,
+ /// Human project name.
+ pub project: String,
+ /// Number of observations deleted.
+ pub observations_deleted: u64,
+ /// Number of authored handoffs deleted.
+ pub handoffs_deleted: u64,
+ /// Number of page rows deleted, counting superseded versions.
+ pub pages_deleted: u64,
+ /// Number of auto-improvement runs deleted.
+ pub auto_improve_runs_deleted: u64,
+ /// Distinct wiki page paths whose database rows were deleted.
+ pub removed_paths: Vec<PagePath>,
+ /// Distinct wiki page paths removed from disk after the database purge.
+ pub files_deleted: Vec<PagePath>,
+ /// Distinct wiki page paths that could not be removed from disk.
+ pub files_failed: Vec<PagePath>,
+ /// Whether the freed bytes were reclaimed (`VACUUM` ran).
+ pub compacted: bool,
+ /// Pre-purge checkpoint, if the tree had uncommitted changes.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub pre_checkpoint: Option<String>,
+ /// Post-purge checkpoint, if the purge changed the tree.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub checkpoint: Option<String>,
+}
+
+async fn remove_purged_session_storage(
+ state: &AdminState,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ removed_paths: &[PagePath],
+) -> (Vec<PagePath>, Vec<PagePath>) {
+ let mut files_deleted = Vec::with_capacity(removed_paths.len());
+ let mut files_failed = Vec::new();
+
+ for path in removed_paths {
+ match state
+ .wiki
+ .remove_page_file(workspace_id, project_id, path)
+ .await
+ {
+ Ok(true) => files_deleted.push(path.clone()),
+ Ok(false) => {}
+ Err(error) => {
+ warn!(
+ operation = "purge-session",
+ path = path.as_str(),
+ error = %error,
+ "session purge failed to remove wiki page file"
+ );
+ files_failed.push(path.clone());
+ }
+ }
+ }
+
+ (files_deleted, files_failed)
+}
+
/// `POST /admin/purge-session` — delete one session and everything derived
/// from it, inside a single workspace/project scope.
async fn handle_purge_session(
@@ -3605,13 +3670,21 @@ async fn handle_purge_session(
actor,
..Default::default()
};
- if let Err(e) = state
+ let mut dispatch_ctx = match state
.wiki
.admit_purge_session(ws_id, proj_id, Some(ctx))
.await
{
- return internal_err(e.to_string());
- }
+ Ok(ctx) => ctx,
+ Err(e) => return internal_err(e.to_string()),
+ };
+
+ let label = format!("{}/{}: {}", req.workspace, req.project, session_id);
+ let pre_checkpoint = match checkpoint_or_500(&state.wiki, format!("pre-purge-session {label}"))
+ {
+ Ok(oid) => oid,
+ Err(e) => return e,
+ };
let compaction = if req.compact {
ai_memory_store::Compaction::Reclaim
@@ -3635,20 +3708,34 @@ async fn handle_purge_session(
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,
- })),
- )
+ let (files_deleted, files_failed) =
+ remove_purged_session_storage(&state, ws_id, proj_id, &summary.removed_paths).await;
+ if !files_failed.is_empty()
+ && let Some(ref mut ctx) = dispatch_ctx
+ {
+ ctx.partial_failure = true;
+ }
+ state.wiki.dispatch_purge(dispatch_ctx.as_ref());
+
+ let checkpoint = checkpoint_or_warn(&state.wiki, format!("purge-session {label}"));
+
+ let report = PurgeSessionReport {
+ 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,
+ files_deleted,
+ files_failed,
+ compacted: summary.compacted,
+ pre_checkpoint,
+ checkpoint,
+ };
+
+ (StatusCode::OK, Json(json_or_empty(&report)))
}
// ---------------------------------------------------------------------
@@ -3888,7 +3975,7 @@ async fn handle_purge_project(
{
c.partial_failure = true;
}
- state.wiki.dispatch_purge_project(dispatch_ctx.as_ref());
+ state.wiki.dispatch_purge(dispatch_ctx.as_ref());
state.active_project.clear_project(proj_id);
invalidate_scope_cache(&state, ScopeInvalidation::Project(proj_id)).await;
@@ -4217,7 +4304,7 @@ async fn delete_workspace_core(
{
c.partial_failure = true;
}
- state.wiki.dispatch_purge_workspace(dispatch_ctx.as_ref());
+ state.wiki.dispatch_purge(dispatch_ctx.as_ref());
state.active_project.clear_workspace(ws_id);
invalidate_scope_cache(state, ScopeInvalidation::Workspace(ws_id)).await;
@@ -6111,7 +6198,7 @@ async fn copy_purge_merge(
{
c.partial_failure = true;
}
- state.wiki.dispatch_purge_project(dispatch_ctx.as_ref());
+ state.wiki.dispatch_purge(dispatch_ctx.as_ref());
// The source project_id was just purged; if it was the published active
// project, the pointer now dangles — clear it so the next hook re-resolves
diff --git a/crates/ai-memory-mcp/tests/suite/admin_move.rs b/crates/ai-memory-mcp/tests/suite/admin_move.rs
index 74be331b..0e504b67 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_move.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_move.rs
@@ -13,7 +13,7 @@
//! both versions survive), then purge the source — there the episodic rows
//! (sessions/observations/handoffs) are dropped by the purge.
-use super::common::post;
+use super::common::{post, spawn_capture_hook};
use ai_memory_core::{AgentKind, PagePath, Sanitized, Sanitizer, Tier};
use ai_memory_mcp::AdminState;
use ai_memory_store::{DecayParams, PrepareWorkstreamRun, Store, WorkstreamSelection};
@@ -2185,24 +2185,7 @@ async fn delete_workspace_reject_policy_aborts_before_db_or_disk_destruction() {
#[tokio::test]
async fn delete_workspace_reports_partial_disk_failure_and_dispatches_notification() {
- let (tx, rx) = tokio::sync::oneshot::channel::<serde_json::Value>();
- let tx = Arc::new(Mutex::new(Some(tx)));
- let tx_for_route = tx.clone();
- let app = Router::new().route(
- "/hook",
- axum_post(move |Json(payload): Json<serde_json::Value>| {
- let tx_for_route = tx_for_route.clone();
- async move {
- if let Some(tx) = tx_for_route.lock().unwrap().take() {
- let _ = tx.send(payload);
- }
- StatusCode::NO_CONTENT
- }
- }),
- );
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let url = format!("http://{}/hook", listener.local_addr().unwrap());
- tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ let (url, rx) = spawn_capture_hook().await;
let tmp = TempDir::new().unwrap();
let chain = AdmissionChain::new(vec![WebhookConfig {
diff --git a/crates/ai-memory-mcp/tests/suite/admin_purge.rs b/crates/ai-memory-mcp/tests/suite/admin_purge.rs
index be4c600a..b4a2f511 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_purge.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_purge.rs
@@ -1,13 +1,13 @@
-//! Integration tests for `POST /admin/purge-project`.
+//! Integration tests for destructive admin purge endpoints.
//!
//! 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 super::common::post;
+use super::common::{get, post, spawn_capture_hook};
use ai_memory_core::{
- AgentKind, NewHandoff, NewObservation, NewSession, ObservationKind, PagePath, ProjectId,
- Sanitized, Sanitizer, SessionId, Tier, WorkspaceId,
+ ActorContext, AgentKind, NewHandoff, NewObservation, NewSession, ObservationKind, PagePath,
+ ProjectId, Sanitized, Sanitizer, SessionId, Tier, WorkspaceId,
};
use ai_memory_mcp::AdminState;
use ai_memory_store::{DecayParams, PrepareWorkstreamRun, Store, WorkstreamSelection};
@@ -18,7 +18,7 @@ use axum::Router;
use axum::http::StatusCode;
use axum::routing::post as route_post;
use serde_json::json;
-use std::path::Path;
+use std::path::{Path, PathBuf};
use tempfile::TempDir;
// ---------------------------------------------------------------------------
@@ -26,8 +26,18 @@ use tempfile::TempDir;
// ---------------------------------------------------------------------------
async fn make_state(tmp: &TempDir) -> (AdminState, Store) {
+ make_state_with_chain(tmp, None).await
+}
+
+async fn make_state_with_chain(
+ tmp: &TempDir,
+ chain: Option<AdmissionChain>,
+) -> (AdminState, Store) {
let store = Store::open(tmp.path()).unwrap();
- let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let mut wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ if let Some(chain) = chain {
+ wiki = wiki.with_admission_chain(chain);
+ }
let db_path = store.db_path().to_path_buf();
let state = AdminState {
ingest_metrics: std::sync::Arc::new(ai_memory_core::IngestMetrics::default()),
@@ -60,6 +70,83 @@ async fn body_json(resp: axum::response::Response) -> serde_json::Value {
serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null)
}
+async fn post_purge_session(
+ state: AdminState,
+ workspace: &str,
+ project: &str,
+ session_id: SessionId,
+) -> axum::response::Response {
+ post(
+ state,
+ "/admin/purge-session",
+ json!({
+ "workspace": workspace,
+ "project": project,
+ "session_id": session_id.to_string(),
+ "confirm": true,
+ }),
+ )
+ .await
+}
+
+async fn seed_ended_session_summary(
+ store: &Store,
+ wiki: &Wiki,
+ workspace: &str,
+ project: &str,
+ session_id: SessionId,
+ body: &str,
+) -> (WorkspaceId, ProjectId, PagePath, PathBuf) {
+ let ws = store
+ .writer
+ .get_or_create_workspace(workspace)
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, project, None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: session_id,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: AgentKind::Codex,
+ cwd: None,
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+
+ let page_path = PagePath::new(format!("sessions/{session_id}.md")).unwrap();
+ let page_id = wiki
+ .write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: page_path.clone(),
+ frontmatter: json!({"title": "Session summary"}),
+ body: body.into(),
+ tier: Tier::Episodic,
+ pinned: false,
+ title: Some("Session summary".into()),
+ admission_ctx: None,
+ author_id: None,
+ actor: ActorContext::anonymous(),
+ })
+ .await
+ .unwrap();
+ store
+ .writer
+ .end_session(session_id, Some(page_id))
+ .await
+ .unwrap();
+
+ let summary_file = wiki.abs_path(ws, proj, &page_path);
+ (ws, proj, page_path, summary_file)
+}
+
/// Seed two projects (`default/keep` and `default/doomed`), each with one
/// page, one session, some observations, and a handoff. Returns IDs for
/// both projects so callers can construct the per-project wiki paths.
@@ -177,6 +264,163 @@ async fn seed_two_projects(store: &Store, wiki: &Wiki) -> (WorkspaceId, ProjectI
// Tests
// ---------------------------------------------------------------------------
+#[tokio::test]
+async fn purge_session_removes_session_summary_file_from_disk() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let session_id = SessionId::new();
+ let (_ws, _proj, page_path, summary_file) = seed_ended_session_summary(
+ &store,
+ &state.wiki,
+ "default",
+ "audit",
+ session_id,
+ "session summary body",
+ )
+ .await;
+
+ assert!(summary_file.exists(), "setup must create the summary file");
+
+ let resp = post_purge_session(state.clone(), "default", "audit", session_id).await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["removed_paths"], json!([page_path.as_str()]));
+ assert_eq!(body["files_deleted"], json!([page_path.as_str()]));
+ assert_eq!(body["files_failed"], json!([]));
+ assert!(
+ !summary_file.exists(),
+ "purge-session must remove the wiki source file, not only DB rows"
+ );
+
+ let read = get(
+ state,
+ &format!(
+ "/admin/read-page?workspace=default&project=audit&path={}",
+ page_path.as_str()
+ ),
+ )
+ .await;
+ assert_eq!(
+ read.status(),
+ StatusCode::NOT_FOUND,
+ "a purged session page must not remain readable from disk"
+ );
+}
+
+#[tokio::test]
+async fn purge_session_keeps_same_path_in_sibling_project() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let session_id = SessionId::new();
+ let (ws, _target, page_path, target_file) = seed_ended_session_summary(
+ &store,
+ &state.wiki,
+ "default",
+ "audit",
+ session_id,
+ "target session summary",
+ )
+ .await;
+ let sibling = store
+ .writer
+ .get_or_create_project(ws, "keep", None)
+ .await
+ .unwrap();
+ state
+ .wiki
+ .write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: sibling,
+ path: page_path.clone(),
+ frontmatter: json!({"title": "Sibling summary"}),
+ body: "sibling session summary".into(),
+ tier: Tier::Episodic,
+ pinned: false,
+ title: Some("Sibling summary".into()),
+ admission_ctx: None,
+ author_id: None,
+ actor: ActorContext::anonymous(),
+ })
+ .await
+ .unwrap();
+ let sibling_file = state.wiki.abs_path(ws, sibling, &page_path);
+ assert!(target_file.exists(), "setup must create target file");
+ assert!(sibling_file.exists(), "setup must create sibling file");
+
+ let resp = post_purge_session(state.clone(), "default", "audit", session_id).await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ assert!(!target_file.exists(), "target session file must be removed");
+ assert!(
+ sibling_file.exists(),
+ "same relative path in a sibling project must survive"
+ );
+
+ let read = get(
+ state,
+ &format!(
+ "/admin/read-page?workspace=default&project=keep&path={}",
+ page_path.as_str()
+ ),
+ )
+ .await;
+ assert_eq!(
+ read.status(),
+ StatusCode::OK,
+ "sibling project page must remain readable"
+ );
+}
+
+/// The SQL purge must commit even when the page file cannot be removed, and
+/// async `purge_session` observers must learn that the disk still holds it.
+#[tokio::test]
+async fn purge_session_reports_file_cleanup_failure_after_db_commit() {
+ let (url, rx) = spawn_capture_hook().await;
+
+ let tmp = TempDir::new().unwrap();
+ let chain = AdmissionChain::new(vec![WebhookConfig {
+ name: "async-mirror".into(),
+ url,
+ timeout_ms: 2_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::PurgeSession],
+ blocking: false,
+ }])
+ .unwrap();
+ let (state, store) = make_state_with_chain(&tmp, Some(chain)).await;
+ let session_id = SessionId::new();
+ let (_ws, _proj, page_path, summary_file) = seed_ended_session_summary(
+ &store,
+ &state.wiki,
+ "default",
+ "audit",
+ session_id,
+ "session summary body",
+ )
+ .await;
+ std::fs::remove_file(&summary_file).unwrap();
+ std::fs::create_dir(&summary_file).unwrap();
+
+ let resp = post_purge_session(state, "default", "audit", session_id).await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["removed_paths"], json!([page_path.as_str()]));
+ assert_eq!(body["files_deleted"], json!([]));
+ assert_eq!(body["files_failed"], json!([page_path.as_str()]));
+ assert!(
+ summary_file.is_dir(),
+ "failed cleanup must be reported without pretending the file path was removed"
+ );
+
+ let payload = tokio::time::timeout(std::time::Duration::from_secs(2), rx)
+ .await
+ .expect("async purge_session dispatch should fire")
+ .unwrap();
+ assert_eq!(payload["ctx"]["op"], "purge_session");
+ assert_eq!(payload["ctx"]["workspace"], "default");
+ assert_eq!(payload["ctx"]["project"], "audit");
+ assert_eq!(payload["ctx"]["partial_failure"], true);
+}
+
/// Missing `confirm: true` must return 400.
#[tokio::test]
async fn purge_project_without_confirm_returns_400() {
diff --git a/crates/ai-memory-mcp/tests/suite/common.rs b/crates/ai-memory-mcp/tests/suite/common.rs
index a48ea594..8260fc36 100644
--- a/crates/ai-memory-mcp/tests/suite/common.rs
+++ b/crates/ai-memory-mcp/tests/suite/common.rs
@@ -2,7 +2,10 @@
use ai_memory_mcp::{AdminState, admin_router};
use axum::body::Body;
-use axum::http::Request;
+use axum::http::{Request, StatusCode};
+use axum::routing::post as route_post;
+use axum::{Json, Router};
+use std::sync::{Arc, Mutex};
use tower::ServiceExt;
/// POST a JSON body to `uri` through a fresh admin router built from `state`.
@@ -31,3 +34,27 @@ pub async fn get(state: AdminState, uri: &str) -> axum::response::Response {
.unwrap();
router.oneshot(req).await.unwrap()
}
+
+/// Spawn a one-shot webhook sink on a free loopback port. Returns its URL
+/// and a receiver that yields the first JSON payload POSTed to it, so a test
+/// can observe what a non-blocking admission webhook was sent.
+pub async fn spawn_capture_hook() -> (String, tokio::sync::oneshot::Receiver<serde_json::Value>) {
+ let (tx, rx) = tokio::sync::oneshot::channel::<serde_json::Value>();
+ let tx = Arc::new(Mutex::new(Some(tx)));
+ let app = Router::new().route(
+ "/hook",
+ route_post(move |Json(payload): Json<serde_json::Value>| {
+ let tx = tx.clone();
+ async move {
+ if let Some(tx) = tx.lock().unwrap().take() {
+ let _ = tx.send(payload);
+ }
+ StatusCode::NO_CONTENT
+ }
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}/hook", listener.local_addr().unwrap());
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ (url, rx)
+}
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 01fd8bd7..ab9480ca 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -3385,7 +3385,7 @@ pub struct PurgeSessionSummary {
/// `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>,
+ pub removed_paths: Vec<PagePath>,
/// Whether the freed bytes were reclaimed (`VACUUM` ran).
pub compacted: bool,
}
@@ -3472,7 +3472,7 @@ pub fn purge_session(
.collect::<rusqlite::Result<Vec<_>>>()?
};
- let removed_paths: Vec<String> = if page_ids.is_empty() {
+ let removed_paths: Vec<PagePath> = if page_ids.is_empty() {
Vec::new()
} else {
let mut stmt = tx.prepare(
@@ -3486,10 +3486,11 @@ pub fn purge_session(
row.get(0)
})
.optional()?;
- if let Some(path) = found
- && !paths.contains(&path)
- {
- paths.push(path);
+ if let Some(path) = found {
+ let path = PagePath::new(path)?;
+ if !paths.contains(&path) {
+ paths.push(path);
+ }
}
}
paths
@@ -5308,7 +5309,7 @@ pub(crate) mod tests {
assert_eq!(summary.pages_deleted, 1);
assert_eq!(
summary.removed_paths,
- vec!["sessions/target.md".to_string()]
+ vec![PagePath::new("sessions/target.md").unwrap()]
);
}
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index 624e7ca0..8a4006bd 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -961,7 +961,7 @@ impl Wiki {
.admit_purge_project(workspace_id, project_id, admission_ctx)
.await?;
self.remove_project_dir(workspace_id, project_id).await?;
- self.dispatch_purge_project(ctx.as_ref());
+ self.dispatch_purge(ctx.as_ref());
Ok(())
}
@@ -1171,17 +1171,36 @@ impl Wiki {
}
}
- /// Dispatch non-blocking purge webhooks after the caller's purge has
- /// completed its durable DB/filesystem work.
- pub fn dispatch_purge_project(&self, admission_ctx: Option<&AdmissionContext>) {
- if let (Some(chain), Some(ctx)) = (&self.admission_chain, admission_ctx) {
- chain.dispatch_async(None, &serde_json::Value::Null, "", ctx);
+ /// Remove one on-disk page file without touching the store.
+ ///
+ /// Used after a scoped store purge has already deleted the authoritative
+ /// rows and returned the affected paths. A missing file is treated as
+ /// already removed; any other filesystem error is reported to the caller.
+ ///
+ /// # Errors
+ /// Returns [`WikiError::Io`] on filesystem errors other than NotFound.
+ pub async fn remove_page_file(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ path: &PagePath,
+ ) -> WikiResult<bool> {
+ let _guard = self.mutation_lock.write().await;
+ let abs = self.abs_path(workspace_id, project_id, path);
+ match std::fs::remove_file(&abs) {
+ Ok(()) => {
+ sync_parent_best_effort(&abs);
+ Ok(true)
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
+ Err(e) => Err(crate::WikiError::Io(e)),
}
}
- /// Dispatch non-blocking purge-workspace webhooks after the caller's purge
- /// has completed its durable DB/filesystem work.
- pub fn dispatch_purge_workspace(&self, admission_ctx: Option<&AdmissionContext>) {
+ /// Dispatch non-blocking purge webhooks after the caller's purge has
+ /// completed its durable DB/filesystem work. The purge kind (project,
+ /// session, workspace) travels in `ctx.op`, set by the matching `admit_*`.
+ pub fn dispatch_purge(&self, admission_ctx: Option<&AdmissionContext>) {
if let (Some(chain), Some(ctx)) = (&self.admission_chain, admission_ctx) {
chain.dispatch_async(None, &serde_json::Value::Null, "", ctx);
}
diff --git a/docs/admission-webhooks.md b/docs/admission-webhooks.md
index a2e1cd27..81f9a131 100644
--- a/docs/admission-webhooks.md
+++ b/docs/admission-webhooks.md
@@ -65,7 +65,8 @@ Webhooks fire on these `op` values today (extensible enum):
`/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.
+ while the session's data is still intact. Non-blocking observers are
+ dispatched again after the SQL purge and page-file cleanup are durable.
- `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/file
@@ -153,6 +154,10 @@ when the source is torn down. The `purge_project` event carries
`partial_failure: true` if the SQL purge committed but the on-disk
dir removal failed afterwards.
+`/admin/purge-session` emits `purge_session`. Its final async observer
+notification carries `partial_failure: true` if the SQL purge committed but
+the session page file could not be removed afterwards.
+
`/admin/delete-workspace` emits `purge_workspace`. Its final async observer
notification carries `partial_failure: true` if the SQL workspace cascade
committed but `<wiki_root>/<workspace_id>` could not be removed.
@@ -220,11 +225,11 @@ the list, not a second header.)
"client": "72836f52-...", // DCR client UUID
"session_id": "019e6d-..."
},
- "op": "write_page", // write_page | consolidate | delete | purge_project | purge_workspace | move_project | move_session
- "partial_failure": true // purge_project/purge_workspace only, and ONLY when set
+ "op": "write_page", // write_page | consolidate | delete | purge_project | purge_session | purge_workspace | move_project | move_session
+ "partial_failure": true // purge_project/purge_session/purge_workspace only, and ONLY when set
// (skipped on the wire when false).
// true → the DB rows were purged but
- // `remove_project_dir` failed afterwards;
+ // filesystem cleanup failed afterwards;
// a filesystem-tracking mirror (git push)
// should refuse to drop its own copy.
}
diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.md
index 8e2921aa..a800b7da 100644
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@ -48,6 +48,7 @@ regulatory erasure request rather than tidying up:
|---|---|---|
| Reachable through the API / MCP tools | no | no |
| Returned by search (FTS) | no | no |
+| Live wiki Markdown file | no, best-effort | no, best-effort |
| 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** |
@@ -97,7 +98,12 @@ 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.
+operation while the data is intact. After the SQL transaction commits, the
+server removes only the returned page paths under that same UUID-keyed project
+root; the response keeps `removed_paths` for the logical DB purge and reports
+actual cleanup in `files_deleted` / `files_failed`. If filesystem removal fails,
+the DB purge is not rolled back, the call still returns 200 with `files_failed`
+populated, and async `purge_session` observers receive `partial_failure: true`.
## What "project isolation" means here