Skip to content

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

Rust

fix(uninstall): clear auto-wire sentinels and keep the hook bearer for partial uninstalls

Éverton Toffanetto66b7567aae36
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e28a61e6..5e2633bb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -176,6 +176,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Native `ai-memory upgrade` accepts release archives whose entries are
`./`-prefixed (`tar -C … -czf … .` as in `release.yml`), instead of
rejecting `Component::CurDir` as an unsafe path. (#802)
+- `ai-memory uninstall` left `ai-memory run`'s auto-wire sentinels in
+ `<data_dir>/autowire-state/`, so after the hooks were removed the next
+ managed launch of that harness on the same binary version skipped wiring and
+ captured nothing. Removing hooks or MCP (a full uninstall, `--only hooks` or
+ `--only mcp`) now deletes every sentinel and lists them in the dry-run plan.
+ `--only mcp`, `--only instructions` and `--only skills` also no longer delete
+ the stored hook bearer that the still-installed hooks read. (#820)
- Native `ai-memory upgrade` treats Linuxbrew (`/home/linuxbrew/.linuxbrew/`)
as package-managed and refuses self-replace there. (#802)
- Native `ai-memory upgrade` container refusal now uses the shared
diff --git a/README.md b/README.md
index 53279495..7bab0785 100644
--- a/README.md
+++ b/README.md
@@ -364,7 +364,9 @@ Auto-wiring is on by default; opt out with `ai-memory run --no-autowire` or
`ai-memory run`).
`ai-memory uninstall --apply` removes everything ai-memory installed,
-and only what it installed. Install commands are idempotent and write
+and only what it installed. It also clears `ai-memory run`'s auto-wire
+record, so the next managed launch wires that harness again; to keep it
+unwired, launch with `--no-autowire` or set `AI_MEMORY_RUN_AUTOWIRE=false`. Install commands are idempotent and write
timestamped backups next to any file they touch.
## Everyday use
diff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rs
index 8fdcdeec..22366a3d 100644
--- a/crates/ai-memory-cli/src/commands/run_autowire.rs
+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs
@@ -52,7 +52,8 @@ pub(crate) fn agent_choice_for_harness(harness: ManagedHarness) -> Option<AgentC
})
}
-/// Where auto-wire records its sentinels.
+/// Where auto-wire records its sentinels. `uninstall` clears it whenever it
+/// removes hooks or MCP, so the next managed launch wires again.
pub(crate) fn autowire_state_dir(data_dir: &Path) -> PathBuf {
data_dir.join("autowire-state")
}
@@ -438,7 +439,8 @@ pub(crate) fn ensure_wired_with(
// Record the attempt even on partial failure: re-applying an idempotent
// install on every launch would nag and churn config. A user who wants a
// retry can re-run install-hooks manually or delete this sentinel under
- // `<data_dir>/autowire-state/`.
+ // `<data_dir>/autowire-state/`; `ai-memory uninstall` clears them all when
+ // it removes hooks or MCP.
write_sentinel(&sentinel);
}
@@ -1142,4 +1144,45 @@ mod tests {
"a present sentinel must short-circuit before the MCP install"
);
}
+
+ /// Clearing the auto-wire state (what `uninstall` does) makes the next
+ /// launch wire again; `uninstall` and the gate must agree on the directory.
+ #[test]
+ fn clearing_autowire_state_rewires_the_next_launch() {
+ let home = tempfile::tempdir().unwrap();
+ let data = tempfile::tempdir().unwrap();
+ let config = test_config(home.path(), data.path());
+ let settings = data.path().join("claude-settings.json");
+ let mcp = data.path().join("claude.json");
+ let user_settings = r#"{"existingUserKey":1}"#;
+ let user_mcp = r#"{"existingMcpKey":1}"#;
+ std::fs::write(&settings, user_settings).unwrap();
+ std::fs::write(&mcp, user_mcp).unwrap();
+ let overrides = WireOverrides {
+ hooks_dir: Some(repo_hooks()),
+ hooks_config_file: Some(settings.clone()),
+ mcp_config_file: Some(mcp.clone()),
+ ..WireOverrides::default()
+ };
+ ensure_wired_with(&config, ManagedHarness::Claude, &overrides, &[]);
+
+ // The wiring is removed by hand; the sentinel alone keeps it that way.
+ std::fs::write(&settings, user_settings).unwrap();
+ std::fs::write(&mcp, user_mcp).unwrap();
+ ensure_wired_with(&config, ManagedHarness::Claude, &overrides, &[]);
+ assert_eq!(std::fs::read_to_string(&mcp).unwrap(), user_mcp);
+
+ // Moving the state aside is, for the gate, the same as clearing it.
+ std::fs::rename(
+ autowire_state_dir(data.path()),
+ data.path().join("cleared-autowire-state"),
+ )
+ .unwrap();
+ ensure_wired_with(&config, ManagedHarness::Claude, &overrides, &[]);
+ assert!(
+ std::fs::read_to_string(&settings)
+ .is_ok_and(|s| s.contains("ai-memory") || s.contains("ai_memory"))
+ );
+ assert!(std::fs::read_to_string(&mcp).is_ok_and(|s| s.contains("ai-memory")));
+ }
}
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index e5e92a92..b851ba76 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -74,6 +74,7 @@ enum DeleteKind {
OpenClawEntrypoint,
KiroCliV3Hooks,
ManagedSkill,
+ AutowireSentinel,
}
impl DeleteKind {
@@ -88,6 +89,7 @@ impl DeleteKind {
Self::OpenClawEntrypoint => "OpenClaw plugin entrypoint",
Self::KiroCliV3Hooks => "Kiro CLI v3 hook file",
Self::ManagedSkill => "managed Agent Skill",
+ Self::AutowireSentinel => "auto-wire sentinel",
}
}
}
@@ -141,7 +143,7 @@ fn push_generated_delete(plan: &mut Vec<PlannedChange>, path: PathBuf, kind: Del
/// 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) -> anyhow::Result<Vec<PlannedChange>> {
+fn build_plan(args: &UninstallArgs, data_dir: &Path) -> anyhow::Result<Vec<PlannedChange>> {
let mut plan = Vec::new();
let want = |k: crate::cli::UninstallOnly| args.only.is_none() || args.only == Some(k);
let name = args.mcp_name.as_deref();
@@ -449,6 +451,24 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {
}
}
+ // ---- Auto-wire sentinels (ai-memory's own state) ----
+ // `ai-memory run` skips wiring while a sentinel exists, so one left behind
+ // would stop the next managed launch from reinstalling what this removes.
+ // All of them go: one keyed on a config home this environment cannot see
+ // costs only an idempotent re-apply.
+ if want(crate::cli::UninstallOnly::Hooks) || want(crate::cli::UninstallOnly::Mcp) {
+ let dir = crate::commands::run_autowire::autowire_state_dir(data_dir);
+ let mut sentinels: Vec<PathBuf> = std::fs::read_dir(&dir)
+ .into_iter()
+ .flatten()
+ .filter_map(|entry| entry.ok().map(|entry| entry.path()))
+ .collect();
+ sentinels.sort();
+ for path in sentinels {
+ push_generated_delete(&mut plan, path, DeleteKind::AutowireSentinel);
+ }
+ }
+
Ok(plan)
}
@@ -610,7 +630,7 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {
let name = args.mcp_name.clone();
let url = args.mcp_url.clone();
- let plan = build_plan(&args)?;
+ let plan = build_plan(&args, &config.data_dir)?;
print_plan(&plan);
if args.purge_data {
for path in data_purge::purge_preview(&config.data_dir) {
@@ -653,9 +673,13 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {
}
// Removing the hooks removes the only readers of the stored bearer, so
- // leaving it on disk would strand a live credential (#552). Best-effort:
- // an unremovable file must not fail a teardown that otherwise succeeded.
- if let Err(error) = crate::config::clear_hook_auth_token(&config.data_dir) {
+ // leaving it on disk would strand a live credential (#552). An uninstall
+ // that keeps the hooks (`--only mcp|instructions|skills`) keeps it: the
+ // native hook, the shell hooks and the generated TypeScript integrations
+ // (the Pi one also bridges MCP) all still read it. Best-effort: an
+ // unremovable file must not fail a teardown that otherwise succeeded.
+ let hooks_removed = args.only.is_none() || args.only == Some(crate::cli::UninstallOnly::Hooks);
+ if hooks_removed && let Err(error) = crate::config::clear_hook_auth_token(&config.data_dir) {
eprintln!(
"ai-memory uninstall warning: could not remove the stored auth token under {}: {error}",
config.data_dir.display()
@@ -1062,6 +1086,9 @@ fn generated_file_is_ours(path: &Path, kind: DeleteKind) -> bool {
content.contains("Auto-generated by `ai-memory install-hooks --agent omp --apply`")
&& content.contains("const AGENT = \"omp\";")
}
+ // Auto-wire writes its sentinels empty; anything else in that
+ // directory is not one of them.
+ DeleteKind::AutowireSentinel => content.is_empty(),
DeleteKind::PiExtension => {
content.contains("Auto-generated by `ai-memory install-hooks --agent pi --apply`")
&& content.contains("const AGENT = \"pi\";")
diff --git a/crates/ai-memory-cli/tests/suite/removal.rs b/crates/ai-memory-cli/tests/suite/removal.rs
index d13fcba1..dd289d12 100644
--- a/crates/ai-memory-cli/tests/suite/removal.rs
+++ b/crates/ai-memory-cli/tests/suite/removal.rs
@@ -1715,3 +1715,115 @@ fn default_uninstall_removes_installed_kimi_code_flavored_url() {
);
assert!(after["mcpServers"].get("other").is_some());
}
+
+/// `ai-memory run` skips auto-wire while its sentinel exists, so an uninstall
+/// that leaves one makes the next managed launch skip wiring and capture
+/// nothing. Hooks or MCP in scope clear every sentinel, even with no other
+/// wiring left; instructions and skills leave them alone.
+#[test]
+fn uninstall_clears_autowire_sentinels_with_hooks_or_mcp() {
+ let _guard = cli_test_lock();
+ for only in [
+ None,
+ Some("hooks"),
+ Some("mcp"),
+ Some("instructions"),
+ Some("skills"),
+ ] {
+ let home = tempfile::tempdir().unwrap();
+ let project = tempfile::tempdir().unwrap();
+ let state = home.path().join(".ai-memory-data/autowire-state");
+ std::fs::create_dir_all(&state).unwrap();
+ let sentinels = [
+ state.join(format!(
+ "claude-code-{}-0123456789abcdef",
+ env!("CARGO_PKG_VERSION")
+ )),
+ // An older release's name, before the location hash.
+ state.join("codex-2.3.1"),
+ ];
+ for path in &sentinels {
+ std::fs::write(path, b"").unwrap();
+ }
+ let foreign = state.join("notes.txt");
+ std::fs::write(&foreign, "not a sentinel").unwrap();
+ let clears = matches!(only, None | Some("hooks" | "mcp"));
+ let uninstall = |extra: &[&str]| {
+ let mut args = vec!["uninstall"];
+ if let Some(only) = only {
+ args.extend(["--only", only]);
+ }
+ args.extend_from_slice(extra);
+ let output = command_with_home(home.path())
+ .args(&args)
+ .current_dir(project.path())
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{args:?}: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ String::from_utf8_lossy(&output.stdout).into_owned()
+ };
+ let plan = uninstall(&[]);
+ assert_eq!(
+ plan.contains("auto-wire sentinel"),
+ clears,
+ "{only:?}: {plan}"
+ );
+ assert!(
+ sentinels.iter().all(|path| path.exists()),
+ "a dry run must not delete"
+ );
+ uninstall(&["--apply", "--yes"]);
+ for path in &sentinels {
+ assert_eq!(path.exists(), !clears, "{only:?}: {}", path.display());
+ }
+ assert!(
+ foreign.exists(),
+ "a file auto-wire did not write must survive"
+ );
+ }
+}
+
+/// The stored hook bearer is read by the hooks, so only an uninstall that
+/// removes them may delete it.
+#[test]
+fn uninstall_keeps_the_hook_bearer_unless_hooks_are_removed() {
+ let _guard = cli_test_lock();
+ let home = tempfile::tempdir().unwrap();
+ let project = tempfile::tempdir().unwrap();
+ let run = |args: &[&str]| {
+ let output = command_with_home(home.path())
+ .args(args)
+ .current_dir(project.path())
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{args:?}: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ };
+ run(&["install-mcp", "--client", "claude-code", "--apply"]);
+ run(&["install-hooks", "--agent", "claude-code", "--apply"]);
+ let data = home.path().join(".ai-memory-data");
+ let bearer = [data.join("auth-token"), data.join("auth-header")];
+ for path in &bearer {
+ std::fs::write(path, "secret\n").unwrap();
+ }
+
+ run(&["uninstall", "--only", "mcp", "--apply", "--yes"]);
+ for path in &bearer {
+ assert!(path.exists(), "--only mcp removed {}", path.display());
+ }
+ run(&["uninstall", "--only", "hooks", "--apply", "--yes"]);
+ for path in &bearer {
+ assert!(
+ !path.exists(),
+ "removing the hooks keeps {}",
+ path.display()
+ );
+ }
+}
diff --git a/docs/cookbook.md b/docs/cookbook.md
index 39301f23..9f4e3d3d 100644
--- a/docs/cookbook.md
+++ b/docs/cookbook.md
@@ -198,9 +198,9 @@ ai-memory serve # run the server
- **Nothing is being remembered**: hooks may not be installed. `ai-memory run
<harness>` installs its hooks + MCP on the first launch per harness,
- ai-memory version and config home. If that harness already launched through
- `run` and its hooks went missing (removed by hand, a failed first wire),
- install them by hand: `ai-memory
+ ai-memory version and config home, and again after `ai-memory uninstall`. If that harness
+ already launched through `run` and its hooks went missing another way
+ (removed by hand, a failed first wire), install them by hand: `ai-memory
install-hooks --agent <your-agent> --apply` and `ai-memory install-mcp
--client <client> --apply`. Then check `ai-memory status` / `ai-memory doctor`.
- **Only *some* agents are being remembered**: run `ai-memory doctor`. It lists
diff --git a/docs/install.md b/docs/install.md
index 866d9fd0..8d7709c1 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -2070,7 +2070,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree
| `setup-agent --agent --to --host-prefix` | `docker run --rm -v` | Extract bundled scripts + print config (one-shot) |
| `install-instructions [--target] [--print] [--no-skills]` | same host environment used for the agent prompt files | Install or update the slim CLAUDE.md / AGENTS.md routing block and, by default, the managed ai-memory Agent Skills |
| `install-skills [--scope] [--agent]` | same host environment used for the agent skill dirs | Install or update only the managed ai-memory Agent Skills |
-| `uninstall --apply` | same host environment used for install | Remove only ai-memory-owned hooks, MCP entries, instruction blocks, managed skill files, and generated plugin files after content/marker validation. Use `--mcp-url` for custom MCP endpoints and `--mcp-name` only to narrow removal. |
+| `uninstall --apply` | same host environment used for install | Remove only ai-memory-owned hooks, MCP entries, instruction blocks, managed skill files, and generated plugin files after content/marker validation. Removing hooks or MCP also deletes the `ai-memory run` auto-wire sentinels under `<data_dir>/autowire-state/`, so the next managed launch wires again. Use `--mcp-url` for custom MCP endpoints and `--mcp-name` only to narrow removal. |
| `llm-test --provider …` | `docker run --rm -e …` | Smoke-test an LLM provider |
| `completions <shell>` | `docker run --rm` or native binary | Print a bash/zsh/fish/PowerShell/elvish completion script; see [`shell-completions.md`](shell-completions.md) |
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index 59dcb110..ceefcca2 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -14,7 +14,9 @@ not already wired, so capture and recall work without a separate `install-hooks`
/ `install-mcp` step (a common footgun: `ai-memory run kimi` used to capture
nothing if the Kimi hooks were never installed). Auto-wire is idempotent and
one-time per harness, binary version and install location (a second config home,
-such as another `CLAUDE_CONFIG_DIR`, gets its own first launch), preserves
+such as another `CLAUDE_CONFIG_DIR`, gets its own first launch; `ai-memory
+uninstall` of hooks or MCP clears that record, so the next launch wires again),
+preserves
unrelated user config, runs
before the harness starts so it picks up the fresh hooks, and is best-effort —
if an install fails it warns and still launches. Harnesses without installer
diff --git a/docs/users.md b/docs/users.md
index ada11cba..e4244337 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -492,6 +492,10 @@ the data dir, both `0600` (the data dir itself is `0700`):
| `<data_dir>/auth-token` | the native `ai-memory hook` command |
| `<data_dir>/auth-header` | the shell hooks, via `curl -H @<file>` |
+`ai-memory uninstall` deletes both files when it removes the hooks (a full
+uninstall or `--only hooks`); `--only mcp`, `--only instructions` and `--only
+skills` keep them for the hooks still installed.
+
It is deliberately **not** written into the agent's own config any more. Before
#552 it went onto the hook's command line — `--auth-token <token>` for native
hooks, an `AI_MEMORY_AUTH_TOKEN=` shell prefix for the script hooks — which put