Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge pull request #28 from djalmajr/fix/hook-self-heal-purged-project
AkitaOnRails3ee11ab9e5b0
diff --cc CHANGELOG.mdindex 299a8bda,16b0888d..78e52890--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -101,26 -99,6 +101,29 @@@ and this project adheres to [Semantic Vtokens do not consume `maxOutputTokens` and truncate strict JSON responses.- `install-mcp --client claude-code` now prints the direct-edit JSON path as`~/.claude.json`, matching the `--apply` path and `claude mcp add` behavior.++- Hook routing now evicts a stale project-cache entry and retries once when a++ live server sees a cached project deleted underneath it, such as after++ `purge-project`, so capture resumes without restarting the server.++### 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. MCP matching is endpoint-based by default; pass `--mcp-url` when the+ server was installed with a custom endpoint and `--mcp-name` only to narrow+ removal to one matching entry. Docker/volume teardown is printed as a hint,+ not executed.++### 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.+- `ai-memory uninstall` only deletes generated plugin/extension files after+ re-validating their ai-memory-generated content, and never treats a matching+ filename or MCP server name alone as proof of ownership.## [0.1.3] - 2026-05-24diff --cc crates/ai-memory-hooks/src/router.rsindex ac9b4f75,a7d98875..11801a37--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@@ -242,18 -239,33 +242,37 @@@ fn render_handoff_markdown(h: &Handoffbuf}-/// Resolve the `(workspace_id, project_id)` pair for a hook event.-///-/// Precedence:-/// 1. `workspace_override` (typically declared by the agent's host-side-/// hook via a `.ai-memory.toml` walk-up) OR `DEFAULT_WORKSPACE_NAME`.-/// 2. `project_override` OR `basename(cwd)` OR fallback to-/// `state.project_id` (when `cwd` is also unavailable).-///-/// Build the `project_cache` key from the (normalised cwd, workspace-/// override, project override) triple. Shared by `resolve_project_ids`-/// (insert/lookup) and `process` (eviction on the stale-cache retry) so-/// the two always agree on the slot.++/// Build the `project_cache` key from the resolved cwd, overrides, and++/// project strategy. Shared by `resolve_project_ids` (insert/lookup) and++/// `process` (eviction on the stale-cache retry) so the two always agree on++/// the slot.+ fn cache_key_for(+ cwd_norm: Option<&str>,+ workspace_override: Option<&str>,+ project_override: Option<&str>,-) -> (String, String, String) {++ project_strategy: ProjectStrategy,++) -> (String, String, String, String) {+ (+ cwd_norm.unwrap_or_default().to_string(),+ workspace_override.unwrap_or_default().to_string(),+ project_override.unwrap_or_default().to_string(),++ project_strategy.as_str().to_string(),+ )+ }+-/// Cache key is `(cwd, workspace_override, project_override)` so the-/// same `cwd` resolved with and without an override (e.g. during a-/// hook-script upgrade window) doesn't poison each other's slot.+/// Resolve the `(workspace_id, project_id)` pair for a hook event.+///+/// Precedence:+/// 1. `workspace_override` (typically declared by the agent's host-side+/// hook via a `.ai-memory.toml` walk-up) OR `DEFAULT_WORKSPACE_NAME`.+/// 2. `project_override` OR marker-selected project strategy OR+/// `basename(cwd)` OR fallback to `state.project_id` (when `cwd` is+/// also unavailable).+///- /// Cache key is `(cwd, workspace_override, project_override, project_strategy)` so the- /// same `cwd` resolved with and without an override (e.g. during a- /// hook-script upgrade window) doesn't poison each other's slot.++/// Cache key is `(cwd, workspace_override, project_override,++/// project_strategy)` so the same `cwd` resolved with and without an++/// override (e.g. during a hook-script upgrade window) doesn't poison each++/// other's slot.async fn resolve_project_ids(state: &HookState,cwd: Option<&str>,@@@ -269,12 -280,7 +288,12 @@@return Ok((state.workspace_id, state.project_id));}- let cache_key = (- cwd_norm.clone().unwrap_or_default(),- workspace_override.unwrap_or("").to_string(),- project_override.unwrap_or("").to_string(),- project_strategy.as_str().to_string(),- let cache_key = cache_key_for(cwd_norm.as_deref(), workspace_override, project_override);++ let cache_key = cache_key_for(++ cwd_norm.as_deref(),++ workspace_override,++ project_override,++ project_strategy,+ );{let cache = state.project_cache.lock().await;@@@ -381,7 -372,40 +400,42 @@@ async fn process(state: &HookState, envagent_kind: env.agent,cwd: env.cwd.as_ref().map(std::path::PathBuf::from),};- state.writer.begin_session(new_session).await?;+ if let Err(e) = state.writer.begin_session(new_session).await {+ // The cached (workspace, project) may have been deleted out from+ // under us — e.g. `purge-project` on a live server drops the row+ // but leaves this in-memory cache pointing at the old id, so+ // begin_session trips the project foreign key. Evict the stale+ // slot, re-resolve (which recreates the project), and retry once.+ warn!(error = %e, "begin_session failed; evicting stale project cache and retrying");+ let cwd_norm = env.cwd.as_deref().filter(|s| !s.is_empty());+ let key = cache_key_for(+ cwd_norm,+ env.workspace_override.as_deref(),+ env.project_override.as_deref(),++ env.project_strategy,+ );+ state.project_cache.lock().await.remove(&key);+ let refreshed = resolve_project_ids(+ state,+ env.cwd.as_deref(),+ env.workspace_override.as_deref(),+ env.project_override.as_deref(),++ env.project_strategy,+ )+ .await?;+ ws = refreshed.0;+ proj = refreshed.1;+ state+ .writer+ .begin_session(NewSession {+ id: session_id,+ workspace_id: ws,+ project_id: proj,+ agent_kind: env.agent,+ cwd: env.cwd.as_ref().map(std::path::PathBuf::from),+ })+ .await?;+ }// Persist the observation row.let kind = env.event.to_observation_kind();@@@ -866,6 -854,67 +920,131 @@@ mod tests}}+ /// If the cached project is deleted out from under the router (e.g.+ /// `purge-project` on a live server), the next event must self-heal:+ /// evict the stale slot, recreate the project, and ingest — instead of+ /// failing forever on the `sessions.project_id` foreign key.+ #[tokio::test]+ async fn process_self_heals_when_cached_project_purged() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let cwd = "/home/user/heal-project";++ // 1) First event creates + caches the project (and a session).+ let env1 = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "user-prompt".into(),+ agent: Some("claude-code".into()),+ cwd: Some(cwd.into()),+ ..Default::default()+ },+ serde_json::json!({ "sessionID": "heal-sess-1" }),+ );+ process(&state, env1).await.unwrap();- let (ws, proj) = resolve_project_ids(&state, Some(cwd), None, None)- .await- .unwrap();++ let (ws, proj) =++ resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)++ .await++ .unwrap();++ // 2) Purge the project — the DB row is gone but the cache still+ // points at it (exactly the purge-on-live-server scenario).+ state+ .writer+ .purge_project(ws, proj, "default/heal-project")+ .await+ .unwrap();+ assert!(- state.project_cache.lock().await.values().any(|ids| *ids == (ws, proj)),++ state++ .project_cache++ .lock()++ .await++ .values()++ .any(|ids| *ids == (ws, proj)),+ "cache still holds the now-deleted project id"+ );++ // 3) Next event with the same cwd must NOT error on the stale FK —+ // the router evicts, recreates, and ingests.+ let env2 = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "user-prompt".into(),+ agent: Some("claude-code".into()),+ cwd: Some(cwd.into()),+ ..Default::default()+ },+ serde_json::json!({ "sessionID": "heal-sess-2" }),+ );+ process(&state, env2)+ .await+ .expect("self-heal: stale cached project must be recreated, not FK-fail");++ // 4) The project was recreated (fresh id) and the event landed.- let (_, proj_new) = resolve_project_ids(&state, Some(cwd), None, None)- .await- .unwrap();- assert_ne!(proj_new, proj, "purged project must be replaced by a fresh one");++ let (_, proj_new) =++ resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)++ .await++ .unwrap();++ assert_ne!(++ proj_new, proj,++ "purged project must be replaced by a fresh one"++ );+ let counts = state.reader.status_counts().await.unwrap();+ assert!(counts.sessions >= 1, "recreated session must be persisted");+ }+++ #[tokio::test]++ async fn process_self_heal_evicts_project_strategy_cache_slot() {++ let tmp = TempDir::new().unwrap();++ let state = make_state(&tmp).await;++++ let repo_dir = tmp.path().join("repo-root-project");++ init_repo_with_commit(&repo_dir);++ let app_dir = repo_dir.join("app");++ std::fs::create_dir_all(&app_dir).unwrap();++ let cwd = app_dir.to_str().unwrap();++++ let env1 = HookEnvelope::from_query_and_body(++ HookQuery {++ event: "user-prompt".into(),++ agent: Some("claude-code".into()),++ cwd: Some(cwd.into()),++ project_strategy: Some("repo-root".into()),++ ..Default::default()++ },++ serde_json::json!({ "sessionID": "heal-repo-root-1" }),++ );++ process(&state, env1).await.unwrap();++ let (ws, proj) =++ resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::RepoRoot)++ .await++ .unwrap();++++ state++ .writer++ .purge_project(ws, proj, "default/repo-root-project")++ .await++ .unwrap();++++ let env2 = HookEnvelope::from_query_and_body(++ HookQuery {++ event: "user-prompt".into(),++ agent: Some("claude-code".into()),++ cwd: Some(cwd.into()),++ project_strategy: Some("repo-root".into()),++ ..Default::default()++ },++ serde_json::json!({ "sessionID": "heal-repo-root-2" }),++ );++ process(&state, env2)++ .await++ .expect("repo-root cache slot must be evicted and recreated");++++ let (_, proj_new) =++ resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::RepoRoot)++ .await++ .unwrap();++ assert_ne!(proj_new, proj);++ }++/// A hook event fires end-to-end through `process`. Validates that/// the session + observation rows land in the resolved project, not/// the server-default scratch project.