Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(upgrade): keep refreshed hooks pointing at the replaced binary path
Marcos Santini51fbd692b75b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 27a8355f..b1c64caa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0provider. (#1026)### Fixed+- `ai-memory upgrade` no longer corrupts every hook command with the kernel's+ ` (deleted)` path suffix. The upgrade replaced its own binary and then+ re-rendered the staged hook configs from the same, now exe-deleted process:+ on Linux `/proc/<pid>/exe` came back as `<path> (deleted)` and that string+ was embedded verbatim, so every hook failed with `not found` until the+ suffix was stripped from the settings file by hand. The refresh now re-runs+ `install-hooks --apply` from the freshly installed binary in a child+ process, and hook rendering strips the kernel marker — falling back to the+ bare `ai-memory` command name when the resolved path is missing — instead of+ embedding a dead absolute path. (#1027)- `ai-memory doctor` now warns when the nearest `.ai-memory.toml`'s`[capture]` section is invalid. This fails closed today — every file andshell tool event is reduced to metadata until the marker is fixed, nothingdiff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 9503b32c..35056f16 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -33,7 +33,8 @@ use crate::commands::render_shared::{build_kiro_cli_v2_hooks_value, build_kiro_cli_v3_hooks_value,build_pool_settings_yaml_with_data_dir, build_profile_payload_for_agent,hook_script_for_claude_code, hook_script_for_current_platform, kimi_code_hook_commands,- local_hook_policy_v1_supported, ts_capture_policy_v1, ts_string_literal, ts_timeout_signal,+ local_hook_policy_v1_supported, strip_deleted_suffix, ts_capture_policy_v1, ts_string_literal,+ ts_timeout_signal,};use crate::commands::uninstall::hook_command_is_ours;use crate::config::{Config, DEFAULT_SERVER_URL};@@ -3244,8 +3245,12 @@ fn build_opencode2_plugin(// path as invoked, like every other native hook config: a canonicalized// one pins the target behind a versioned symlink or junction.let native_hook = if capture_assistant {- let exe =- std::env::current_exe().context("cannot locate ai-memory native hook executable")?;+ // Strip the kernel's ` (deleted)` readlink marker before baking: a+ // re-apply from a process whose binary was just replaced under it must+ // not bake the artifact into the generated module.+ let exe = strip_deleted_suffix(+ std::env::current_exe().context("cannot locate ai-memory native hook executable")?,+ );ts_string_literal(&strip_windows_verbatim_prefix(&exe.to_string_lossy()))} else {"undefined".to_string()diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 81fe726e..3d0e549e 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -19,7 +19,7 @@//! lives here is only the *data* both consume.use std::borrow::Cow;-use std::path::Path;+use std::path::{Path, PathBuf};use base64::Engine as _;use serde_json::{Value, json};@@ -483,9 +483,7 @@ pub(crate) fn build_zero_hooks_config(data_dir: Option<&Path>,project_strategy: Option<&str>,) -> serde_json::Value {- let exe = std::env::current_exe()- .map(|p| p.to_string_lossy().into_owned())- .unwrap_or_else(|_| "ai-memory".to_string());+ let exe = hook_embedded_exe_path().to_string_lossy().into_owned();let hooks: Vec<serde_json::Value> = ZERO_EVENTS.iter().map(|(zero_event, our_event)| {@@ -571,9 +569,7 @@ pub(crate) fn build_zcode_hooks_config(data_dir: Option<&Path>,project_strategy: Option<&str>,) -> serde_json::Value {- let exe = std::env::current_exe()- .map(|p| p.to_string_lossy().into_owned())- .unwrap_or_else(|_| "ai-memory".to_string());+ let exe = hook_embedded_exe_path().to_string_lossy().into_owned();let mut events = serde_json::Map::new();for (zcode_event, our_event) in ZCODE_EVENTS {let mut args: Vec<String> = Vec::new();@@ -1582,6 +1578,53 @@ pub(crate) fn local_hook_policy_v1_supported() -> bool {)}+/// Fallback when no usable executable path can be embedded: the bare command+/// name, resolved through `PATH` when each hook runs. Every embed site already+/// fell back to this spelling when `current_exe()` errored.+const FALLBACK_HOOK_EXE: &str = "ai-memory";++/// Strip the ` (deleted)` marker the Linux kernel appends to the+/// `/proc/<pid>/exe` readlink once the executable's inode has been unlinked or+/// replaced (Rust std passes the marker through verbatim —+/// rust-lang/rust#40284). It is a read artifact, never part of a real file+/// name.+pub(crate) fn strip_deleted_suffix(exe: PathBuf) -> PathBuf {+ match exe.to_str() {+ Some(text) => text+ .strip_suffix(" (deleted)")+ .map(PathBuf::from)+ .unwrap_or(exe),+ None => exe,+ }+}++/// The executable path to embed in a rendered hook command, given what+/// `current_exe()` produced.+///+/// The classic corrupting sequence is `ai-memory upgrade`: it replaces its own+/// binary and then re-renders the staged hook configs from the same, now+/// exe-deleted process, so `current_exe()` comes back as `<path> (deleted)`.+/// Stripping the marker yields the path that now holds the freshly installed+/// binary. A missing file or a failed resolution falls back to+/// [`FALLBACK_HOOK_EXE`] instead of baking a dead absolute path into every+/// hook command.+fn embedded_exe_from(raw: Option<PathBuf>) -> PathBuf {+ let Some(exe) = raw else {+ return PathBuf::from(FALLBACK_HOOK_EXE);+ };+ let stripped = strip_deleted_suffix(exe);+ if stripped.is_file() {+ stripped+ } else {+ PathBuf::from(FALLBACK_HOOK_EXE)+ }+}++/// [`embedded_exe_from`] over this process's own executable.+pub(crate) fn hook_embedded_exe_path() -> PathBuf {+ embedded_exe_from(std::env::current_exe().ok())+}+fn hook_command(script: &Path,server_url: &str,@@ -2210,6 +2253,52 @@ mod tests {#[cfg(windows)]use std::process::Stdio;+ #[test]+ fn strip_deleted_suffix_removes_only_the_trailing_kernel_marker() {+ assert_eq!(+ strip_deleted_suffix(PathBuf::from("/opt/ai-memory/bin/ai-memory (deleted)")),+ PathBuf::from("/opt/ai-memory/bin/ai-memory")+ );+ // A marker mid-path is a legitimate directory name, not the kernel's+ // artifact; only the trailing suffix reads as one.+ let mid = PathBuf::from("/opt/dir (deleted)/ai-memory");+ assert_eq!(strip_deleted_suffix(mid.clone()), mid);+ let clean = PathBuf::from("/opt/ai-memory/bin/ai-memory");+ assert_eq!(strip_deleted_suffix(clean.clone()), clean);+ }++ #[test]+ fn embedded_exe_strips_the_marker_when_the_stripped_path_exists() {+ // The exact corruption window of `ai-memory upgrade`: the process is+ // still executing the old inode after the rename-over replace, so+ // `current_exe()` carries the marker while the stripped path already+ // holds the freshly installed binary.+ let dir = tempfile::tempdir().expect("tempdir");+ let exe = dir.path().join("ai-memory");+ fs::write(&exe, b"binary").expect("write exe");+ let deleted = PathBuf::from(format!("{} (deleted)", exe.display()));+ assert_eq!(embedded_exe_from(Some(deleted)), exe);+ }++ #[test]+ fn embedded_exe_falls_back_when_the_resolved_path_is_missing() {+ // A failed resolution or a dead path must not bake a broken absolute+ // path into hook commands; the bare name resolves through PATH when+ // each hook runs.+ assert_eq!(embedded_exe_from(None), PathBuf::from("ai-memory"));+ assert_eq!(+ embedded_exe_from(Some(PathBuf::from("/nonexistent/ai-memory (deleted)"))),+ PathBuf::from("ai-memory")+ );+ }++ #[test]+ fn hook_embedded_exe_path_names_an_existing_file_without_marker() {+ let exe = hook_embedded_exe_path();+ assert!(exe.is_file(), "{} should exist", exe.display());+ assert!(!exe.to_string_lossy().ends_with(" (deleted)"));+ }+fn decode_powershell_encoded_command(command: &str) -> String {let (_, encoded) = command.split_once(" -EncodedCommand ")diff --git a/crates/ai-memory-cli/src/commands/upgrade.rs b/crates/ai-memory-cli/src/commands/upgrade.rsindex 191e413c..18ded704 100644--- a/crates/ai-memory-cli/src/commands/upgrade.rs+++ b/crates/ai-memory-cli/src/commands/upgrade.rs@@ -37,7 +37,7 @@ use flate2::read::GzDecoder;use sha2::{Digest, Sha256};use tracing::info;-use crate::cli::{AgentChoice, InstallHooksArgs, UpgradeArgs};+use crate::cli::{AgentChoice, UpgradeArgs};use crate::commands::install_hooks;use crate::config::Config;use crate::install_layout::{HOOKS_DIR_NAME, shipped_binary_name};@@ -72,7 +72,7 @@ pub async fn run(config: &Config, args: UpgradeArgs) -> Result<()> {apply_extracted_release(extract_root.path(), &exe)?;// Sync FS after await is intentional for this CLI one-shot path.- refresh_staged_hooks(config)?;+ refresh_staged_hooks(config, &exe)?;warn_remote_server(config);println!("✓ upgraded to {tag}");info!(%tag, path = %exe.display(), "native upgrade complete");@@ -701,7 +701,17 @@ fn list_staged_agents(hooks_root: &Path) -> Result<(StagedAgentList, Vec<String>Ok((agents, unknown))}-fn refresh_staged_hooks(config: &Config) -> Result<()> {+/// Re-run `install-hooks --apply` for every staged agent — through the freshly+/// installed binary, as child processes.+///+/// This must not render hook configs from THIS process: it has just replaced+/// its own executable on disk, so a `current_exe()` here resolves against the+/// unlinked old inode. On Linux the kernel then reports `/proc/<pid>/exe` as+/// `<path> (deleted)`, and that string used to be embedded verbatim into every+/// hook command, breaking them all with `not found` until the suffix was+/// stripped by hand. A child process started from the new binary resolves its+/// own valid exe instead.+fn refresh_staged_hooks(config: &Config, exe: &Path) -> Result<()> {let hooks_root = staged_hooks_root(config);if !hooks_root.is_dir() {println!("→ no staged hook scripts found at {}", hooks_root.display());@@ -716,7 +726,7 @@ fn refresh_staged_hooks(config: &Config) -> Result<()> {);return Ok(());}- refresh_agent_list(config, &agents);+ refresh_agent_list(exe, &agents);Ok(())}@@ -736,39 +746,37 @@ fn collect_refreshable_agents(hooks_root: &Path) -> Result<StagedAgentList> {Ok(agents)}-fn refresh_agent_list(config: &Config, agents: &StagedAgentList) {+fn refresh_agent_list(exe: &Path, agents: &StagedAgentList) {let names: Vec<_> = agents.iter().map(|(n, _)| n.as_str()).collect();println!("→ refreshing staged hook scripts for: {}", names.join(" "));- for (name, agent) in agents {- apply_staged_agent_hooks(config, name, *agent);+ for (name, _) in agents {+ apply_staged_agent_hooks(exe, name);}}-fn apply_staged_agent_hooks(config: &Config, name: &str, agent: AgentChoice) {+fn apply_staged_agent_hooks(exe: &Path, name: &str) {println!(" ai-memory install-hooks --agent {name} --apply");- if let Err(err) = install_hooks::run(config, apply_hooks_args(agent)) {- println!(- " (skipped — {err:#}; re-run with the same --server-url / --auth-token used originally)"- );+ let mut command = refresh_agent_command(exe, name);+ match command.status() {+ Ok(status) if status.success() => {}+ Ok(status) => println!(+ " (skipped — install-hooks exited with {status}; re-run with the same \+ --server-url / --auth-token used originally)"+ ),+ Err(error) => println!(+ " (skipped — {error}; re-run with the same --server-url / --auth-token used \+ originally)"+ ),}}-fn apply_hooks_args(agent: AgentChoice) -> InstallHooksArgs {- InstallHooksArgs {- agent,- hooks_dir: None,- server_url: None,- auth_token: None,- as_user: None,- apply: true,- config_file: None,- project_strategy: None,- capture_assistant: false,- capture_mode: None,- no_capture_prompts: false,- capture_prompts: false,- profile: None,- }+/// Refresh through the installed binary's own path, never a bare name: `PATH`+/// may hold an older copy (or nothing), while the just-installed release lives+/// at `exe`.+fn refresh_agent_command(exe: &Path, agent_name: &str) -> std::process::Command {+ let mut command = std::process::Command::new(exe);+ command.args(["install-hooks", "--agent", agent_name, "--apply"]);+ command}fn warn_remote_server(config: &Config) {@@ -917,6 +925,28 @@ mod tests {use zip::ZipWriter;use zip::write::SimpleFileOptions;+ #[test]+ fn refresh_command_targets_the_installed_binary_with_apply() {+ // The refresh must go through the just-installed binary's own path —+ // a bare name could resolve to an older copy on PATH — and must ask+ // for a full --apply so the staged hook configs are re-rendered.+ let command = refresh_agent_command(Path::new("/opt/ai-memory/ai-memory"), "claude-code");+ assert_eq!(+ command.get_program(),+ std::ffi::OsStr::new("/opt/ai-memory/ai-memory")+ );+ let args: Vec<_> = command.get_args().collect();+ assert_eq!(+ args,+ vec![+ std::ffi::OsStr::new("install-hooks"),+ std::ffi::OsStr::new("--agent"),+ std::ffi::OsStr::new("claude-code"),+ std::ffi::OsStr::new("--apply"),+ ]+ );+ }+#[test]fn release_asset_name_for_covers_unix_and_windows_matrix() {// Table-driven so Linux CI still guards macos-* and windows mapping.