Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(cli): purge-session previews what it would delete before --confirm
Maxsuel Einsteina43da2641107
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 11150555..89d5c55c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -237,6 +237,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`session-end` cannot double-close a session. (#623 follow-up, #933)### Changed+- `ai-memory purge-session` without `--confirm` now previews what a confirmed+ purge would delete before refusing, the same way `purge-project` does (#945):+ `Would purge session from <ws>/<proj>: N observations, N handoffs, N pages,+ N auto-improve runs.` (the session id itself is never printed). The server+ takes a new `dry_run` field on `POST /admin/purge-session` that always wins+ over `confirm`. It only counts; no delete, wiki file removal, webhook,+ audit row or checkpoint runs. `POST /admin/purge-session`'s confirmed+ report also gains two new fields, always present on both the preview and+ the confirmed response: `collateral_observations_deleted` and+ `collateral_handoffs_denulled`, counting what the purge cascades into+ *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)- `ai-memory purge-project` without `--confirm` now previews what a confirmedpurge would delete before refusing: `Would purge <ws>/<proj>: N pages, Nsessions, N observations, …`, with the same 404/409 a real purge gives.diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex cc9758cf..fd7182a4 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -1247,6 +1247,18 @@ pub struct PurgeSessionArgs {pub project: Option<String>,/// REQUIRED for the purge to run. Without this flag the CLI errors/// out — purging is destructive and irreversible.+ ///+ /// Before erroring, the CLI asks the server for a preview (bounded to a+ /// few seconds, auth refresh included): the reported counts+ /// (observations, handoffs, pages, auto-improve runs, plus any+ /// collateral rows a purge of this session would delete or orphan in+ /// *another* project) come from the same queries a confirmed purge+ /// itself uses to decide what to delete. The preview is best-effort and+ /// never changes the outcome, only what gets printed before it: a+ /// 404/403 (or anything else unexpected) prints the server's own error+ /// first; a timeout, an unreachable server, or an older server that+ /// predates this preview just gets the plain refusal, same as before+ /// this existed.#[arg(long)]pub confirm: bool,/// Also reclaim the freed bytes: rebuild the affected FTS indexes anddiff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 78d3c9d3..9e8b352a 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -62,6 +62,7 @@ pub mod path_util;pub mod pending_writes;pub mod project;pub mod project_registry;+pub mod purge_preview;pub mod purge_project;pub mod purge_session;pub mod read_page;diff --git a/crates/ai-memory-cli/src/commands/purge_preview.rs b/crates/ai-memory-cli/src/commands/purge_preview.rsnew file mode 100644index 00000000..e14eb624--- /dev/null+++ b/crates/ai-memory-cli/src/commands/purge_preview.rs@@ -0,0 +1,103 @@+//! Shared best-effort dry-run preview machinery for `purge-project` and+//! `purge-session`.+//!+//! Both subcommands refuse without `--confirm`, but first ask the server for+//! a bounded preview (`"dry_run": true`, which wins over `confirm`+//! server-side) of what the confirmed run would do. The HTTP round trip, its+//! timeout, and the classification of the result into "print this" vs "stay+//! silent" are identical between the two commands — only the request body's+//! shape, the endpoint path, and the summary line's wording differ, so those+//! stay in `purge_project.rs` / `purge_session.rs` and this module holds only+//! what would otherwise be copy-pasted between them.++use std::time::Duration;++use serde::Serialize;++use crate::config::Config;+use crate::http_client::{ServerEndpoint, ServerResponseError, post_json};++/// How long the preview request (auth resolution plus the HTTP round trip)+/// is allowed to take before this falls back to the plain refusal. The+/// preview is optional information layered on top of a refusal that must+/// still happen either way, so it must never be the reason `--confirm` takes+/// noticeably longer than it used to.+pub const PREVIEW_TIMEOUT: Duration = Duration::from_secs(5);++/// What became of the best-effort preview request, reduced to what deciding+/// whether — and what — to print needs. Kept separate from the network call+/// itself so the printing decision is a pure function and testable without a+/// server.+pub enum PreviewOutcome {+ /// A 200 with `"dry_run": true`: the server understood the request and+ /// ran the preview.+ Previewed(serde_json::Value),+ /// A 200 without `dry_run` set: an old-enough server both predates the+ /// field AND happens to 200 an unrecognized shape. Treated the same as+ /// not getting a preview at all.+ Ignored,+ /// A non-2xx response with a body worth showing: the scope resolved to+ /// something the operator should know about before the refusal (a 404+ /// naming the missing project/session, a 409 naming a live managed run,+ /// a 403 naming the auth problem), or an unexpected status this command+ /// has no specific handling for.+ Refused { status: u16, body: String },+ /// The request predates `dry_run` support (400, the pre-existing+ /// "confirm=true" refusal body) — not worth repeating, since `run` below+ /// prints its own version of exactly that message next regardless.+ OlderServer,+ /// Timed out or never reached a server at all (DNS/connect failure,+ /// auth-refresh hang, etc). Indistinguishable from the operator's+ /// perspective, and neither is this command's business to diagnose.+ Unreachable,+}++/// Run the preview request under [`PREVIEW_TIMEOUT`] and classify the+/// result. Auth resolution (`ServerEndpoint::from_config_resolving_auth`,+/// which can itself refresh an OIDC token over the network) runs inside the+/// same timeout so a hung refresh cannot silently make a `--confirm`-less+/// purge command block far longer than the rest of it ever has.+pub async fn run_preview<Req: Serialize>(+ config: &Config,+ path: &str,+ request: &Req,+) -> PreviewOutcome {+ let attempt = tokio::time::timeout(PREVIEW_TIMEOUT, async {+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;+ post_json::<_, serde_json::Value>(&endpoint, path, request).await+ })+ .await;++ let Ok(result) = attempt else {+ return PreviewOutcome::Unreachable;+ };+ match result {+ Ok(report) if report["dry_run"].as_bool().unwrap_or(false) => {+ PreviewOutcome::Previewed(report)+ }+ Ok(_) => PreviewOutcome::Ignored,+ Err(e) => match e.downcast_ref::<ServerResponseError>() {+ Some(resp) if resp.status().as_u16() == 400 => PreviewOutcome::OlderServer,+ Some(resp) => PreviewOutcome::Refused {+ status: resp.status().as_u16(),+ body: resp.body().to_string(),+ },+ // Not an HTTP response at all: connect/DNS failure, request+ // timeout already handled above, or a body that failed to+ // deserialize as JSON.+ None => PreviewOutcome::Unreachable,+ },+ }+}++/// Format a `PreviewOutcome::Refused` body as the one line every caller+/// prints before its refusal: `Preview refused (<status>): <message>`. The+/// message is the server's own `{"error": ...}` string when the body parses+/// that way, and the raw body verbatim otherwise.+pub fn refused_message(status: u16, body: &str) -> String {+ let message = serde_json::from_str::<serde_json::Value>(body)+ .ok()+ .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string))+ .unwrap_or_else(|| body.to_string());+ format!("Preview refused ({status}): {message}")+}diff --git a/crates/ai-memory-cli/src/commands/purge_project.rs b/crates/ai-memory-cli/src/commands/purge_project.rsindex 8650e477..91f31890 100644--- a/crates/ai-memory-cli/src/commands/purge_project.rs+++ b/crates/ai-memory-cli/src/commands/purge_project.rs@@ -1,13 +1,12 @@//! `ai-memory purge-project` — thin HTTP client for project purge.-use std::time::Duration;-use anyhow::{Result, bail};use serde::Serialize;use crate::cli::PurgeProjectArgs;+use crate::commands::purge_preview::{PreviewOutcome, refused_message, run_preview};use crate::config::Config;-use crate::http_client::{ServerEndpoint, ServerResponseError, post_json};+use crate::http_client::{ServerEndpoint, post_json};/// Request sent to `POST /admin/purge-project`.#[derive(Serialize)]@@ -29,13 +28,6 @@ struct PurgeProjectRequest {dry_run: bool,}-/// How long the preview request (auth resolution plus the HTTP round trip)-/// is allowed to take before this falls back to the plain refusal. The-/// preview is optional information layered on top of a refusal that must-/// still happen either way, so it must never be the reason `--confirm` takes-/// noticeably longer than it used to.-const PREVIEW_TIMEOUT: Duration = Duration::from_secs(5);-/// One line naming what a purge (real or previewed) removed, in the fixed/// order the operator can grep for: pages, sessions, observations, handoffs,/// embeddings, workstreams, managed runs. `verb` is `"Purged"` for a@@ -79,34 +71,6 @@ fn purge_summary_line(verb: &str, label: &str, report: &serde_json::Value) -> Stline}-/// What became of the best-effort preview request, reduced to what deciding-/// whether — and what — to print needs. Kept separate from the network call-/// itself so the printing decision is a pure function and testable without a-/// server.-enum PreviewOutcome {- /// A 200 with `"dry_run": true`: the server understood the request and- /// ran the preview.- Previewed(serde_json::Value),- /// A 200 without `dry_run` set: an old-enough server both predates the- /// field AND happens to 200 an unrecognized shape. Treated the same as- /// not getting a preview at all.- Ignored,- /// A non-2xx response with a body worth showing: the scope resolved to- /// something the operator should know about before the refusal (a 404- /// naming the missing project, a 409 naming the live managed run, a 403- /// naming the auth problem), or an unexpected status this command has no- /// specific handling for.- Refused { status: u16, body: String },- /// The request predates `dry_run` support (400, the pre-existing- /// "confirm=true" refusal body) — not worth repeating, since `run` below- /// prints its own version of exactly that message next regardless.- OlderServer,- /// Timed out or never reached a server at all (DNS/connect failure,- /// auth-refresh hang, etc). Indistinguishable from the operator's- /// perspective, and neither is this command's business to diagnose.- Unreachable,-}-/// Decide what to print, if anything, before the refusal — pure, so it is/// unit-tested without a server. `fallback_label` is used only when the/// server's own report has no `label` field.@@ -116,51 +80,11 @@ fn preview_message(outcome: &PreviewOutcome, fallback_label: &str) -> Option<Strlet label = report["label"].as_str().unwrap_or(fallback_label);Some(purge_summary_line("Would purge", label, report))}- PreviewOutcome::Refused { status, body } => {- let message = serde_json::from_str::<serde_json::Value>(body)- .ok()- .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string))- .unwrap_or_else(|| body.clone());- Some(format!("Preview refused ({status}): {message}"))- }+ PreviewOutcome::Refused { status, body } => Some(refused_message(*status, body)),PreviewOutcome::Ignored | PreviewOutcome::OlderServer | PreviewOutcome::Unreachable => None,}}-/// Run the preview request under [`PREVIEW_TIMEOUT`] and classify the-/// result. Auth resolution (`ServerEndpoint::from_config_resolving_auth`,-/// which can itself refresh an OIDC token over the network) runs inside the-/// same timeout so a hung refresh cannot silently make `--confirm`-less-/// purge-project block far longer than the rest of this command ever has.-async fn run_preview(config: &Config, request: &PurgeProjectRequest) -> PreviewOutcome {- let attempt = tokio::time::timeout(PREVIEW_TIMEOUT, async {- let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;- post_json::<_, serde_json::Value>(&endpoint, "/admin/purge-project", request).await- })- .await;-- let Ok(result) = attempt else {- return PreviewOutcome::Unreachable;- };- match result {- Ok(report) if report["dry_run"].as_bool().unwrap_or(false) => {- PreviewOutcome::Previewed(report)- }- Ok(_) => PreviewOutcome::Ignored,- Err(e) => match e.downcast_ref::<ServerResponseError>() {- Some(resp) if resp.status().as_u16() == 400 => PreviewOutcome::OlderServer,- Some(resp) => PreviewOutcome::Refused {- status: resp.status().as_u16(),- body: resp.body().to_string(),- },- // Not an HTTP response at all: connect/DNS failure, request- // timeout already handled above, or a body that failed to- // deserialize as JSON.- None => PreviewOutcome::Unreachable,- },- }-}-/// Run the `purge-project` subcommand.////// Resolves the project name (auto-derived from the git repo root when@@ -170,8 +94,9 @@ async fn run_preview(config: &Config, request: &PurgeProjectRequest) -> PreviewO/// Without `--confirm`, first asks the server for a preview (`dry_run:/// true`, which wins over `confirm` server-side): the server reports the/// counts a confirmed purge would produce without deleting anything. That-/// preview is best-effort, bounded by [`PREVIEW_TIMEOUT`], and never changes-/// the outcome — only what gets printed before it:+/// preview is best-effort, bounded by+/// [`purge_preview::PREVIEW_TIMEOUT`](crate::commands::purge_preview::PREVIEW_TIMEOUT),+/// and never changes the outcome — only what gets printed before it:/// - a successful preview prints the "Would purge ..." line;/// - a 404/409/403 (or any other unexpected status) prints the server's own/// error first, since the operator asked what would happen and the server@@ -197,7 +122,7 @@ pub async fn run(config: &Config, args: PurgeProjectArgs) -> Result<()> {compact: args.compact,dry_run: true,};- let outcome = run_preview(config, &request).await;+ let outcome = run_preview(config, "/admin/purge-project", &request).await;let fallback_label = format!("{}/{}", workspace, project);if let Some(line) = preview_message(&outcome, &fallback_label) {println!("{line}");@@ -455,7 +380,7 @@ mod tests {).await;let config = config_for(&tmp, url);- let outcome = run_preview(&config, &preview_request()).await;+ let outcome = run_preview(&config, "/admin/purge-project", &preview_request()).await;assert!(matches!(outcome, PreviewOutcome::OlderServer));assert!(preview_message(&outcome, "default/scratch").is_none());}@@ -471,7 +396,7 @@ mod tests {).await;let config = config_for(&tmp, url);- let outcome = run_preview(&config, &preview_request()).await;+ let outcome = run_preview(&config, "/admin/purge-project", &preview_request()).await;match &outcome {PreviewOutcome::Refused { status, body } => {assert_eq!(*status, 404);@@ -501,7 +426,7 @@ mod tests {).await;let config = config_for(&tmp, url);- let outcome = run_preview(&config, &preview_request()).await;+ let outcome = run_preview(&config, "/admin/purge-project", &preview_request()).await;let msg = preview_message(&outcome, "default/scratch").expect("must print a line");assert!(msg.starts_with("Would purge default/scratch: 3 pages, 1 sessions, 1063"));}@@ -518,7 +443,7 @@ mod tests {let addr = listener.local_addr().unwrap();drop(listener);let config = config_for(&tmp, format!("http://{addr}"));- let outcome = run_preview(&config, &preview_request()).await;+ let outcome = run_preview(&config, "/admin/purge-project", &preview_request()).await;assert!(matches!(outcome, PreviewOutcome::Unreachable));assert!(preview_message(&outcome, "default/scratch").is_none());}diff --git a/crates/ai-memory-cli/src/commands/purge_session.rs b/crates/ai-memory-cli/src/commands/purge_session.rsindex 8517031b..32992797 100644--- a/crates/ai-memory-cli/src/commands/purge_session.rs+++ b/crates/ai-memory-cli/src/commands/purge_session.rs@@ -4,6 +4,7 @@ use anyhow::{Result, bail};use serde::Serialize;use crate::cli::PurgeSessionArgs;+use crate::commands::purge_preview::{PreviewOutcome, refused_message, run_preview};use crate::config::Config;use crate::http_client::{ServerEndpoint, post_json};@@ -16,6 +17,72 @@ struct PurgeSessionRequest {confirm: bool,/// Rebuild the FTS indexes and VACUUM after the delete commits.compact: bool,+ /// Preview only: wins over `confirm` on the server (mirrors+ /// `purge-project`, which itself mirrors `reclaim-ledger-versions`), so+ /// this is always sent alongside `confirm: false` here — never both+ /// true. Older servers that predate this field simply never look at it+ /// (an unknown JSON field is not a deserialize error), which is why the+ /// fallback in [`purge_preview::run_preview`](crate::commands::purge_preview::run_preview)+ /// only has to handle the request failing outright, never the field+ /// being silently misread.+ dry_run: bool,+}++/// One line naming what a session purge (real or previewed) removed, in the+/// fixed order the operator can grep for: observations, handoffs, pages,+/// auto-improve runs. `verb` is `"Purged"` for a confirmed run or `"Would+/// purge"` for a preview — everything else about the line is identical, so a+/// script matching one also matches the other.+///+/// The session id is deliberately never part of this line, confirmed or+/// previewed: the caller already has it (they passed `--session-id`), and+/// this command exists to make a session stop existing — echoing its id+/// into terminal scrollback and shell history leaves a pointer to the thing+/// just erased (or about to be). The scope (`label`) and the counts are what+/// confirm the operation did, or would do, what was asked.+fn purge_summary_line(verb: &str, label: &str, report: &serde_json::Value) -> String {+ let observations = report["observations_deleted"].as_u64().unwrap_or(0);+ let handoffs = report["handoffs_deleted"].as_u64().unwrap_or(0);+ let pages = report["pages_deleted"].as_u64().unwrap_or(0);+ let auto_improve_runs = report["auto_improve_runs_deleted"].as_u64().unwrap_or(0);+ let mut line = format!(+ "{verb} session from {label}: {observations} observations, {handoffs} handoffs, \+ {pages} pages, {auto_improve_runs} auto-improve runs."+ );+ // The mirror of the incident `purge-project`'s own preview guards+ // against, one level down at session granularity: purging this session+ // also collaterally deletes/orphans rows that live in *other* projects,+ // via this session's own id (not the project's rows) cascading. Silent+ // when zero so the common case reads exactly as before.+ let collateral_observations = report["collateral_observations_deleted"]+ .as_u64()+ .unwrap_or(0);+ if collateral_observations > 0 {+ line.push_str(&format!(+ " Plus {collateral_observations} observations in other projects via this session."+ ));+ }+ let collateral_handoffs = report["collateral_handoffs_denulled"].as_u64().unwrap_or(0);+ if collateral_handoffs > 0 {+ line.push_str(&format!(+ " Plus {collateral_handoffs} handoffs in other projects that will lose their \+ session reference (set to NULL, not deleted)."+ ));+ }+ line+}++/// Decide what to print, if anything, before the refusal — pure, so it is+/// unit-tested without a server. `fallback_label` is used only when the+/// server's own report has no scope to build a label from (this endpoint has+/// no `label` field, unlike `purge-project`, so the caller always supplies+/// one built from `--workspace`/`--project`).+fn preview_message(outcome: &PreviewOutcome, label: &str) -> Option<String> {+ match outcome {+ PreviewOutcome::Previewed(report) => Some(purge_summary_line("Would purge", label, report)),+ PreviewOutcome::Refused { status, body } => Some(refused_message(*status, body)),+ PreviewOutcome::Ignored | PreviewOutcome::OlderServer | PreviewOutcome::Unreachable => None,+ }}/// Run the `purge-session` subcommand.@@ -25,6 +92,21 @@ struct PurgeSessionRequest {/// session that does not belong to it, so a UUID alone is never authority/// over another workspace or project.///+/// Without `--confirm`, first asks the server for a preview (`dry_run:+/// true`, which wins over `confirm` server-side, exactly like+/// `purge-project`): the server reports the counts a confirmed purge would+/// produce without deleting anything. That preview is best-effort, bounded+/// by+/// [`purge_preview::PREVIEW_TIMEOUT`](crate::commands::purge_preview::PREVIEW_TIMEOUT),+/// and never changes the outcome — only what gets printed before it:+/// - a successful preview prints the "Would purge session from ..." line;+/// - a 404/403 (or any other unexpected status) prints the server's own+/// error first, since the operator asked what would happen and the server+/// has an answer, just not the one this command expected;+/// - a plain 400 (an older server that predates `dry_run`), a timeout, or an+/// unreachable server print nothing extra — the refusal below already+/// says everything a 400 would.+////// # Errors/// Returns an error when `--confirm` is absent, the session id is not a/// UUID, the server is unreachable, or the server returns a non-2xx@@ -44,7 +126,21 @@ pub async fn run(config: &Config, args: PurgeSessionArgs) -> Result<()> {);}+ let label = format!("{workspace}/{project}");+if !args.confirm {+ let request = PurgeSessionRequest {+ workspace: workspace.clone(),+ project: project.clone(),+ session_id: session_id.to_owned(),+ confirm: false,+ compact: args.compact,+ dry_run: true,+ };+ let outcome = run_preview(config, "/admin/purge-session", &request).await;+ if let Some(line) = preview_message(&outcome, &label) {+ println!("{line}");+ }bail!("purge-session is destructive and irreversible.\n\Re-run with --confirm to proceed:\n\n \@@ -63,24 +159,12 @@ pub async fn run(config: &Config, args: PurgeSessionArgs) -> Result<()> {session_id: session_id.to_owned(),confirm: true,compact: args.compact,+ dry_run: false,},).await?;- let n = |key: &str| report[key].as_u64().unwrap_or(0);- // The session id is deliberately not echoed. The caller passed it, so- // repeating it adds nothing they do not have, and this command exists to- // make a session stop existing — writing its id into terminal scrollback- // and shell history leaves a pointer to the thing just erased. The scope- // and the counts are what confirm the operation did what was asked.- println!(- "Purged session from {workspace}/{project}: \- {} observations, {} handoffs, {} pages, {} auto-improve runs.",- n("observations_deleted"),- n("handoffs_deleted"),- n("pages_deleted"),- n("auto_improve_runs_deleted"),- );+ println!("{}", purge_summary_line("Purged", &label, &report));if let Some(paths) = report["files_deleted"].as_array()&& !paths.is_empty(){@@ -112,3 +196,253 @@ pub async fn run(config: &Config, args: PurgeSessionArgs) -> Result<()> {}Ok(())}++#[cfg(test)]+mod tests {+ use super::*;++ fn report(dry_run: bool) -> serde_json::Value {+ serde_json::json!({+ "session_id": "00000000-0000-0000-0000-000000000000",+ "workspace": "default",+ "project": "my-project",+ "observations_deleted": 1063,+ "handoffs_deleted": 0,+ "pages_deleted": 1,+ "auto_improve_runs_deleted": 2,+ "removed_paths": [],+ "collateral_observations_deleted": 0,+ "collateral_handoffs_denulled": 0,+ "files_deleted": [],+ "files_failed": [],+ "compacted": false,+ "dry_run": dry_run,+ })+ }++ /// Pins the exact wording and field order a script would grep for, and+ /// that the session id never appears in it.+ /// `purge_summary_line` is the single source for both the confirmed+ /// "Purged" line and the preview's "Would purge" line, so this also+ /// proves the two can never drift apart.+ #[test]+ fn purge_summary_line_matches_the_documented_wording() {+ let confirmed = report(false);+ let line = purge_summary_line("Purged", "default/my-project", &confirmed);+ assert_eq!(+ line,+ "Purged session from default/my-project: 1063 observations, 0 handoffs, \+ 1 pages, 2 auto-improve runs."+ );+ assert!(+ !line.contains("00000000"),+ "the session id must never appear in the printed line: {line}"+ );++ let preview = report(true);+ assert_eq!(+ purge_summary_line("Would purge", "default/my-project", &preview),+ "Would purge session from default/my-project: 1063 observations, 0 handoffs, \+ 1 pages, 2 auto-improve runs."+ );+ }++ /// Missing counters must not panic and must not silently show as+ /// non-zero.+ #[test]+ fn purge_summary_line_defaults_missing_counters_to_zero() {+ let empty = serde_json::json!({});+ assert_eq!(+ purge_summary_line("Would purge", "default/x", &empty),+ "Would purge session from default/x: 0 observations, 0 handoffs, \+ 0 pages, 0 auto-improve runs."+ );+ }++ /// The mirror-of-the-incident collateral counts, when present, must be+ /// visible in the same line the operator already reads — silent when+ /// zero (the common case), spelled out when not.+ #[test]+ fn purge_summary_line_calls_out_collateral_damage_when_present() {+ let mut r = report(true);+ r["collateral_observations_deleted"] = serde_json::json!(7);+ r["collateral_handoffs_denulled"] = serde_json::json!(2);+ let line = purge_summary_line("Would purge", "default/looks-empty", &r);+ assert!(+ line.contains("Plus 7 observations in other projects via this session."),+ "collateral observations must be called out: {line}"+ );+ assert!(+ line.contains("Plus 2 handoffs in other projects"),+ "collateral handoffs must be called out: {line}"+ );+ }++ /// A successful preview prints the "Would purge" line.+ #[test]+ fn preview_message_prints_the_would_purge_line_on_success() {+ let outcome = PreviewOutcome::Previewed(report(true));+ let msg = preview_message(&outcome, "default/my-project").expect("must print a line");+ assert!(msg.starts_with("Would purge session from default/my-project:"));+ }++ /// A 404 (session outside the named scope) is worth showing before the+ /// refusal: the operator asked what would happen, and 404 is the+ /// server's answer.+ #[test]+ fn preview_message_surfaces_a_404_before_the_refusal() {+ let outcome = PreviewOutcome::Refused {+ status: 404,+ body: r#"{"error":"session ... not found in this workspace/project"}"#.to_string(),+ };+ let msg = preview_message(&outcome, "default/ghost").expect("must print a line");+ assert_eq!(+ msg,+ "Preview refused (404): session ... not found in this workspace/project"+ );+ }++ /// A body that isn't the expected `{"error": ...}` shape still prints+ /// something rather than nothing — the raw body, verbatim.+ #[test]+ fn preview_message_falls_back_to_the_raw_body_when_not_json() {+ let outcome = PreviewOutcome::Refused {+ status: 403,+ body: "Forbidden".to_string(),+ };+ let msg = preview_message(&outcome, "default/x").expect("must print a line");+ assert_eq!(msg, "Preview refused (403): Forbidden");+ }++ /// The three silent-fallback cases: an older server's plain 400, a+ /// timeout/connect failure, and a 200 that oddly never set `dry_run`.+ #[test]+ fn preview_message_is_silent_for_older_server_unreachable_and_ignored() {+ assert!(preview_message(&PreviewOutcome::OlderServer, "default/x").is_none());+ assert!(preview_message(&PreviewOutcome::Unreachable, "default/x").is_none());+ assert!(preview_message(&PreviewOutcome::Ignored, "default/x").is_none());+ }++ // -----------------------------------------------------------------+ // `run_preview` against a real (local) server: proves the HTTP-status+ // classification end to end, not just the pure `preview_message` mapping+ // above.+ // -----------------------------------------------------------------++ fn config_for(tmp: &tempfile::TempDir, server_url: String) -> Config {+ Config {+ data_dir: tmp.path().to_path_buf(),+ server_url,+ ..Config::default()+ }+ }++ async fn spawn_fixed_response(status: u16, body: &'static str) -> String {+ let app = axum::Router::new().route(+ "/admin/purge-session",+ axum::routing::post(move || async move {+ (+ axum::http::StatusCode::from_u16(status).unwrap(),+ axum::Json(serde_json::from_str::<serde_json::Value>(body).unwrap()),+ )+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });+ format!("http://{addr}")+ }++ fn preview_request() -> PurgeSessionRequest {+ PurgeSessionRequest {+ workspace: "default".into(),+ project: "scratch".into(),+ session_id: "00000000-0000-0000-0000-000000000000".into(),+ confirm: false,+ compact: false,+ dry_run: true,+ }+ }++ /// An older server that predates `dry_run` answers the plain 400+ /// "confirm=true" refusal it always has — the CLI must fall back+ /// silently, not print anything extra.+ #[tokio::test]+ async fn run_preview_classifies_a_400_as_older_server() {+ let tmp = tempfile::TempDir::new().unwrap();+ let url = spawn_fixed_response(+ 400,+ r#"{"error": "destructive operation requires confirm=true"}"#,+ )+ .await;+ let config = config_for(&tmp, url);+ let outcome = run_preview(&config, "/admin/purge-session", &preview_request()).await;+ assert!(matches!(outcome, PreviewOutcome::OlderServer));+ assert!(preview_message(&outcome, "default/scratch").is_none());+ }++ /// A 404 is surfaced: the operator asked what a purge of this session+ /// would do, and "no such session" is a real, useful answer.+ #[tokio::test]+ async fn run_preview_classifies_a_404_as_refused_and_surfaces_the_message() {+ let tmp = tempfile::TempDir::new().unwrap();+ let url = spawn_fixed_response(+ 404,+ r#"{"error": "session ... not found in this workspace/project"}"#,+ )+ .await;+ let config = config_for(&tmp, url);+ let outcome = run_preview(&config, "/admin/purge-session", &preview_request()).await;+ match &outcome {+ PreviewOutcome::Refused { status, body } => {+ assert_eq!(*status, 404);+ assert!(body.contains("not found"));+ }+ _ => panic!("expected Refused, got a different outcome"),+ }+ let msg = preview_message(&outcome, "default/scratch").expect("must print a line");+ assert_eq!(+ msg,+ "Preview refused (404): session ... not found in this workspace/project"+ );+ }++ /// A successful preview (200, `dry_run: true`) is a `Previewed` outcome+ /// carrying the report through untouched.+ #[tokio::test]+ async fn run_preview_classifies_a_successful_preview() {+ let tmp = tempfile::TempDir::new().unwrap();+ let url = spawn_fixed_response(+ 200,+ r#"{"session_id": "00000000-0000-0000-0000-000000000000", "workspace": "default",+ "project": "scratch", "observations_deleted": 1063, "handoffs_deleted": 0,+ "pages_deleted": 1, "auto_improve_runs_deleted": 2, "removed_paths": [],+ "collateral_observations_deleted": 0, "collateral_handoffs_denulled": 0,+ "files_deleted": [], "files_failed": [], "compacted": false, "dry_run": true}"#,+ )+ .await;+ let config = config_for(&tmp, url);+ let outcome = run_preview(&config, "/admin/purge-session", &preview_request()).await;+ let msg = preview_message(&outcome, "default/scratch").expect("must print a line");+ assert!(msg.starts_with("Would purge session from default/scratch: 1063 observations"));+ }++ /// Nothing listening at all (connection refused) must classify as+ /// `Unreachable`, the same as a timeout — both are silent fallbacks.+ #[tokio::test]+ async fn run_preview_classifies_a_connection_failure_as_unreachable() {+ let tmp = tempfile::TempDir::new().unwrap();+ // Bind then drop immediately: the port is very likely free again by+ // the time the request lands, and nothing else can be listening on+ // it inside this test's short lifetime.+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ drop(listener);+ let config = config_for(&tmp, format!("http://{addr}"));+ let outcome = run_preview(&config, "/admin/purge-session", &preview_request()).await;+ assert!(matches!(outcome, PreviewOutcome::Unreachable));+ assert!(preview_message(&outcome, "default/scratch").is_none());+ }+}diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex db9ee4d1..36739cdf 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -3966,6 +3966,16 @@ struct PurgeSessionRequest {/// the cost and for what it does not guarantee.#[serde(default)]compact: bool,+ /// Preview only: report the counts a purge of this session would produce+ /// without deleting anything. Wins over `confirm` — `{"confirm": true,+ /// "dry_run": true}` still only previews, exactly like `purge-project`+ /// treats its own `dry_run` field (which itself mirrors+ /// `reclaim-ledger-versions`) — so a preview request can never+ /// accidentally become destructive. `#[serde(default)]` keeps an older+ /// CLI, built before this field existed, parsing the same request it+ /// always sent.+ #[serde(default)]+ dry_run: bool,}/// Wire-format summary returned by `POST /admin/purge-session`.@@ -3987,6 +3997,17 @@ pub struct PurgeSessionReport {pub auto_improve_runs_deleted: u64,/// Distinct wiki page paths whose database rows were deleted.pub removed_paths: Vec<PagePath>,+ /// `observations` rows in a **different** project, deleted collaterally+ /// because their `session_id` is this session (`observations.session_id`+ /// is `ON DELETE CASCADE`, without regard to the observation's own+ /// `project_id`). 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 project whose `from_session_id` or+ /// `accepted_by_session` is set to `NULL` (not deleted — those columns+ /// are `ON DELETE SET NULL`) because they referenced this session.+ pub collateral_handoffs_denulled: u64,/// 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.@@ -3999,6 +4020,14 @@ pub struct PurgeSessionReport {/// Post-purge checkpoint, if the purge changed the tree.#[serde(skip_serializing_if = "Option::is_none")]pub checkpoint: Option<String>,+ /// `true` for a preview: `dry_run: true` in the request always wins over+ /// `confirm`, so this is only ever `false` on a run that actually+ /// deleted rows. `removed_paths` on a preview are paths a confirmed+ /// purge *would* remove; `files_deleted`/`files_failed` are always empty+ /// and `pre_checkpoint`/`checkpoint` always absent, since no wiki file+ /// was touched, no admission webhook ran, and no audit row was written.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub dry_run: bool,}/// `POST /admin/purge-session` — delete one session and everything derived@@ -4010,6 +4039,12 @@ async fn handle_purge_session(Json(req): Json<PurgeSessionRequest>,) -> impl IntoResponse {let author_id = author_ext.map(|axum::Extension(u)| u);+ // `dry_run` always wins, exactly like `purge-project`: `{"confirm":+ // true, "dry_run": true}` must never run the destructive path just+ // because `confirm` also happened to be set.+ if req.dry_run {+ return purge_session_preview(&state, &req, author_id).await;+ }if !req.confirm {return (StatusCode::BAD_REQUEST,@@ -4108,11 +4143,102 @@ async fn handle_purge_session(pages_deleted: summary.pages_deleted,auto_improve_runs_deleted: summary.auto_improve_runs_deleted,removed_paths: summary.removed_paths,+ collateral_observations_deleted: summary.collateral_observations_deleted,+ collateral_handoffs_denulled: summary.collateral_handoffs_denulled,files_deleted,files_failed,compacted: summary.compacted,pre_checkpoint,checkpoint,+ dry_run: false,+ };++ (StatusCode::OK, Json(json_or_empty(&report)))+}++/// Preview branch of `POST /admin/purge-session`: reached whenever `dry_run`+/// is true, regardless of `confirm` (see the `dry_run`-always-wins check in+/// `handle_purge_session`). Goes straight through `state.writer.purge_session`+/// under [`ai_memory_store::PurgeMode::Preview`] — bypassing `Wiki::purge_session`+/// entirely, unlike the confirmed path above — because that wrapper's+/// file-removal loop walks `summary.removed_paths` and deletes each one from+/// disk; under `PurgeMode::Preview` those paths are *predictions*, not rows+/// that are actually gone, and running the wrapper would delete a live wiki+/// file the database still points to.+///+/// Deliberately skipped, mirroring `purge-project`'s preview: the blocking+/// admission call (`admit_purge_session`, nothing was decided yet), wiki file+/// removal, and both checkpoints (the git tree does not change). Because+/// admission never runs, a `200` here is not a promise the confirmed purge+/// will succeed.+///+/// Scope resolution and its `404` run exactly as the real purge's do, so an+/// unknown workspace/project/session answers identically either way.+async fn purge_session_preview(+ state: &Arc<AdminState>,+ req: &PurgeSessionRequest,+ author_id: Option<ai_memory_core::UserId>,+) -> (StatusCode, Json<serde_json::Value>) {+ let session_id = match req.session_id.trim().parse::<SessionId>() {+ Ok(id) => id,+ Err(_) => {+ return (+ StatusCode::BAD_REQUEST,+ Json(serde_json::json!({ "error": "session_id must be a full UUID" })),+ );+ }+ };++ let (ws_id, proj_id) = match lookup_ws_proj_no_create(state, &req.workspace, &req.project).await+ {+ Ok(ids) => ids,+ Err(e) => return e,+ };++ let summary = match state+ .writer+ .purge_session(+ ws_id,+ proj_id,+ session_id,+ author_id,+ // A preview never deletes anything, so there is nothing to+ // reclaim; `ops::purge_session` 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,+ // Absent from this scope is a 404, not a fault — same as the+ // confirmed path.+ 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 = PurgeSessionReport {+ session_id: session_id.to_string(),+ workspace: req.workspace.clone(),+ project: req.project.clone(),+ 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,+ collateral_observations_deleted: summary.collateral_observations_deleted,+ collateral_handoffs_denulled: summary.collateral_handoffs_denulled,+ files_deleted: Vec::new(),+ files_failed: Vec::new(),+ compacted: false,+ pre_checkpoint: None,+ checkpoint: None,+ dry_run: true,};(StatusCode::OK, Json(json_or_empty(&report)))@@ -12349,6 +12475,89 @@ mod tests {);}+ /// The `purge-session` 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 `default/scratch` project), while the+ /// DB user and anonymous requests below never get that far.+ #[tokio::test]+ async fn multiuser_purge_session_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": "default",+ "project": "scratch",+ "session_id": ai_memory_core::SessionId::new().to_string(),+ "confirm": false,+ "dry_run": true+ });++ let root_resp = router+ .clone()+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/admin/purge-session")+ .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/purge-session")+ .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/purge-session")+ .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_purge.rs b/crates/ai-memory-mcp/tests/suite/admin_purge.rsindex c5b20ea6..5ca7aa41 100644--- a/crates/ai-memory-mcp/tests/suite/admin_purge.rs+++ b/crates/ai-memory-mcp/tests/suite/admin_purge.rs@@ -427,6 +427,525 @@ async fn purge_session_reports_file_cleanup_failure_after_db_commit() {assert_eq!(payload["ctx"]["partial_failure"], true);}+/// A preview (no `confirm`, `dry_run: true`) must report the same counts a+/// confirmed purge right after it then actually produces, and must leave the+/// session's page file and DB row untouched.+#[tokio::test]+async fn purge_session_dry_run_reports_the_same_counts_the_confirmed_purge_will() {+ 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;+ // `seed_ended_session_summary` does not itself insert an observation;+ // add one explicitly so `observations_deleted` has something real to+ // count and this test actually exercises that field.+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ session_id,+ 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();++ let preview = post(+ state.clone(),+ "/admin/purge-session",+ json!({+ "workspace": "default",+ "project": "audit",+ "session_id": session_id.to_string(),+ "confirm": false,+ "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["observations_deleted"], 1);+ assert_eq!(preview_body["pages_deleted"], 1);+ assert_eq!(preview_body["removed_paths"], json!([page_path.as_str()]));+ 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 summary file and the session row survive.+ assert!(+ summary_file.exists(),+ "a preview must not remove the session's page file"+ );++ let confirmed = post_purge_session(state, "default", "audit", session_id).await;+ assert_eq!(confirmed.status(), StatusCode::OK);+ let confirmed_body = body_json(confirmed).await;+ assert_eq!(+ confirmed_body.get("dry_run"),+ None,+ "a confirmed purge report has no dry_run key"+ );+ for field in ["observations_deleted", "pages_deleted"] {+ assert_eq!(+ confirmed_body[field], preview_body[field],+ "the confirmed purge's {field} must match what the preview reported"+ );+ }+ assert!(+ !summary_file.exists(),+ "the confirmed purge must remove the session's page file"+ );+}++/// A dry run must not dispatch the admission webhook: nothing was decided+/// yet, so there is nothing for a mirror to act on.+#[tokio::test]+async fn purge_session_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::PurgeSession],+ blocking: false,+ }])+ .unwrap();+ let (state, store) = make_state_with_chain(&tmp, Some(chain)).await;+ let session_id = SessionId::new();+ seed_ended_session_summary(+ &store,+ &state.wiki,+ "default",+ "audit",+ session_id,+ "session summary body",+ )+ .await;++ let resp = post(+ state,+ "/admin/purge-session",+ json!({+ "workspace": "default",+ "project": "audit",+ "session_id": session_id.to_string(),+ "confirm": false,+ "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 purge-session admission webhook"+ );+}++/// A session outside the named scope must still 404 on a preview, exactly+/// like the confirmed purge does.+#[tokio::test]+async fn purge_session_dry_run_nonexistent_returns_404() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ store+ .writer+ .get_or_create_project(ws, "audit", None)+ .await+ .unwrap();++ let resp = post(+ state,+ "/admin/purge-session",+ json!({+ "workspace": "default",+ "project": "audit",+ "session_id": SessionId::new().to_string(),+ "confirm": false,+ "dry_run": true+ }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);+ let body = body_json(resp).await;+ assert!(body["error"].as_str().unwrap_or("").contains("not found"));+}++/// A non-existent workspace must also 404 on a preview.+#[tokio::test]+async fn purge_session_dry_run_nonexistent_workspace_returns_404() {+ let tmp = TempDir::new().unwrap();+ let (state, _store) = make_state(&tmp).await;++ let resp = post(+ state,+ "/admin/purge-session",+ json!({+ "workspace": "ghost-workspace",+ "project": "x",+ "session_id": SessionId::new().to_string(),+ "confirm": false,+ "dry_run": true+ }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);+}++/// Adversarial: the session id is never authority on its own, even at the+/// preview entry point. A session that belongs to project `default/audit`+/// must not be previewable by naming a different, real project in the same+/// workspace, or a different, real workspace whose project happens to share+/// the name `audit` — both must 404, and the 404 body must carry no counts+/// (not a zeroed-out report an operator could mistake for "this scope holds+/// nothing"). Control: previewing under the session's own scope still+/// succeeds and does carry counts.+#[tokio::test]+async fn purge_session_dry_run_refuses_a_session_outside_its_named_scope() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ let session_id = SessionId::new();+ seed_ended_session_summary(+ &store,+ &state.wiki,+ "default",+ "audit",+ session_id,+ "session summary body",+ )+ .await;+ // A sibling project in the same workspace as the session.+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ store+ .writer+ .get_or_create_project(ws, "other-project", None)+ .await+ .unwrap();+ // A different workspace whose project happens to share the name "audit".+ let other_ws = store+ .writer+ .get_or_create_workspace("other-workspace")+ .await+ .unwrap();+ store+ .writer+ .get_or_create_project(other_ws, "audit", None)+ .await+ .unwrap();++ let wrong_project = post(+ state.clone(),+ "/admin/purge-session",+ json!({+ "workspace": "default",+ "project": "other-project",+ "session_id": session_id.to_string(),+ "confirm": false,+ "dry_run": true+ }),+ )+ .await;+ assert_eq!(+ wrong_project.status(),+ StatusCode::NOT_FOUND,+ "a real project that does not hold this session must still 404"+ );+ let wrong_project_body = body_json(wrong_project).await;+ assert!(+ wrong_project_body.get("observations_deleted").is_none()+ && wrong_project_body.get("pages_deleted").is_none(),+ "a 404 must carry no counts: {wrong_project_body}"+ );++ let wrong_workspace = post(+ state.clone(),+ "/admin/purge-session",+ json!({+ "workspace": "other-workspace",+ "project": "audit",+ "session_id": session_id.to_string(),+ "confirm": false,+ "dry_run": true+ }),+ )+ .await;+ assert_eq!(+ wrong_workspace.status(),+ StatusCode::NOT_FOUND,+ "a same-named project in a different, real workspace must still 404"+ );+ let wrong_workspace_body = body_json(wrong_workspace).await;+ assert!(+ wrong_workspace_body.get("observations_deleted").is_none()+ && wrong_workspace_body.get("pages_deleted").is_none(),+ "a 404 must carry no counts: {wrong_workspace_body}"+ );++ // Control: the session's own scope still previews fine, and does report+ // counts — proving the two 404s above are the scope check, not a broken+ // route.+ let control = post(+ state,+ "/admin/purge-session",+ json!({+ "workspace": "default",+ "project": "audit",+ "session_id": session_id.to_string(),+ "confirm": false,+ "dry_run": true+ }),+ )+ .await;+ assert_eq!(+ control.status(),+ StatusCode::OK,+ "the session's own scope must still preview"+ );+ let control_body = body_json(control).await;+ assert_eq!(control_body["dry_run"], true);+ assert!(control_body.get("pages_deleted").is_some());+}++/// Mirrors `purge_project_confirm_true_and_dry_run_true_still_only_previews`:+/// `dry_run` must always win over `confirm`. `{"confirm": true, "dry_run":+/// true}` must never run the real destructive purge.+#[tokio::test]+async fn purge_session_confirm_true_and_dry_run_true_still_only_previews() {+ 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;+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ session_id,+ 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();++ let resp = post(+ state,+ "/admin/purge-session",+ json!({+ "workspace": "default",+ "project": "audit",+ "session_id": session_id.to_string(),+ "confirm": true,+ "dry_run": true+ }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::OK);+ let body = body_json(resp).await;+ assert_eq!(+ body["dry_run"], true,+ "confirm: true must not defeat dry_run: true"+ );+ assert_eq!(body["observations_deleted"], 1);+ assert_eq!(body["pages_deleted"], 1);++ // The only proof that matters: nothing was actually deleted. Checking+ // only the page file would still pass if the handler passed+ // `PurgeMode::Commit` to the writer instead of `Preview` — the DB rows+ // are what a real purge actually removes, so check those too.+ assert!(+ summary_file.exists(),+ "{{confirm: true, dry_run: true}} must not delete the session's page file"+ );+ assert!(+ store+ .reader+ .find_session_scope(session_id)+ .await+ .unwrap()+ .is_some(),+ "{{confirm: true, dry_run: true}} must not delete the session row"+ );+ assert_eq!(+ store.reader.status_counts().await.unwrap().observations,+ 1,+ "{{confirm: true, dry_run: true}} must not delete the session's observation"+ );+}++/// The mirror of the incident `purge-project`'s preview guards against, one+/// level down at session granularity: purging a session also collaterally+/// deletes an observation stamped into a *different* project (because+/// `observations.session_id` cascades regardless of the observation's own+/// `project_id`), and orphans (nulls the session reference of, without+/// deleting) a handoff that lives in that other project too.+#[tokio::test]+async fn purge_session_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project()+ {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;++ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let owner = store+ .writer+ .get_or_create_project(ws, "owner", None)+ .await+ .unwrap();+ let other = store+ .writer+ .get_or_create_project(ws, "other", None)+ .await+ .unwrap();++ let sid = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ id: sid,+ workspace_id: ws,+ project_id: owner,+ agent_kind: AgentKind::ClaudeCode,+ cwd: None,+ actor_user: None,+ })+ .await+ .unwrap();+ // Collateral observation: session lives in `owner`, observation is+ // stamped into `other`.+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ session_id: sid,+ workspace_id: ws,+ project_id: other,+ 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 `owner` session.+ store+ .writer+ .insert_handoff(NewHandoff {+ workspace_id: ws,+ project_id: other,+ 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/purge-session",+ json!({+ "workspace": "default",+ "project": "owner",+ "session_id": sid.to_string(),+ "confirm": false,+ "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/purge-session",+ json!({+ "workspace": "default",+ "project": "owner",+ "session_id": sid.to_string(),+ "confirm": 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 project; only the collateral rows are affected.+ assert_eq!(+ store.reader.status_counts().await.unwrap().observations,+ 0,+ "the collateral observation in `other` must actually be gone"+ );+}+/// Missing `confirm: true` must return 400.#[tokio::test]async fn purge_project_without_confirm_returns_400() {diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 1e2dbc14..2fe9ab6d 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -4563,9 +4563,25 @@ pub struct PurgeSessionSummary {pub pages_deleted: u64,/// `auto_improve_runs` rows removed.pub auto_improve_runs_deleted: u64,- /// On-disk wiki paths whose rows are gone, for the caller to unlink.+ /// On-disk wiki paths whose rows are gone, for the caller to unlink. On a+ /// [`PurgeMode::Preview`] run these are the paths a confirmed purge+ /// *would* remove — nothing was actually deleted, so the caller must not+ /// unlink them.pub removed_paths: Vec<PagePath>,- /// Whether the freed bytes were reclaimed (`VACUUM` ran).+ /// `observations` rows in a **different** project, deleted collaterally+ /// because their `session_id` is this session+ /// (`observations.session_id` is `ON DELETE CASCADE`, without regard to+ /// the observation's own `project_id`) — the same shape+ /// [`PurgeSummary::collateral_observations_deleted`] guards against, one+ /// level down at session granularity.+ pub collateral_observations_deleted: u64,+ /// `handoffs` rows in a different project whose `from_session_id` or+ /// `accepted_by_session` is set to `NULL` (not deleted — those columns+ /// are `ON DELETE SET NULL`) because they referenced this session.+ pub collateral_handoffs_denulled: u64,+ /// Whether the freed bytes were reclaimed (`VACUUM` ran). Always `false`+ /// for a [`PurgeMode::Preview`] run — nothing was deleted, so there is+ /// nothing to reclaim.pub compacted: bool,}@@ -4603,6 +4619,14 @@ pub struct PurgeSessionSummary {/// ownership, and removing it would destroy another session's record. Those/// rows keep their content and lose only the `accepted_by_session` pointer,/// via the existing `ON DELETE SET NULL`.+///+/// `mode = `[`PurgeMode::Preview`] runs every count above — including the two+/// collateral ones — and returns without ever issuing a `DELETE`, the+/// tombstone insert, or the audit row: the transaction so far has only ever+/// read, so rolling it back is free. The counts are read the same way the+/// confirmed call itself decides what to delete — not a separately+/// maintained estimate — but they are a snapshot, not a promise: a write+/// between the preview and a later `--confirm` can change them.pub fn purge_session(conn: &mut Connection,workspace_id: WorkspaceId,@@ -4610,6 +4634,7 @@ pub fn purge_session(session_id: SessionId,author_id: Option<ai_memory_core::UserId>,compaction: Compaction,+ mode: PurgeMode,) -> StoreResult<PurgeSessionSummary> {let wid = workspace_id.as_bytes();let pid = project_id.as_bytes();@@ -4692,6 +4717,88 @@ pub fn purge_session(.collect::<rusqlite::Result<Vec<_>>>()?};+ // A later manual rewrite at this path is still the live wiki file, and+ // must survive. This used to be answered by re-querying `is_latest`+ // AFTER the `DELETE FROM pages` loop below had already run — which only+ // works when a `DELETE` actually happens. Restructured (not a behavior+ // fix: the two computations agree on every existing test) to answer the+ // identical question before anything is cut, by excluding this purge's+ // own `page_ids` from the live rows found at each path instead of+ // re-checking `is_latest` post-delete. That lets a [`PurgeMode::Preview`]+ // run predict the same set a [`PurgeMode::Commit`] run would actually+ // remove, without ever issuing a `DELETE` to find out.+ let removed_paths = {+ let mut stmt = tx.prepare(+ "SELECT id FROM pages \+ WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3 AND is_latest = 1",+ )?;+ let mut paths_to_remove = Vec::new();+ for path in removed_paths {+ let live_ids: Vec<Vec<u8>> = stmt+ .query_map(+ rusqlite::params![&wid[..], &pid[..], path.as_str()],+ |row| row.get::<_, Vec<u8>>(0),+ )?+ .collect::<rusqlite::Result<Vec<_>>>()?;+ let has_live_page = live_ids.iter().any(|id| !page_ids.contains(id));+ if !has_live_page {+ paths_to_remove.push(path);+ }+ }+ paths_to_remove+ };++ // Collateral damage in OTHER projects, the same shape [`purge_project`]+ // guards against, one level down at session granularity:+ // `observations.session_id` is `ON DELETE CASCADE` (V01) with no regard+ // for the observation's own `project_id`, so an observation stamped into+ // a sibling project by this session is deleted right along with it.+ let collateral_observations_deleted: u64 = tx.query_row(+ "SELECT COUNT(*) FROM observations WHERE session_id = ?1 AND project_id != ?2",+ rusqlite::params![&sid[..], &pid[..]],+ |row| row.get(0),+ )?;+ // `handoffs.from_session_id` / `accepted_by_session` are `ON DELETE SET+ // NULL` (V02): a handoff living in another project — authored by this+ // session, or accepted by it — is not deleted, but loses the link back+ // to it.+ let collateral_handoffs_denulled: u64 = tx.query_row(+ "SELECT COUNT(*) FROM handoffs \+ WHERE project_id != ?1 AND (from_session_id = ?2 OR accepted_by_session = ?2)",+ rusqlite::params![&pid[..], &sid[..]],+ |row| row.get(0),+ )?;++ if mode == PurgeMode::Preview {+ // Same counts a confirmed purge would produce, read the same way it+ // decides what to delete — via `SELECT`, never a `DELETE` rolled+ // back. Nothing was written, so rolling back here is free.+ let observations_deleted: u64 = tx.query_row(+ "SELECT COUNT(*) FROM observations \+ WHERE session_id = ?1 AND workspace_id = ?2 AND project_id = ?3",+ rusqlite::params![&sid[..], &wid[..], &pid[..]],+ |row| row.get(0),+ )?;+ // Authored only. See the note above about accepted handoffs.+ let handoffs_deleted: u64 = tx.query_row(+ "SELECT COUNT(*) FROM handoffs \+ WHERE from_session_id = ?1 AND workspace_id = ?2 AND project_id = ?3",+ rusqlite::params![&sid[..], &wid[..], &pid[..]],+ |row| row.get(0),+ )?;+ tx.rollback()?;+ return Ok(PurgeSessionSummary {+ observations_deleted,+ handoffs_deleted,+ pages_deleted: page_ids.len() as u64,+ auto_improve_runs_deleted: run_ids.len() as u64,+ removed_paths,+ collateral_observations_deleted,+ collateral_handoffs_denulled,+ compacted: false,+ });+ }+// ---- delete, innermost first ----for run in &run_ids {@@ -4722,25 +4829,6 @@ pub fn purge_session(rusqlite::params![&id[..], &wid[..], &pid[..]],)? as u64;}- // A later manual rewrite at this path is still the live wiki file.- let removed_paths = {- let mut stmt = tx.prepare(- "SELECT EXISTS(SELECT 1 FROM pages WHERE workspace_id = ?1 AND project_id = ?2 \- AND path = ?3 AND is_latest = 1)",- )?;- let mut paths_to_remove = Vec::new();- for path in removed_paths {- let has_live_page: bool = stmt.query_row(- rusqlite::params![&wid[..], &pid[..], path.as_str()],- |row| row.get(0),- )?;- if !has_live_page {- paths_to_remove.push(path);- }- }- paths_to_remove- };-// Deleted explicitly rather than left to the cascade so the row count is// known and can be reported. Measured: this does *not* change what the// FTS index retains — with an external-content table the cascade already@@ -4796,6 +4884,8 @@ pub fn purge_session(pages_deleted,auto_improve_runs_deleted,removed_paths,+ collateral_observations_deleted,+ collateral_handoffs_denulled,compacted: compaction == Compaction::Reclaim,})}@@ -7130,7 +7220,16 @@ pub(crate) mod tests {let (_tmp, mut conn, ws, proj) = fresh_db();let (sid, _page) = seed_session(&mut conn, ws, proj, "target");- let summary = purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();+ let summary = purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .unwrap();assert_eq!(count(&conn, "SELECT COUNT(*) FROM sessions"),@@ -7174,11 +7273,36 @@ pub(crate) mod tests {}end_session(&mut conn, &sid, latest.as_ref()).unwrap();- let summary = purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();+ let preview = purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Preview,+ )+ .unwrap();++ let summary = purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .unwrap();assert_eq!(summary.pages_deleted, 3);// The manual version survives, but as history: nothing is latest at// the path any more, so its wiki file is unlinked with the summary.assert_eq!(summary.removed_paths, vec![PagePath::new(path).unwrap()]);+ // The preview must have predicted the same path, without deleting+ // anything: `removed_paths` is computed by excluding this purge's+ // own page ids from the live rows at each path, not by re-querying+ // `is_latest` after a `DELETE` that a preview never issues.+ assert_eq!(preview.removed_paths, summary.removed_paths);let survivor: (Vec<u8>, bool) = conn.query_row("SELECT id, is_latest FROM pages", [], |row| {Ok((row.get(0)?, row.get(1)?))@@ -7201,9 +7325,32 @@ pub(crate) mod tests {end_session(&mut conn, &sid, Some(&latest)).unwrap();let manual = upsert_page(&mut conn, &page(ws, proj, &path, "manual rewrite")).unwrap();- let summary = purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();+ let preview = purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Preview,+ )+ .unwrap();++ let summary = purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .unwrap();assert_eq!(summary.pages_deleted, 2);assert!(summary.removed_paths.is_empty());+ // The preview must agree: the later manual rewrite is still live at+ // this path, so neither run reports it as removed.+ assert_eq!(preview.removed_paths, summary.removed_paths);assert_eq!(count(&conn, "SELECT COUNT(*) FROM pages"), 2);let survivor: (Vec<u8>, bool) = conn.query_row(@@ -7228,7 +7375,16 @@ pub(crate) mod tests {upsert_page(&mut conn, &session_page(ws, proj, sid, "checkpoint 1")).unwrap();upsert_page(&mut conn, &session_page(ws, proj, sid, "checkpoint 2")).unwrap();- let summary = purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();+ let summary = purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .unwrap();assert_eq!(summary.pages_deleted, 2);assert_eq!(count(&conn, "SELECT COUNT(*) FROM pages"), 0);assert_eq!(@@ -7254,7 +7410,16 @@ pub(crate) mod tests {let latest = upsert_page(&mut conn, &session_page(ws, proj, sid, "new summary")).unwrap();end_session(&mut conn, &sid, Some(&latest)).unwrap();- let summary = purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();+ let summary = purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .unwrap();assert_eq!(summary.pages_deleted, 2);assert_eq!(count(&conn, "SELECT COUNT(*) FROM pages"), 0);}@@ -7267,7 +7432,16 @@ pub(crate) mod tests {let (target, _) = seed_session(&mut conn, ws, proj, "target");let (keep, keep_page) = seed_session(&mut conn, ws, proj, "keep");- purge_session(&mut conn, ws, proj, target, None, Compaction::Skip).unwrap();+ purge_session(+ &mut conn,+ ws,+ proj,+ target,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .unwrap();assert_eq!(count(&conn, "SELECT COUNT(*) FROM sessions"), 1);let survivor: Vec<u8> = conn@@ -7297,8 +7471,16 @@ pub(crate) mod tests {let other = get_or_create_project(&mut conn, &ws, "other", None).unwrap();let (sid, _) = seed_session(&mut conn, ws, proj, "target");- let err = purge_session(&mut conn, ws, other, sid, None, Compaction::Skip)- .expect_err("a session outside the named project must not be purgeable");+ let err = purge_session(+ &mut conn,+ ws,+ other,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .expect_err("a session outside the named project must not be purgeable");assert!(matches!(err, StoreError::NotFound(_)), "got {err:?}");assert_eq!(@@ -7318,8 +7500,16 @@ pub(crate) mod tests {let proj2 = get_or_create_project(&mut conn, &ws2, "scratch", None).unwrap();let (sid, _) = seed_session(&mut conn, ws, proj, "target");- let err = purge_session(&mut conn, ws2, proj2, sid, None, Compaction::Skip)- .expect_err("cross-workspace purge must be refused");+ let err = purge_session(+ &mut conn,+ ws2,+ proj2,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .expect_err("cross-workspace purge must be refused");assert!(matches!(err, StoreError::NotFound(_)));assert_eq!(count(&conn, "SELECT COUNT(*) FROM sessions"), 1);}@@ -7337,7 +7527,16 @@ pub(crate) mod tests {).unwrap();- purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();+ purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .unwrap();let survived: i64 = conn.query_row(@@ -7818,7 +8017,16 @@ pub(crate) mod tests {).unwrap();- let summary = purge_session(&mut conn, ws, proj, accepter, None, Compaction::Skip).unwrap();+ let summary = purge_session(+ &mut conn,+ ws,+ proj,+ accepter,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .unwrap();assert_eq!(summary.handoffs_deleted, 0, "accepting is not authorship");assert_eq!(count(&conn, "SELECT COUNT(*) FROM handoffs"),@@ -7826,7 +8034,16 @@ pub(crate) mod tests {"the authoring session's handoff survives");- let summary = purge_session(&mut conn, ws, proj, author, None, Compaction::Skip).unwrap();+ let summary = purge_session(+ &mut conn,+ ws,+ proj,+ author,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .unwrap();assert_eq!(summary.handoffs_deleted, 1,"the author's handoff is removed"@@ -7842,9 +8059,26 @@ pub(crate) mod tests {let (sid, _) = seed_session(&mut conn, ws, proj, "target");let (keep, _) = seed_session(&mut conn, ws, proj, "keep");- purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();- let err = purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip)- .expect_err("already gone");+ purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .unwrap();+ let err = purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .expect_err("already gone");assert!(matches!(err, StoreError::NotFound(_)));assert_eq!(count(&conn, "SELECT COUNT(*) FROM sessions"),@@ -7867,7 +8101,16 @@ pub(crate) mod tests {let (sid, _) = seed_session(&mut conn, ws, proj, "target");let (_keep, _) = seed_session(&mut conn, ws, proj, "keep");- purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();+ purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .unwrap();let gone: i64 = conn.query_row(@@ -7948,7 +8191,16 @@ pub(crate) mod tests {let (sid, _) = seed_session(&mut conn, ws, proj, "target");let (_keep, _) = seed_session(&mut conn, ws, proj, "keep");- let summary = purge_session(&mut conn, ws, proj, sid, None, Compaction::Reclaim).unwrap();+ let summary = purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Reclaim,+ PurgeMode::Commit,+ )+ .unwrap();assert!(summary.compacted, "the summary reports that VACUUM ran");conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);").ok();@@ -7963,6 +8215,360 @@ pub(crate) mod tests {);}+ /// Row counts of every table a real session purge touches, used to prove+ /// a dry run changed nothing. `purged_sessions` and `audit_log` are+ /// included deliberately: both are written inside the same transaction+ /// as the delete, so a rollback must take them back out too, not just+ /// the cascade.+ fn session_row_snapshot(conn: &Connection) -> Vec<(&'static str, i64)> {+ [+ "sessions",+ "observations",+ "handoffs",+ "pages",+ "page_embeddings",+ "auto_improve_runs",+ "auto_improve_rejections",+ "purged_sessions",+ "audit_log",+ ]+ .iter()+ .map(|table| {+ (+ *table,+ count(conn, &format!("SELECT COUNT(*) FROM {table}")),+ )+ })+ .collect()+ }++ /// 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+ /// (barring a write landing in between, which neither this nor a real+ /// `--confirm`-less-then-`--confirm` operator workflow can rule out).+ ///+ /// Seeds one of everything `purge_session` touches — an authored+ /// handoff, a handoff only *accepted* (which must survive and must not+ /// count), and an auto-improve run with its own rejection row — and+ /// compares the whole [`PurgeSessionSummary`] (`PartialEq`-derived)+ /// rather than a hand-picked subset of fields, so a field added later+ /// that the preview forgets to compute is caught here instead of only in+ /// a narrower, field-by-field test.+ #[test]+ fn purge_session_dry_run_reports_the_same_counts_a_real_purge_would() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ // Built by hand, rather than through `seed_session`, so the session+ // stays open long enough to accept a handoff below — an ended+ // session cannot accept one, and `seed_session` ends it as its last+ // step. Ended further down, once the accept has happened.+ let sid = SessionId::new();+ let canary_session = hook_session(sid, ws, proj, None);+ begin_session(&mut conn, &canary_session).unwrap();+ let mut canary_obs = hook_observation(&canary_session);+ canary_obs.body = "obs-canary".into();+ insert_observation(&mut conn, &canary_obs).unwrap();+ let (other, _) = seed_session(&mut conn, ws, proj, "other-author");++ // A handoff this session authored: must be deleted.+ insert_handoff(+ &mut conn,+ &NewHandoff {+ workspace_id: ws,+ project_id: proj,+ from_session_id: Some(sid),+ from_agent: AgentKind::ClaudeCode,+ to_agent: None,+ cwd: None,+ summary: "authored by canary".into(),+ open_questions: vec![],+ next_steps: vec![],+ files_touched: vec![],+ owner_user: None,+ },+ )+ .unwrap();++ // A handoff authored by a DIFFERENT session and only *accepted* by+ // this one: must survive, and must not count toward+ // `handoffs_deleted` (accepting is not authorship).+ let accepted_only = insert_handoff(+ &mut conn,+ &NewHandoff {+ workspace_id: ws,+ project_id: proj,+ from_session_id: Some(other),+ from_agent: AgentKind::ClaudeCode,+ to_agent: None,+ cwd: None,+ summary: "authored by other, accepted by canary".into(),+ open_questions: vec![],+ next_steps: vec![],+ files_touched: vec![],+ owner_user: None,+ },+ )+ .unwrap();+ let mut claim = handoff_acceptance(accepted_only, ws, proj);+ claim.accepting_session = Some(sid);+ accept_handoff(&mut conn, &claim).unwrap();++ // Now end the session, with its own summary page — mirroring what+ // `seed_session` would have done, had the accept above not needed+ // the session to still be open.+ let canary_page = upsert_page(+ &mut conn,+ &page(ws, proj, "sessions/canary.md", "page-canary"),+ )+ .unwrap();+ end_session(&mut conn, &sid, Some(&canary_page)).unwrap();++ // An auto-improve run this session produced, plus a rejection row+ // that references it. `purge_session` deletes rejections+ // referencing a session's own runs explicitly, before the runs+ // themselves, rather than relying on `source_run_id`'s+ // `ON DELETE SET NULL` — see the `auto_improve_rejections` delete+ // loop below.+ let run_id = uuid::Uuid::now_v7();+ conn.execute(+ "INSERT INTO auto_improve_runs \+ (id, workspace_id, project_id, session_id, proposal_actor_json, created_at) \+ VALUES (?1, ?2, ?3, ?4, '{}', 1)",+ rusqlite::params![+ run_id.as_bytes(),+ ws.as_bytes(),+ proj.as_bytes(),+ sid.as_bytes()+ ],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO auto_improve_rejections \+ (id, workspace_id, project_id, reason, normalized_fingerprint, summary, \+ source_run_id, created_at) \+ VALUES (?1, ?2, ?3, 'duplicate', 'fp-canary', 'rejected proposal', ?4, 1)",+ rusqlite::params![+ &uuid::Uuid::now_v7().as_bytes()[..],+ ws.as_bytes(),+ proj.as_bytes(),+ run_id.as_bytes()+ ],+ )+ .unwrap();++ let preview = purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Preview,+ )+ .expect("a dry run must not error");+ assert_eq!(preview.observations_deleted, 1);+ assert_eq!(preview.pages_deleted, 1);+ assert_eq!(+ preview.auto_improve_runs_deleted, 1,+ "the session's own run must be counted"+ );+ assert_eq!(+ preview.handoffs_deleted, 1,+ "only the authored handoff counts, not the accepted-only one"+ );+ assert_eq!(+ preview.removed_paths,+ vec![PagePath::new("sessions/canary.md").unwrap()]+ );+ assert!(!preview.compacted, "a rolled-back run never reclaims bytes");++ let real = purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .expect("the confirmed purge must still succeed after the preview");+ assert_eq!(+ PurgeSessionSummary {+ compacted: false,+ ..real+ },+ preview,+ "the dry run's whole summary must match what the confirmed run actually deletes, \+ field for field"+ );++ // The accepted-only handoff survives the confirmed purge too.+ assert_eq!(+ count(&conn, "SELECT COUNT(*) FROM handoffs"),+ 1,+ "the accepted-only handoff must survive the confirmed purge"+ );+ }++ /// Bite check: every table a real session purge touches, the tombstone,+ /// and the audit trail must all be identical before and after a+ /// [`PurgeMode::Preview`] run. If `Preview` ever fell through to the+ /// `Commit` path's `DELETE` / tombstone insert / audit insert, this is+ /// the test that would catch it.+ #[test]+ fn purge_session_dry_run_changes_nothing() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let (sid, _page) = seed_session(&mut conn, ws, proj, "canary");++ let before = session_row_snapshot(&conn);++ let preview = purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Preview,+ )+ .expect("a dry run must not error");+ assert!(preview.observations_deleted >= 1);+ assert!(preview.pages_deleted >= 1);++ let after = session_row_snapshot(&conn);+ assert_eq!(+ before, after,+ "a dry run must leave every table a session purge touches unchanged"+ );+ }++ /// The same collateral shape [`purge_project`]'s preview guards against,+ /// one level down at session granularity: purging session `sid` (which+ /// lives in `proj`) also collaterally deletes an observation stamped+ /// into a *different* project (`observations.session_id` is `ON DELETE+ /// CASCADE`, V01, with no regard for the observation's own+ /// `project_id`), and orphans (nulls the session reference of, without+ /// deleting) a handoff that lives in that other project too+ /// (`handoffs.from_session_id`/`accepted_by_session` are `ON DELETE SET+ /// NULL`, V02). Neither shows up in the plain+ /// `observations_deleted`/`handoffs_deleted` counts, which is exactly+ /// why the two `collateral_*` fields exist.+ #[test]+ fn purge_session_counts_collateral_damage_in_another_project() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let other = get_or_create_project(&mut conn, &ws, "other", None).unwrap();+ let (sid, _page) = seed_session(&mut conn, ws, proj, "owner");++ // Collateral observation: session lives in `proj`, observation is+ // stamped into `other`.+ let stray_observation = NewObservation {+ session_id: sid,+ workspace_id: ws,+ project_id: other,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "stray".into(),+ body: "obs-in-other-project".into(),+ importance: 5,+ };+ insert_observation(&mut conn, &stray_observation).unwrap();++ // Collateral handoff: lives in `other`, authored by the `proj`+ // session.+ insert_handoff(+ &mut conn,+ &NewHandoff {+ workspace_id: ws,+ project_id: other,+ from_session_id: Some(sid),+ from_agent: ai_memory_core::AgentKind::ClaudeCode,+ to_agent: None,+ cwd: None,+ summary: "handoff in other project".into(),+ open_questions: vec![],+ next_steps: vec![],+ files_touched: vec![],+ owner_user: None,+ },+ )+ .unwrap();++ let preview = purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Preview,+ )+ .expect("a preview must not error");+ assert_eq!(+ preview.collateral_observations_deleted, 1,+ "the observation in the other project must be counted as collateral"+ );+ assert_eq!(+ preview.collateral_handoffs_denulled, 1,+ "the handoff in the other project must be counted as collateral"+ );+ // The preview changed nothing: both rows are still exactly as+ // seeded.+ let obs_in_other: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM observations WHERE project_id = ?1",+ rusqlite::params![&other.as_bytes()[..]],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(obs_in_other, 1);++ let real = purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .expect("the confirmed purge must succeed");+ assert_eq!(real.collateral_observations_deleted, 1);+ assert_eq!(real.collateral_handoffs_denulled, 1);++ // The prediction must match what the cascade actually did: the+ // collateral observation is really gone from the other project...+ let obs_in_other_after: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM observations WHERE project_id = ?1",+ rusqlite::params![&other.as_bytes()[..]],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(+ obs_in_other_after, 0,+ "the collaterally-cascaded observation must actually be gone"+ );+ // ...and the handoff row itself survives (it belongs to `other`,+ // which was never purged) but its session reference is nulled, not+ // the row.+ let (handoffs_in_other, from_session_id): (i64, Option<Vec<u8>>) = conn+ .query_row(+ "SELECT COUNT(*), MAX(from_session_id) FROM handoffs WHERE project_id = ?1",+ rusqlite::params![&other.as_bytes()[..]],+ |r| Ok((r.get(0)?, r.get(1)?)),+ )+ .unwrap();+ assert_eq!(+ handoffs_in_other, 1,+ "the handoff row in the other project must survive"+ );+ assert!(+ from_session_id.is_none(),+ "the handoff's from_session_id must be nulled, not the row deleted"+ );+ }+/// A purge must be terminal. The events that produced a session can sit/// undelivered in a client hook spool for days (#493 measured spools with/// thousands), so without a tombstone the next drain recreates the session@@ -7972,7 +8578,16 @@ pub(crate) mod tests {fn a_purged_session_is_not_recreated_by_late_arriving_events() {let (_tmp, mut conn, ws, proj) = fresh_db();let (sid, _) = seed_session(&mut conn, ws, proj, "target");- purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();+ purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .unwrap();// Exactly what a spool drain delivers after the purge.let session = hook_session(sid, ws, proj, None);@@ -7996,7 +8611,16 @@ pub(crate) mod tests {let (_tmp, mut conn, ws, proj) = fresh_db();let other = get_or_create_project(&mut conn, &ws, "other", None).unwrap();let (sid, _) = seed_session(&mut conn, ws, proj, "target");- purge_session(&mut conn, ws, proj, sid, None, Compaction::Skip).unwrap();+ purge_session(+ &mut conn,+ ws,+ proj,+ sid,+ None,+ Compaction::Skip,+ PurgeMode::Commit,+ )+ .unwrap();let elsewhere = hook_session(sid, ws, other, None);begin_session(&mut conn, &elsewhere)diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 34b34302..0fe67eaa 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -413,6 +413,9 @@ pub(crate) enum WriteCmd {author_id: Option<ai_memory_core::UserId>,/// 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<crate::ops::PurgeSessionSummary>>,},/// Reclaim free pages on demand: rebuild the FTS indexes and `VACUUM`,@@ -1898,6 +1901,11 @@ impl WriterHandle {/// cleanup. Calling this directly commits the rows with no guard, so a/// watcher reindex can reinsert the page before the file is removed (#653).///+ /// `mode = `[`ops::PurgeMode::Preview`] stops right after counting and+ /// never issues the delete — see [`ops::purge_session`] for why, and for+ /// the two collateral counts (`collateral_observations_deleted`,+ /// `collateral_handoffs_denulled`) either mode reports.+ ////// # Errors/// [`StoreError::NotFound`] when the session is absent from that scope,/// [`StoreError::WriterClosed`], or a propagated SQL error.@@ -1908,6 +1916,7 @@ impl WriterHandle {session_id: SessionId,author_id: Option<ai_memory_core::UserId>,compaction: crate::ops::Compaction,+ mode: crate::ops::PurgeMode,) -> StoreResult<crate::ops::PurgeSessionSummary> {let (tx, rx) = oneshot::channel();self.send(WriteCmd::PurgeSession {@@ -1916,6 +1925,7 @@ impl WriterHandle {session_id,author_id,compaction,+ mode,reply: tx,}).await?;@@ -3559,6 +3569,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {session_id,author_id,compaction,+ mode,reply,} => {let result = ops::purge_session(@@ -3568,6 +3579,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {session_id,author_id,compaction,+ mode,);send_or_warn(reply, result, "purge_session");}diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex 6135c65e..8a30f313 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -1292,9 +1292,21 @@ impl Wiki {compaction: ai_memory_store::Compaction,) -> WikiResult<PurgeSessionOutcome> {let _guard = self.mutation_lock.write().await;+ // Always `Commit`: a caller that only wants a preview (the HTTP+ // handler's `dry_run` branch) goes straight through+ // `WriterHandle::purge_session` instead, bypassing this wrapper+ // entirely, so the file-removal loop below never runs over paths+ // that a preview only *predicts* would be removed.let summary = self.writer- .purge_session(workspace_id, project_id, session_id, author_id, compaction)+ .purge_session(+ workspace_id,+ project_id,+ session_id,+ author_id,+ compaction,+ ai_memory_store::PurgeMode::Commit,+ ).await?;let mut files_deleted = Vec::with_capacity(summary.removed_paths.len());let mut files_failed = Vec::new();diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex 5de74c1e..cc48a346 100644--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@ -9,7 +9,7 @@ on a homelab box where mistakes are harder to undo.| Command | Safe with server **running**? | Wipes data? | Reversible? | Notes ||---|---|---|---|---|| `purge-project --confirm` | ✅ yes | the one project's data, **plus** any observation stamped into a different project by one of this project's sessions (cascades regardless of the observation's own `project_id`), and it nulls (does not delete) the session reference on any handoff in a different project that this project's sessions authored or accepted | no | Deletes the UUID-namespaced wiki root and raw workstream segments. Refuses with `409` while a managed workstream under the project holds a live run lease — `--force` overrides. Logical delete by default; `--compact` additionally rebuilds the FTS indexes and `VACUUM`s (see below). Without `--confirm` it previews the same counts, including the cross-project ones, before refusing — see below. |-| `purge-session --session-id --confirm` | ✅ yes | the one session's data | no | Deletes one session by UUID: its row, its observations, the handoffs it **authored**, its `sessions/<id>.md` page and every superseded version, their embeddings, and its auto-improve runs. Strictly scoped — a session that does not belong to the named workspace/project is a `404` and nothing is deleted. Handoffs the session only *accepted* are kept: that text belongs to the session that wrote it. Logical delete by default; `--compact` additionally rebuilds the FTS indexes and `VACUUM`s (see below). |+| `purge-session --session-id --confirm` | ✅ yes | the one session's data, **plus** any observation stamped into a different project by this session (cascades regardless of the observation's own `project_id`), and it nulls (does not delete) the session reference on any handoff in a different project that this session authored or accepted | no | Deletes one session by UUID: its row, its observations, the handoffs it **authored**, its `sessions/<id>.md` page and every superseded version, their embeddings, and its auto-improve runs. Strictly scoped — a session that does not belong to the named workspace/project is a `404` and nothing is deleted. Handoffs the session only *accepted* are kept: that text belongs to the session that wrote it. Logical delete by default; `--compact` additionally rebuilds the FTS indexes and `VACUUM`s (see below). Without `--confirm` it previews the same counts, including the cross-project ones, before refusing — see below. || `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. |@@ -70,6 +70,65 @@ the purge still contains everything. Removing the bytes from the live SQLitefile is worth doing on its own terms; do not describe it to a user as aguarantee that the content is unrecoverable, because it is not.+### Preview without `--confirm`++Without `--confirm`, the CLI first asks the server for a preview+(`"dry_run": true` in the request, exactly like `purge-project`'s own field).+`dry_run` always wins over `confirm` — `{"confirm": true, "dry_run": true}`+still only previews — so a preview request can never become destructive by+accident.++The preview runs the same lookups and counts a confirmed purge uses to decide+what to delete — same 404 for a session outside the named scope — including+two cross-project counts for what purging this *session* collaterally+deletes or orphans in a *different* project through its own id+(`collateral_observations_deleted`, `collateral_handoffs_denulled` — the same+shape `purge-project`'s preview reports one level up, at project rather than+session granularity), without ever issuing the `DELETE`. It never runs the+delete and rolls it back. Because nothing is deleted, `removed_paths` in the+reply names the wiki page paths a confirmed purge *would* remove — not paths+already gone — and `files_deleted`/`files_failed` are always empty, since no+file is touched; neither the `purged_sessions` tombstone nor the `audit_log`+row is written, and neither checkpoint is taken. The reply carries+`"dry_run": true`. The CLI prints:++```+Would purge session from default/my-app: 1063 observations, 0 handoffs, 1 pages, 0 auto-improve runs.+```++(with a trailing "Plus N observations in other projects via this session" /+"Plus N handoffs ..." clause when either cross-project count is non-zero;+note the session id itself is never printed — the caller already has it, and+this command exists to make a session stop existing), then still refuses with+the existing "destructive and irreversible" message and a non-zero exit — the+preview is information layered on top of the refusal, never a substitute for+`--confirm`.++A preview also skips the blocking admission call a confirmed purge makes+before deleting anything (`admit_purge_session`): nothing was decided yet, so+there is nothing for a `Reject`-policy webhook to act on. This means a `200`+preview is not a guarantee — that same webhook only runs on the confirmed+path and can still refuse the real purge afterward.++If the server is unreachable, times out (a few seconds, auth-token refresh+included), or predates this field (a plain `400`), the CLI falls back+silently to the plain refusal with no preview line. A `404`/`403` (or any+other unexpected status) prints the server's own error before the refusal+instead, since the operator asked what would happen and the server has a+real answer.++A handoff this session only *accepted* (did not author) keeps its row and+its text either way — confirmed or previewed — and loses only its+`accepted_by_session` pointer (`ON DELETE SET NULL`) once the session row is+actually gone; it is never counted in `handoffs_deleted`. Two more places a+purged session's id is referenced are neither counted nor previewed today,+as a known follow-up: `agent_messages.from_session_id` /+`claimed_by_session` (the cross-project mailbox, V64) and another project's+`auto_improve_runs.session_id`, both `ON DELETE SET NULL` and out of scope+for this preview's two `collateral_*` fields, which only cover observations+and handoffs — the same set `purge-project`'s own preview covers, one level+up.+### The same is true of `purge-project` and `delete-workspace`Every row above applies unchanged to `ai-memory purge-project --compact` and todiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex c873e2c1..87455a96 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -42,7 +42,7 @@ boundary not yet built.| 8d | Messaging: inferred-scope read is diagnosed (#854) | `scope.rs` `is_inferred`; `server.rs` `inferred_scope_hint` on empty pop/list | `agent_messages_briefing.rs` `no_scope_pop_that_misses_the_mail_is_diagnosed_not_a_silent_null` | STRONG || 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; create only via `create_explicit_scope` | `scope.rs` no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors` | STRONG || 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) | `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 | `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) | 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 || 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 |