Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(install): harden symlink-preserving apply
AkitaOnRails2e822644138b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 760e8080..0ecd1b5c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -39,6 +39,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0including subdirectories and linked worktrees. (#259)### Fixed+- Installer `--apply` modes now write through symlinked agent configuration+ files instead of atomically replacing the symlink itself. Symlink chains and+ dangling final targets are preserved, while backups remain next to the+ user-facing configuration path. (#264)- SessionEnd re-consolidation now converges by comparing the currentobservation count with a persisted count stamped by the latest completedend, instead of comparing independently generated wall-clock timestamps.diff --git a/crates/ai-memory-cli/src/commands/apply_shared.rs b/crates/ai-memory-cli/src/commands/apply_shared.rsindex dc7a40b1..5c4730db 100644--- a/crates/ai-memory-cli/src/commands/apply_shared.rs+++ b/crates/ai-memory-cli/src/commands/apply_shared.rs@@ -4,7 +4,8 @@//!//! Every write goes through [`apply_atomic`], which://!-//! 1. Reads the existing file (or empty string if absent).+//! 1. Resolves a symlink chain without replacing the link, then reads the+//! existing target file (or empty string if absent).//! 2. Runs the caller-supplied mutator to compute the new content.//! 3. If the new content equals the old, returns `NoOp` — never//! touches the disk on a redundant call.@@ -62,9 +63,10 @@ pub fn apply_atomic<F>(path: &Path, mutator: F) -> Result<ApplyOutcome>whereF: FnOnce(&str) -> Result<String>,{- let existed = path.exists();+ let write_target = resolve_write_target(path)?;+ let existed = write_target.exists();let original = if existed {- fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?+ fs::read_to_string(&write_target).with_context(|| format!("reading {}", path.display()))?} else {String::new()};@@ -75,7 +77,7 @@ wherereturn Ok(ApplyOutcome::NoOp);}- if let Some(parent) = path.parent()+ if let Some(parent) = write_target.parent()&& !parent.as_os_str().is_empty(){fs::create_dir_all(parent)@@ -84,11 +86,11 @@ whereif existed {let backup = backup_path_for(path);- fs::copy(path, &backup)+ fs::copy(&write_target, &backup).with_context(|| format!("backing up {} → {}", path.display(), backup.display()))?;}- write_atomic(path, &new_content)?;+ write_atomic(&write_target, &new_content)?;Ok(if existed {ApplyOutcome::Updated} else {@@ -96,6 +98,43 @@ where})}+/// Follow final-component symlinks to the path that an atomic rename should+/// replace. This also handles a dangling final target, which `canonicalize`+/// cannot resolve, without replacing the user's symlink itself.+fn resolve_write_target(path: &Path) -> Result<PathBuf> {+ const MAX_SYMLINK_DEPTH: usize = 40;++ let mut target = path.to_path_buf();+ for _ in 0..MAX_SYMLINK_DEPTH {+ match fs::symlink_metadata(&target) {+ Ok(metadata) if metadata.file_type().is_symlink() => {+ let destination = fs::read_link(&target)+ .with_context(|| format!("resolving symlink {}", target.display()))?;+ target = if destination.is_absolute() {+ destination+ } else {+ target+ .parent()+ .filter(|parent| !parent.as_os_str().is_empty())+ .unwrap_or_else(|| Path::new("."))+ .join(destination)+ };+ }+ Ok(_) => return Ok(target),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(target),+ Err(error) => {+ return Err(error)+ .with_context(|| format!("inspecting symlink {}", target.display()));+ }+ }+ }++ anyhow::bail!(+ "refusing to write through a symlink chain deeper than {MAX_SYMLINK_DEPTH}: {}",+ path.display()+ )+}+fn backup_path_for(path: &Path) -> PathBuf {let stamp = Timestamp::now().as_second();let mut bak = path.as_os_str().to_owned();@@ -104,45 +143,23 @@ fn backup_path_for(path: &Path) -> PathBuf {}/// Atomic write via the canonical [`ai_memory_wiki::write_atomic`]-/// (tempfile + fsync + rename + parent-dir fsync). Two wrinkles kept here:-///-/// - When the target is a **symlink**, write to the file it points at instead-/// of letting `rename(2)` replace the link with a regular file. Dotfiles-/// managers (stow, chezmoi, bare-git) symlink config files like-/// `~/.claude/settings.json` into a tracked repo; clobbering the link-/// silently de-syncs that repo. The staged-hooks dir is already followed-/// (see `same_canonical_dir`); this brings file writes in line with it.-/// - The tempfile MUST land in the same directory as the (resolved) target so+/// (tempfile + fsync + rename + parent-dir fsync). The one wrinkle kept+/// here: the tempfile MUST land in the same directory as the resolved target so/// `rename(2)` stays intra-filesystem — otherwise we get EXDEV/// ("Invalid cross-device link"). A bare relative path like `CLAUDE.md`/// has an *empty* parent, so treat it as `.` (current directory); a/// `$TMPDIR` fallback would sit on a different filesystem than the/// project in just about every realistic setup.fn write_atomic(path: &Path, content: &str) -> Result<()> {- let target = deref_symlink(path);- let has_parent = target.parent().is_some_and(|p| !p.as_os_str().is_empty());- let target = if has_parent {- target- } else {- Path::new(".").join(&target)+ let path = match path.parent() {+ Some(parent) if !parent.as_os_str().is_empty() => path.to_path_buf(),+ _ => Path::new(".").join(path),};- ai_memory_wiki::write_atomic(&target, content.as_bytes())- .with_context(|| format!("writing {}", target.display()))?;+ ai_memory_wiki::write_atomic(&path, content.as_bytes())+ .with_context(|| format!("writing {}", path.display()))?;Ok(())}-/// Resolve a symlinked target to the real file it points at. Non-symlinks —-/// and dangling links, which can't be canonicalized — are returned unchanged,-/// preserving the prior behavior for every non-symlink caller.-fn deref_symlink(path: &Path) -> PathBuf {- match fs::symlink_metadata(path) {- Ok(meta) if meta.file_type().is_symlink() => {- fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())- }- _ => path.to_path_buf(),- }-}-// --------------------------------------------------------------------// JSON mutation helpers// --------------------------------------------------------------------@@ -288,6 +305,50 @@ mod tests {assert_eq!(fs::read_to_string(&link).unwrap(), "new\n");}+ #[cfg(unix)]+ #[test]+ fn apply_through_dangling_relative_symlink_creates_target_and_keeps_link() {+ use std::os::unix::fs::symlink;++ let tmp = TempDir::new().unwrap();+ let target_dir = tmp.path().join("dotfiles");+ fs::create_dir(&target_dir).unwrap();+ let target = target_dir.join("settings.json");+ let link = tmp.path().join("settings.json");+ symlink("dotfiles/settings.json", &link).unwrap();++ let outcome = apply_atomic(&link, |_| Ok("new\n".into())).unwrap();++ assert_eq!(outcome, ApplyOutcome::Created);+ assert!(+ fs::symlink_metadata(&link)+ .unwrap()+ .file_type()+ .is_symlink()+ );+ assert_eq!(fs::read_to_string(&target).unwrap(), "new\n");+ }++ #[cfg(unix)]+ #[test]+ fn apply_rejects_a_symlink_loop_without_replacing_it() {+ use std::os::unix::fs::symlink;++ let tmp = TempDir::new().unwrap();+ let link = tmp.path().join("settings.json");+ symlink("settings.json", &link).unwrap();++ let error = apply_atomic(&link, |_| Ok("new\n".into())).unwrap_err();++ assert!(format!("{error:#}").contains("symlink chain deeper"));+ assert!(+ fs::symlink_metadata(&link)+ .unwrap()+ .file_type()+ .is_symlink()+ );+ }+#[test]fn json_mutator_preserves_user_keys() {let original = r#"{"unrelated":"keep me","mcpServers":{"foo":{"url":"http://foo"}}}"#;diff --git a/docs/install.md b/docs/install.mdindex 8cc4c812..7d34a530 100644--- a/docs/install.md+++ b/docs/install.md@@ -141,6 +141,11 @@ without env vars or flags, hooks reuse the existing ai-memory MCP entry forthat agent when possible. This keeps remote MCP config and lifecycle capturepointed at the same server instead of falling back to loopback.+All installer `--apply` modes preserve symlinked configuration files: the+atomic update is written to the symlink target, including a missing final+target, while the timestamped backup stays next to the user-facing config+path. This keeps stow, chezmoi, and similar dotfile-managed installs linked.+`init`, `serve`, and `generate-auth-token` do not need these env vars becausethey either create local files or start the server itself.