Skip to content

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

Rust

feat(admin): delete-workspace previews what it would delete before confirm

Maxsuel Einstein344ea37fc187
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84aada7a..f97e9797 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -264,6 +264,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
*other* projects through this session's own id. The CLI still exits
non-zero without `--confirm`; against an older server, or if the preview
times out, it prints only the existing refusal. (#957)
+- `POST /admin/delete-workspace` takes a `dry_run` field that always wins
+ over `force` and previews what a confirmed delete would remove, with the
+ same 404/409 a confirmed delete gives. It only counts: no admission call,
+ directory removal, mirror dispatch or checkpoint. The preview and the
+ confirmed response now also report `sessions_deleted`,
+ `observations_deleted`, `handoffs_deleted` and `embeddings_deleted`
+ (previously only projects, pages, workstreams and managed runs), plus
+ `collateral_observations_deleted` and `collateral_handoffs_denulled` for
+ rows in *other* workspaces reached through this workspace's sessions.
+ `merge-workspace` is unaffected. There is no CLI subcommand, so this is
+ HTTP-only. (#963)
- `ai-memory purge-project` without `--confirm` now previews what a confirmed
purge would delete before refusing: `Would purge <ws>/<proj>: N pages, N
sessions, N observations, …`, with the same 404/409 a real purge gives.
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 36739cdf..5578c615 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -4752,6 +4752,16 @@ struct DeleteWorkspaceRequest {
/// the cost and for what it does not guarantee.
#[serde(default)]
compact: bool,
+ /// Preview only: report the counts a delete of this workspace would
+ /// produce without deleting anything. Wins over `force` in the sense
+ /// that matters — `{"force": true, "dry_run": true}` still only
+ /// previews, exactly like `purge-project` treats its own `dry_run` field,
+ /// so a preview request can never accidentally become destructive.
+ /// `#[serde(default)]` here is what keeps an *old* caller (built before
+ /// this field existed, so it never sends `dry_run` at all) parsing the
+ /// same request it always sent.
+ #[serde(default)]
+ dry_run: bool,
}
/// Wire-format summary returned by `POST /admin/delete-workspace`.
@@ -4763,6 +4773,27 @@ pub struct DeleteWorkspaceResult {
pub projects_deleted: u64,
/// `pages` rows removed via cascade (all versions).
pub pages_deleted: u64,
+ /// `sessions` rows removed via cascade.
+ pub sessions_deleted: u64,
+ /// `observations` rows removed via cascade.
+ pub observations_deleted: u64,
+ /// `handoffs` rows removed via cascade.
+ pub handoffs_deleted: u64,
+ /// `page_embeddings` rows removed via cascade.
+ pub embeddings_deleted: u64,
+ /// `observations` rows in a **different** workspace, deleted collaterally
+ /// because their `session_id` belongs to a session that lived in this one
+ /// (`observations.session_id` is `ON DELETE CASCADE`, without regard to
+ /// the observation's own `workspace_id`) — the mirror of the incident
+ /// `purge-project`'s preview guards against, one level up. Always
+ /// present, zero when there is none, so a caller can tell "no collateral
+ /// damage" apart from "field absent on an older server".
+ pub collateral_observations_deleted: u64,
+ /// `handoffs` rows in a different workspace whose `from_session_id` or
+ /// `accepted_by_session` is set to `NULL` (not deleted — those columns
+ /// are `ON DELETE SET NULL`) because they referenced a session that lived
+ /// in this workspace.
+ pub collateral_handoffs_denulled: u64,
/// Managed `workstreams` rows removed via cascade.
pub workstreams_deleted: u64,
/// `managed_runs` rows removed via cascade.
@@ -4784,6 +4815,15 @@ pub struct DeleteWorkspaceResult {
/// Post-delete mirror checkpoint, if one was taken.
#[serde(skip_serializing_if = "Option::is_none")]
pub checkpoint: Option<String>,
+ /// `true` for a preview: `dry_run: true` in the request always wins, so
+ /// this is only ever `false` on a run that actually deleted rows. The
+ /// counts above are read directly by the same queries a confirmed delete
+ /// uses to decide what to remove — never by running the delete and
+ /// rolling it back — so `files_deleted`/`files_failed` are always empty
+ /// and `pre_checkpoint`/`checkpoint` always absent: no wiki directory was
+ /// touched, no admission webhook ran, and no purge dispatch went out.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub dry_run: bool,
}
/// `POST /admin/delete-workspace` — remove a workspace and, via cascade, every
@@ -4942,6 +4982,13 @@ async fn handle_delete_workspace(
actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
Json(req): Json<DeleteWorkspaceRequest>,
) -> impl IntoResponse {
+ // `dry_run` always wins, exactly like `purge-project` (its handler checks
+ // `req.dry_run` before anything else regardless of any other field): a
+ // caller must never be able to combine `dry_run: true` with `force: true`
+ // and get a real delete.
+ if req.dry_run {
+ return delete_workspace_preview(&state, &req.workspace, req.force).await;
+ }
let actor = actor_ext
.map(|axum::Extension(a)| a)
.unwrap_or_else(ai_memory_core::ActorContext::anonymous);
@@ -5013,7 +5060,7 @@ async fn delete_workspace_core(
let summary = match state
.writer
- .delete_workspace(ws_id, force, compaction)
+ .delete_workspace(ws_id, force, compaction, ai_memory_store::PurgeMode::Commit)
.await
{
Ok(s) => s,
@@ -5062,6 +5109,12 @@ async fn delete_workspace_core(
workspace: workspace.to_string(),
projects_deleted: summary.projects_deleted,
pages_deleted: summary.pages_deleted,
+ sessions_deleted: summary.sessions_deleted,
+ observations_deleted: summary.observations_deleted,
+ handoffs_deleted: summary.handoffs_deleted,
+ embeddings_deleted: summary.embeddings_deleted,
+ collateral_observations_deleted: summary.collateral_observations_deleted,
+ collateral_handoffs_denulled: summary.collateral_handoffs_denulled,
workstreams_deleted: summary.workstreams_deleted,
managed_runs_deleted: summary.managed_runs_deleted,
workstream_ids: summary.workstream_ids,
@@ -5070,9 +5123,106 @@ async fn delete_workspace_core(
files_failed,
pre_checkpoint,
checkpoint: checkpoint_or_warn(&state.wiki, format!("delete-workspace {workspace}")),
+ dry_run: false,
})
}
+/// Preview branch of `POST /admin/delete-workspace`: reached whenever
+/// `dry_run` is true, regardless of `force`. `ai_memory_store::delete_workspace`
+/// under `PurgeMode::Preview` counts every row a confirmed delete would remove
+/// — via the same `SELECT`s the confirmed path itself uses to decide what to
+/// delete, not a separately-maintained estimate — and returns without ever
+/// issuing the `DELETE`, so there is no cascade to roll back.
+///
+/// Deliberately skipped, unlike [`delete_workspace_core`]: it never opens the
+/// blocking admission call (`admit_purge_workspace`) at all — nothing was
+/// decided yet, so there is nothing for a mirror to act on — plus on-disk
+/// directory removal (nothing was deleted) and both checkpoints (the git tree
+/// does not change). Because admission never runs, a `200` here is not a
+/// guarantee: a `Reject`-policy or scope-guard admission webhook only runs on
+/// the confirmed path and can still refuse the real delete afterward.
+///
+/// Scope resolution and the non-empty-workspace guard run exactly as the real
+/// delete's do, so an unknown workspace (404) or a non-empty workspace
+/// without `force` (409) answers identically either way.
+async fn delete_workspace_preview(
+ state: &Arc<AdminState>,
+ workspace: &str,
+ force: bool,
+) -> (StatusCode, Json<serde_json::Value>) {
+ let ws_id = match lookup_ws_no_create(state, workspace).await {
+ Ok(id) => id,
+ Err(e) => return e,
+ };
+
+ let summary = match state
+ .writer
+ .delete_workspace(
+ ws_id,
+ force,
+ // A preview never deletes anything, so there is nothing to
+ // reclaim; `ops::delete_workspace` also forces `compacted: false`
+ // for `PurgeMode::Preview` regardless of this value.
+ ai_memory_store::Compaction::Skip,
+ ai_memory_store::PurgeMode::Preview,
+ )
+ .await
+ {
+ Ok(s) => s,
+ // Same conflict a confirmed delete would hit, reported the same way:
+ // the preview is a promise of what a real delete would do, and a real
+ // delete would refuse here too.
+ Err(e @ StoreError::WorkspaceNotEmpty(_)) => {
+ return (
+ StatusCode::CONFLICT,
+ Json(serde_json::json!({
+ "error": format!(
+ "{e} (pass \"force\": true alongside \"dry_run\": true to preview a \
+ non-empty workspace)"
+ )
+ })),
+ );
+ }
+ // A race between the `lookup_ws_no_create` above and this call (the
+ // workspace was deleted in between): the same 404 a confirmed delete
+ // would give for the same race, rather than a 500 or a 200 full of
+ // zeros.
+ Err(e @ StoreError::NotFound(_)) => {
+ return (
+ StatusCode::NOT_FOUND,
+ Json(serde_json::json!({ "error": e.to_string() })),
+ );
+ }
+ Err(e) => return internal_err(e.to_string()),
+ };
+
+ let report = DeleteWorkspaceResult {
+ workspace: workspace.to_string(),
+ projects_deleted: summary.projects_deleted,
+ pages_deleted: summary.pages_deleted,
+ sessions_deleted: summary.sessions_deleted,
+ observations_deleted: summary.observations_deleted,
+ handoffs_deleted: summary.handoffs_deleted,
+ embeddings_deleted: summary.embeddings_deleted,
+ collateral_observations_deleted: summary.collateral_observations_deleted,
+ collateral_handoffs_denulled: summary.collateral_handoffs_denulled,
+ workstreams_deleted: summary.workstreams_deleted,
+ managed_runs_deleted: summary.managed_runs_deleted,
+ workstream_ids: summary.workstream_ids,
+ compacted: false,
+ files_deleted: Vec::new(),
+ files_failed: Vec::new(),
+ pre_checkpoint: None,
+ checkpoint: None,
+ dry_run: true,
+ };
+
+ (
+ StatusCode::OK,
+ Json(serde_json::to_value(&report).unwrap_or_else(|_| serde_json::json!({}))),
+ )
+}
+
/// JSON request body for `POST /admin/rename-project`.
#[derive(Deserialize)]
struct RenameProjectRequest {
@@ -12558,6 +12708,86 @@ mod tests {
);
}
+ /// The `delete-workspace` preview branch sits behind the same root-only
+ /// gate, reached through the same handler and route as the confirmed
+ /// path — mirrors `multiuser_purge_project_dry_run_rejects_db_user_and_anonymous`
+ /// above.
+ /// The root control case proves the gate — not the route — is what is
+ /// being tested: root reaches the handler (answered with `404`, since
+ /// this router's store has no `ghost-workspace`), while the DB user and
+ /// anonymous requests below never get that far.
+ #[tokio::test]
+ async fn multiuser_delete_workspace_dry_run_rejects_db_user_and_anonymous() {
+ let (_tmp, router) = user_admin_test_router("root-token");
+ post_create_user(
+ &router,
+ "root-token",
+ serde_json::json!({"username": "alice"}),
+ )
+ .await;
+
+ let preview_body = serde_json::json!({
+ "workspace": "ghost-workspace",
+ "force": false,
+ "dry_run": true
+ });
+
+ let root_resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/admin/delete-workspace")
+ .header("content-type", "application/json")
+ .header("authorization", "Bearer root-token")
+ .body(Body::from(serde_json::to_vec(&preview_body).unwrap()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ root_resp.status(),
+ StatusCode::NOT_FOUND,
+ "root must reach the preview handler, not be blocked by the auth gate"
+ );
+
+ let db_user_resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/admin/delete-workspace")
+ .header("content-type", "application/json")
+ .header("authorization", "Bearer db-user-token")
+ .body(Body::from(serde_json::to_vec(&preview_body).unwrap()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ db_user_resp.status(),
+ StatusCode::FORBIDDEN,
+ "a dry-run preview must stay root-only for DB users in multi-user mode"
+ );
+
+ let anon_resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/admin/delete-workspace")
+ .header("content-type", "application/json")
+ .body(Body::from(serde_json::to_vec(&preview_body).unwrap()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ anon_resp.status(),
+ StatusCode::UNAUTHORIZED,
+ "a dry-run preview must require authentication in multi-user mode"
+ );
+ }
#[tokio::test]
async fn multiuser_operational_admin_routes_allow_root() {
let (_tmp, router) = user_admin_test_router("root-token");
diff --git a/crates/ai-memory-mcp/tests/suite/admin_move.rs b/crates/ai-memory-mcp/tests/suite/admin_move.rs
index ee46a2db..1204b3e0 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_move.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_move.rs
@@ -14,7 +14,10 @@
//! (sessions/observations/handoffs) are dropped by the purge.
use super::common::{post, spawn_capture_hook};
-use ai_memory_core::{AgentKind, PagePath, Sanitized, Sanitizer, Tier};
+use ai_memory_core::{
+ AgentKind, NewHandoff, NewObservation, NewSession, ObservationKind, PagePath, Sanitized,
+ Sanitizer, SessionId, Tier,
+};
use ai_memory_mcp::AdminState;
use ai_memory_store::{DecayParams, PrepareWorkstreamRun, Store, WorkstreamSelection};
use ai_memory_wiki::{
@@ -1985,6 +1988,725 @@ async fn delete_workspace_unknown_is_404() {
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
+/// A preview must report the same counts a confirmed delete right after it
+/// then produces — every numeric field plus `workstream_ids`, not a
+/// hand-picked subset — and must not touch the database row, the wiki
+/// directory, or a managed workstream's raw segment directory in the
+/// meantime (a regression that made preview call
+/// `remove_workstream_segment_storage` would fail the raw-dir assertions
+/// below). Mirrors
+/// `purge_project_dry_run_reports_the_same_counts_the_confirmed_purge_will`
+/// one level up, at workspace granularity.
+#[tokio::test]
+async fn delete_workspace_dry_run_reports_the_same_counts_the_confirmed_delete_will() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ let ws = store
+ .writer
+ .get_or_create_workspace("victim")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "proj", None)
+ .await
+ .unwrap();
+ let page_id = state
+ .wiki
+ .write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new("notes/a.md".to_string()).unwrap(),
+ frontmatter: json!({"title": "notes/a.md"}),
+ body: "body".to_string(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: Some("notes/a.md".into()),
+ admission_ctx: None,
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ evidence: Vec::new(),
+ })
+ .await
+ .unwrap();
+
+ let sid = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: sid,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: None,
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_observation(Sanitized::new(
+ NewObservation {
+ session_id: sid,
+ workspace_id: ws,
+ project_id: proj,
+ kind: ObservationKind::UserPrompt,
+ extension: None,
+ source_event: None,
+ title: "obs".into(),
+ body: "obs body".into(),
+ importance: 5,
+ },
+ &Sanitizer::builtin(),
+ ))
+ .await
+ .unwrap();
+ 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: "handoff".into(),
+ open_questions: vec![],
+ next_steps: vec![],
+ files_touched: vec![],
+ owner_user: None,
+ })
+ .await
+ .unwrap();
+ store
+ .writer
+ .store_embeddings(vec![ai_memory_store::EmbeddingWrite {
+ page_id,
+ vector_bytes: vec![0u8; 4],
+ provider: "test".into(),
+ model: "model".into(),
+ dim: 1,
+ }])
+ .await
+ .unwrap();
+
+ let prepared = store
+ .writer
+ .prepare_workstream_run(PrepareWorkstreamRun {
+ workspace_id: ws,
+ project_id: proj,
+ repo_fingerprint: "repo".into(),
+ worktree_fingerprint: "worktree".into(),
+ cwd: "/repo".into(),
+ agent: AgentKind::Codex,
+ automatic_harness: false,
+ available_agents: vec![AgentKind::Codex],
+ selection: WorkstreamSelection::Current,
+ lease_owner: "test".into(),
+ })
+ .await
+ .unwrap();
+ assert!(
+ store
+ .writer
+ .cancel_managed_run(prepared.run_id)
+ .await
+ .unwrap()
+ );
+ let raw_dir = tmp
+ .path()
+ .join("raw/workstreams")
+ .join(prepared.workstream_id.to_string());
+ std::fs::create_dir_all(&raw_dir).unwrap();
+ std::fs::write(raw_dir.join("000001.jsonl"), "event\n").unwrap();
+
+ let ws_dir = state.wiki.root().join(ws.to_string());
+ assert!(
+ ws_dir.exists(),
+ "the workspace directory must exist before either call"
+ );
+ assert!(
+ raw_dir.exists(),
+ "the raw workstream segment directory must exist before either call"
+ );
+
+ let preview = post(
+ state.clone(),
+ "/admin/delete-workspace",
+ json!({ "workspace": "victim", "force": true, "dry_run": true }),
+ )
+ .await;
+ assert_eq!(preview.status(), StatusCode::OK, "a preview must succeed");
+ let preview_body = body_json(preview).await;
+ assert_eq!(preview_body["dry_run"], true);
+ assert_eq!(preview_body["projects_deleted"], 1);
+ assert_eq!(preview_body["pages_deleted"], 1);
+ assert_eq!(preview_body["sessions_deleted"], 1);
+ assert_eq!(preview_body["observations_deleted"], 1);
+ assert_eq!(preview_body["handoffs_deleted"], 1);
+ assert_eq!(preview_body["embeddings_deleted"], 1);
+ assert_eq!(preview_body["collateral_observations_deleted"], 0);
+ assert_eq!(preview_body["collateral_handoffs_denulled"], 0);
+ assert_eq!(preview_body["workstreams_deleted"], 1);
+ assert_eq!(preview_body["managed_runs_deleted"], 1);
+ assert_eq!(
+ preview_body["workstream_ids"],
+ json!([prepared.workstream_id.to_string()])
+ );
+ assert_eq!(preview_body["files_deleted"], json!([]));
+ assert_eq!(preview_body["files_failed"], json!([]));
+ assert_eq!(preview_body["compacted"], false);
+ assert!(
+ preview_body.get("pre_checkpoint").is_none(),
+ "a preview must not checkpoint the wiki tree"
+ );
+ assert!(
+ preview_body.get("checkpoint").is_none(),
+ "a preview must not checkpoint the wiki tree"
+ );
+
+ // Nothing was touched: the workspace directory, the raw workstream
+ // segment directory, and the workspace row are all still there.
+ assert!(
+ ws_dir.exists(),
+ "a preview must not remove the workspace directory"
+ );
+ assert!(
+ raw_dir.exists(),
+ "a preview must not remove the raw workstream segment directory"
+ );
+ assert!(
+ store
+ .reader
+ .find_workspace("victim".into())
+ .await
+ .unwrap()
+ .is_some(),
+ "a preview must not delete the workspace row"
+ );
+
+ // The confirmed delete right after it must succeed with the same counts.
+ let confirmed = post(
+ state,
+ "/admin/delete-workspace",
+ json!({ "workspace": "victim", "force": true }),
+ )
+ .await;
+ assert_eq!(confirmed.status(), StatusCode::OK);
+ let confirmed_body = body_json(confirmed).await;
+ assert_eq!(
+ confirmed_body.get("dry_run"),
+ None,
+ "a confirmed delete report has no dry_run key"
+ );
+ for field in [
+ "projects_deleted",
+ "pages_deleted",
+ "sessions_deleted",
+ "observations_deleted",
+ "handoffs_deleted",
+ "embeddings_deleted",
+ "collateral_observations_deleted",
+ "collateral_handoffs_denulled",
+ "workstreams_deleted",
+ "managed_runs_deleted",
+ "workstream_ids",
+ ] {
+ assert_eq!(
+ confirmed_body[field], preview_body[field],
+ "the confirmed delete's {field} must match what the preview reported"
+ );
+ }
+ assert!(
+ !ws_dir.exists(),
+ "the confirmed delete must remove the workspace directory"
+ );
+ assert!(
+ !raw_dir.exists(),
+ "the confirmed delete must remove the raw workstream segment directory"
+ );
+}
+
+/// `dry_run` must always win over `force`. A caller must never be able to
+/// combine `dry_run: true` with `force: true` and get a real delete — mirrors
+/// `purge_project_confirm_true_and_dry_run_true_still_only_previews`.
+#[tokio::test]
+async fn delete_workspace_force_true_and_dry_run_true_still_only_previews() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ seed_page(&store, &state.wiki, "victim", "proj", "notes/a.md", "body").await;
+ let ws = store
+ .reader
+ .find_workspace("victim".into())
+ .await
+ .unwrap()
+ .expect("workspace exists");
+ let ws_dir = state.wiki.root().join(ws.to_string());
+
+ let resp = post(
+ state,
+ "/admin/delete-workspace",
+ json!({ "workspace": "victim", "force": true, "dry_run": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(
+ body["dry_run"], true,
+ "force: true must not defeat dry_run: true"
+ );
+ assert_eq!(body["projects_deleted"], 1);
+
+ // The only proof that matters: nothing was actually deleted.
+ assert!(
+ ws_dir.exists(),
+ "{{force: true, dry_run: true}} must not delete the workspace directory"
+ );
+ assert!(
+ store
+ .reader
+ .find_workspace("victim".into())
+ .await
+ .unwrap()
+ .is_some(),
+ "{{force: true, dry_run: true}} must not delete the workspace row"
+ );
+}
+
+/// A non-empty workspace previewed without `force` must still 409, exactly
+/// like the confirmed delete would — the preview promises to describe what a
+/// confirmed call would do, and a confirmed call would refuse here too.
+#[tokio::test]
+async fn delete_workspace_dry_run_refuses_non_empty_without_force() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ seed_page(&store, &state.wiki, "victim", "proj", "notes/a.md", "body").await;
+
+ let resp = post(
+ state,
+ "/admin/delete-workspace",
+ json!({ "workspace": "victim", "dry_run": true }),
+ )
+ .await;
+ assert_eq!(
+ resp.status(),
+ StatusCode::CONFLICT,
+ "a non-empty workspace preview without force must still 409"
+ );
+ assert!(
+ store
+ .reader
+ .find_workspace("victim".into())
+ .await
+ .unwrap()
+ .is_some(),
+ "a refused preview must not remove the workspace"
+ );
+}
+
+/// A non-existent workspace must still 404 on a preview, exactly like the
+/// confirmed delete does.
+#[tokio::test]
+async fn delete_workspace_dry_run_nonexistent_workspace_returns_404() {
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_state(&tmp).await;
+ let resp = post(
+ state,
+ "/admin/delete-workspace",
+ json!({ "workspace": "ghost", "dry_run": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);
+}
+
+/// A dry run must not dispatch the admission webhook: nothing was decided
+/// yet, so there is nothing for a mirror to act on. Mirrors
+/// `purge_project_dry_run_does_not_dispatch_admission_webhook`.
+#[tokio::test]
+async fn delete_workspace_dry_run_does_not_dispatch_admission_webhook() {
+ 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::PurgeWorkspace],
+ blocking: false,
+ }])
+ .unwrap();
+ let (state, store) = make_state_with_chain(&tmp, chain).await;
+ seed_page(&store, &state.wiki, "victim", "proj", "notes/a.md", "body").await;
+
+ let resp = post(
+ state,
+ "/admin/delete-workspace",
+ json!({ "workspace": "victim", "force": true, "dry_run": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let outcome = tokio::time::timeout(std::time::Duration::from_millis(300), rx).await;
+ assert!(
+ outcome.is_err(),
+ "a dry run must not dispatch the delete-workspace admission webhook"
+ );
+}
+
+/// The mirror of the incident, exercised through the HTTP route: deleting a
+/// workspace also collaterally deletes an observation stamped into a
+/// *different* workspace (because `observations.session_id` cascades
+/// regardless of the observation's own `workspace_id`), and orphans (nulls
+/// the session reference of, without deleting) a handoff that lives in that
+/// other workspace too. Mirrors
+/// `purge_project_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project`
+/// one level up, at workspace granularity.
+#[tokio::test]
+async fn delete_workspace_dry_run_and_confirmed_delete_both_report_collateral_damage_in_another_workspace()
+ {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ let doomed_ws = store
+ .writer
+ .get_or_create_workspace("doomed")
+ .await
+ .unwrap();
+ let doomed_proj = store
+ .writer
+ .get_or_create_project(doomed_ws, "proj", None)
+ .await
+ .unwrap();
+ let other_ws = store.writer.get_or_create_workspace("other").await.unwrap();
+ let other_proj = store
+ .writer
+ .get_or_create_project(other_ws, "proj", None)
+ .await
+ .unwrap();
+
+ let sid = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: sid,
+ workspace_id: doomed_ws,
+ project_id: doomed_proj,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: None,
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+ // Collateral observation: session lives in `doomed`, observation is
+ // stamped into `other` (a different workspace).
+ store
+ .writer
+ .insert_observation(Sanitized::new(
+ NewObservation {
+ session_id: sid,
+ workspace_id: other_ws,
+ project_id: other_proj,
+ kind: ObservationKind::UserPrompt,
+ extension: None,
+ source_event: None,
+ title: "collateral".into(),
+ body: "collateral body".into(),
+ importance: 5,
+ },
+ &Sanitizer::builtin(),
+ ))
+ .await
+ .unwrap();
+ // Collateral handoff: lives in `other`, authored by the `doomed` session.
+ store
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: other_ws,
+ project_id: other_proj,
+ from_session_id: Some(sid),
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "collateral handoff".into(),
+ open_questions: vec![],
+ next_steps: vec![],
+ files_touched: vec![],
+ owner_user: None,
+ })
+ .await
+ .unwrap();
+
+ let preview = post(
+ state.clone(),
+ "/admin/delete-workspace",
+ json!({ "workspace": "doomed", "force": true, "dry_run": true }),
+ )
+ .await;
+ assert_eq!(preview.status(), StatusCode::OK);
+ let preview_body = body_json(preview).await;
+ assert_eq!(preview_body["collateral_observations_deleted"], 1);
+ assert_eq!(preview_body["collateral_handoffs_denulled"], 1);
+
+ let confirmed = post(
+ state,
+ "/admin/delete-workspace",
+ json!({ "workspace": "doomed", "force": true }),
+ )
+ .await;
+ assert_eq!(confirmed.status(), StatusCode::OK);
+ let confirmed_body = body_json(confirmed).await;
+ assert_eq!(confirmed_body["collateral_observations_deleted"], 1);
+ assert_eq!(confirmed_body["collateral_handoffs_denulled"], 1);
+
+ // `other` survives as a workspace; only the collateral rows are affected.
+ assert!(
+ store
+ .reader
+ .find_workspace("other".into())
+ .await
+ .unwrap()
+ .is_some(),
+ "the other workspace must survive"
+ );
+ assert_eq!(
+ store.reader.status_counts().await.unwrap().observations,
+ 0,
+ "the collateral observation in `other` must actually be gone"
+ );
+}
+
+/// Adversarial control: previewing workspace A must never count rows that
+/// live in workspace B, even though both hold a like-named project and B
+/// has its own full set of sessions/observations/handoffs. Also pins the
+/// reverse direction: a session that lives in B but stamps an observation
+/// directly into A must be counted in A's own `observations_deleted` (its
+/// row's own `workspace_id` is A), never in `collateral_observations_deleted`
+/// (which only counts rows whose own `workspace_id` is NOT A) — the two
+/// counts are mutually exclusive by construction (`workspace_id = ?1` vs
+/// `workspace_id != ?1`), so this proves there is no double count either.
+#[tokio::test]
+async fn delete_workspace_dry_run_never_counts_a_different_workspaces_rows() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ // Workspace A: the one being previewed.
+ let ws_a = store
+ .writer
+ .get_or_create_workspace("workspace-a")
+ .await
+ .unwrap();
+ let proj_a = store
+ .writer
+ .get_or_create_project(ws_a, "proj", None)
+ .await
+ .unwrap();
+ seed_page(
+ &store,
+ &state.wiki,
+ "workspace-a",
+ "proj",
+ "notes/a.md",
+ "a",
+ )
+ .await;
+ let sid_a = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: sid_a,
+ workspace_id: ws_a,
+ project_id: proj_a,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: None,
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_observation(Sanitized::new(
+ NewObservation {
+ session_id: sid_a,
+ workspace_id: ws_a,
+ project_id: proj_a,
+ kind: ObservationKind::UserPrompt,
+ extension: None,
+ source_event: None,
+ title: "a-own".into(),
+ body: "a's own observation".into(),
+ importance: 5,
+ },
+ &Sanitizer::builtin(),
+ ))
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: ws_a,
+ project_id: proj_a,
+ from_session_id: Some(sid_a),
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "a's own handoff".into(),
+ open_questions: vec![],
+ next_steps: vec![],
+ files_touched: vec![],
+ owner_user: None,
+ })
+ .await
+ .unwrap();
+
+ // Workspace B: two projects, its own full set of rows. None of this may
+ // ever be counted for a preview of A.
+ let ws_b = store
+ .writer
+ .get_or_create_workspace("workspace-b")
+ .await
+ .unwrap();
+ let proj_b1 = store
+ .writer
+ .get_or_create_project(ws_b, "proj", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .get_or_create_project(ws_b, "proj2", None)
+ .await
+ .unwrap();
+ seed_page(
+ &store,
+ &state.wiki,
+ "workspace-b",
+ "proj",
+ "notes/b.md",
+ "b",
+ )
+ .await;
+ seed_page(
+ &store,
+ &state.wiki,
+ "workspace-b",
+ "proj2",
+ "notes/c.md",
+ "c",
+ )
+ .await;
+ let sid_b = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: sid_b,
+ workspace_id: ws_b,
+ project_id: proj_b1,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: None,
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_observation(Sanitized::new(
+ NewObservation {
+ session_id: sid_b,
+ workspace_id: ws_b,
+ project_id: proj_b1,
+ kind: ObservationKind::UserPrompt,
+ extension: None,
+ source_event: None,
+ title: "b-own".into(),
+ body: "b's own observation".into(),
+ importance: 5,
+ },
+ &Sanitizer::builtin(),
+ ))
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: ws_b,
+ project_id: proj_b1,
+ from_session_id: Some(sid_b),
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "b's own handoff".into(),
+ open_questions: vec![],
+ next_steps: vec![],
+ files_touched: vec![],
+ owner_user: None,
+ })
+ .await
+ .unwrap();
+
+ // Reverse-direction case: B's session stamps an observation directly
+ // into A (own `workspace_id` = A). Must count as A's own, not collateral.
+ store
+ .writer
+ .insert_observation(Sanitized::new(
+ NewObservation {
+ session_id: sid_b,
+ workspace_id: ws_a,
+ project_id: proj_a,
+ kind: ObservationKind::UserPrompt,
+ extension: None,
+ source_event: None,
+ title: "cross".into(),
+ body: "stamped into a by b's session".into(),
+ importance: 5,
+ },
+ &Sanitizer::builtin(),
+ ))
+ .await
+ .unwrap();
+
+ let resp = post(
+ state,
+ "/admin/delete-workspace",
+ json!({ "workspace": "workspace-a", "force": true, "dry_run": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(
+ body["projects_deleted"], 1,
+ "must count only workspace-a's own project, not workspace-b's two"
+ );
+ assert_eq!(body["pages_deleted"], 1);
+ assert_eq!(
+ body["sessions_deleted"], 1,
+ "workspace-b's session must not be counted"
+ );
+ assert_eq!(
+ body["observations_deleted"], 2,
+ "a's own observation plus the one stamped into it by b's session"
+ );
+ assert_eq!(
+ body["handoffs_deleted"], 1,
+ "workspace-b's handoff must not be counted"
+ );
+ assert_eq!(
+ body["collateral_observations_deleted"], 0,
+ "the cross-stamped observation belongs to A itself and is not collateral"
+ );
+ assert_eq!(body["collateral_handoffs_denulled"], 0);
+
+ // Control: workspace-b's rows are untouched by the previewed workspace.
+ assert!(
+ store
+ .reader
+ .find_workspace("workspace-b".into())
+ .await
+ .unwrap()
+ .is_some()
+ );
+}
+
#[tokio::test]
async fn rename_workspace_ok_collision_and_unknown() {
// OK: renames in place; old name no longer resolves, new one does.
diff --git a/crates/ai-memory-store/src/grants.rs b/crates/ai-memory-store/src/grants.rs
index 0682f57e..0956d179 100644
--- a/crates/ai-memory-store/src/grants.rs
+++ b/crates/ai-memory-store/src/grants.rs
@@ -904,9 +904,14 @@ mod tests {
w.grant_memory(f.alice, api, GrantLevel::Write, None)
.await
.unwrap();
- w.delete_workspace(team, true, crate::Compaction::Skip)
- .await
- .unwrap();
+ w.delete_workspace(
+ team,
+ true,
+ crate::Compaction::Skip,
+ crate::PurgeMode::Commit,
+ )
+ .await
+ .unwrap();
assert!(all_rows(&f.store, f.alice, api).is_empty());
}
@@ -972,9 +977,14 @@ mod tests {
assert_eq!(listing[0].project, "client-renamed");
// And deleting the workspace it left does not take it.
- w.delete_workspace(f.ws, true, crate::Compaction::Skip)
- .await
- .unwrap();
+ w.delete_workspace(
+ f.ws,
+ true,
+ crate::Compaction::Skip,
+ crate::PurgeMode::Commit,
+ )
+ .await
+ .unwrap();
assert_eq!(all_rows(&f.store, f.alice, f.client).len(), 1);
}
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 5d51183e..48a22254 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -5289,12 +5289,34 @@ pub fn purge_project(
}
/// Summary returned by [`delete_workspace`].
-#[derive(Debug, Default, Clone)]
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct DeleteWorkspaceSummary {
/// Projects removed (0 when the workspace was already empty).
pub projects_deleted: u64,
/// `pages` rows removed via cascade (all versions).
pub pages_deleted: u64,
+ /// `sessions` rows removed via cascade.
+ pub sessions_deleted: u64,
+ /// `observations` rows removed via cascade.
+ pub observations_deleted: u64,
+ /// `handoffs` rows removed via cascade (every handoff whose own
+ /// `workspace_id` is this workspace, not just the ones this workspace's
+ /// sessions authored or accepted).
+ pub handoffs_deleted: u64,
+ /// `page_embeddings` rows removed via cascade (cascades through pages).
+ pub embeddings_deleted: u64,
+ /// `observations` rows belonging to a **different** workspace, deleted
+ /// collaterally because `observations.session_id` is `ON DELETE CASCADE`
+ /// to `sessions` without regard to the observation's own `workspace_id`
+ /// — the same shape [`PurgeSummary::collateral_observations_deleted`] and
+ /// [`PurgeSessionSummary::collateral_observations_deleted`] guard
+ /// against, one level up at workspace granularity.
+ pub collateral_observations_deleted: u64,
+ /// `handoffs` rows belonging to a different workspace whose
+ /// `from_session_id` or `accepted_by_session` is about to be set to
+ /// `NULL` (not deleted — those columns are `ON DELETE SET NULL`) because
+ /// they referenced a session that lived in this workspace.
+ pub collateral_handoffs_denulled: u64,
/// Managed `workstreams` rows removed via cascade.
pub workstreams_deleted: u64,
/// `managed_runs` rows removed via cascade.
@@ -5313,6 +5335,18 @@ pub struct DeleteWorkspaceSummary {
/// observations / handoffs / managed workstreams. The caller removes the
/// on-disk workspace and raw workstream directories afterwards.
///
+/// `mode = `[`PurgeMode::Preview`] runs every count below — including the two
+/// collateral ones — against the same rows in `projects`, `pages`, `sessions`,
+/// `observations`, `handoffs`, `page_embeddings`, `workstreams` and
+/// `managed_runs` the confirmed call would delete, then returns without ever
+/// issuing the `DELETE`, the tombstone insert, or the reclaim: the
+/// transaction so far has only ever read, so rolling it back is free (see
+/// [`PurgeMode::Preview`]'s doc). The non-empty-workspace guard
+/// runs identically under both modes, so a preview of a workspace that would
+/// be refused reports the same [`StoreError::WorkspaceNotEmpty`] a confirmed
+/// call would, rather than a set of counts that were never going to be
+/// produced.
+///
/// # Errors
/// [`StoreError::WorkspaceNotEmpty`] when it still holds projects and `force`
/// is false; [`StoreError::NotFound`] when the workspace does not exist.
@@ -5321,9 +5355,26 @@ pub fn delete_workspace(
workspace_id: &WorkspaceId,
force: bool,
compaction: Compaction,
+ mode: PurgeMode,
) -> StoreResult<DeleteWorkspaceSummary> {
let tx = conn.transaction()?;
let wid = workspace_id.as_bytes();
+
+ // Checked up front, under both modes: a `Commit` run would otherwise only
+ // discover a missing workspace via the `DELETE FROM workspaces` below
+ // returning zero rows, and a `Preview` run issues no `DELETE` at all — so
+ // without this, previewing a nonexistent workspace would silently return
+ // every count as zero instead of `NotFound`, unlike every other lookup in
+ // this codebase.
+ let exists: i64 = tx.query_row(
+ "SELECT COUNT(*) FROM workspaces WHERE id = ?1",
+ rusqlite::params![&wid[..]],
+ |row| row.get(0),
+ )?;
+ if exists == 0 {
+ return Err(StoreError::NotFound("workspace".into()));
+ }
+
let count = |sql: &str| -> StoreResult<u64> {
let n: Option<i64> = tx
.query_row(sql, rusqlite::params![&wid[..]], |row| row.get(0))
@@ -5336,12 +5387,46 @@ pub fn delete_workspace(
return Err(StoreError::WorkspaceNotEmpty(projects_deleted));
}
let pages_deleted = count("SELECT COUNT(*) FROM pages WHERE workspace_id = ?1")?;
+ let sessions_deleted = count("SELECT COUNT(*) FROM sessions WHERE workspace_id = ?1")?;
+ let observations_deleted = count("SELECT COUNT(*) FROM observations WHERE workspace_id = ?1")?;
+ let handoffs_deleted = count("SELECT COUNT(*) FROM handoffs WHERE workspace_id = ?1")?;
+ // 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 workspace_id = ?1)",
+ )?;
let workstreams_deleted = count("SELECT COUNT(*) FROM workstreams WHERE workspace_id = ?1")?;
let managed_runs_deleted = count(
"SELECT COUNT(*) FROM managed_runs mr \
JOIN workstreams w ON w.id = mr.workstream_id \
WHERE w.workspace_id = ?1",
)?;
+
+ // Collateral damage in OTHER workspaces, via `sessions` cascading out of
+ // this one. `observations.session_id` is `ON DELETE CASCADE` (V01) with
+ // no regard for the observation's own `workspace_id`, so an observation
+ // stamped into a different workspace's project — the same shape
+ // `purge_project`'s preview guards against, one level up — is deleted
+ // right along with the session that wrote it, even though nothing in
+ // that other workspace's own row count says so.
+ let collateral_observations_deleted = count(
+ "SELECT COUNT(*) FROM observations \
+ WHERE workspace_id != ?1 \
+ AND session_id IN (SELECT id FROM sessions WHERE workspace_id = ?1)",
+ )?;
+ // `handoffs.from_session_id` / `accepted_by_session` are `ON DELETE SET
+ // NULL` (V02): a handoff living in another workspace is not deleted, but
+ // loses the link back to whichever of this workspace's sessions authored
+ // or accepted it.
+ let collateral_handoffs_denulled = count(
+ "SELECT COUNT(*) FROM handoffs \
+ WHERE workspace_id != ?1 \
+ AND ( \
+ from_session_id IN (SELECT id FROM sessions WHERE workspace_id = ?1) \
+ OR accepted_by_session IN (SELECT id FROM sessions WHERE workspace_id = ?1) \
+ )",
+ )?;
+
let workstream_ids: Vec<String> = {
let mut stmt = tx.prepare("SELECT id FROM workstreams WHERE workspace_id = ?1")?;
let rows = stmt
@@ -5352,6 +5437,28 @@ pub fn delete_workspace(
.collect::<Result<Vec<_>, _>>()?
};
+ if mode == PurgeMode::Preview {
+ // Nothing was written — every statement above was a `SELECT` — so
+ // rolling back here is immediate; it never had to pay for the
+ // `DELETE FROM workspaces` cascade this function's `Commit` mode runs
+ // below, which is the whole point (see `PurgeMode::Preview`'s doc).
+ tx.rollback()?;
+ return Ok(DeleteWorkspaceSummary {
+ projects_deleted,
+ pages_deleted,
+ sessions_deleted,
+ observations_deleted,
+ handoffs_deleted,
+ embeddings_deleted,
+ collateral_observations_deleted,
+ collateral_handoffs_denulled,
+ workstreams_deleted,
+ managed_runs_deleted,
+ workstream_ids,
+ compacted: false,
+ });
+ }
+
let removed = tx.execute(
"DELETE FROM workspaces WHERE id = ?1",
rusqlite::params![&wid[..]],
@@ -5380,6 +5487,12 @@ pub fn delete_workspace(
Ok(DeleteWorkspaceSummary {
projects_deleted,
pages_deleted,
+ sessions_deleted,
+ observations_deleted,
+ handoffs_deleted,
+ embeddings_deleted,
+ collateral_observations_deleted,
+ collateral_handoffs_denulled,
workstreams_deleted,
managed_runs_deleted,
workstream_ids,
@@ -6387,7 +6500,8 @@ pub(crate) mod tests {
let prepared = open_managed_run(&mut conn, &ws, &proj);
// Non-empty (holds the "scratch" project + a page) → refused w/o force.
- let err = delete_workspace(&mut conn, &ws, false, Compaction::Skip).unwrap_err();
+ let err = delete_workspace(&mut conn, &ws, false, Compaction::Skip, PurgeMode::Commit)
+ .unwrap_err();
assert!(
matches!(err, StoreError::WorkspaceNotEmpty(n) if n >= 1),
"expected WorkspaceNotEmpty, got {err:?}"
@@ -6402,7 +6516,8 @@ pub(crate) mod tests {
assert_eq!(ws_still, 1, "refused delete must not touch the row");
// Force cascades: project + page gone, workspace row gone.
- let summary = delete_workspace(&mut conn, &ws, true, Compaction::Skip).unwrap();
+ let summary =
+ delete_workspace(&mut conn, &ws, true, Compaction::Skip, PurgeMode::Commit).unwrap();
assert!(
summary.projects_deleted >= 1 && summary.pages_deleted >= 1,
"{summary:?}"
@@ -6424,7 +6539,8 @@ pub(crate) mod tests {
// Deleting again → NotFound.
assert!(matches!(
- delete_workspace(&mut conn, &ws, true, Compaction::Skip).unwrap_err(),
+ delete_workspace(&mut conn, &ws, true, Compaction::Skip, PurgeMode::Commit)
+ .unwrap_err(),
StoreError::NotFound(_)
));
}
@@ -6433,7 +6549,14 @@ pub(crate) mod tests {
fn delete_workspace_empty_succeeds_without_force() {
let (_tmp, mut conn, _ws, _proj) = fresh_db();
let empty = get_or_create_workspace(&mut conn, "orphan-ws").unwrap();
- let summary = delete_workspace(&mut conn, &empty, false, Compaction::Skip).unwrap();
+ let summary = delete_workspace(
+ &mut conn,
+ &empty,
+ false,
+ Compaction::Skip,
+ PurgeMode::Commit,
+ )
+ .unwrap();
assert_eq!(summary.projects_deleted, 0);
assert_eq!(summary.pages_deleted, 0);
assert_eq!(summary.workstreams_deleted, 0);
@@ -6648,7 +6771,7 @@ pub(crate) mod tests {
fn delete_workspace_tombstones_the_whole_workspace() {
let (_tmp, mut conn, ws, proj) = fresh_db();
- delete_workspace(&mut conn, &ws, true, Compaction::Skip).unwrap();
+ delete_workspace(&mut conn, &ws, true, Compaction::Skip, PurgeMode::Commit).unwrap();
// The whole-workspace tombstone covers every project id in that ws,
// including ones whose rows are already gone via cascade.
@@ -7025,6 +7148,7 @@ pub(crate) mod tests {
"managed_runs",
"workstream_events",
"projects",
+ "workspaces",
"purged_scopes",
"audit_log",
]
@@ -7104,11 +7228,19 @@ pub(crate) mod tests {
let skipped = {
let other = get_or_create_workspace(&mut conn, "doomed").unwrap();
- delete_workspace(&mut conn, &other, false, Compaction::Skip).unwrap()
+ delete_workspace(
+ &mut conn,
+ &other,
+ false,
+ Compaction::Skip,
+ PurgeMode::Commit,
+ )
+ .unwrap()
};
assert!(!skipped.compacted, "the default does not VACUUM");
- let summary = delete_workspace(&mut conn, &ws, true, Compaction::Reclaim).unwrap();
+ let summary =
+ delete_workspace(&mut conn, &ws, true, Compaction::Reclaim, PurgeMode::Commit).unwrap();
assert!(summary.compacted, "the summary reports that VACUUM ran");
conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);").ok();
@@ -7119,6 +7251,195 @@ pub(crate) mod tests {
);
}
+ /// A preview's counts come from the same `SELECT`s the confirmed path
+ /// uses to decide what to delete, not a separately-maintained estimate,
+ /// so a preview and the confirmed run right after it must agree exactly —
+ /// compared as the whole struct, not a hand-picked subset of fields, so a
+ /// field added later cannot silently go uncompared. Mirrors
+ /// `purge_project_dry_run_reports_the_same_counts_a_real_purge_would` one
+ /// level up, at workspace granularity.
+ #[test]
+ fn delete_workspace_dry_run_reports_the_same_counts_a_real_delete_would() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let (_sid, page_id) = seed_session(&mut conn, ws, proj, "canaryws");
+ let prepared = open_managed_run(&mut conn, &ws, &proj);
+ store_embeddings(
+ &mut conn,
+ &[EmbeddingWrite {
+ page_id,
+ vector_bytes: vec![0u8; 4],
+ provider: "test".into(),
+ model: "model".into(),
+ dim: 1,
+ }],
+ )
+ .unwrap();
+
+ let preview = delete_workspace(&mut conn, &ws, true, Compaction::Skip, PurgeMode::Preview)
+ .expect("a dry run must not error");
+ assert_eq!(preview.projects_deleted, 1);
+ assert_eq!(preview.pages_deleted, 1);
+ assert_eq!(preview.sessions_deleted, 1);
+ assert_eq!(preview.observations_deleted, 1);
+ assert_eq!(preview.embeddings_deleted, 1);
+ assert_eq!(preview.workstreams_deleted, 1);
+ assert_eq!(preview.managed_runs_deleted, 1);
+ assert_eq!(
+ preview.workstream_ids,
+ vec![prepared.workstream_id.to_string()]
+ );
+ assert!(!preview.compacted, "a rolled-back run never reclaims bytes");
+
+ let real = delete_workspace(&mut conn, &ws, true, Compaction::Skip, PurgeMode::Commit)
+ .expect("the confirmed delete must still succeed after the preview");
+ assert_eq!(
+ real, preview,
+ "the dry run's whole summary must match what the confirmed run actually deletes \
+ (both ran with the same Compaction::Skip, so `compacted` agrees too)"
+ );
+ }
+
+ /// Bite check: every table's row count must be identical before and
+ /// after a [`PurgeMode::Preview`] run of `delete_workspace` — including
+ /// `workspaces` itself and `purged_scopes`, the two tables a confirmed
+ /// delete's own transaction writes to directly (`delete_workspace`, unlike
+ /// `purge_project`, writes no `audit_log` row at all, so that table's
+ /// count is trivially unchanged either way and is included here only for
+ /// parity with the other bite checks). If `Preview` ever fell through to
+ /// the `Commit` path's `DELETE` / tombstone insert, this is the test that
+ /// would catch it. Mirrors `purge_project_dry_run_changes_nothing`.
+ #[test]
+ fn delete_workspace_dry_run_changes_nothing() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let prepared = open_managed_run(&mut conn, &ws, &proj);
+ seed_workstream_event(&conn, &prepared.workstream_id, "canaryevt");
+ seed_session(&mut conn, ws, proj, "canaryws");
+
+ let before = row_snapshot(&conn);
+
+ let preview = delete_workspace(
+ &mut conn,
+ &ws,
+ true, // force: a live managed run and a project sit under this workspace
+ Compaction::Skip,
+ PurgeMode::Preview,
+ )
+ .expect("a dry run must not error even with a live managed run");
+ assert!(preview.pages_deleted >= 1);
+ assert!(preview.observations_deleted >= 1);
+ assert_eq!(preview.workstreams_deleted, 1);
+ assert_eq!(preview.managed_runs_deleted, 1);
+
+ let after = row_snapshot(&conn);
+ assert_eq!(
+ before, after,
+ "a dry run must leave every table's row count unchanged, including workspaces itself"
+ );
+ }
+
+ /// The mirror of the incident this whole feature guards against, one
+ /// level up from `purge_project_counts_collateral_damage_in_another_project`:
+ /// deleting a workspace reaches OUT and takes rows from a *different*
+ /// workspace. `observations.session_id` is `ON DELETE CASCADE` (V01) with
+ /// no regard for the observation's own `workspace_id`, and
+ /// `handoffs.from_session_id` / `accepted_by_session` are `ON DELETE SET
+ /// NULL` (V02) — neither of which the plain
+ /// `observations_deleted`/`handoffs_deleted` counts (by `workspace_id =
+ /// W`) can see, because these rows belong to a different workspace.
+ #[test]
+ fn delete_workspace_dry_run_and_confirmed_delete_both_report_collateral_damage_in_another_workspace()
+ {
+ let (_tmp, mut conn, doomed_ws, doomed_proj) = fresh_db();
+ let (sid, _page) = seed_session(&mut conn, doomed_ws, doomed_proj, "doomed-owner");
+
+ let other_ws = get_or_create_workspace(&mut conn, "other").unwrap();
+ let other_proj = get_or_create_project(&mut conn, &other_ws, "other-proj", None).unwrap();
+
+ // Collateral observation: session lives in `doomed_ws`, observation is
+ // stamped into `other_ws`.
+ let collateral_obs = NewObservation {
+ session_id: sid,
+ workspace_id: other_ws,
+ project_id: other_proj,
+ kind: ObservationKind::UserPrompt,
+ extension: None,
+ source_event: None,
+ title: "collateral".into(),
+ body: "obs-collateral".into(),
+ importance: 5,
+ };
+ insert_observation(&mut conn, &collateral_obs).unwrap();
+
+ // Collateral handoff: lives in `other_ws`, authored by the `doomed_ws`
+ // session.
+ insert_handoff(
+ &mut conn,
+ &NewHandoff {
+ workspace_id: other_ws,
+ project_id: other_proj,
+ from_session_id: Some(sid),
+ from_agent: ai_memory_core::AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "collateral handoff".into(),
+ open_questions: vec![],
+ next_steps: vec![],
+ files_touched: vec![],
+ owner_user: None,
+ },
+ )
+ .unwrap();
+
+ let preview = delete_workspace(
+ &mut conn,
+ &doomed_ws,
+ true,
+ Compaction::Skip,
+ PurgeMode::Preview,
+ )
+ .expect("a dry run must not error");
+ assert_eq!(preview.collateral_observations_deleted, 1);
+ assert_eq!(preview.collateral_handoffs_denulled, 1);
+
+ let confirmed = delete_workspace(
+ &mut conn,
+ &doomed_ws,
+ true,
+ Compaction::Skip,
+ PurgeMode::Commit,
+ )
+ .expect("the confirmed delete must still succeed after the preview");
+ assert_eq!(confirmed.collateral_observations_deleted, 1);
+ assert_eq!(confirmed.collateral_handoffs_denulled, 1);
+
+ // `other_ws` survives as a workspace; only the collateral rows are
+ // affected.
+ let other_ws_still: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM workspaces WHERE id = ?1",
+ rusqlite::params![other_ws.as_bytes()],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(other_ws_still, 1, "the other workspace must survive");
+ let observations_left = count(&conn, "SELECT COUNT(*) FROM observations");
+ assert_eq!(
+ observations_left, 0,
+ "the collateral observation in `other_ws` must actually be gone"
+ );
+ let from_session_id: Option<Vec<u8>> = conn
+ .query_row(
+ "SELECT from_session_id FROM handoffs WHERE workspace_id = ?1",
+ rusqlite::params![other_ws.as_bytes()],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert!(
+ from_session_id.is_none(),
+ "the handoff's from_session_id must be nulled, not the row deleted"
+ );
+ }
+
/// The premise of #549: after a large delete the space is *not* returned
/// to the filesystem — SQLite keeps the pages on its freelist for reuse.
/// `compact` is what gives them back, without deleting anything itself.
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 0fe67eaa..4273c8b5 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -441,6 +441,9 @@ pub(crate) enum WriteCmd {
force: bool,
/// Whether to reclaim the freed bytes afterwards (`VACUUM`).
compaction: crate::ops::Compaction,
+ /// [`crate::ops::PurgeMode::Preview`] stops right after counting and
+ /// never issues the delete — see [`crate::ops::PurgeMode`]'s doc.
+ mode: crate::ops::PurgeMode,
reply: oneshot::Sender<StoreResult<DeleteWorkspaceSummary>>,
},
/// Rename a workspace's `name` column (UUID-keyed dir doesn't move).
@@ -1935,6 +1938,11 @@ impl WriterHandle {
/// Delete a workspace and, via the `workspace_id` cascade, every project /
/// page / session under it. Refuses a non-empty workspace unless `force`.
///
+ /// `mode = `[`ops::PurgeMode::Preview`] stops right after counting and
+ /// never issues the delete — see [`ops::delete_workspace`] for why, and
+ /// for the two collateral counts (`collateral_observations_deleted`,
+ /// `collateral_handoffs_denulled`) either mode reports.
+ ///
/// # Errors
/// [`StoreError::WorkspaceNotEmpty`] when it still holds projects and
/// `force` is false; [`StoreError::NotFound`] when the workspace is absent;
@@ -1944,12 +1952,14 @@ impl WriterHandle {
workspace_id: WorkspaceId,
force: bool,
compaction: crate::ops::Compaction,
+ mode: crate::ops::PurgeMode,
) -> StoreResult<DeleteWorkspaceSummary> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::DeleteWorkspace {
workspace_id,
force,
compaction,
+ mode,
reply: tx,
})
.await?;
@@ -3601,9 +3611,11 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
workspace_id,
force,
compaction,
+ mode,
reply,
} => {
- let result = ops::delete_workspace(&mut conn, &workspace_id, force, compaction);
+ let result =
+ ops::delete_workspace(&mut conn, &workspace_id, force, compaction, mode);
send_or_warn(reply, result, "delete_workspace");
}
WriteCmd::RenameWorkspace {
diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.md
index cc48a346..e79bf586 100644
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@ -13,7 +13,7 @@ on a homelab box where mistakes are harder to undo.
| `handoffs --expire-all --confirm` | ✅ yes | no (state change only) | no (but nothing is destroyed) | Marks every **open** handoff in the scope `expired` so it stops being offered to an agent. Rows, summaries and provenance are kept and stay visible in the audit log. Unlike the automatic sweep it does **not** spare manual handoffs or ones from another directory — those exemptions are exactly what a leftover backlog is made of, so honouring them would clear nothing. `--older-than-days N` keeps recent batons. Owner-scoped: never touches another user's baton. |
| `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. Logical delete by default; `"compact": true` additionally rebuilds the FTS indexes and `VACUUM`s (see below). |
+| `/admin/delete-workspace` | ✅ yes | the workspace and every child project, **plus** any observation stamped into a different workspace by one of this workspace's sessions (cascades regardless of the observation's own `workspace_id`), and it nulls (does not delete) the session reference on any handoff in a different workspace that this workspace's sessions authored or accepted | 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. Logical delete by default; `"compact": true` additionally rebuilds the FTS indexes and `VACUUM`s (see below). `"dry_run": true` previews the same counts, including the cross-workspace ones, without deleting anything — see below. |
| `move-project --confirm` | ✅ yes | source only in the merge case (a `Reject`-policy `purge_project` webhook can still abort the source teardown leaving everything intact) | no | Fresh destination → lossless **true move** (re-stamp `workspace_id`, keep `project_id`, rename the dir): sessions/observations/handoffs + history all survive. Destination with a same-named project → **copy+purge merge**: only latest pages migrate. |
| `move-session <id> --to --confirm` | ✅ yes | no | yes (move it back) | Re-stamps one session (or every session touching `--from-project`) into another project: `sessions`, `observations`, its `handoffs`, consolidation jobs, auto-improve runs/claims and its `sessions/<id>.md` page, one transaction per session; the page file moves with it (`--pages move`, default) or is retired for regeneration. Without `--confirm` it is a real dry run (rolled back). Refuses with `409` an open session or a pending consolidation job unless `--force`. |
| `backup --to` | ✅ yes | no | n/a | Streams a gzipped tarball from the server's online `sqlite3 .backup` plus the wiki tree. Safe alongside the live writer. |
@@ -405,7 +405,13 @@ logical delete; see
2. Run blocking `op=purge_workspace` admission. A reject-policy webhook aborts
before DB rows or files are removed.
3. Take a pre-delete checkpoint if the wiki tree is dirty.
-4. Delete the workspace in one writer-actor transaction.
+4. Delete the workspace in one writer-actor transaction, counting
+ `projects_deleted`, `pages_deleted`, `sessions_deleted`,
+ `observations_deleted`, `handoffs_deleted`, `embeddings_deleted`,
+ `workstreams_deleted`, `managed_runs_deleted`, plus the two cross-workspace
+ counts (`collateral_observations_deleted`, `collateral_handoffs_denulled`
+ — the same shape `purge-project`'s preview reports one level down, at
+ project rather than workspace granularity) before issuing the `DELETE`.
5. Remove `<wiki_root>/<workspace_id>` and every affected
`<data_dir>/raw/workstreams/<workstream_id>` directory from disk. The
response reports `workstreams_deleted`, `managed_runs_deleted`, and the
@@ -424,6 +430,33 @@ Failure modes:
populated and `partial_failure: true` on async mirror notifications; manual
cleanup of the reported path is required.
+#### Preview with `"dry_run": true`
+
+`"dry_run": true` in the request body always wins — `{"force": true,
+"dry_run": true}` still only previews — so a preview request can never
+become destructive by accident, the same pattern `purge-project` uses for
+its own `dry_run` field. The preview runs step 4's
+counts (including the two cross-workspace ones) against the same rows a
+confirmed delete would remove, using the same `409` for a non-empty
+workspace without `force` and the same `404` for an unknown workspace, and
+returns before ever issuing the `DELETE`. Steps 2, 3, 5, 6, and 7 never run
+under `dry_run`: no admission call, no wiki directory removal, no mirror
+dispatch, no checkpoint — `files_deleted`/`files_failed` are always empty and
+`pre_checkpoint`/`checkpoint` are always absent. The reply carries
+`"dry_run": true`. There is no CLI subcommand for `delete-workspace` today,
+so this preview is HTTP-only.
+
+The two `collateral_*` fields cover only observations and handoffs, the same
+set `purge-project`'s own preview covers. `agent_messages` (V64, the
+cross-workspace mailbox) is affected the same cross-workspace way and is
+neither counted nor previewed today, as a known follow-up: a message TO a
+*different* workspace's mailbox is deleted outright if it was sent FROM the
+workspace being deleted (`from_workspace_id` is `ON DELETE CASCADE`, with no
+regard for the message's own `to_workspace_id`), and `from_session_id`/
+`claimed_by_session` pointers on messages elsewhere are nulled, not deleted,
+when they reference a session that lived in the deleted workspace (`ON DELETE
+SET NULL`).
+
### `move-project`
```bash
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 87455a96..1c060b8c 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -44,6 +44,7 @@ boundary not yet built.
| 10 | Destructive-op live-process refusal + confirm flags (invariant #9); `purge-project`'s `dry_run` always wins over `confirm` so a preview request can never become destructive | `ai-memory-cli/src/commands/process_guard.rs` `sibling_processes` + confirm flags in `reset`/`restore`/`reindex`/`uninstall --purge-data`/`purge_project`; `admin.rs` `handle_purge_project` checks `req.dry_run` unconditionally, before `req.confirm`, mirroring `reclaim-ledger-versions` | `admin_purge.rs` confirm→400; `removal.rs` — injected live-sibling makes each destructive command bail before touching the data dir; `admin_purge.rs` `purge_project_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing (the regression this row now also covers); `ops.rs` `purge_project_dry_run_changes_nothing` — every project-scoped row count, the `purged_scopes` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_project_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_project_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — a purge of project P collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project Q (via `sessions` cascading out of P), and both the preview and the confirmed report count it | STRONG |
| 10b | Session purge is scope+owner-bound (no cross-session/project over-delete); `purge-session`'s `dry_run` always wins over `confirm`, same as `purge-project` | `ai-memory-store/src/ops.rs` `purge_session` — selection scoped to `(workspace_id, project_id)` and keyed on this session's own `summary_page_id` **or** `path='sessions/<sid>.md'` + `json_extract(frontmatter_json,'$.session_id')=<sid>` (frontmatter owner, not the recursive latest-chain); `in_scope==0 → NotFound` fail-closed; whole op in one transaction; `admin.rs` `handle_purge_session` checks `req.dry_run` unconditionally, before `req.confirm` | `ops.rs` `purge_session_leaves_a_sibling_session_in_the_same_project_intact`, `…refuses_a_session_from_another_project_and_deletes_nothing`, `…refuses_a_session_from_another_workspace`, `…does_not_delete_an_identically_pathed_page_in_another_project`, `…removes_older_summary_versions_without_deleting_prior_manual_page` (#862); `admin_purge.rs` `purge_session_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing; `ops.rs` `purge_session_dry_run_changes_nothing` — every table a session purge touches, the `purged_sessions` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_session_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_session_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — purging session S collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project (via `S`'s own id cascading), and both the preview and the confirmed report count it; `admin_purge.rs` `purge_session_dry_run_refuses_a_session_outside_its_named_scope` — the same session previewed under a different real project (same workspace) or a different real workspace whose project shares the name both 404 with no counts in the body, with the session's own scope as the 200 control | STRONG |
| 10c | Ledger reclaim is content-gated, not filename-gated (invariant #16) | `ai-memory-store/src/ops.rs` `reclaim_ledger_versions` — a candidate row must pass `ai_memory_core::log_ledger::body_opens_with_log_ledger` on its own `body`, and only `is_latest=0 AND superseded_at IS NULL` rows are eligible, so decay-owned rows stay with `forget-sweep`; confirm gate in `admin.rs` `handle_reclaim_ledger_versions` | `reclaim_ledger_versions.rs` `a_prose_page_wearing_the_ledger_name_keeps_its_whole_version_chain`, `an_ordinary_page_chain_in_another_project_is_untouched`, `a_decay_tombstone_stays_with_the_sweep_that_owns_it`; `admin_reclaim_ledger_versions.rs` `deleting_without_confirm_is_refused_and_changes_nothing` (with dry-run and confirmed controls) | STRONG |
+| 10d | Workspace delete's own row counts are scope-bound to `workspace_id` (a workspace's *own* rows are never over- or under-counted by a sibling workspace's), its cross-workspace observation/handoff cascade is reported by both preview and confirm rather than prevented (same as `purge-project` one level down), the non-empty guard fails closed without `force`, and `delete-workspace`'s `dry_run` always wins | `ai-memory-store/src/ops.rs` `delete_workspace` — every direct count and the `DELETE FROM workspaces` itself are scoped by `workspace_id = ?1`; the two `collateral_*` counts are scoped by `workspace_id != ?1` so a row is counted as one or the other but never both; `projects_deleted > 0 && !force → WorkspaceNotEmpty` fail-closed, and a missing workspace is `NotFound`, both checked identically under `PurgeMode::Preview` and `PurgeMode::Commit`; whole op in one transaction; `admin.rs` `handle_delete_workspace` checks `req.dry_run` unconditionally, before building the confirmed path, mirroring `reclaim-ledger-versions`/`purge-project`; root-only gate is the shared `/admin/*` multi-user auth ladder, not a separate check | `admin_move.rs` `delete_workspace_dry_run_never_counts_a_different_workspaces_rows` — previewing workspace A counts only its own project/page/session/observation/handoff rows, not workspace B's (which holds two like-named projects and its own full row set), and a session living in B that stamps an observation directly into A is counted in A's own `observations_deleted`, never in `collateral_observations_deleted` (the two counts are mutually exclusive by construction); `admin_move.rs` `delete_workspace_force_true_and_dry_run_true_still_only_previews` — `{"force": true, "dry_run": true}` deletes nothing; `ops.rs` `delete_workspace_dry_run_changes_nothing` — every table's row count, including `workspaces` itself and the `purged_scopes` tombstone (the two tables a confirmed delete's own transaction writes to), is identical before/after a `PurgeMode::Preview` run; `ops.rs` `delete_workspace_dry_run_and_confirmed_delete_both_report_collateral_damage_in_another_workspace` and `admin_move.rs` of the same name — deleting workspace W collaterally deletes an observation, and orphans a handoff's session reference, in a *different* workspace (via `sessions` cascading out of W), and both the preview and the confirmed response count it identically — the cascade itself is reported, not blocked, by either; `admin_move.rs` `delete_workspace_dry_run_refuses_non_empty_without_force` / `delete_workspace_dry_run_nonexistent_workspace_returns_404` — same `409`/`404` a confirmed delete would give; `admin.rs` `multiuser_delete_workspace_dry_run_rejects_db_user_and_anonymous` — root reaches the preview handler (404 control), DB user gets 403, anonymous gets 401 | STRONG |
| 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded` | STRONG |
| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn) | `capture_policy.rs` per-agent `…honors_exclusions` tests | STRONG |
| 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH |