Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
chore(uninstall): move the auto-wire sentinel sweep to its own change
Éverton Toffanetto7d81d6072182
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c06607f8..56176a56 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -196,13 +196,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0context likewise read a whitespace-only `CRUSH_GLOBAL_CONFIG` or`XDG_CONFIG_HOME` as a directory, and now falls back to the default globalconfig. (#820)-- `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)- A managed Crush launch with a context packet dropped the `CRUSH.md` and`AGENTS.md` Crush loads by default: Crush only adds them while`global_context_paths` is empty, and the packet filled it. The launcher nowdiff --git a/README.md b/README.mdindex 7bab0785..53279495 100644--- a/README.md+++ b/README.md@@ -364,9 +364,7 @@ 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. 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+and only what it installed. Install commands are idempotent and writetimestamped backups next to any file they touch.## Everyday usediff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rsindex 56c76051..7c3f0698 100644--- a/crates/ai-memory-cli/src/commands/run_autowire.rs+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs@@ -52,16 +52,15 @@ pub(crate) fn agent_choice_for_harness(harness: ManagedHarness) -> Option<AgentC})}-/// Sentinel marking that auto-wire already ran for this agent, binary version-/// and install location. The version re-wires the fresh hook bundle after an-/// upgrade; the hashed hook and MCP config locations give each config home its-/// own first launch.-/// Where auto-wire records its sentinels. `uninstall` clears it whenever it-/// removes hooks or MCP, so the next managed launch wires again.+/// Where auto-wire records its sentinels.pub(crate) fn autowire_state_dir(data_dir: &Path) -> PathBuf {data_dir.join("autowire-state")}+/// Sentinel marking that auto-wire already ran for this agent, binary version+/// and install location. The version re-wires the fresh hook bundle after an+/// upgrade; the hashed hook and MCP config locations give each config home its+/// own first launch.fn sentinel_path(data_dir: &Path, agent: AgentChoice, targets: &[String]) -> PathBuf {let digest = format!("{:x}", Sha256::digest(targets.join("\n").as_bytes()));let name = format!(@@ -439,8 +438,7 @@ 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/`; `ai-memory uninstall` clears them all when- // it removes hooks or MCP.+ // `<data_dir>/autowire-state/`.write_sentinel(&sentinel);}@@ -694,47 +692,6 @@ mod tests {);}- /// 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")));- }-/// A blank `--env` value masks the process one and counts as unset, so/// hooks, MCP and native session import all fall back to the defaults the/// installers pick on their own, never to a whitespace-named directory.diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex ea8f1bf0..b064a118 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -74,7 +74,6 @@ enum DeleteKind {OpenClawEntrypoint,KiroCliV3Hooks,ManagedSkill,- AutowireSentinel,}impl DeleteKind {@@ -89,7 +88,6 @@ impl DeleteKind {Self::OpenClawEntrypoint => "OpenClaw plugin entrypoint",Self::KiroCliV3Hooks => "Kiro CLI v3 hook file",Self::ManagedSkill => "managed Agent Skill",- Self::AutowireSentinel => "auto-wire sentinel",}}}@@ -175,7 +173,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, data_dir: &Path) -> anyhow::Result<Vec<PlannedChange>> {+fn build_plan(args: &UninstallArgs) -> 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();@@ -489,24 +487,6 @@ fn build_plan(args: &UninstallArgs, data_dir: &Path) -> anyhow::Result<Vec<Plann}}- // ---- 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)}@@ -668,7 +648,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, &config.data_dir)?;+ let plan = build_plan(&args)?;print_plan(&plan);if args.purge_data {for path in data_purge::purge_preview(&config.data_dir) {@@ -711,13 +691,9 @@ 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). 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) {+ // 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) {eprintln!("ai-memory uninstall warning: could not remove the stored auth token under {}: {error}",config.data_dir.display()@@ -1124,9 +1100,6 @@ 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.rsindex 2791a897..b693743f 100644--- a/crates/ai-memory-cli/tests/suite/removal.rs+++ b/crates/ai-memory-cli/tests/suite/removal.rs@@ -292,118 +292,6 @@ fn relocated_codex_uninstall_sweeps_active_and_legacy_mcp() {}}-/// `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()- );- }-}-/// `PI_CONFIG_DIR` renames OMP's `~/.omp` root for the extension and/// `mcp.json` (an XDG data dir moves only sessions), and uninstall also sweeps/// the `~/.omp` locations earlier releases wrote whatever the variable said.diff --git a/docs/cookbook.md b/docs/cookbook.mdindex 9f4e3d3d..39301f23 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, 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+ 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-memoryinstall-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 listsdiff --git a/docs/install.md b/docs/install.mdindex 9eceab21..249d771f 100644--- a/docs/install.md+++ b/docs/install.md@@ -2078,7 +2078,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. 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. |+| `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. || `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.mdindex 629fd28d..e371a065 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -14,9 +14,7 @@ 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 capturenothing if the Kimi hooks were never installed). Auto-wire is idempotent andone-time per harness, binary version and install location (a second config home,-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+such as another `CLAUDE_CONFIG_DIR`, gets its own first launch), preservesunrelated user config, runsbefore 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 installerdiff --git a/docs/users.md b/docs/users.mdindex e4244337..ada11cba 100644--- a/docs/users.md+++ b/docs/users.md@@ -492,10 +492,6 @@ 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 nativehooks, an `AI_MEMORY_AUTH_TOKEN=` shell prefix for the script hooks — which put