Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
docs: drop internal superpowers planning artifacts from the branch
wleche0f87f004f32
diff --git a/docs/superpowers/plans/2026-05-24-uninstall-command.md b/docs/superpowers/plans/2026-05-24-uninstall-command.mddeleted file mode 100644index 5aeaf35e..00000000--- a/docs/superpowers/plans/2026-05-24-uninstall-command.md+++ /dev/null@@ -1,1404 +0,0 @@-# Uninstall Command Implementation Plan--> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.--**Goal:** Add `ai-memory uninstall` — the symmetric inverse of `install-hooks` / `install-mcp` / `install-instructions` — that detects and removes ai-memory's wiring across all agents, optionally purges data via the `reset` path, and prints (never executes) a Docker teardown hint.--**Architecture:** A single local (non-HTTP) subcommand in `commands/uninstall.rs`. The detection/removal logic is a set of **pure functions over file content** (string in → string out + a list of removed items), so the hard parts are unit-testable without the filesystem. The orchestrator resolves per-agent config paths (helpers extracted into the `install_*` modules), reads each file, runs the matching pure function, and writes back through the existing `apply_shared::apply_atomic` (atomic + timestamped backup). Hook entries are matched by the unconditional `AI_MEMORY_HOOK_URL=` prefix install inlines into the command; MCP servers by name **or** endpoint; the instructions block by its `<!-- ai-memory:start/end -->` markers.--**Tech Stack:** Rust 2024, `clap` derive, `serde_json`, `toml_edit`, `anyhow`, `sysinfo` (via `process_guard`), `tempfile` (via `apply_shared`). Spec: `docs/superpowers/specs/2026-05-24-uninstall-command-design.md`.-------## File structure--| File | Responsibility | Change |-|---|---|---|-| `crates/ai-memory-cli/src/commands/uninstall.rs` | Pure detection/removal fns + typed plan + orchestrator `run` | **Create** |-| `crates/ai-memory-cli/src/commands/mod.rs` | Module registry | Modify: add `pub mod uninstall;` |-| `crates/ai-memory-cli/src/cli.rs` | `Command::Uninstall`, `UninstallArgs`, `UninstallOnly` | Modify |-| `crates/ai-memory-cli/src/main.rs` | Dispatch arm | Modify (~line 63) |-| `crates/ai-memory-cli/src/commands/install_hooks.rs` | Extract `pub(crate)` per-agent hook-config path helpers | Modify |-| `crates/ai-memory-cli/src/commands/install_mcp.rs` | Extract `pub(crate) fn mcp_config_path(client)` | Modify |-| `tests/` (workspace) or `crates/ai-memory-cli/tests/uninstall.rs` | Integration test of the orchestrator on a temp HOME | **Create** (Task 11) |-| `CHANGELOG.md` | Note the new command | Modify (Task 11) |--All pure functions and their unit tests live in `commands/uninstall.rs` under `#[cfg(test)] mod tests`. The orchestrator depends only on those pure fns + `apply_shared` + `process_guard` + the path helpers.-------## Task 1: Scaffold module, plan types, and the instructions stripper--The instructions block is the simplest removal (pure string surgery against the markers) and a good first pure function. It also forces the module to exist and compile.--**Files:**-- Create: `crates/ai-memory-cli/src/commands/uninstall.rs`-- Modify: `crates/ai-memory-cli/src/commands/mod.rs`--- [ ] **Step 1: Register the module**--In `crates/ai-memory-cli/src/commands/mod.rs`, add the line in alphabetical position (after `setup_agent` or wherever it fits the existing order):--```rust-pub mod uninstall;-```--- [ ] **Step 2: Write the failing test for the instructions stripper**--Create `crates/ai-memory-cli/src/commands/uninstall.rs` with:--```rust-//! `ai-memory uninstall` — the symmetric inverse of install-hooks /-//! install-mcp / install-instructions. Detects ai-memory's wiring in-//! every supported agent's config and removes only that, never-//! third-party entries. Optional `--purge-data` wipes wiki/db/raw via-//! the reset path. Docker teardown is printed, never executed.-//!-//! Design: docs/superpowers/specs/2026-05-24-uninstall-command-design.md--use ai_memory_core::{MARKER_END, MARKER_START};--/// Remove the `<!-- ai-memory:start -->`…`<!-- ai-memory:end -->`-/// block (inclusive) from a CLAUDE.md / AGENTS.md. Returns the new-/// content and whether a block was found. Inverse of-/// `install_instructions::merge_instructions_block`: an install-/// followed by an uninstall round-trips to the original file.-fn strip_instructions_block(content: &str) -> (String, bool) {- let Some(start) = content.find(MARKER_START) else {- return (content.to_string(), false);- };- let Some(end_rel) = content[start..].find(MARKER_END) else {- return (content.to_string(), false);- };- let end = start + end_rel + MARKER_END.len();- // Consume a trailing newline after the end marker if present.- let after = if content.as_bytes().get(end).copied() == Some(b'\n') {- end + 1- } else {- end- };- let mut head = content[..start].to_string();- let tail = &content[after..];- // When the block sat at EOF, install added a blank-line separator- // before it; drop that artifact so install→uninstall round-trips.- if tail.is_empty() && head.ends_with("\n\n") {- head.pop();- }- (format!("{head}{tail}"), true)-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn strip_instructions_round_trips_with_install_append() {- let original = "# Title\n";- // Mirror install_instructions::merge append behavior:- let block = format!("{MARKER_START}\nBODY\n{MARKER_END}\n");- let installed = format!("{original}\n{block}");- let (stripped, found) = strip_instructions_block(&installed);- assert!(found);- assert_eq!(stripped, original, "uninstall must restore the original file");- }-- #[test]- fn strip_instructions_preserves_surrounding_content() {- let content = format!("# Top\n\n{MARKER_START}\nBODY\n{MARKER_END}\n\nMore notes.\n");- let (stripped, found) = strip_instructions_block(&content);- assert!(found);- assert!(stripped.contains("# Top"));- assert!(stripped.contains("More notes."));- assert!(!stripped.contains("BODY"));- assert!(!stripped.contains(MARKER_START));- }-- #[test]- fn strip_instructions_no_block_is_noop() {- let content = "# Just a readme\n";- let (stripped, found) = strip_instructions_block(content);- assert!(!found);- assert_eq!(stripped, content);- }-}-```--- [ ] **Step 3: Run the tests to verify they pass**--Run: `cargo test -p ai-memory-cli uninstall::tests::strip_instructions -- --nocapture`-Expected: 3 tests PASS. (`MARKER_START`/`MARKER_END` are re-exported from `ai_memory_core` — verified in `routing_snippet.rs`.)--- [ ] **Step 4: Verify it compiles clean**--Run: `cargo clippy -p ai-memory-cli --all-targets -- -D warnings`-Expected: no warnings. (`run` doesn't exist yet — that's fine; the dispatch arm comes in Task 7.)--- [ ] **Step 5: Commit**--```bash-git add crates/ai-memory-cli/src/commands/uninstall.rs crates/ai-memory-cli/src/commands/mod.rs-git commit -m "feat(uninstall): module scaffold + instructions-block stripper"-```-------## Task 2: Hook command signature predicate--The single most important detection rule: a hook entry is ai-memory's iff its command carries the `AI_MEMORY_HOOK_URL=` prefix (inlined unconditionally by install — `render_shared.rs:239`, present even with no auth).--**Files:**-- Modify: `crates/ai-memory-cli/src/commands/uninstall.rs`--- [ ] **Step 1: Write the failing tests**--Add to `uninstall.rs` (above the `#[cfg(test)]` module, add the fn; add the tests inside the module):--```rust-/// True when a hook command string was written by ai-memory. Install-/// inlines `AI_MEMORY_HOOK_URL=<url> [AI_MEMORY_AUTH_TOKEN=…] <path>`-/// into the command (render_shared.rs); the `AI_MEMORY_HOOK_URL=`-/// prefix is unconditional, so it is the reliable signature —-/// independent of auth, --server-url, --hooks-dir, --host-prefix.-fn hook_command_is_ours(command: &str) -> bool {- command.contains("AI_MEMORY_HOOK_URL=")-}-```--Inside `mod tests`:--```rust-#[test]-fn hook_signature_matches_no_auth_default() {- let cmd = "AI_MEMORY_HOOK_URL=http://127.0.0.1:49374 /home/u/.local/share/ai-memory/hooks/claude-code/stop.sh";- assert!(hook_command_is_ours(cmd));-}--#[test]-fn hook_signature_matches_with_auth_and_custom_prefix() {- let cmd = "AI_MEMORY_HOOK_URL=http://lan:49374 AI_MEMORY_AUTH_TOKEN=abc /etc/custom/session-start.sh";- assert!(hook_command_is_ours(cmd));-}--#[test]-fn hook_signature_rejects_third_party_with_generic_name() {- // A user's own hook that happens to be named stop.sh — no prefix.- assert!(!hook_command_is_ours("/usr/local/bin/my-stop.sh"));- assert!(!hook_command_is_ours("/opt/tools/hooks/session-start.sh"));-}-```--- [ ] **Step 2: Run tests to verify they pass**--Run: `cargo test -p ai-memory-cli uninstall::tests::hook_signature`-Expected: 3 tests PASS.--- [ ] **Step 3: Commit**--```bash-git add crates/ai-memory-cli/src/commands/uninstall.rs-git commit -m "feat(uninstall): hook command signature predicate"-```-------## Task 3: Hook JSON stripper (both shapes, prune empties)--Removes ai-memory entries from a hooks JSON file. Handles Nested (Claude/Codex/Gemini: `{matcher, hooks:[{command}]}`) and Flat (Cursor: `{command, matcher}`) shapes by inspecting each entry. Prunes an event key when its array empties, and the `hooks` object when it empties.--**Files:**-- Modify: `crates/ai-memory-cli/src/commands/uninstall.rs`--- [ ] **Step 1: Write the failing tests**--Add the functions to `uninstall.rs`:--```rust-use anyhow::Result;-use crate::commands::apply_shared::mutate_json;--/// Result of stripping ai-memory entries from a hooks JSON file.-struct HookRemoval {- new_content: String,- removed_events: Vec<String>,-}--/// An entry (one element of an event's array) is ai-memory's when its-/// command carries the signature — at the entry level (Flat shape) or-/// inside its nested `hooks` array (Nested shape).-fn hook_entry_is_ours(entry: &serde_json::Value) -> bool {- if let Some(cmd) = entry.get("command").and_then(|c| c.as_str())- && hook_command_is_ours(cmd)- {- return true;- }- if let Some(inner) = entry.get("hooks").and_then(|h| h.as_array()) {- return inner.iter().any(|h| {- h.get("command")- .and_then(|c| c.as_str())- .is_some_and(hook_command_is_ours)- });- }- false-}--/// Remove ai-memory hook entries from a settings/hooks JSON document.-/// Preserves third-party entries (including siblings under the same-/// event). Prunes an event key when emptied and the `hooks` object-/// when emptied. Detection is by signature, so stale event keys-/// outside the current vocabulary are caught too.-fn strip_ai_memory_hooks(content: &str) -> Result<HookRemoval> {- let mut removed_events = Vec::new();- let new_content = mutate_json(content, |root| {- let Some(hooks) = root.get_mut("hooks").and_then(|h| h.as_object_mut()) else {- return Ok(());- };- let events: Vec<String> = hooks.keys().cloned().collect();- for event in events {- let Some(arr) = hooks.get_mut(&event).and_then(|v| v.as_array_mut()) else {- continue;- };- let before = arr.len();- arr.retain(|entry| !hook_entry_is_ours(entry));- if arr.len() != before {- removed_events.push(event.clone());- }- if arr.is_empty() {- hooks.remove(&event);- }- }- if hooks.is_empty() {- root.remove("hooks");- }- Ok(())- })?;- Ok(HookRemoval {- new_content,- removed_events,- })-}-```--Inside `mod tests`:--```rust-#[test]-fn strip_hooks_nested_removes_ours_keeps_third_party() {- let content = r#"{- "hooks": {- "SessionStart": [- {"matcher":"","hooks":[{"type":"command","command":"AI_MEMORY_HOOK_URL=http://h /x/session-start.sh"}]}- ],- "Notification": [- {"matcher":"","hooks":[{"type":"command","command":"/usr/bin/notify.sh"}]}- ]- }- }"#;- let out = strip_ai_memory_hooks(content).unwrap();- assert_eq!(out.removed_events, vec!["SessionStart".to_string()]);- let v: serde_json::Value = serde_json::from_str(&out.new_content).unwrap();- assert!(v["hooks"].get("SessionStart").is_none(), "our event pruned");- assert!(v["hooks"].get("Notification").is_some(), "third-party kept");-}--#[test]-fn strip_hooks_flat_cursor_shape() {- let content = r#"{- "version": 1,- "hooks": {- "stop": [- {"type":"command","command":"AI_MEMORY_HOOK_URL=http://h /x/stop.sh","matcher":""}- ]- }- }"#;- let out = strip_ai_memory_hooks(content).unwrap();- assert_eq!(out.removed_events, vec!["stop".to_string()]);- let v: serde_json::Value = serde_json::from_str(&out.new_content).unwrap();- assert!(v["hooks"].get("stop").is_none());- assert_eq!(v["version"], 1, "sibling top-level key preserved");-}--#[test]-fn strip_hooks_prunes_emptied_hooks_object() {- let content = r#"{"hooks":{"Stop":[{"type":"command","command":"AI_MEMORY_HOOK_URL=x /a/stop.sh"}]}}"#;- let out = strip_ai_memory_hooks(content).unwrap();- let v: serde_json::Value = serde_json::from_str(&out.new_content).unwrap();- assert!(v.get("hooks").is_none(), "emptied hooks object removed");-}--#[test]-fn strip_hooks_preserves_third_party_with_generic_basename() {- // Same event, two entries: ours + a user hook named stop.sh w/o signature.- let content = r#"{- "hooks": {- "Stop": [- {"matcher":"","hooks":[{"type":"command","command":"AI_MEMORY_HOOK_URL=x /a/stop.sh"}]},- {"matcher":"","hooks":[{"type":"command","command":"/home/u/scripts/stop.sh"}]}- ]- }- }"#;- let out = strip_ai_memory_hooks(content).unwrap();- let v: serde_json::Value = serde_json::from_str(&out.new_content).unwrap();- let arr = v["hooks"]["Stop"].as_array().unwrap();- assert_eq!(arr.len(), 1, "only ours removed");- assert!(arr[0]["hooks"][0]["command"].as_str().unwrap().contains("/home/u/scripts/stop.sh"));-}--#[test]-fn strip_hooks_no_hooks_key_is_noop() {- let content = r#"{"unrelated":true}"#;- let out = strip_ai_memory_hooks(content).unwrap();- assert!(out.removed_events.is_empty());-}-```--- [ ] **Step 2: Run tests to verify they pass**--Run: `cargo test -p ai-memory-cli uninstall::tests::strip_hooks`-Expected: 5 tests PASS.--- [ ] **Step 3: Run clippy**--Run: `cargo clippy -p ai-memory-cli --all-targets -- -D warnings`-Expected: no warnings.--- [ ] **Step 4: Commit**--```bash-git add crates/ai-memory-cli/src/commands/uninstall.rs-git commit -m "feat(uninstall): shape-aware hook JSON stripper"-```-------## Task 4: MCP JSON stripper (name OR endpoint match)--Removes the ai-memory MCP server from a JSON client config. Matches by key name (default `ai-memory`) OR endpoint (`url`/`httpUrl` field equals the server URL, or a `mcp-remote` `args` array containing it). Navigates to the correct servers object per client.--**Files:**-- Modify: `crates/ai-memory-cli/src/commands/uninstall.rs`--- [ ] **Step 1: Write the failing tests**--Add to `uninstall.rs`:--```rust-use crate::cli::McpClient;--/// Where the servers object lives in each JSON client's config.-/// (Codex is TOML — handled separately in Task 5.)-fn mcp_servers_path(client: McpClient) -> Option<&'static [&'static str]> {- match client {- McpClient::ClaudeCode- | McpClient::ClaudeDesktop- | McpClient::Cursor- | McpClient::GeminiCli => Some(&["mcpServers"]),- McpClient::OpenCode => Some(&["mcp"]),- McpClient::Openclaw => Some(&["mcp", "servers"]),- McpClient::Codex | McpClient::Pi => None,- }-}--/// True when an MCP server entry is ai-memory's: keyed by the expected-/// name, OR its url/httpUrl equals the endpoint, OR it is a-/// `mcp-remote` stdio shim whose args contain the endpoint.-fn mcp_entry_is_ours(- key: &str,- entry: &serde_json::Value,- name: &str,- url: &str,-) -> bool {- if key == name {- return true;- }- for field in ["url", "httpUrl"] {- if entry.get(field).and_then(|v| v.as_str()) == Some(url) {- return true;- }- }- if let Some(args) = entry.get("args").and_then(|a| a.as_array()) {- let has_remote = args.iter().any(|a| a.as_str() == Some("mcp-remote"));- let has_url = args.iter().any(|a| a.as_str() == Some(url));- if has_remote && has_url {- return true;- }- }- false-}--/// Remove ai-memory's MCP server from a JSON client config. Returns-/// the new content and the names removed. Prunes the (possibly nested)-/// servers object and its parents if they empty.-fn strip_mcp_json(- content: &str,- client: McpClient,- name: &str,- url: &str,-) -> Result<(String, Vec<String>)> {- let Some(path) = mcp_servers_path(client) else {- return Ok((content.to_string(), Vec::new()));- };- let mut removed = Vec::new();- let new_content = mutate_json(content, |root| {- // Walk down to the servers object without creating missing parents.- let mut cursor: &mut serde_json::Map<String, serde_json::Value> = root;- for (depth, key) in path.iter().enumerate() {- let is_last = depth == path.len() - 1;- if is_last {- let Some(servers) = cursor.get_mut(*key).and_then(|v| v.as_object_mut()) else {- return Ok(());- };- let keys: Vec<String> = servers.keys().cloned().collect();- for k in keys {- let ours = servers- .get(&k)- .is_some_and(|e| mcp_entry_is_ours(&k, e, name, url));- if ours {- servers.remove(&k);- removed.push(k);- }- }- if servers.is_empty() {- cursor.remove(*key);- }- } else {- let Some(next) = cursor.get_mut(*key).and_then(|v| v.as_object_mut()) else {- return Ok(());- };- cursor = next;- }- }- Ok(())- })?;- Ok((new_content, removed))-}-```--Inside `mod tests`:--```rust-#[test]-fn strip_mcp_claude_by_name_keeps_others() {- let content = r#"{"mcpServers":{"ai-memory":{"type":"http","url":"http://127.0.0.1:49374/mcp"},"other":{"url":"http://x"}}}"#;- let (out, removed) = strip_mcp_json(content, McpClient::ClaudeCode, "ai-memory", "http://127.0.0.1:49374/mcp").unwrap();- assert_eq!(removed, vec!["ai-memory".to_string()]);- let v: serde_json::Value = serde_json::from_str(&out).unwrap();- assert!(v["mcpServers"].get("ai-memory").is_none());- assert!(v["mcpServers"].get("other").is_some());-}--#[test]-fn strip_mcp_by_endpoint_under_custom_name() {- let content = r#"{"mcpServers":{"my-mem":{"url":"http://127.0.0.1:49374/mcp"}}}"#;- let (out, removed) = strip_mcp_json(content, McpClient::ClaudeCode, "ai-memory", "http://127.0.0.1:49374/mcp").unwrap();- assert_eq!(removed, vec!["my-mem".to_string()], "matched by endpoint, not name");- let v: serde_json::Value = serde_json::from_str(&out).unwrap();- assert!(v.get("mcpServers").is_none(), "emptied servers object pruned");-}--#[test]-fn strip_mcp_claude_desktop_mcp_remote_args() {- let content = r#"{"mcpServers":{"weird-name":{"command":"npx","args":["-y","mcp-remote","http://127.0.0.1:49374/mcp"]}}}"#;- let (_out, removed) = strip_mcp_json(content, McpClient::ClaudeDesktop, "ai-memory", "http://127.0.0.1:49374/mcp").unwrap();- assert_eq!(removed, vec!["weird-name".to_string()]);-}--#[test]-fn strip_mcp_openclaw_nested_servers() {- let content = r#"{"mcp":{"servers":{"ai-memory":{"url":"http://127.0.0.1:49374/mcp"}}}}"#;- let (out, removed) = strip_mcp_json(content, McpClient::Openclaw, "ai-memory", "http://127.0.0.1:49374/mcp").unwrap();- assert_eq!(removed, vec!["ai-memory".to_string()]);- let v: serde_json::Value = serde_json::from_str(&out).unwrap();- // mcp.servers emptied → pruned; mcp may remain empty or be pruned by parent logic (servers removed).- assert!(v["mcp"].get("servers").is_none());-}--#[test]-fn strip_mcp_no_match_is_noop() {- let content = r#"{"mcpServers":{"other":{"url":"http://x"}}}"#;- let (_out, removed) = strip_mcp_json(content, McpClient::ClaudeCode, "ai-memory", "http://127.0.0.1:49374/mcp").unwrap();- assert!(removed.is_empty());-}-```--- [ ] **Step 2: Run tests**--Run: `cargo test -p ai-memory-cli uninstall::tests::strip_mcp`-Expected: 5 tests PASS.--- [ ] **Step 3: Commit**--```bash-git add crates/ai-memory-cli/src/commands/uninstall.rs-git commit -m "feat(uninstall): MCP JSON stripper (name or endpoint match)"-```-------## Task 5: MCP TOML stripper (Codex)--Codex registers `[mcp_servers.<name>]` in `~/.codex/config.toml`. Remove the matching child table by name or `url`, preserving comments and other tables (via `toml_edit`). Leave an emptied `[mcp_servers]` header in place (cosmetic, valid) per the spec.--**Files:**-- Modify: `crates/ai-memory-cli/src/commands/uninstall.rs`--- [ ] **Step 1: Write the failing tests**--Add to `uninstall.rs`:--```rust-use crate::commands::apply_shared::mutate_toml;--/// Remove ai-memory's Codex MCP table by name or `url`. Returns new-/// content and removed names. Preserves comments + other tables.-fn strip_mcp_toml(content: &str, name: &str, url: &str) -> Result<(String, Vec<String>)> {- let mut removed = Vec::new();- let new_content = mutate_toml(content, |doc| {- let Some(servers) = doc.get_mut("mcp_servers").and_then(|i| i.as_table_mut()) else {- return Ok(());- };- let keys: Vec<String> = servers.iter().map(|(k, _)| k.to_string()).collect();- for k in keys {- let matches_url = servers- .get(&k)- .and_then(|item| item.get("url"))- .and_then(|u| u.as_str())- == Some(url);- if k == name || matches_url {- servers.remove(&k);- removed.push(k);- }- }- Ok(())- })?;- Ok((new_content, removed))-}-```--Inside `mod tests`:--```rust-#[test]-fn strip_mcp_toml_by_name_keeps_comments_and_tables() {- let content = "# my codex config\n[other]\nkeep = true\n\n[mcp_servers.ai-memory]\nurl = \"http://127.0.0.1:49374/mcp\"\n";- let (out, removed) = strip_mcp_toml(content, "ai-memory", "http://127.0.0.1:49374/mcp").unwrap();- assert_eq!(removed, vec!["ai-memory".to_string()]);- assert!(out.contains("# my codex config"));- assert!(out.contains("[other]"));- assert!(!out.contains("[mcp_servers.ai-memory]"));-}--#[test]-fn strip_mcp_toml_by_url_under_custom_name() {- let content = "[mcp_servers.custom]\nurl = \"http://127.0.0.1:49374/mcp\"\n";- let (out, removed) = strip_mcp_toml(content, "ai-memory", "http://127.0.0.1:49374/mcp").unwrap();- assert_eq!(removed, vec!["custom".to_string()]);- assert!(!out.contains("custom"));-}--#[test]-fn strip_mcp_toml_no_match_is_noop() {- let content = "[mcp_servers.other]\nurl = \"http://x\"\n";- let (_out, removed) = strip_mcp_toml(content, "ai-memory", "http://127.0.0.1:49374/mcp").unwrap();- assert!(removed.is_empty());-}-```--- [ ] **Step 2: Run tests**--Run: `cargo test -p ai-memory-cli uninstall::tests::strip_mcp_toml`-Expected: 3 tests PASS. (If the `toml_edit` `Item::get("url")` access doesn't resolve a child table's value, adjust to `servers.get(&k).and_then(|i| i.as_table()).and_then(|t| t.get("url"))` — same intent.)--- [ ] **Step 3: Commit**--```bash-git add crates/ai-memory-cli/src/commands/uninstall.rs-git commit -m "feat(uninstall): Codex MCP TOML stripper"-```-------## Task 6: Extract per-agent config-path helpers--The orchestrator needs each agent's config path. Today those paths are inlined inside the private `apply_to_*` functions. Extract them into `pub(crate)` helpers in the same module (light, in-module refactor — DRY, no new cross-cutting registry per workflow rule #6) and have the install path call them too.--**Files:**-- Modify: `crates/ai-memory-cli/src/commands/install_hooks.rs`-- Modify: `crates/ai-memory-cli/src/commands/install_mcp.rs`--- [ ] **Step 1: Add hook-config path helpers in `install_hooks.rs`**--Add near the top of `install_hooks.rs` (after imports):--```rust-/// `~/.claude/settings.json` — Claude Code hooks live under `hooks`.-pub(crate) fn claude_settings_path() -> anyhow::Result<std::path::PathBuf> {- Ok(dirs::home_dir()- .context("could not locate $HOME for ~/.claude/settings.json")?- .join(".claude")- .join("settings.json"))-}--/// `~/.codex/hooks.json`.-pub(crate) fn codex_hooks_path() -> anyhow::Result<std::path::PathBuf> {- Ok(dirs::home_dir()- .context("could not locate $HOME for ~/.codex/hooks.json")?- .join(".codex")- .join("hooks.json"))-}--/// `~/.cursor/hooks.json`.-pub(crate) fn cursor_hooks_path() -> anyhow::Result<std::path::PathBuf> {- Ok(dirs::home_dir()- .context("could not locate $HOME for ~/.cursor/hooks.json")?- .join(".cursor")- .join("hooks.json"))-}--/// `~/.gemini/settings.json`.-pub(crate) fn gemini_settings_path() -> anyhow::Result<std::path::PathBuf> {- Ok(dirs::home_dir()- .context("could not locate $HOME for ~/.gemini/settings.json")?- .join(".gemini")- .join("settings.json"))-}--/// `~/.config/opencode/plugins/ai-memory.ts` — OpenCode's plugin file.-pub(crate) fn opencode_plugin_path() -> anyhow::Result<std::path::PathBuf> {- Ok(dirs::home_dir()- .context("could not locate $HOME for ~/.config/opencode")?- .join(".config")- .join("opencode")- .join("plugins")- .join("ai-memory.ts"))-}-```--- [ ] **Step 2: Point the install fns at the helpers (DRY)**--In `apply_to_claude_code_settings`, replace the inline path block:--```rust- let path = match &args.config_file {- Some(p) => p.clone(),- None => dirs::home_dir()- .context("could not locate $HOME for ~/.claude/settings.json")?- .join(".claude")- .join("settings.json"),- };-```--with:--```rust- let path = match &args.config_file {- Some(p) => p.clone(),- None => claude_settings_path()?,- };-```--Do the equivalent substitution in `apply_to_codex_settings` (`codex_hooks_path()?`), the Cursor apply fn (`cursor_hooks_path()?`), and the Gemini apply fn (`gemini_settings_path()?`). Confirm the OpenCode apply fn already resolves `~/.config/opencode/plugins/ai-memory.ts`; if it inlines that path, swap it to `opencode_plugin_path()?`.--- [ ] **Step 3: Add `mcp_config_path` in `install_mcp.rs`**--`resolve_config_file(args)` (lines ~64-110) maps client → path but takes the full `InstallMcpArgs` (for the `--config-file` override). Lift the `home` binding + the `match args.client { … }` body into a standalone `mcp_config_path(client)`, and make `resolve_config_file` delegate. Note: Claude Code's **MCP** config is `~/.claude.json` (NOT `~/.claude/settings.json`, which is the hooks file).--Add this function (the match body is moved verbatim from the current `resolve_config_file`):--```rust-/// Default MCP config-file path for a client (ignores any-/// `--config-file` override). Shared by install and uninstall.-///-/// # Errors-/// Returns an error for `Pi` (no MCP config), for Claude Desktop on-/// unsupported OSes, or when `$HOME` can't be resolved.-pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf> {- use crate::cli::McpClient;- let home = dirs::home_dir().context("could not locate $HOME for config-file auto-detect")?;- Ok(match client {- // Claude Code reads MCP registrations from ~/.claude.json (the- // file `claude mcp add` operates on), NOT ~/.claude/settings.json.- McpClient::ClaudeCode => home.join(".claude.json"),- McpClient::Codex => home.join(".codex").join("config.toml"),- McpClient::OpenCode => home.join(".config").join("opencode").join("opencode.json"),- McpClient::Cursor => home.join(".cursor").join("mcp.json"),- McpClient::ClaudeDesktop => {- #[cfg(target_os = "macos")]- {- home.join("Library")- .join("Application Support")- .join("Claude")- .join("claude_desktop_config.json")- }- #[cfg(target_os = "windows")]- {- home.join("AppData")- .join("Roaming")- .join("Claude")- .join("claude_desktop_config.json")- }- #[cfg(not(any(target_os = "macos", target_os = "windows")))]- {- bail!(- "Claude Desktop is not officially distributed for this OS. \- Pass --config-file explicitly if you know where it lives."- );- }- }- McpClient::GeminiCli => home.join(".gemini").join("settings.json"),- McpClient::Openclaw => home.join(".openclaw").join("config.json"),- McpClient::Pi => bail!("pi has no MCP config file (MCP not supported)"),- })-}-```--Then rewrite `resolve_config_file` to delegate (preserving the `--config-file` override):--```rust-fn resolve_config_file(args: &InstallMcpArgs) -> Result<PathBuf> {- if let Some(p) = &args.config_file {- return Ok(p.clone());- }- mcp_config_path(args.client)-}-```--This is behavior-preserving: the same paths, the same `bail!`s, just relocated so uninstall can call `mcp_config_path` without constructing `InstallMcpArgs`.--- [ ] **Step 4: Build and run the existing install tests to confirm no regression**--Run: `cargo test -p ai-memory-cli install_hooks install_mcp`-Expected: all existing install tests still PASS (the refactor is behavior-preserving).--Run: `cargo clippy -p ai-memory-cli --all-targets -- -D warnings`-Expected: no warnings (watch for an unused `mcp_config_path` until Task 8 uses it — add `#[allow(dead_code)]` only if the lint fires before Task 8; remove it in Task 8).--- [ ] **Step 5: Commit**--```bash-git add crates/ai-memory-cli/src/commands/install_hooks.rs crates/ai-memory-cli/src/commands/install_mcp.rs-git commit -m "refactor(install): extract per-agent config-path helpers for reuse"-```-------## Task 7: CLI surface + dispatch wiring--Add the subcommand, its args, and the `--only` enum, then wire dispatch. The orchestrator `run` is stubbed to a clean "nothing to do yet" so the binary compiles and the command is reachable; the real logic lands in Tasks 8–10.--**Files:**-- Modify: `crates/ai-memory-cli/src/cli.rs`-- Modify: `crates/ai-memory-cli/src/main.rs`-- Modify: `crates/ai-memory-cli/src/commands/uninstall.rs`--- [ ] **Step 1: Add the `Command::Uninstall` variant**--In `cli.rs`, inside `pub enum Command { … }`, add (near the other lifecycle commands):--```rust- /// Remove ai-memory's wiring (hooks, MCP, instructions) from all- /// detected agents. Dry-run unless `--apply`.- Uninstall(UninstallArgs),-```--- [ ] **Step 2: Define `UninstallArgs` and `UninstallOnly`**--In `cli.rs`, add (next to `ResetArgs`):--```rust-/// Which concern `uninstall` should touch. Omitted = all three.-#[derive(Debug, Clone, Copy, clap::ValueEnum)]-pub enum UninstallOnly {- Hooks,- Mcp,- Instructions,-}--/// Arguments for `uninstall`.-#[derive(Debug, Args)]-pub struct UninstallArgs {- /// Actually modify files. Without it, prints the removal plan and- /// exits (dry-run), mirroring `reset` without `--confirm`.- #[arg(long)]- pub apply: bool,- /// After removing the wiring, wipe wiki/, db/, raw/ via the reset- /// path (refuses if another ai-memory process is alive). Only- /// meaningful with `--apply`.- #[arg(long)]- pub purge_data: bool,- /// Limit to one concern. Omitted = hooks + mcp + instructions.- #[arg(long, value_enum)]- pub only: Option<UninstallOnly>,- /// Skip the interactive confirmation when a TTY is attached.- #[arg(long)]- pub yes: bool,-}-```--- [ ] **Step 3: Add the dispatch arm in `main.rs`**--After the `Command::RenameProject(...)` arm (~line 63):--```rust- Command::Uninstall(args) => commands::uninstall::run(&config, args),-```--(`uninstall::run` is synchronous like `reset::run` — no `.await`.)--- [ ] **Step 4: Add the stub `run` in `uninstall.rs`**--Add to `uninstall.rs`:--```rust-use crate::config::Config;-use crate::cli::UninstallArgs;--/// Run the `uninstall` subcommand.-///-/// # Errors-/// Returns an error if a config file is malformed or a removal write-/// fails. Absent files / nothing-to-remove are not errors.-pub fn run(_config: &Config, _args: UninstallArgs) -> anyhow::Result<()> {- // Implemented in Tasks 8–10.- println!("uninstall: not yet implemented");- Ok(())-}-```--- [ ] **Step 5: Build and verify the command is reachable**--Run: `cargo run -p ai-memory-cli -- uninstall --help`-Expected: clap prints the `--apply`, `--purge-data`, `--only`, `--yes` flags.--Run: `cargo clippy -p ai-memory-cli --all-targets -- -D warnings`-Expected: no warnings.--- [ ] **Step 6: Commit**--```bash-git add crates/ai-memory-cli/src/cli.rs crates/ai-memory-cli/src/main.rs crates/ai-memory-cli/src/commands/uninstall.rs-git commit -m "feat(uninstall): CLI surface + dispatch (stub run)"-```-------## Task 8: Orchestrator — build the plan and dry-run print--Collect a typed plan across agents using the pure functions and the path helpers. Print it grouped by file. Without `--apply`, stop here.--**Files:**-- Modify: `crates/ai-memory-cli/src/commands/uninstall.rs`--- [ ] **Step 1: Add plan types and the planning function**--Add to `uninstall.rs`:--```rust-use std::path::PathBuf;-use crate::commands::{install_hooks, install_mcp};-use crate::config::DEFAULT_MCP_URL;--/// One file the uninstall will touch, plus what it will do to it.-#[derive(Debug)]-enum PlannedChange {- /// JSON/TOML rewrite removing the listed items (events or server names).- Rewrite { path: PathBuf, removed: Vec<String> },- /// Whole-file delete (OpenCode plugin).- DeleteFile { path: PathBuf },-}--/// Build the full removal plan by reading each existing config file and-/// running the matching pure stripper. Missing files / no-matches-/// produce no entry. `name`/`url` identify the MCP server.-fn build_plan(args: &UninstallArgs) -> Result<Vec<PlannedChange>> {- let mut plan = Vec::new();- let want = |k: crate::cli::UninstallOnly| args.only.is_none() || args.only == Some(k);- let name = "ai-memory";- let url = DEFAULT_MCP_URL;-- // ---- Hooks (JSON configs) ----- if want(crate::cli::UninstallOnly::Hooks) {- let hook_files = [- install_hooks::claude_settings_path()?,- install_hooks::codex_hooks_path()?,- install_hooks::cursor_hooks_path()?,- install_hooks::gemini_settings_path()?,- ];- for path in hook_files {- if !path.exists() {- continue;- }- let content = std::fs::read_to_string(&path)- .with_context(|| format!("reading {}", path.display()))?;- let removal = strip_ai_memory_hooks(&content)?;- if !removal.removed_events.is_empty() {- plan.push(PlannedChange::Rewrite {- path,- removed: removal.removed_events,- });- }- }- // OpenCode plugin file: presence = it's ours (we wrote it).- let plugin = install_hooks::opencode_plugin_path()?;- if plugin.exists() {- plan.push(PlannedChange::DeleteFile { path: plugin });- }- }-- // ---- MCP (per client) ----- if want(crate::cli::UninstallOnly::Mcp) {- use crate::cli::McpClient::*;- for client in [ClaudeCode, Codex, OpenCode, Cursor, ClaudeDesktop, GeminiCli, Openclaw] {- // Pi has no MCP config — skip silently (never bail on uninstall).- let Ok(path) = install_mcp::mcp_config_path(client) else {- continue;- };- if !path.exists() {- continue;- }- let content = std::fs::read_to_string(&path)- .with_context(|| format!("reading {}", path.display()))?;- let (_new, removed) = if matches!(client, Codex) {- strip_mcp_toml(&content, name, url)?- } else {- strip_mcp_json(&content, client, name, url)?- };- if !removed.is_empty() {- plan.push(PlannedChange::Rewrite { path, removed });- }- }- }-- // ---- Instructions (cwd CLAUDE.md / AGENTS.md) ----- if want(crate::cli::UninstallOnly::Instructions) {- let cwd = std::env::current_dir().context("getting CWD for instruction removal")?;- for name_md in ["CLAUDE.md", "AGENTS.md"] {- let path = cwd.join(name_md);- if !path.exists() {- continue;- }- let content = std::fs::read_to_string(&path)- .with_context(|| format!("reading {}", path.display()))?;- let (_new, found) = strip_instructions_block(&content);- if found {- plan.push(PlannedChange::Rewrite {- path,- removed: vec!["instruction block".to_string()],- });- }- }- }-- Ok(plan)-}--/// Print the plan, one line per file, mirroring `reset`'s dry-run style.-fn print_plan(plan: &[PlannedChange]) {- if plan.is_empty() {- println!("Nothing to remove. ai-memory wiring not found.");- return;- }- for change in plan {- match change {- PlannedChange::Rewrite { path, removed } => {- println!("would remove {} from {}", removed.join(", "), path.display());- }- PlannedChange::DeleteFile { path } => {- println!("would delete {}", path.display());- }- }- }-}-```--- [ ] **Step 2: Wire the dry-run into `run`**--Replace the stub body of `run`:--```rust-pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {- let plan = build_plan(&args)?;- print_plan(&plan);- if !args.apply {- println!("(dry-run; pass --apply to remove)");- return Ok(());- }- // --apply path lands in Task 9.- let _ = config;- Ok(())-}-```--Add the needed `use anyhow::Context;` at the top if not already present.--- [ ] **Step 3: Manually exercise the dry-run**--Run: `cargo run -p ai-memory-cli -- uninstall`-Expected: either "Nothing to remove…" or a list of `would remove …` lines, then `(dry-run; pass --apply to remove)`. No files changed.--Run: `cargo clippy -p ai-memory-cli --all-targets -- -D warnings`-Expected: no warnings (remove any temporary `#[allow(dead_code)]` from Task 6 now that `mcp_config_path` is used).--- [ ] **Step 4: Commit**--```bash-git add crates/ai-memory-cli/src/commands/uninstall.rs-git commit -m "feat(uninstall): build removal plan + dry-run output"-```-------## Task 9: Orchestrator — apply the wiring removal--With `--apply`, rewrite each planned file via `apply_atomic` (re-running the pure stripper so the write is atomic + backed up) and delete the OpenCode plugin. Confirm interactively when a TTY is attached.--**Files:**-- Modify: `crates/ai-memory-cli/src/commands/uninstall.rs`--- [ ] **Step 1: Add the apply function**--Add to `uninstall.rs`:--```rust-use std::io::IsTerminal;-use crate::commands::apply_shared::apply_atomic;--/// Re-run the matching stripper inside `apply_atomic` so the actual-/// write is atomic + backed up. `client` is `Some` for MCP rewrites,-/// `None` for hook/instruction rewrites (distinguished by filename).-fn apply_change(change: &PlannedChange, name: &str, url: &str) -> Result<()> {- match change {- PlannedChange::DeleteFile { path } => {- std::fs::remove_file(path)- .with_context(|| format!("deleting {}", path.display()))?;- println!("✓ deleted {}", path.display());- }- PlannedChange::Rewrite { path, .. } => {- let file = path.file_name().and_then(|f| f.to_str()).unwrap_or("");- let outcome = apply_atomic(path, |existing| {- if file == "CLAUDE.md" || file == "AGENTS.md" {- Ok(strip_instructions_block(existing).0)- } else if file == "config.toml" {- Ok(strip_mcp_toml(existing, name, url)?.0)- } else {- // hooks settings/hooks.json OR an mcpServers JSON file:- // run BOTH strippers; each is a no-op if its key is absent.- let after_hooks = strip_ai_memory_hooks(existing)?.new_content;- // Try every JSON MCP client shape; the right one matches.- let mut out = after_hooks;- for client in [- crate::cli::McpClient::ClaudeCode,- crate::cli::McpClient::OpenCode,- crate::cli::McpClient::Openclaw,- ] {- out = strip_mcp_json(&out, client, name, url)?.0;- }- Ok(out)- }- })?;- println!("✓ {} {}", outcome.verb(), path.display());- }- }- Ok(())-}-```--> Note: a hooks file and an MCP file can be the **same physical file** — Gemini CLI keeps both hooks and `mcpServers` in `~/.gemini/settings.json` (Claude Code, by contrast, splits them: hooks in `~/.claude/settings.json`, MCP in `~/.claude.json`). Two consequences: (1) running both the hook stripper and the JSON MCP strippers on any non-`config.toml` JSON file is safe — each only removes keys it recognizes (`hooks`, `mcpServers`, `mcp`, `mcp.servers`); (2) `build_plan` may list the same Gemini path twice (once from the hooks pass, once from the MCP pass). That's fine: `apply_change` runs both strippers each time, so the first `Rewrite` removes everything and the second is a clean `apply_atomic` NoOp (one extra "no-op" report line, no double backup).--- [ ] **Step 2: Extend `run` to apply with confirmation**--Replace the `--apply` placeholder in `run`:--```rust-pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {- let name = "ai-memory";- let url = crate::config::DEFAULT_MCP_URL;-- let plan = build_plan(&args)?;- print_plan(&plan);- if !args.apply {- println!("(dry-run; pass --apply to remove)");- return Ok(());- }- if plan.is_empty() && !args.purge_data {- return Ok(());- }-- if std::io::stdin().is_terminal() && !args.yes {- eprint!("Proceed with removal? [y/N] ");- use std::io::Write as _;- std::io::stderr().flush().ok();- let mut line = String::new();- std::io::stdin().read_line(&mut line).ok();- if !matches!(line.trim().to_lowercase().as_str(), "y" | "yes") {- println!("aborted.");- return Ok(());- }- }-- for change in &plan {- apply_change(change, name, url)?;- }-- // --purge-data + Docker hint land in Task 10.- let _ = config;- Ok(())-}-```--- [ ] **Step 3: Manual end-to-end test against a fake HOME**--```bash-# Build once.-cargo build -p ai-memory-cli-# Seed a fake claude settings.json with our hook + a third-party hook.-mkdir -p /tmp/fakehome/.claude-cat > /tmp/fakehome/.claude/settings.json <<'JSON'-{"hooks":{"Stop":[{"matcher":"","hooks":[{"type":"command","command":"AI_MEMORY_HOOK_URL=http://h /x/stop.sh"}]}],"Notification":[{"matcher":"","hooks":[{"type":"command","command":"/usr/bin/n.sh"}]}]}}-JSON-HOME=/tmp/fakehome ./target/debug/ai-memory uninstall --apply --only hooks --yes-```-Expected: `✓ updated /tmp/fakehome/.claude/settings.json`; the file now keeps `Notification`, drops `Stop`; a `.bak-<ts>` sits next to it. Verify:-```bash-cat /tmp/fakehome/.claude/settings.json # no "Stop", "Notification" intact-ls /tmp/fakehome/.claude/ # settings.json + settings.json.bak-...-```--- [ ] **Step 4: Run clippy + full crate tests**--Run: `cargo clippy -p ai-memory-cli --all-targets -- -D warnings`-Run: `cargo test -p ai-memory-cli uninstall`-Expected: clean; all unit tests PASS.--- [ ] **Step 5: Commit**--```bash-git add crates/ai-memory-cli/src/commands/uninstall.rs-git commit -m "feat(uninstall): apply wiring removal with backups + confirmation"-```-------## Task 10: `--purge-data`, Docker hint, and exit codes--After wiring removal, optionally purge data through the same guard the `reset` command uses. Always print the Docker teardown hint. If purge is refused because a process is alive, report that wiring succeeded but data was not purged, and exit non-zero.--**Files:**-- Modify: `crates/ai-memory-cli/src/commands/uninstall.rs`--- [ ] **Step 1: Add purge + hint logic to `run`**--Replace the tail of `run` (the `// --purge-data … ` and `let _ = config;` lines) with:--```rust- let mut purge_refused = false;- if args.purge_data {- let siblings = crate::process_guard::sibling_processes();- if !siblings.is_empty() {- eprintln!(- "{}",- crate::process_guard::busy_message("purge data", &siblings)- );- eprintln!("wiring was removed, but data was NOT purged (process alive).");- purge_refused = true;- } else {- for sub in ["wiki", "db", "raw"] {- let path = config.data_dir.join(sub);- if path.exists() {- std::fs::remove_dir_all(&path)- .with_context(|| format!("removing {}", path.display()))?;- std::fs::create_dir_all(&path)- .with_context(|| format!("recreating {}", path.display()))?;- println!("✓ purged {}", path.display());- }- }- }- }-- print_docker_hint(args.purge_data && !purge_refused);-- if purge_refused {- anyhow::bail!("uninstall completed wiring removal but could not purge data");- }- Ok(())-}--/// Print the manual Docker teardown steps (never executed). When the-/// data was purged locally, note that; otherwise remind how to wipe it.-fn print_docker_hint(data_purged: bool) {- println!();- println!("Wiring removed. ai-memory's server + data live in its container/volume —");- println!("tear those down manually:");- println!(" docker compose -f docker/docker-compose.yml down -v");- println!(" docker volume rm ai-memory-data # if you used the default volume");- println!(" rm -f bin/ai-memory # the wrapper script, if installed");- if !data_purged {- println!();- println!("Local data dir was left intact. To wipe it: `ai-memory reset --confirm` (or re-run with --purge-data).");- }-}-```--> The purge loop mirrors `reset::run` (same `["wiki","db","raw"]`, same `process_guard`, same remove+recreate). It is duplicated rather than calling `reset::run` because `reset` builds its own `ResetArgs` and prints its own messages; the loop here is three lines and keeps uninstall's reporting coherent. If you prefer reuse, factor `reset`'s body into a `pub(crate) fn purge_data_dirs(config)` and call it from both — either is acceptable.--- [ ] **Step 2: Manual test — purge with no server running**--```bash-HOME=/tmp/fakehome AI_MEMORY_DATA_DIR=/tmp/fakedata ./target/debug/ai-memory init-mkdir -p /tmp/fakedata/wiki/x-HOME=/tmp/fakehome AI_MEMORY_DATA_DIR=/tmp/fakedata ./target/debug/ai-memory uninstall --apply --purge-data --yes-echo "exit: $?"-ls /tmp/fakedata/wiki # empty (recreated)-```-Expected: `✓ purged …/wiki` etc., the Docker hint, exit 0.--- [ ] **Step 3: Manual test — purge refused while a server is alive**--```bash-HOME=/tmp/fakehome AI_MEMORY_DATA_DIR=/tmp/fakedata ./target/debug/ai-memory serve --transport http --bind 127.0.0.1:49999 &-SERVER=$!-sleep 1-HOME=/tmp/fakehome AI_MEMORY_DATA_DIR=/tmp/fakedata ./target/debug/ai-memory uninstall --apply --purge-data --yes-echo "exit: $?" # expect non-zero-kill $SERVER-```-Expected: wiring removal lines, then the busy message + "data was NOT purged", the Docker hint, and a non-zero exit.--- [ ] **Step 4: Run clippy + crate tests**--Run: `cargo clippy -p ai-memory-cli --all-targets -- -D warnings`-Run: `cargo test -p ai-memory-cli`-Expected: clean; all PASS.--- [ ] **Step 5: Commit**--```bash-git add crates/ai-memory-cli/src/commands/uninstall.rs-git commit -m "feat(uninstall): --purge-data via reset guard + Docker teardown hint"-```-------## Task 11: Integration test, docs, and final verification--End-to-end test on a temp HOME exercising the orchestrator (install → uninstall round-trip), plus CHANGELOG and a full workspace gate.--**Files:**-- Create: `crates/ai-memory-cli/tests/uninstall.rs`-- Modify: `CHANGELOG.md`--- [ ] **Step 1: Write the integration test**--Create `crates/ai-memory-cli/tests/uninstall.rs`:--```rust-//! End-to-end: install hooks into a temp HOME, then uninstall, and-//! assert the file round-trips (our entries gone, third-party intact).--use std::process::Command;--fn bin() -> &'static str {- env!("CARGO_BIN_EXE_ai-memory")-}--#[test]-fn install_then_uninstall_round_trip_claude_hooks() {- let home = tempfile::tempdir().unwrap();- let claude = home.path().join(".claude");- std::fs::create_dir_all(&claude).unwrap();- // Pre-seed a third-party hook we must NOT touch.- std::fs::write(- claude.join("settings.json"),- r#"{"hooks":{"Notification":[{"matcher":"","hooks":[{"type":"command","command":"/usr/bin/n.sh"}]}]}}"#,- )- .unwrap();-- // Install ai-memory hooks for Claude Code.- let status = Command::new(bin())- .args(["install-hooks", "--agent", "claude-code", "--apply"])- .env("HOME", home.path())- .status()- .unwrap();- assert!(status.success());-- // Uninstall (hooks only) and verify.- let status = Command::new(bin())- .args(["uninstall", "--apply", "--only", "hooks", "--yes"])- .env("HOME", home.path())- .status()- .unwrap();- assert!(status.success());-- let after: serde_json::Value =- serde_json::from_str(&std::fs::read_to_string(claude.join("settings.json")).unwrap())- .unwrap();- // Third-party hook survived.- assert!(after["hooks"]["Notification"].is_array());- // None of our events remain (SessionStart etc. all gone).- for ours in ["SessionStart", "SessionEnd", "PreToolUse", "PostToolUse", "Stop", "PreCompact", "UserPromptSubmit"] {- assert!(after["hooks"].get(ours).is_none(), "{ours} should be removed");- }-}--#[test]-fn uninstall_dry_run_changes_nothing() {- let home = tempfile::tempdir().unwrap();- let claude = home.path().join(".claude");- std::fs::create_dir_all(&claude).unwrap();- let original = r#"{"hooks":{"Stop":[{"matcher":"","hooks":[{"type":"command","command":"AI_MEMORY_HOOK_URL=x /a/stop.sh"}]}]}}"#;- std::fs::write(claude.join("settings.json"), original).unwrap();-- let status = Command::new(bin())- .args(["uninstall", "--only", "hooks"]) // no --apply- .env("HOME", home.path())- .status()- .unwrap();- assert!(status.success());-- let after = std::fs::read_to_string(claude.join("settings.json")).unwrap();- assert_eq!(after, original, "dry-run must not modify the file");-}-```--- [ ] **Step 2: Run the integration test**--Run: `cargo test -p ai-memory-cli --test uninstall`-Expected: both tests PASS. (If `install-hooks` requires `--server-url` or staging args in this environment, pass the same defaults the other install tests use — check `crates/ai-memory-cli/tests/` for the established pattern and mirror it.)--- [ ] **Step 3: Update CHANGELOG**--In `CHANGELOG.md`, under the unreleased/top section, add:--```markdown-### Added-- `ai-memory uninstall` — removes ai-memory's hooks, MCP registration, and- CLAUDE.md/AGENTS.md instruction block across all detected agents (dry-run by- default; `--apply` to execute, with timestamped backups). `--purge-data`- wipes wiki/db/raw via the reset guard. `--only hooks|mcp|instructions` to- narrow. Docker/volume teardown is printed as a hint, not executed.-```--- [ ] **Step 4: Full workspace gate (CLAUDE.md rule #3)**--Run:-```bash-cargo fmt --all -- --check-cargo clippy --workspace --all-targets -- -D warnings-cargo test --workspace-```-Expected: no fmt diffs, no clippy warnings, all tests green. Fix anything that fails before committing.--- [ ] **Step 5: Commit**--```bash-git add crates/ai-memory-cli/tests/uninstall.rs CHANGELOG.md-git commit -m "test(uninstall): install→uninstall round-trip + dry-run integration tests; changelog"-```-------## Self-review notes (for the implementer)--- **Spec coverage:** §3 CLI → Tasks 7; §4.1 hooks → Tasks 2–3; §4.2 MCP → Tasks 4–5; §4.3 instructions → Task 1; §4.4 OpenCode plugin delete → Tasks 8–9; §5 architecture (pure fns + extracted path helpers, no central registry) → Tasks 1–6; §6 execution flow → Tasks 8–10; §7 error handling (absent=no-op, malformed=bail via `mutate_json`/`mutate_toml`, purge-refused=non-zero) → Tasks 8–10; §8 tests incl. no-auth + third-party preserve + endpoint match + dry-run → Tasks 2–4, 11; §9 limitations (per-project not scanned, Docker printed, plugin unconditional) → honored by construction.-- **Out of scope confirmed:** no `--config-file` CLI flag (path override is a function param only); no `--force-remove-all`; no per-project config scanning.-- **Type consistency:** `strip_ai_memory_hooks → HookRemoval{new_content, removed_events}`; `strip_mcp_json/strip_mcp_toml → (String, Vec<String>)`; `strip_instructions_block → (String, bool)`; `PlannedChange::{Rewrite{path,removed}, DeleteFile{path}}`; `mcp_config_path(McpClient)`, `claude_settings_path()` etc. — names used identically across Tasks 8–9.-- **Watch:** `toml_edit` child-value access in Task 5 (adjust `.get("url")` to go through `as_table()` if needed); the same physical file serving both hooks + MCP (Task 9 note) — running both strippers is safe and idempotent.diff --git a/docs/superpowers/plans/2026-05-25-uninstall-dryrun-purge-preview.md b/docs/superpowers/plans/2026-05-25-uninstall-dryrun-purge-preview.mddeleted file mode 100644index 8bdb50c9..00000000--- a/docs/superpowers/plans/2026-05-25-uninstall-dryrun-purge-preview.md+++ /dev/null@@ -1,671 +0,0 @@-# Uninstall dry-run purge preview + shared data-wipe helper — Implementation Plan--> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.--**Goal:** Make `uninstall --purge-data` preview the data wipe in dry-run and refuse up front when an `ai-memory` process is alive, and route the `reset`↔`uninstall` wipe through one shared helper — pinned by characterization tests for the currently-untested `reset`.--**Architecture:** Extract a mute `commands/data_purge` helper (one `WIPE_SUBDIRS` const + `purge_preview` + `purge_data_dirs`, returning `anyhow::Result` with per-path context, no logging/printing/guard). `reset.rs` and `uninstall.rs` call it and keep their own output + guard. `uninstall --purge-data` moves its live-process guard to the top of the apply path (all-or-nothing).--**Tech Stack:** Rust 2024, `anyhow`, `tempfile` (dev), `cargo llvm-cov` (local coverage), `cargo test`.--**Spec:** `docs/superpowers/specs/2026-05-25-uninstall-dryrun-purge-preview-design.md`-------## File structure--- **Create** `crates/ai-memory-cli/src/commands/data_purge.rs` — the mute wipe helper + its unit tests. One responsibility: "which subdirs the reset/uninstall wipe touches, and how to wipe one."-- **Modify** `crates/ai-memory-cli/src/commands/mod.rs` — register `pub mod data_purge;`.-- **Modify** `crates/ai-memory-cli/src/commands/reset.rs` — add characterization tests; drop local `const SUBDIRS`; call the helper.-- **Modify** `crates/ai-memory-cli/src/commands/uninstall.rs` — up-front purge guard (option B), call the helper, dry-run purge preview; remove `purge_refused` flow.-- **Modify** `crates/ai-memory-cli/tests/uninstall.rs` — dry-run purge preview integration test + `#[ignore]` guard test.-- **Modify** `CHANGELOG.md` — note the behavior change.--> **Environment assumption for tests:** the in-process `reset` tests and the-> `#[ignore]` guard test assume **no live `ai-memory` server** during-> `cargo test` (true in CI; if running locally with a server up, stop it).-> `process_guard::sibling_processes()` matches processes named `ai-memory`.-------### Task 1: Characterize `reset` (pin current behavior BEFORE refactor)--These call `reset::run` in-process (no spawned `ai-memory` process → not racy) and assert filesystem effects, not stdout. They must pass against the **current** code and survive the Task 3 refactor unchanged.--**Files:**-- Modify: `crates/ai-memory-cli/src/commands/reset.rs` (append a `#[cfg(test)] mod tests`)--- [ ] **Step 1: Append the characterization tests**--At the end of `crates/ai-memory-cli/src/commands/reset.rs`:--```rust-#[cfg(test)]-mod tests {- use super::*;- use std::fs;- use std::path::Path;-- fn seed(dir: &Path) {- for sub in ["wiki", "db", "raw"] {- fs::create_dir_all(dir.join(sub)).unwrap();- fs::write(dir.join(sub).join("f.txt"), b"x").unwrap();- }- fs::create_dir_all(dir.join("logs")).unwrap();- fs::write(dir.join("logs").join("app.log"), b"log").unwrap();- }-- fn config_for(dir: &Path) -> Config {- Config {- data_dir: dir.to_path_buf(),- ..Config::default()- }- }-- #[test]- fn reset_dry_run_leaves_files() {- let tmp = tempfile::tempdir().unwrap();- seed(tmp.path());- run(&config_for(tmp.path()), ResetArgs { confirm: false }).unwrap();- assert!(tmp.path().join("wiki/f.txt").exists());- assert!(tmp.path().join("db/f.txt").exists());- assert!(tmp.path().join("raw/f.txt").exists());- }-- #[test]- fn reset_apply_wipes_data_keeps_logs() {- let tmp = tempfile::tempdir().unwrap();- seed(tmp.path());- run(&config_for(tmp.path()), ResetArgs { confirm: true }).unwrap();- for sub in ["wiki", "db", "raw"] {- assert!(tmp.path().join(sub).is_dir(), "{sub} dir should remain");- assert!(!tmp.path().join(sub).join("f.txt").exists(), "{sub} emptied");- }- assert!(tmp.path().join("logs/app.log").exists(), "logs preserved");- }-- #[test]- fn reset_apply_skips_absent_subdir() {- let tmp = tempfile::tempdir().unwrap();- fs::create_dir_all(tmp.path().join("wiki")).unwrap();- fs::write(tmp.path().join("wiki/f.txt"), b"x").unwrap();- // db/ and raw/ intentionally absent.- run(&config_for(tmp.path()), ResetArgs { confirm: true }).unwrap();- assert!(!tmp.path().join("wiki/f.txt").exists());- assert!(tmp.path().join("wiki").is_dir());- }-}-```--- [ ] **Step 2: Run against current code — must PASS**--Run: `cargo test -p ai-memory-cli reset::tests:: -- --test-threads=1`-Expected: 3 passed. (If they fail because a real `ai-memory` server is running locally, stop it and re-run.)--- [ ] **Step 3: Commit**--```bash-git add crates/ai-memory-cli/src/commands/reset.rs-git commit -m "test(reset): characterize wipe + dry-run before refactor"-```-------### Task 2: Create the `data_purge` helper (TDD)--**Files:**-- Create: `crates/ai-memory-cli/src/commands/data_purge.rs`-- Modify: `crates/ai-memory-cli/src/commands/mod.rs:10` (register module)--- [ ] **Step 1: Register the module**--In `crates/ai-memory-cli/src/commands/mod.rs`, add the line in alphabetical order (after `pub mod commit;`, before `pub mod embed;`):--```rust-pub mod data_purge;-```--- [ ] **Step 2: Create the file with tests + unimplemented bodies (failing)**--Create `crates/ai-memory-cli/src/commands/data_purge.rs`:--```rust-//! Shared data-dir wipe primitive used by `reset` and `uninstall --purge-data`.-//! Mute by design: returns the affected paths; callers own logging/printing and-//! the live-process guard (invariant #9). The remove+recreate is not atomic —-//! pre-existing, matches `reset`/`restore`.--use std::path::{Path, PathBuf};--use anyhow::Context;--/// The subdirectories wiped by `reset` / `uninstall --purge-data`.-/// `logs/` and `models/` are intentionally excluded and never wiped. This is-/// the reset/uninstall set only — `init` and `restore` declare their own-/// (different) sets by design; do not converge them here.-pub(crate) const WIPE_SUBDIRS: &[&str] = &["wiki", "db", "raw"];--/// Paths that WOULD be purged (existing wipe subdirs), for dry-run preview.-pub(crate) fn purge_preview(data_dir: &Path) -> Vec<PathBuf> {- todo!()-}--/// Wipe each existing wipe-subdir (remove + recreate empty). Returns the paths-/// actually purged (the subset that existed). Missing subdirs are skipped, not-/// errors. Carries per-path context on failure.-pub(crate) fn purge_data_dirs(data_dir: &Path) -> anyhow::Result<Vec<PathBuf>> {- todo!()-}--#[cfg(test)]-mod tests {- use super::*;- use std::fs;-- fn seed(dir: &Path) {- for sub in ["wiki", "db", "raw"] {- fs::create_dir_all(dir.join(sub)).unwrap();- fs::write(dir.join(sub).join("f.txt"), b"x").unwrap();- }- fs::create_dir_all(dir.join("logs")).unwrap();- fs::write(dir.join("logs").join("app.log"), b"log").unwrap();- }-- #[test]- fn purge_data_dirs_wipes_set_keeps_logs() {- let tmp = tempfile::tempdir().unwrap();- seed(tmp.path());- let purged = purge_data_dirs(tmp.path()).unwrap();- assert_eq!(purged.len(), 3);- for sub in ["wiki", "db", "raw"] {- assert!(tmp.path().join(sub).is_dir());- assert!(!tmp.path().join(sub).join("f.txt").exists());- }- assert!(tmp.path().join("logs/app.log").exists());- }-- #[test]- fn purge_data_dirs_skips_absent() {- let tmp = tempfile::tempdir().unwrap();- fs::create_dir_all(tmp.path().join("wiki")).unwrap();- let purged = purge_data_dirs(tmp.path()).unwrap();- assert_eq!(purged, vec![tmp.path().join("wiki")]);- }-- #[test]- fn purge_missing_data_dir_is_noop() {- let tmp = tempfile::tempdir().unwrap();- let missing = tmp.path().join("nope");- assert!(purge_preview(&missing).is_empty());- assert!(purge_data_dirs(&missing).unwrap().is_empty());- assert!(!missing.exists());- }-- #[test]- fn purge_preview_lists_only_existing() {- let tmp = tempfile::tempdir().unwrap();- fs::create_dir_all(tmp.path().join("db")).unwrap();- assert_eq!(purge_preview(tmp.path()), vec![tmp.path().join("db")]);- }-}-```--- [ ] **Step 3: Run — must FAIL**--Run: `cargo test -p ai-memory-cli data_purge::`-Expected: tests fail (panic `not yet implemented` from `todo!()`).--- [ ] **Step 4: Implement the two functions**--Replace the two `todo!()` bodies:--```rust-pub(crate) fn purge_preview(data_dir: &Path) -> Vec<PathBuf> {- WIPE_SUBDIRS- .iter()- .map(|s| data_dir.join(s))- .filter(|p| p.exists())- .collect()-}--pub(crate) fn purge_data_dirs(data_dir: &Path) -> anyhow::Result<Vec<PathBuf>> {- let mut purged = Vec::new();- for sub in WIPE_SUBDIRS {- let path = data_dir.join(sub);- if !path.exists() {- continue;- }- std::fs::remove_dir_all(&path)- .with_context(|| format!("removing {}", path.display()))?;- std::fs::create_dir_all(&path)- .with_context(|| format!("recreating {}", path.display()))?;- purged.push(path);- }- Ok(purged)-}-```--- [ ] **Step 5: Run — must PASS**--Run: `cargo test -p ai-memory-cli data_purge::`-Expected: 4 passed.--- [ ] **Step 6: Commit**--```bash-git add crates/ai-memory-cli/src/commands/data_purge.rs crates/ai-memory-cli/src/commands/mod.rs-git commit -m "feat(cli): add mute data_purge helper (shared wipe primitive)"-```-------### Task 3: Route `reset` through the helper--**Files:**-- Modify: `crates/ai-memory-cli/src/commands/reset.rs:1-48`--- [ ] **Step 1: Replace the imports + `run` body, drop `SUBDIRS`**--Replace everything from the top of the file through the end of `run` (the `const SUBDIRS` line and the two `for sub in SUBDIRS` loops) with:--```rust-//! `ai-memory reset --confirm` — wipe wiki/, db/, raw/ contents.-//!-//! Refuses to run while another `ai-memory` process is alive (lesson from-//! basic-memory #765, where a zombie process holding the old SQLite-//! inode caused phantom search results after a reset).--use anyhow::{Result, bail};--use crate::cli::ResetArgs;-use crate::commands::data_purge;-use crate::config::Config;-use crate::process_guard::{busy_message, sibling_processes};--/// Run the `reset` subcommand.-///-/// # Errors-/// Returns an error if another `ai-memory` process is running, if-/// `--confirm` was not provided, or if a directory cannot be removed.-pub fn run(config: &Config, args: ResetArgs) -> Result<()> {- let siblings = sibling_processes();- if !siblings.is_empty() {- bail!(busy_message("reset", &siblings));- }-- if !args.confirm {- for path in data_purge::purge_preview(&config.data_dir) {- println!("would remove {}", path.display());- }- println!("(dry-run; pass --confirm to wipe)");- return Ok(());- }-- for path in data_purge::purge_data_dirs(&config.data_dir)? {- tracing::info!(path = %path.display(), "reset");- }- tracing::info!("reset complete");- Ok(())-}-```--(Leave the `#[cfg(test)] mod tests` from Task 1 untouched below this.)--- [ ] **Step 2: Run reset + helper tests — must PASS unchanged**--Run: `cargo test -p ai-memory-cli reset:: data_purge:: -- --test-threads=1`-Expected: all green (Task 1's 3 + Task 2's 4). This proves the refactor is behavior-preserving.--- [ ] **Step 3: Commit**--```bash-git add crates/ai-memory-cli/src/commands/reset.rs-git commit -m "refactor(reset): use shared data_purge helper"-```-------### Task 4: `uninstall` — up-front purge guard (option B) + helper--**Files:**-- Modify: `crates/ai-memory-cli/src/commands/uninstall.rs:14` (import) and `:203-263` (`run` apply path)--- [ ] **Step 1: Add `data_purge` to the imports**--Change line 14 of `crates/ai-memory-cli/src/commands/uninstall.rs` from:--```rust-use crate::commands::{install_hooks, install_mcp};-```--to:--```rust-use crate::commands::{data_purge, install_hooks, install_mcp};-```--- [ ] **Step 2: Rewrite the apply path of `run`**--Replace the block from `if plan.is_empty() && !args.purge_data {` (currently line 213) through the final `Ok(())` of `run` (currently line 262) with:--```rust- if plan.is_empty() && !args.purge_data {- return Ok(());- }-- // All-or-nothing: when we're going to purge data, refuse before touching- // anything if an ai-memory process is alive (matches reset's guard-at-top).- // Wiring-only uninstall stays unguarded — it edits agent config files the- // server never touches.- if args.purge_data {- let siblings = crate::process_guard::sibling_processes();- if !siblings.is_empty() {- anyhow::bail!(crate::process_guard::busy_message("purge data", &siblings));- }- }-- if std::io::stdin().is_terminal() && !args.yes {- eprint!("Proceed with removal? [y/N] ");- use std::io::Write as _;- std::io::stderr().flush().ok();- let mut line = String::new();- std::io::stdin().read_line(&mut line).ok();- if !matches!(line.trim().to_lowercase().as_str(), "y" | "yes") {- println!("aborted.");- return Ok(());- }- }-- for change in &plan {- apply_change(change, name, url, args.only)?;- }-- if args.purge_data {- for path in data_purge::purge_data_dirs(&config.data_dir)? {- println!("✓ purged {}", path.display());- }- }-- print_docker_hint(args.purge_data);-- Ok(())-```--This removes the `purge_refused` flag, the mid-flow `sibling_processes()` check, the two `eprintln!` warnings, and the end-of-run conditional `bail!`.--- [ ] **Step 3: Verify the existing uninstall suite stays green**--Run: `cargo test -p ai-memory-cli --test uninstall`-Expected: the existing tests pass (none use `--purge-data`, so the apply rewrite must not regress them).--- [ ] **Step 4: Append the apply+purge happy-path test (covers the new apply lines)**--At the end of `crates/ai-memory-cli/tests/uninstall.rs`:--```rust-#[test]-fn uninstall_purge_data_apply_wipes() {- let home = tempfile::tempdir().unwrap();- let data = tempfile::tempdir().unwrap();- for sub in ["wiki", "db", "raw"] {- std::fs::create_dir_all(data.path().join(sub)).unwrap();- std::fs::write(data.path().join(sub).join("f.txt"), b"x").unwrap();- }- std::fs::create_dir_all(data.path().join("logs")).unwrap();- std::fs::write(data.path().join("logs/app.log"), b"l").unwrap();-- let out = Command::new(bin())- .args(["uninstall", "--apply", "--yes", "--purge-data"])- .env("HOME", home.path())- .env("AI_MEMORY_DATA_DIR", data.path())- .output()- .unwrap();- assert!(- out.status.success(),- "stderr: {}",- String::from_utf8_lossy(&out.stderr)- );-- for sub in ["wiki", "db", "raw"] {- assert!(data.path().join(sub).is_dir(), "{sub} dir should remain");- assert!(!data.path().join(sub).join("f.txt").exists(), "{sub} emptied");- }- assert!(data.path().join("logs/app.log").exists(), "logs preserved");- let stdout = String::from_utf8(out.stdout).unwrap();- assert!(stdout.contains("✓ purged"), "stdout was: {stdout}");-}-```--> Note: relies on no concurrent sibling `ai-memory` process tripping the guard.-> If this flakes under parallel test load, serialize it (e.g. a file lock) or-> add a short retry; do not weaken the assertions.--- [ ] **Step 5: Run — must PASS**--Run: `cargo test -p ai-memory-cli --test uninstall uninstall_purge_data_apply_wipes`-Expected: PASS (data wiped, logs kept, `✓ purged` printed).--- [ ] **Step 6: Commit**--```bash-git add crates/ai-memory-cli/src/commands/uninstall.rs crates/ai-memory-cli/tests/uninstall.rs-git commit -m "feat(uninstall): all-or-nothing --purge-data guard + shared wipe; apply test"-```-------### Task 5: `uninstall` dry-run purge preview (TDD)--**Files:**-- Modify: `crates/ai-memory-cli/tests/uninstall.rs` (append test)-- Modify: `crates/ai-memory-cli/src/commands/uninstall.rs:207-212` (`run` dry-run section)--- [ ] **Step 1: Append the failing integration test**--At the end of `crates/ai-memory-cli/tests/uninstall.rs`:--```rust-#[test]-fn uninstall_dry_run_previews_purge() {- let home = tempfile::tempdir().unwrap();- let data = tempfile::tempdir().unwrap();- for sub in ["wiki", "db", "raw"] {- std::fs::create_dir_all(data.path().join(sub)).unwrap();- std::fs::write(data.path().join(sub).join("f.txt"), b"x").unwrap();- }-- let out = Command::new(bin())- .args(["uninstall", "--purge-data"]) // dry-run: no --apply- .env("HOME", home.path())- .env("AI_MEMORY_DATA_DIR", data.path())- .output()- .unwrap();- assert!(out.status.success());-- let stdout = String::from_utf8(out.stdout).unwrap();- assert!(stdout.contains("would purge"), "stdout was: {stdout}");- for sub in ["wiki", "db", "raw"] {- let p = data.path().join(sub);- assert!(- stdout.contains(&p.display().to_string()),- "missing {sub} in: {stdout}"- );- // Dry-run must not delete.- assert!(p.join("f.txt").exists(), "{sub} must be untouched");- }-}-```--- [ ] **Step 2: Run — must FAIL**--Run: `cargo test -p ai-memory-cli --test uninstall uninstall_dry_run_previews_purge`-Expected: FAIL — stdout has no `would purge` line yet.--- [ ] **Step 3: Add the dry-run preview to `run`**--In `crates/ai-memory-cli/src/commands/uninstall.rs`, change the dry-run section (currently lines 207-212) from:--```rust- let plan = build_plan(&args)?;- print_plan(&plan);- if !args.apply {- println!("(dry-run; pass --apply to remove)");- return Ok(());- }-```--to:--```rust- let plan = build_plan(&args)?;- print_plan(&plan);- if args.purge_data {- for path in data_purge::purge_preview(&config.data_dir) {- println!("would purge {}", path.display());- }- }- if !args.apply {- println!("(dry-run; pass --apply to remove)");- return Ok(());- }-```--- [ ] **Step 4: Run — must PASS**--Run: `cargo test -p ai-memory-cli --test uninstall uninstall_dry_run_previews_purge`-Expected: PASS.--- [ ] **Step 5: Commit**--```bash-git add crates/ai-memory-cli/src/commands/uninstall.rs crates/ai-memory-cli/tests/uninstall.rs-git commit -m "feat(uninstall): preview data purge in dry-run; test"-```-------### Task 6: Best-effort guard test (`#[ignore]`)--The guard refusal can't be tested deterministically (sysinfo reads the live process table; no injection seam; rule #6 forbids refactoring `process_guard`). This `#[ignore]`d test spawns a real sibling for manual verification.--**Files:**-- Modify: `crates/ai-memory-cli/tests/uninstall.rs` (append test)--- [ ] **Step 1: Append the ignored test**--```rust-/// Best-effort, NOT in the default run (see spec H3): the live-process guard-/// inspects the real OS process table via sysinfo with no injection seam.-/// Run with `cargo test -p ai-memory-cli --test uninstall -- --ignored`.-#[test]-#[ignore]-fn purge_data_refuses_when_sibling_alive() {- let home = tempfile::tempdir().unwrap();- let data = tempfile::tempdir().unwrap();- let claude = home.path().join(".claude");- std::fs::create_dir_all(&claude).unwrap();- let settings = claude.join("settings.json");- let original = r#"{"hooks":{"Stop":[{"matcher":"","hooks":[{"type":"command","command":"AI_MEMORY_HOOK_URL=x /a/stop.sh"}]}]}}"#;- std::fs::write(&settings, original).unwrap();-- // Long-lived sibling `ai-memory` process.- let mut serve = Command::new(bin())- .arg("serve")- .env("HOME", home.path())- .env("AI_MEMORY_DATA_DIR", data.path())- .spawn()- .unwrap();- std::thread::sleep(std::time::Duration::from_millis(800));-- let out = Command::new(bin())- .args(["uninstall", "--apply", "--yes", "--purge-data"])- .env("HOME", home.path())- .env("AI_MEMORY_DATA_DIR", data.path())- .output()- .unwrap();-- serve.kill().ok();- serve.wait().ok();-- assert!(!out.status.success(), "should refuse while a sibling is alive");- // All-or-nothing: wiring must be untouched.- assert_eq!(- std::fs::read_to_string(&settings).unwrap(),- original,- "no wiring should be removed when the purge is refused up front"- );-}-```--- [ ] **Step 2: Run it explicitly to sanity-check (best-effort)**--Run: `cargo test -p ai-memory-cli --test uninstall -- --ignored purge_data_refuses_when_sibling_alive`-Expected: PASS. (If `serve` fails to bind the default port because another instance is up, free the port and retry — this is why it's `#[ignore]`.)--- [ ] **Step 3: Commit**--```bash-git add crates/ai-memory-cli/tests/uninstall.rs-git commit -m "test(uninstall): ignored best-effort guard-refusal test"-```-------### Task 7: Coverage check, CHANGELOG, full gate--**Files:**-- Modify: `CHANGELOG.md`--- [ ] **Step 1: Install tooling + measure CHANGED-LINE coverage (diff vs main)**--```bash-cargo install cargo-llvm-cov # one-time; pulls llvm-tools-preview if needed-pipx install diff_cover || pip install --user diff-cover # one-time-cargo llvm-cov --cobertura --output-path target/cov.xml -p ai-memory-cli-diff-cover target/cov.xml --compare-branch main-```--Expected: on the **changed lines only**, `data_purge` (critical logic) ≥ 90%-(its unit tests cover ~100%), and changed lines in `reset::run` / `uninstall::run`-≥ 80%. The single expected miss is the option-B `bail!` line in `uninstall`-(only the `#[ignore]` sibling test reaches it). If anything else changed is-uncovered, add a focused test until it clears, then re-run.--- [ ] **Step 2: Add CHANGELOG entry**--In `CHANGELOG.md`, under the top/unreleased section:--```markdown-### Changed-- `ai-memory uninstall --purge-data` now previews the `wiki/`/`db/`/`raw/`- wipe in dry-run (mirroring `reset`) and refuses **up front** if an- `ai-memory` process is alive (all-or-nothing) instead of removing the- wiring and then skipping the purge. The data wipe is now shared with- `reset` via a single internal helper.-```--- [ ] **Step 3: Run the full CLAUDE.md gate**--```bash-cargo fmt --all -- --check-cargo clippy --workspace --all-targets -- -D warnings-cargo test --workspace-```--Expected: no fmt diffs, no clippy warnings, all tests green.--- [ ] **Step 4: Commit**--```bash-git add CHANGELOG.md-git commit -m "docs(changelog): uninstall dry-run purge preview + all-or-nothing guard"-```-------## Self-review--- **Spec coverage:** dry-run preview → Task 5; shared mute helper (`WIPE_SUBDIRS`/`purge_preview`/`purge_data_dirs`, `anyhow::Result` + context) → Task 2; `reset` uses it, wording/tracing kept → Task 3; `uninstall` uses it + option B up-front guard, `purge_refused` removed → Task 4; characterization-first for untested `reset` → Task 1; apply+purge happy-path test (covers new apply lines) → Task 4; changed-line coverage 90/80 via `diff-cover` vs main, local → Task 7; `#[ignore]` guard test per H3 → Task 6; CHANGELOG → Task 7. All spec sections map to a task.-- **Placeholder scan:** no TBD/TODO; every code step shows full code; the only `todo!()` is the intentional TDD red state in Task 2 Step 2, made green in Step 4.-- **Type consistency:** `WIPE_SUBDIRS`, `purge_preview(&Path) -> Vec<PathBuf>`, `purge_data_dirs(&Path) -> anyhow::Result<Vec<PathBuf>>` used identically in Tasks 2/3/4/5; `ResetArgs { confirm }` and `Config { data_dir, ..Default }` match the real signatures; `print_docker_hint(bool)` call updated to drop `purge_refused`.-```diff --git a/docs/superpowers/specs/2026-05-24-uninstall-command-design.md b/docs/superpowers/specs/2026-05-24-uninstall-command-design.mddeleted file mode 100644index 15ecfb44..00000000--- a/docs/superpowers/specs/2026-05-24-uninstall-command-design.md+++ /dev/null@@ -1,306 +0,0 @@-# Design — `ai-memory uninstall` command--**Date:** 2026-05-24-**Branch:** `feat/uninstall-command`-**Status:** design approved, pending spec review--## 1. Problem--`ai-memory` ships a rich install surface — `install-hooks`, `install-mcp`,-`install-instructions`, `setup-agent` — but **no inverse**. Removing the-integration today means the user must, by hand:--- delete the 7 hook entries from `~/.claude/settings.json` /- `~/.codex/hooks.json` / `~/.cursor/hooks.json` / `~/.gemini/settings.json`,-- delete the OpenCode plugin file `~/.config/opencode/plugins/ai-memory.ts`,-- delete the MCP server registration from each client config,-- delete the `<!-- ai-memory:start -->`…`<!-- ai-memory:end -->` block from- `CLAUDE.md` / `AGENTS.md`,-- and remember to wipe the data dir.--This is error-prone and undiscoverable. `agentmemory` has a `remove` command;-`ai-memory` should have a symmetric one, scoped to its own distribution model.--The v0.3 roadmap (`docs/v0.3-roadmap.md`) does **not** list this; it is an-unplanned gap, not a documented non-goal.--## 2. Scope--**In scope (the "wiring"):**-- Remove ai-memory hook entries from every supported agent's config.-- Remove the ai-memory MCP server registration from every supported client.-- Remove the ai-memory instruction block from `CLAUDE.md` / `AGENTS.md`.-- Optionally (`--purge-data`) wipe `wiki/`, `db/`, `raw/` via the existing- `reset` path.--**Out of scope (printed as a hint, never executed):**-- Docker teardown (`docker compose down -v`, `docker volume rm`,- removing the `bin/ai-memory` wrapper). `ai-memory` runs inside the- container; the CLI is a thin client (invariant #16) and does not own the- container lifecycle. We print the commands for the user to run.--**Explicitly rejected (YAGNI / unbounded):**-- A `--force-remove-all` flag that deletes user-edited hooks. User-modified- entries are preserved by design and reported as skipped; no force escape- hatch in v1.-- Scanning per-project config files (`.cursor/mcp.json`, project-local- `AGENTS.md`) across the filesystem. Unbounded search; these files are in- the user's repos, git-visible, and their own concern. We document the- limitation. `uninstall` touches `$HOME`-rooted locations only.--## 3. CLI surface--New **local** (non-HTTP) subcommand, in the invariant-#16 exception bucket-alongside `install-*` and `reset` (pre/post-server local setup; no running-server required).--```-ai-memory uninstall [--apply] [--purge-data] [--only <kind>]- [--config-file <PATH>] [--yes]-```--| Flag | Default | Effect |-|---|---|---|-| *(none)* | — | **Dry-run.** Detect and print the removal plan; write nothing; exit 0. Mirrors `install-* without --apply` and `reset` without `--confirm`. |-| `--apply` | off | Execute the plan. Each touched file is rewritten via `apply_atomic` (tmp+rename+fsync) with a `.bak-<unix-ts>` backup. |-| `--purge-data` | off | After the wiring removal, wipe `wiki/`, `db/`, `raw/` through the `reset` path. Only meaningful with `--apply`. |-| `--only <kind>` | all | Limit to one concern: `hooks` \| `mcp` \| `instructions`. Omitted = all three. |-| `--yes` | off | Skip the single interactive confirmation when a TTY is attached. |--There is **no `--config-file` flag**. With the default "remove from all agents-at once", a single path override cannot disambiguate which agent's many config-files it applies to (Claude's `settings.json`, Codex's `hooks.json`, …). Path-override exists only as a **function parameter** on each `plan_removal(...)`-(see §5), used by tests — not exposed on the CLI.--### Why `--only` instead of `--agent`--The codebase has **two distinct enums** that do not line up:--- `AgentChoice` (cli.rs) — hooks/instructions targets: ClaudeCode, Codex,- Cursor, GeminiCli, OpenCode, Openclaw.-- `McpClient` (cli.rs) — MCP targets: ClaudeCode, Codex, OpenCode, Cursor,- **ClaudeDesktop**, **Pi**, GeminiCli, … — includes MCP-only clients with- no hooks.--A single `--agent` flag cannot address both axes (it would silently miss-ClaudeDesktop/Pi for MCP). `uninstall` defaults to "remove everything we-detect" and offers `--only` to narrow by *concern*, not by agent. Detection-loops over **both** enums: `AgentChoice` for hooks/instructions, `McpClient`-for MCP. This keeps the user from needing to know which enum an agent lives in.--## 4. Detection & safe identification (the core)--The command scans known `$HOME`-rooted config locations and removes **only-entries it can positively attribute to ai-memory**, never third-party config.--### 4.1 Hooks — shape-aware, signature-based--Hook JSON is **not** a flat key. Per `render_shared.rs`:--- `HookShape::Nested` (Claude Code, Codex, Gemini CLI):- `"<Event>": [ { "matcher":"", "hooks":[ {"type":"command","command":"…"} ] } ]`-- `HookShape::Flat` (Cursor):- `"<event>": [ { "type":"command","command":"…","matcher":"" } ]`--Removal therefore operates **inside the array**, and the `command` lives at a-different depth per shape:--- Nested: `["<Event>"][i].hooks[j].command`-- Flat: `["<event>"][i].command`--Find the entry whose `command` matches the ai-memory signature, remove that-entry (the innermost `hooks[j]` object for Nested; the array element for Flat),-and prune the event key only if its array becomes empty. It never blindly-deletes an event key.--**Signature — primary signal: the `command` string contains the literal-`AI_MEMORY_HOOK_URL=`.** Install **inlines** the env vars into the command-string rather than a JSON `env` field (verified at `render_shared.rs:225-243`;-Claude Code does not honour an `env` field at this level). The rendered command-is `AI_MEMORY_HOOK_URL=<url> [AI_MEMORY_AUTH_TOKEN=<t> ] <abs-path>/<script>.sh`,-and the `AI_MEMORY_HOOK_URL=` prefix is written **unconditionally**-(`render_shared.rs:239`, before the auth-token branch). So this signal is-present even in the **no-auth default** (invariant #13) and is independent of-`--server-url`, `--hooks-dir`, and `--host-prefix`. There is **no** JSON `env`-block to match — an earlier draft of this spec wrongly relied on one.--The 7 known script basenames (`session-start.sh`, `user-prompt-submit.sh`,-`pre-tool-use.sh`, `post-tool-use.sh`, `pre-compact.sh`, `stop.sh`,-`session-end.sh`) are a **secondary corroboration**, not the primary key —-basename-only would risk a false positive on a coincidentally-named third-party-`stop.sh`. An entry whose `command` lacks the `AI_MEMORY_HOOK_URL=` prefix is-treated as **not ours** (user-modified or third-party): preserved and reported-as skipped.--**Stale events:** an entry carrying the ai-memory signature is removed **even-if its event name is outside the agent's current vocabulary** (e.g. a Codex-`SessionEnd` left by an older install — Codex's current vocab has no-`SessionEnd`; see `install_hooks.rs` stale-key cleanup). Detection is by-signature, not by the current event list. Note that install already proactively-removes such stale keys, so uninstall may never encounter one — but the-signature rule covers it if it does.--### 4.2 MCP — matched by endpoint, not just name--`install-mcp` writes `mcpServers.<name>` (default `ai-memory`, overridable via-`--name`). Removal must not assume the default name. An MCP server entry is-ai-memory's when **either**:--- it carries a `"url"` field equal to the ai-memory `server_url` (HTTP-transport- clients: Claude Code, Cursor, Gemini CLI, Openclaw; Codex's `config.toml`- uses `[mcp_servers.<name>]` with `url = "…"`), **or**-- it is a stdio shim — `"command": "npx"` with an `"args"` array that contains- both `"mcp-remote"` and the ai-memory `server_url` as elements (Claude- Desktop). Matching scans the variadic `args` array for the URL element; extra- `--header` args (when auth is set) do not affect the match.--This is name-independent and survives a custom `--name` install.--Per-client location nuances (settings.json `mcpServers`, Codex `config.toml`-`[mcp_servers]`, Cursor `~/.cursor/mcp.json`, OpenCode `opencode.json`,-Claude Desktop via `mcp-remote`) are resolved by the same per-`McpClient`-path logic the install path already encodes. `Pi` is MCP-unsupported (install-bails); for uninstall it is a **silent no-op**, never a bail (§6).--### 4.3 Instructions — marker block--Strip the text between `MARKER_START` (`<!-- ai-memory:start -->`) and-`MARKER_END` (`<!-- ai-memory:end -->`), inclusive, from `CLAUDE.md` /-`AGENTS.md`, collapsing the surrounding blank line. This is the exact inverse-of `install-instructions` and reuses the markers from-`ai-memory-core/src/routing_snippet.rs`. The rest of the file is untouched.--### 4.4 OpenCode — file deletion, not key removal--OpenCode's hooks are a **plugin file**: `install_hooks.rs` writes-`~/.config/opencode/plugins/ai-memory.ts`. Removal is a **file delete** of-that exact path (a `RemovalAction` of kind `PluginFile`), not a JSON-key edit.-OpenCode's MCP entry (in `opencode.json`) is handled by §4.2.--The plugin file is deleted **unconditionally** if present — hand-edits to it-are not detected. This is symmetric with install, which **overwrites** the-plugin unconditionally (`install_hooks.rs:314`: "Overwrite unconditionally —-the schema is versioned"). Hashing the file against the rendered template to-skip user-edited copies would be inconsistent with install and is YAGNI for-v1.--## 5. Architecture--Interface = single `uninstall` subcommand (approach A). Reversal logic lives-**next to** the install logic it mirrors (approach C): each `install_*` module-gains a `plan_removal(...)` that returns typed actions; `commands/uninstall.rs`-is a thin orchestrator.--```-commands/uninstall.rs # orchestrator: loop enums, collect, print, apply-commands/install_hooks.rs # + plan_removal_hooks(agent, cfg_override)-commands/install_mcp.rs # + plan_removal_mcp(client, cfg_override)-commands/install_instructions.rs # + plan_removal_instructions(target)-```--Per-agent path resolution currently inlined inside the `apply_to_*` functions-is **extracted into small local helper functions within the same module**-(e.g. `claude_settings_path()`, `codex_hooks_path()`), so both the install and-the removal path call them. This is light, in-module refactoring in service of-the feature — no new cross-cutting registry (would be scope creep per-workflow rule #6). If removal logic turns out identical across several agents-during implementation, minor consolidation may happen then.--### RemovalAction (typed plan)--```rust-struct RemovalAction {- file: PathBuf,- kind: RemovalKind, // HookEntry | McpServer | InstructionBlock | PluginFile- detail: String, // human-readable: which event / server name / file- status: ActionStatus // WillRemove | SkippedUserModified-}-```--## 6. Execution flow--1. **Collect.** Loop `AgentChoice` (hooks + instructions) and `McpClient`- (MCP); call each module's `plan_removal`; gather `RemovalAction`s. Missing- config / absent key = no action (not an error). Agents with no relevant- surface produce **no actions and never bail**: `Openclaw` has no hooks- (install prints and mutates nothing), and `Pi` has no MCP (install bails) —- for uninstall both are silent no-ops, so iterating the full enums adds no- confusing errors, just absent entries.-2. **Present.** Print the plan grouped by file, one line per action, marking- `remove` vs `skipped (user-modified)`. Format mirrors `reset.rs`- (one-per-line + a trailing hint). Without `--apply`, **stop here**, exit 0.-3. **Confirm.** With `--apply` and an interactive TTY, ask one confirmation- (`--yes` skips). Non-interactive (docker/CI) proceeds — consistent with the- project's docker-first, non-interactive posture.-4. **Apply wiring.** Rewrite each affected file via `apply_atomic` +- `mutate_json` / `mutate_toml`; delete `PluginFile`s. When removing the last- ai-memory entry empties a JSON parent object (e.g. `hooks` → `{}`), remove- that parent key but **never delete the user's config file**. For TOML,- remove the leaf key/table only; leave an emptied parent table header in- place (cosmetic, syntactically valid).-- **Asymmetry with install (intentional).** Install writes each event with- `hooks.insert(event, value)` — it **overwrites the whole event key**, so it- cannot preserve a pre-existing third-party hook under that event. Uninstall- does the opposite: it removes only the *matching* array entry and preserves- any sibling third-party entry. The two are deliberately not mirror images —- install can't know what's third-party; uninstall must try to preserve it.- Entry-level removal is therefore the safe choice even though, in the common- case (no manual post-install edits), the event array holds only ai-memory's- entry and the whole key is pruned anyway.-5. **Purge data (optional).** Only if `--purge-data` and `--apply`. Runs- **after** wiring. Reuses `commands::reset`: `process_guard::sibling_processes()`- refuses with `busy_message` if any `ai-memory` is alive, else- `remove_dir_all` on `wiki/`, `db/`, `raw/`.-6. **Report.** Summary of removed / skipped actions + backup paths. Then the- Docker teardown hint (printed, never executed). If `--purge-data` was- refused (live process), the report states clearly that **wiring removal- succeeded but data was not purged**, and the command exits non-zero — the- wiring success is not masked by the purge failure.--## 7. Error handling--| Situation | Behaviour |-|---|---|-| Config file or key absent | Not an error. Reported as "nothing to remove"; idempotent no-op; exit 0. |-| Malformed JSON/TOML in user's file | Fail with `anyhow::Context`, **write nothing**, suggest manual edit. Same defensive stance as install ("a bad merge is very user-visible"). |-| `--purge-data` with live sibling process | `bail!(busy_message(...))` for the purge step; wiring already applied — report both facts; exit non-zero. |-| `$HOME` unresolvable | Clear error, as in `install-*`. |-| Partial failure across files | Each file is atomic in isolation; an earlier file's backup is intact if a later file fails. Final report lists done vs not-done. |-| Hook matches basename but no corroborating signal | Preserved; reported as `skipped (user-modified)`. No force override in v1. |--## 8. Testing (TDD — test before implementation, rule #5)--Unit tests per `plan_removal` and for the orchestrator:--- **Detects** an ai-memory hook entry (nested shape) and (flat shape, Cursor).-- **Detects the no-auth default**: a hook whose command is- `AI_MEMORY_HOOK_URL=<url> <path>/stop.sh` (no `AI_MEMORY_AUTH_TOKEN`) is still- matched via the unconditional `AI_MEMORY_HOOK_URL=` prefix.-- **Preserves** a third-party hook sharing a generic basename (`stop.sh`) whose- command lacks the `AI_MEMORY_HOOK_URL=` prefix → not removed (not reported as- ours at all).-- **Removes** an ai-memory hook entry whose event is outside the current- vocabulary (stale `SessionEnd` for Codex).-- **Prunes** an event key only when its array empties; leaves sibling- third-party entries intact.-- **MCP**: removes the server matched by endpoint URL even under a custom- `--name`; preserves an unrelated MCP server.-- **Instructions**: removes the marker block, leaves text before/after intact;- idempotent on a file with no block.-- **OpenCode**: deletes the `ai-memory.ts` plugin file; no-op if absent.-- **Idempotency**: second run is a no-op, exit 0.-- **Dry-run** writes nothing (content + mtime unchanged); `--apply` writes and- produces a `.bak-<ts>`.-- **Emptied parent**: JSON parent key removed, file kept; TOML leaf removed,- table header kept.-- **`--purge-data`** refuses with a live sibling (mock `process_guard`) and the- report shows wiring-done / data-not-purged with non-zero exit.--## 9. Open limitations (documented, not bugs)--- Per-project config files are not scanned (see §2, rejected).-- Docker/volume/wrapper teardown is printed, not executed (see §2).-- A hook the user redirected to a non-ai-memory wrapper script is preserved- (no force removal in v1).diff --git a/docs/superpowers/specs/2026-05-25-uninstall-dryrun-purge-preview-design.md b/docs/superpowers/specs/2026-05-25-uninstall-dryrun-purge-preview-design.mddeleted file mode 100644index 49195080..00000000--- a/docs/superpowers/specs/2026-05-25-uninstall-dryrun-purge-preview-design.md+++ /dev/null@@ -1,315 +0,0 @@-# Design — dry-run purge preview + shared data-wipe helper--> Date: 2026-05-25 · Branch: `feat/uninstall-command`-> Follow-on to [`2026-05-24-uninstall-command-design.md`](2026-05-24-uninstall-command-design.md).-> Revised after subagent design review (see "Review resolutions" at the end).--## Problem--Two issues surfaced while exercising `ai-memory uninstall --purge-data`:--1. **Dry-run gap.** `uninstall --purge-data` without `--apply` prints only the- wiring removal plan and never mentions that `wiki/`/`db/`/`raw/` would be- wiped. The most destructive part of the operation is invisible until the- user commits with `--apply`. By contrast `reset` (without `--confirm`)- lists `would remove <path>` for each data subdir. The behavior is safe- (dry-run touches nothing), but the **output is asymmetric and misleading**.--2. **Duplicated wipe logic.** The data-wipe primitive — the subdir list- `["wiki","db","raw"]` plus the `remove_dir_all` + `create_dir_all` loop —- exists in both `commands/reset.rs` and `commands/uninstall.rs`. `reset` is- the original (commit `5e29909`, M1-D); `uninstall` **copied** it when- `--purge-data` landed (commit `3e3d44a`). The subdir list is a semantic- contract ("what constitutes ai-memory data for a wipe"); having it in two- places risks drift on a destructive operation.--## Goals--- `uninstall --purge-data` dry-run previews the data wipe, mirroring `reset`'s- per-subdir style.-- The `reset`↔`uninstall` wipe primitive lives in exactly one place, shared by- both, without coupling their divergent orchestration (guard, output).-- No behavioral regression to `reset` (which currently has **zero tests**),- and no loss of `uninstall`'s per-path error context.-- `uninstall --purge-data` is **all-or-nothing**: if another `ai-memory`- process is alive it refuses *up front*, before removing any wiring — no- half-done state. Matches `reset`'s guard-at-top.-- Coverage on the **changed lines** (diff vs `main`): critical logic ≥ 90%,- rest ≥ 80% (line coverage, local inspection — see Coverage).--## Non-goals--- No change to `reset`'s public behavior, flags, guard semantics, or output- wording.-- `uninstall` *without* `--purge-data` stays **unguarded**: wiring removal is- safe while the server runs (it only edits agent config files the server- never touches), so it does not require the server stopped.-- No unification of `reset`'s "would remove" wording with `uninstall`'s- "would purge" / "✓ purged" — each command keeps its own phrasing.-- **No unification with `init`/`restore`.** Those declare *different* subdir- sets on purpose (`init` = `wiki,raw,db,models`; `restore` = `wiki,db`); the- shared helper is scoped to the `reset`↔`uninstall` set `wiki,db,raw` only.-- The `remove_dir_all` → `create_dir_all` sequence is **not atomic** (a crash- between the two leaves a deleted-but-not-recreated subdir). This is- pre-existing behavior shared by `reset` and `restore`; making it atomic is- out of scope.--## Design--### 1. New module `commands/data_purge.rs` (mute helper)--Single home for the `reset`↔`uninstall` knowledge "which subdirs are wiped,-and how to wipe one". **No logging, no printing, no process check** — callers-own output and the live-process guard. Returns `anyhow::Result` with per-path-context so callers keep meaningful error messages. Sits alongside the existing-shared command helpers (`apply_shared.rs`, `render_shared.rs`,-`purge_project.rs`); it stays **CLI-local** (not in `ai-memory-core`) because-the wiped set is operation-specific, not a single domain-wide constant.--```rust-//! Shared data-dir wipe primitive used by `reset` and `uninstall --purge-data`.-//! Mute by design: returns the affected paths; callers own logging/printing-//! and the live-process guard (invariant #9). The remove+recreate is not-//! atomic — pre-existing, matches reset/restore.--use std::path::{Path, PathBuf};-use anyhow::Context;--/// The subdirectories wiped by `reset` / `uninstall --purge-data`.-/// `logs/` and `models/` are intentionally excluded and never wiped.-/// NOTE: this is the reset/uninstall set only — `init` and `restore` declare-/// their own (different) sets by design; do not converge them here.-pub(crate) const WIPE_SUBDIRS: &[&str] = &["wiki", "db", "raw"];--/// Paths that WOULD be purged (existing wipe subdirs), for dry-run preview.-pub(crate) fn purge_preview(data_dir: &Path) -> Vec<PathBuf> {- WIPE_SUBDIRS- .iter()- .map(|s| data_dir.join(s))- .filter(|p| p.exists())- .collect()-}--/// Wipe each existing wipe-subdir (remove + recreate empty). Returns the-/// paths actually purged (the subset that existed). Missing subdirs are-/// skipped, not errors. Carries per-path context on failure.-pub(crate) fn purge_data_dirs(data_dir: &Path) -> anyhow::Result<Vec<PathBuf>> {- let mut purged = Vec::new();- for sub in WIPE_SUBDIRS {- let path = data_dir.join(sub);- if !path.exists() {- continue;- }- std::fs::remove_dir_all(&path)- .with_context(|| format!("removing {}", path.display()))?;- std::fs::create_dir_all(&path)- .with_context(|| format!("recreating {}", path.display()))?;- purged.push(path);- }- Ok(purged)-}-```--Registered with `mod data_purge;` in `commands/mod.rs`.--### 2. `reset.rs` — call the helper, keep guard + wording + tracing--- Remove the local `const SUBDIRS`.-- Dry-run branch: `for p in data_purge::purge_preview(&config.data_dir) { println!("would remove {}", p.display()); }` then keep `(dry-run; pass --confirm to wipe)`.-- Apply branch: `for p in data_purge::purge_data_dirs(&config.data_dir)? { tracing::info!(path = %p.display(), "reset"); }` then keep `tracing::info!("reset complete")`.-- The `bail!` process guard at the top is **unchanged**. (`reset::run` already- returns `anyhow::Result`, so the helper's `anyhow::Result` slots in; reset- *gains* per-path error context it lacked.)--### 3. `uninstall.rs` — fix the dry-run gap + use the helper--- **Dry-run fix.** In `run()`, after `print_plan(&plan)` and before the- `if !args.apply { … return }` early exit, add:- ```rust- if args.purge_data {- for p in data_purge::purge_preview(&config.data_dir) {- println!("would purge {}", p.display());- }- }- ```-- **Up-front guard (option B / all-or-nothing).** After the dry-run early- return and before applying any wiring change, when `args.purge_data`:- ```rust- if args.purge_data {- let siblings = sibling_processes();- if !siblings.is_empty() {- bail!(busy_message("purge data", &siblings)); // nothing removed yet- }- }- ```- This refuses the whole command before touching anything if a process is- alive, matching `reset`'s guard-at-top. The TOCTOU window between this check- and the wipe is the same as `reset`'s and is accepted.-- **Apply wiring, then purge** (guard already passed — no per-purge refusal):- ```rust- for change in &plan { apply_change(change, name, url, args.only)?; }- if args.purge_data {- for p in data_purge::purge_data_dirs(&config.data_dir)? {- println!("✓ purged {}", p.display());- }- }- ```- The per-path error context is preserved (now inside the helper). The old- **mid-flow** `sibling_processes()` check, the `purge_refused` flag, the two- `eprintln!` warnings, and the end-of-run conditional `bail!` are **removed** —- the up-front guard replaces them. `print_docker_hint(args.purge_data)` is- still called (no longer gated on `purge_refused`).--### Output ordering--Dry-run with both wiring and purge:-```-would remove SessionStart, … from /…/.claude/settings.json-would remove instruction block from /…/CLAUDE.md-would purge /…/ai-memory/wiki-would purge /…/ai-memory/db-would purge /…/ai-memory/raw-(dry-run; pass --apply to remove)-```--**Accepted edge case:** when no wiring is found but `--purge-data` is set,-the dry-run prints `Nothing to remove. ai-memory wiring not found.` followed-by the `would purge …` lines. "Nothing to remove" refers to *wiring*; the-purge lines cover *data*. Technically correct; left as-is for simplicity.--## Testing--### Order (characterization-first, then TDD)--1. **Characterize `reset` against current code (must be green BEFORE refactor).**- These test the `reset` *command* (not the helper), so they survive the- refactor unchanged and prove observable equivalence:- - dry-run (no `--confirm`): seed `wiki`/`db`/`raw` with files → asserts- `would remove <path>` per subdir, prints `(dry-run; pass --confirm to wipe)`,- and **nothing is deleted**.- - apply (`--confirm`): asserts `wiki`/`db`/`raw` end empty (dirs remain,- files gone), `logs/` untouched, absent subdir skipped without error.- - **The process-guard refusal path is NOT characterized here.**- `process_guard::sibling_processes()` inspects the live OS process table- via `sysinfo` with no injection seam; testing the refusal deterministically- would require spawning a real long-lived `ai-memory` process (flaky) or- refactoring `process_guard` (forbidden by rule #6). The guard is untouched- by this refactor, so a refactor-invariance test of it adds nothing.-2. **Unit test `data_purge`** (fails: module absent) → create helper → green:- - `purge_data_dirs`: seed `wiki`/`db`/`raw` + `logs/` → returns the 3 paths,- those dirs emptied, `logs/` intact; missing subdir skipped (not returned,- no error).- - `purge_preview`: returns only existing subdirs.- - missing `data_dir` entirely: `purge_preview` → empty; `purge_data_dirs`- → `Ok(vec![])`, creates nothing.-3. **Refactor** `reset.rs` and `uninstall.rs` to use the helper → step 1 + 2- tests stay green.-4. **Integration test `uninstall --purge-data` dry-run** (fails) → implement- preview → green: stdout contains `would purge …/wiki|db|raw` AND the seeded- files still exist on disk afterward.-5. **Integration test `uninstall --purge-data --apply --yes` happy path**- (temp HOME + temp data dir, no sibling): asserts `wiki`/`db`/`raw` emptied,- `logs/` intact, `✓ purged` printed. Covers the new apply-side lines for the- changed-line coverage target. (Small flake risk if another test spawns- `ai-memory` concurrently and trips the guard; serialize/retry if it surfaces.)-6. **Option-B guard (best-effort, `#[ignore]`).** With `--purge-data --apply`- and a live sibling `ai-memory` process, the command bails and **no wiring is- removed** (all-or-nothing). Like H3 this cannot be tested deterministically- (`sysinfo` reads the live process table, no injection seam, and rule #6- forbids refactoring `process_guard`); described as an `#[ignore]`d- integration test that spawns a real sibling, plus manual verification. The- happy path (no sibling) is covered by the existing round-trip + the new- dry-run test.--Symlinked subdirs are out of scope; behavior matches existing `reset`-(pre-existing) and is not tested.--### Coverage--- **Scope: only the lines changed/added on this branch (the diff vs `main`),- not whole files.** Pre-existing untouched code (e.g. the already-committed- `strip_*` / `build_plan`) is out of scope.-- Tool: **`cargo llvm-cov`** for the report + **`diff-cover`** against `main`- for the changed-line numbers. Local inspection, not a CI gate (CI runs- fmt/clippy/test/deny/audit only).- - `cargo llvm-cov --cobertura --output-path target/cov.xml -p ai-memory-cli`- - `diff-cover target/cov.xml --compare-branch main`-- Targets on the changed lines (line coverage):- - **Critical logic ≥ 90%**: the new `data_purge` helper (covered ~100% by its- own unit tests).- - **Rest ≥ 80%**: changed lines in `reset::run` (reset characterization- tests) and `uninstall::run` (dry-run preview test + apply+purge happy-path- test).-- **Lone accepted gap:** the option-B `bail!` line in `uninstall` is only- reached by the `#[ignore]` sibling test (sysinfo, per H3); it is the single- uncovered changed line.--## Project-rule checks--- **Invariant #9 (live-process guard before destructive op):** preserved and- strengthened — for `uninstall --purge-data` the guard now runs **up front**- (all-or-nothing), matching `reset`. The mute helper performs no guard itself;- each caller owns it.-- **Invariant #10 (atomic file writes: tmp + rename + fsync):** **N/A here.**- #10 governs *file-content* writes (config files, wiki pages, via- `apply_shared`); this is a *directory-tree wipe*. There is no meaningful- atomic rmdir+mkdir primitive, and `reset` (reset.rs:42-43) and `restore`- (restore.rs:56,60) already use raw `remove_dir_all`. The wipe is- intentionally non-atomic and matches existing behavior.-- **Invariant #16 (CLI is a thin HTTP client):** unaffected — `reset` and- `--purge-data` are listed #16 exceptions (server-stopped lifecycle ops); the- helper is local-FS by design and not reachable from any server-backed command.-- **Workflow rule #5 (test before implementation):** honored via the- characterization-first then TDD order above.-- **Workflow rule #6 (no refactor outside the milestone):** touching- `reset.rs` is in-scope because *this feature* created the drift (uninstall- copied reset's wipe in `3e3d44a`); consolidating both call sites onto one- primitive is the minimal way to remove that risk. `reset` is the original and- is touched deliberately, pinned by the characterization tests written first.-- **CLAUDE.md gate (rule #3):** `cargo fmt --all -- --check`,- `cargo clippy --workspace --all-targets -- -D warnings`,- `cargo test --workspace` all green before commit.--## Out-of-scope findings (logged, not addressed here)--- **`models/` is created but never wiped.** `init.rs:13` creates- `wiki,raw,db,models`, but `reset`/`--purge-data` wipe only `wiki,db,raw` —- `models/` survives a reset (like `logs/`). Likely intentional (downloaded- embedding models), but undocumented. Candidate for a separate issue;- not changed here.--## Behavior change adopted (post-review, maintainer request)--- **Option B — all-or-nothing `--purge-data`.** The previous behavior removed- the wiring, then *skipped* the data purge (with a warning + non-zero exit) if- an `ai-memory` process was alive, leaving a half-done state. The guard now- moves to the **top** of the apply path: `uninstall --purge-data` refuses- before removing anything if a process is alive. Wiring-only `uninstall`- (no `--purge-data`) stays unguarded, since editing agent config files is safe- while the server runs. This makes `uninstall` (disconnect integration) and- `reset` (wipe data) consistent in their guard discipline, and clarifies the- mental model: `uninstall` removes integration (keeps data unless- `--purge-data`); `reset` wipes data (keeps integration).--## Review resolutions (subagent critique → disposition)--- **H1 (helper would drop uninstall's `with_context`):** accepted — helper- returns `anyhow::Result` with per-path context (reset *gains* context).-- **H2 (#10 not addressed):** accepted — explicit N/A note added.-- **H3 (guard test infeasible):** accepted — guard refusal removed from the- characterization set with rationale.-- **M1 (coverage scope/metric):** the maintainer later scoped coverage to the- **changed lines only** (diff vs `main`) — which resolves the reviewer's- "whole-file / already-committed" concern. Measured with `cargo llvm-cov`- cobertura + `diff-cover`, line coverage, local (non-CI).-- **M2 (`build_plan` is not "pure"):** accepted — moved to the ≥80% bucket;- 90% bucket reframed as "critical logic", not "pure".-- **M3 (reset-rationale inverted):** accepted — corrected (reset is the- original; uninstall copied it).-- **M4 (move const to core?):** rejected as stated — the grep found *four*- divergent sets (`init` adds `models`, `restore` is `wiki,db` only), so the- sets legitimately differ; helper stays CLI-local and scoped to the- reset↔uninstall set. Surfaced the `models/` discrepancy as an out-of-scope- finding.-- **M5 / L1 / L2 / L4:** accepted — #16 note, missing-`data_dir` test,- symlink sentence, and llvm-cov placed under "local, not CI-gated".