Skip to content

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

Rust

fix(install-hooks): follow Claude Code's project-file location and keep backups out of the checkout

AkitaOnRails31686ec7e38e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c6827ec6..906edce0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,12 +10,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Added `install-hooks --agent claude-code --scope project`, which writes the
hook configuration to the checkout's gitignored `.claude/settings.local.json`
- (at the git root, where Claude Code reads it) instead of the user-level
- `settings.json`, so capture is opted in per repository. The installer warns
- when that file is not ignored by git and refuses the inline-token fallback
- for it; `uninstall` run inside the checkout sweeps it; `upgrade` and the
+ (where Claude Code reads it: the git root, or the launch directory on
+ Windows and when the repository root is the home directory) instead of the
+ user-level `settings.json`, so capture is opted in per repository. The
+ installer warns when that file is not ignored by git, refuses the
+ inline-token fallback for it, notes when the other scope also carries
+ ai-memory hooks, and keeps its backups under the data dir instead of the
+ checkout; `uninstall` run inside the checkout sweeps it and reminds you to
+ do the same in other project-scoped checkouts; `upgrade` and the
`ai-memory run` auto-wire no longer add user-level Claude Code hooks on top
- of a project-scoped install. (#NNN)
+ of a project-scoped install. (#1034)
- Added explicit MCP behavior annotations (title, read-only, destructive,
idempotent, and open-world hints) to all 23 tools. Reordered the MCP server
instructions so scope selection, untrusted-memory handling, deliberate
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 370e949d..076677aa 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -2917,9 +2917,11 @@ pub struct InstallHooksArgs {
#[arg(long)]
pub config_file: Option<PathBuf>,
/// Where to write the hook configuration. `project` targets the
- /// repository's `.claude/settings.local.json` (at the git root, else the
- /// current directory) so capture is opted in per checkout instead of for
- /// every session; Claude Code reads it alongside the user-level hooks.
+ /// repository's `.claude/settings.local.json` (at the git root; in the
+ /// current directory outside a repository, on Windows, or when the
+ /// repository root is the home directory) so capture is opted in per
+ /// checkout instead of for every session; Claude Code reads it alongside
+ /// the user-level hooks.
/// Claude Code only; ignores `CLAUDE_CONFIG_DIR`. Cannot be combined
/// with `--config-file`, which names the target file directly.
#[arg(
diff --git a/crates/ai-memory-cli/src/commands/apply_shared.rs b/crates/ai-memory-cli/src/commands/apply_shared.rs
index 5c4730db..b42afe32 100644
--- a/crates/ai-memory-cli/src/commands/apply_shared.rs
+++ b/crates/ai-memory-cli/src/commands/apply_shared.rs
@@ -10,7 +10,8 @@
//! 3. If the new content equals the old, returns `NoOp` — never
//! touches the disk on a redundant call.
//! 4. Otherwise copies the existing file to `<path>.bak-<unix-ts>`
-//! so the user has a recovery path.
+//! so the user has a recovery path ([`apply_atomic_with_backup`] can
+//! put it in a private directory instead).
//! 5. Writes the new content via the canonical
//! [`ai_memory_wiki::write_atomic`] (sibling tempfile + fsync +
//! rename + parent-dir fsync).
@@ -60,6 +61,34 @@ impl ApplyOutcome {
/// # Errors
/// Propagates IO + mutator failures.
pub fn apply_atomic<F>(path: &Path, mutator: F) -> Result<ApplyOutcome>
+where
+ F: FnOnce(&str) -> Result<String>,
+{
+ apply_atomic_with_backup(path, None, mutator)
+}
+
+/// A backup kept away from the file it protects: `<dir>/<stem>-<unix-ts>`
+/// plus the target's extension, owner-only on Unix. For a target inside a
+/// checkout, where a sibling `.bak-<ts>` would show up untracked and could be
+/// committed with whatever the file held.
+#[derive(Debug, Clone)]
+pub struct PrivateBackup {
+ /// Directory the backup is written to; created owner-only when missing.
+ pub dir: PathBuf,
+ /// File-name prefix that tells this target's backups apart in `dir`.
+ pub stem: String,
+}
+
+/// [`apply_atomic`], writing the backup to `private_backup` instead of next
+/// to `path` when one is given.
+///
+/// # Errors
+/// Propagates IO + mutator failures.
+pub fn apply_atomic_with_backup<F>(
+ path: &Path,
+ private_backup: Option<&PrivateBackup>,
+ mutator: F,
+) -> Result<ApplyOutcome>
where
F: FnOnce(&str) -> Result<String>,
{
@@ -85,9 +114,15 @@ where
}
if existed {
- let backup = backup_path_for(path);
- fs::copy(&write_target, &backup)
- .with_context(|| format!("backing up {} → {}", path.display(), backup.display()))?;
+ match private_backup {
+ None => {
+ let backup = backup_path_for(path);
+ fs::copy(&write_target, &backup).with_context(|| {
+ format!("backing up {} → {}", path.display(), backup.display())
+ })?;
+ }
+ Some(private) => write_private_backup(path, private, &original)?,
+ }
}
write_atomic(&write_target, &new_content)?;
@@ -142,6 +177,29 @@ fn backup_path_for(path: &Path) -> PathBuf {
PathBuf::from(bak)
}
+fn write_private_backup(path: &Path, private: &PrivateBackup, original: &str) -> Result<()> {
+ let mut name = format!("{}-{}", private.stem, Timestamp::now().as_second());
+ if let Some(extension) = path.extension() {
+ name.push('.');
+ name.push_str(&extension.to_string_lossy());
+ }
+ let backup = private.dir.join(name);
+ let context = || format!("backing up {} → {}", path.display(), backup.display());
+ crate::commands::path_util::create_private_dir(&private.dir).with_context(context)?;
+ // Owner-only from creation: the content can carry machine-specific hook
+ // commands, and on Unix the mode is set before any byte is written.
+ let mut options = fs::OpenOptions::new();
+ options.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt as _;
+ options.mode(0o600);
+ }
+ let mut file = options.open(&backup).with_context(context)?;
+ std::io::Write::write_all(&mut file, original.as_bytes()).with_context(context)?;
+ Ok(())
+}
+
/// Atomic write via the canonical [`ai_memory_wiki::write_atomic`]
/// (tempfile + fsync + rename + parent-dir fsync). The one wrinkle kept
/// here: the tempfile MUST land in the same directory as the resolved target so
@@ -242,6 +300,56 @@ mod tests {
assert_eq!(fs::read_to_string(&p).unwrap(), "hello\n");
}
+ /// A private backup lands in its own directory, owner-only, and leaves
+ /// nothing next to the target; the default still backs up beside it.
+ #[test]
+ fn private_backup_lands_outside_the_target_directory() {
+ let tmp = TempDir::new().unwrap();
+ let checkout = tmp.path().join("checkout");
+ fs::create_dir_all(&checkout).unwrap();
+ let target = checkout.join("settings.local.json");
+ fs::write(&target, "old\n").unwrap();
+ let backups = tmp.path().join("data").join("backups");
+ let private = PrivateBackup {
+ dir: backups.clone(),
+ stem: "checkout-id".to_string(),
+ };
+
+ let outcome =
+ apply_atomic_with_backup(&target, Some(&private), |_| Ok("new\n".into())).unwrap();
+ assert_eq!(outcome, ApplyOutcome::Updated);
+ assert_eq!(fs::read_to_string(&target).unwrap(), "new\n");
+ let siblings: Vec<_> = fs::read_dir(&checkout)
+ .unwrap()
+ .flatten()
+ .map(|entry| entry.file_name())
+ .collect();
+ assert_eq!(siblings, ["settings.local.json"], "no backup beside it");
+ let saved: Vec<_> = fs::read_dir(&backups).unwrap().flatten().collect();
+ assert_eq!(saved.len(), 1);
+ let name = saved[0].file_name().to_string_lossy().into_owned();
+ assert!(
+ name.starts_with("checkout-id-") && name.ends_with(".json"),
+ "{name}"
+ );
+ assert_eq!(fs::read_to_string(saved[0].path()).unwrap(), "old\n");
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt as _;
+ let mode = saved[0].metadata().unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode, 0o600);
+ }
+
+ // Control: without a private backup the copy sits next to the target.
+ apply_atomic(&target, |_| Ok("newer\n".into())).unwrap();
+ assert!(
+ fs::read_dir(&checkout)
+ .unwrap()
+ .flatten()
+ .any(|entry| entry.file_name().to_string_lossy().contains(".bak-"))
+ );
+ }
+
#[test]
fn apply_to_unchanged_file_is_noop_and_no_backup() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 576ffbbe..a5d7371e 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -23,7 +23,9 @@ use anyhow::{Context, Result};
use crate::cli::{
AgentChoice, CaptureModeArg, HookInstallScope, InstallHooksArgs, McpClient, ProjectStrategyArg,
};
-use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json, mutate_toml};
+use crate::commands::apply_shared::{
+ ApplyOutcome, PrivateBackup, apply_atomic, apply_atomic_with_backup, mutate_json, mutate_toml,
+};
use crate::commands::install_mcp;
use crate::commands::openclaw_plugin;
use crate::commands::path_util::{home_dir, strip_windows_verbatim_prefix};
@@ -83,19 +85,80 @@ pub(crate) fn claude_settings_target(args: &InstallHooksArgs) -> Result<PathBuf>
}
}
-/// `<repo root>/.claude/settings.local.json` for the checkout containing
-/// `cwd`, else `<cwd>/.claude/settings.local.json`. This mirrors where Claude
-/// Code reads that file (code.claude.com/docs/en/settings, "Where Claude Code
-/// looks for each file"): the git repository root even when launched in a
-/// subdirectory, the *main* checkout's root from a linked worktree, and the
-/// launch directory outside a repository or on Windows — so Windows users
-/// launch from the root. `CLAUDE_CONFIG_DIR` relocates only the user-level
-/// files, so it plays no part here.
+/// The `.claude/settings.local.json` Claude Code reads for a session launched
+/// in `cwd` (code.claude.com/docs/en/settings, "Where Claude Code looks for
+/// each file"): at the git repository root even when launched in a
+/// subdirectory (the *main* checkout's root from a linked worktree), but in
+/// the launch directory itself outside a repository, on Windows, and when the
+/// repository root is the home directory. `CLAUDE_CONFIG_DIR` relocates only
+/// the user-level files, so it plays no part here.
pub(crate) fn project_claude_settings_local(cwd: &Path) -> PathBuf {
- ai_memory_consolidate::discover_main_repo_root(cwd)
- .unwrap_or_else(|_| cwd.to_path_buf())
- .join(".claude")
- .join("settings.local.json")
+ project_claude_settings_local_for(cwd, cfg!(windows), home_dir().as_deref())
+}
+
+/// [`project_claude_settings_local`] with the platform and home directory
+/// injected, so the Windows and home-repository rules are testable anywhere.
+fn project_claude_settings_local_for(cwd: &Path, is_windows: bool, home: Option<&Path>) -> PathBuf {
+ let base = if is_windows {
+ cwd.to_path_buf()
+ } else {
+ match ai_memory_consolidate::discover_main_repo_root(cwd) {
+ Ok(root) if !home.is_some_and(|home| same_directory(&root, home)) => root,
+ _ => cwd.to_path_buf(),
+ }
+ };
+ base.join(".claude").join("settings.local.json")
+}
+
+/// Whether two paths name the same directory. libgit2 reports the repository
+/// root resolved while the home path may not be (`/var` vs `/private/var` on
+/// macOS), so a lexical mismatch falls back to comparing resolved paths; the
+/// result only picks a directory and is never stored.
+fn same_directory(a: &Path, b: &Path) -> bool {
+ a == b
+ || matches!(
+ (fs::canonicalize(a), fs::canonicalize(b)),
+ (Ok(a), Ok(b)) if a == b
+ )
+}
+
+/// Where an update to a project `.claude/settings.local.json` keeps the prior
+/// file: under the data dir, never in the checkout. Claude Code's ignore rule
+/// covers only that file name, so a sibling `.bak-<ts>` would show up in
+/// `git status` carrying the full hook commands.
+pub(crate) fn project_settings_backup(data_dir: &Path, settings: &Path) -> PrivateBackup {
+ PrivateBackup {
+ dir: data_dir.join("backups").join("claude-settings-local"),
+ stem: project_settings_backup_stem(settings),
+ }
+}
+
+/// A file-name stem naming the checkout `settings` sits in: its directory
+/// flattened to safe characters and bounded to the tail (the repository name
+/// end), plus a short hash of the full path so checkouts that flatten alike
+/// stay apart.
+fn project_settings_backup_stem(settings: &Path) -> String {
+ use sha2::{Digest as _, Sha256};
+ let checkout = settings
+ .parent()
+ .and_then(Path::parent)
+ .unwrap_or(settings)
+ .to_string_lossy();
+ let mut flat = String::with_capacity(checkout.len());
+ for c in checkout.chars() {
+ let c = if c.is_ascii_alphanumeric() || matches!(c, '.' | '_') {
+ c
+ } else {
+ '-'
+ };
+ if !(c == '-' && flat.ends_with('-')) {
+ flat.push(c);
+ }
+ }
+ let flat = flat.trim_matches('-');
+ let tail = &flat[flat.len().saturating_sub(64)..];
+ let digest = format!("{:x}", Sha256::digest(checkout.as_bytes()));
+ format!("{}-{}", tail.trim_start_matches('-'), &digest[..12])
}
/// The `hooks` table of a Claude-shaped settings document (`hooks` → event →
@@ -140,9 +203,12 @@ pub(crate) fn settings_file_carries_ai_memory_hooks(path: &Path) -> bool {
/// Re-copy the Claude Code hook scripts into the stable staging dir the
/// installed hook commands point at, without touching any settings file.
-/// `upgrade` uses it when the only Claude Code install is `--scope project`:
-/// the project files keep pointing at this dir, so refreshing it is what
-/// keeps them current.
+/// `upgrade` uses it when the only Claude Code install is `--scope project`,
+/// so a platform whose hook commands run these scripts gets the new ones.
+/// Native-hook commands call the absolute `ai-memory` binary instead, which
+/// the upgrade replaces in place. Either way the project files themselves are
+/// not rewritten: a change to the hook commands reaches a checkout only when
+/// `install-hooks --scope project --apply` is re-run there.
pub(crate) fn restage_claude_code_scripts(
data_dir: &Path,
hooks_dir: Option<&Path>,
@@ -1845,7 +1911,7 @@ fn apply_to_claude_code_settings_in(
),
capture_prompts,
);
- apply_to_claude_code_settings_with_payload(payload, args, capture_prompts)
+ apply_to_claude_code_settings_with_payload(payload, args, data_dir, capture_prompts)
}
fn apply_to_claude_code_settings_with_staged(
@@ -1868,12 +1934,13 @@ fn apply_to_claude_code_settings_with_staged(
),
capture_prompts,
);
- apply_to_claude_code_settings_with_payload(payload, args, capture_prompts)
+ apply_to_claude_code_settings_with_payload(payload, args, data_dir, capture_prompts)
}
fn apply_to_claude_code_settings_with_payload(
payload: serde_json::Value,
args: &InstallHooksArgs,
+ data_dir: &Path,
capture_prompts: bool,
) -> Result<()> {
let path = claude_settings_target(args)?;
@@ -1882,7 +1949,9 @@ fn apply_to_claude_code_settings_with_payload(
.and_then(|v| v.as_object())
.context("internal: build_claude_code_payload didn't return a hooks object")?
.clone();
- let outcome = apply_atomic(&path, |existing| {
+ let private_backup =
+ (args.scope == HookInstallScope::Project).then(|| project_settings_backup(data_dir, &path));
+ let outcome = apply_atomic_with_backup(&path, private_backup.as_ref(), |existing| {
mutate_json(existing, |root| {
// Get-or-create the top-level `hooks` table, then merge our
// event keys in via `overlay_event_hooks`: our entries replace
@@ -1903,16 +1972,38 @@ fn apply_to_claude_code_settings_with_payload(
Ok(())
})
})?;
+ let backup_note = match &private_backup {
+ Some(backup) => format!("backup written under {}", backup.dir.display()),
+ None => "backup written next to it".to_string(),
+ };
println!(
"✓ {} {} ({})",
outcome.verb(),
path.display(),
match outcome {
ApplyOutcome::Created => "new file",
- ApplyOutcome::Updated => "backup written next to it",
+ ApplyOutcome::Updated => &backup_note,
ApplyOutcome::NoOp => "already up to date",
}
);
+ // Claude Code runs the hooks of both scopes. Identical handlers dedupe, but
+ // installs that differ (capture flags, project strategy) capture twice.
+ if args.config_file.is_none()
+ && let Some(other) = match args.scope {
+ HookInstallScope::Project => claude_settings_path().ok(),
+ HookInstallScope::Global => std::env::current_dir()
+ .ok()
+ .map(|cwd| project_claude_settings_local(&cwd)),
+ }
+ && other != path
+ && settings_file_carries_ai_memory_hooks(&other)
+ {
+ eprintln!(
+ "[ai-memory] note: {} also carries ai-memory hooks; Claude Code runs both, so keep \
+ one scope or install both with the same flags.",
+ other.display()
+ );
+ }
// Claude Code adds `**/.claude/settings.local.json` to the global git
// excludes only when it creates the file itself; a file ai-memory created
// has no such guarantee, and its hook commands carry machine-specific
@@ -1921,7 +2012,7 @@ fn apply_to_claude_code_settings_with_payload(
&& ai_memory_consolidate::path_is_git_ignored(&path) == Some(false)
{
eprintln!(
- "[ai-memory] warning: {} is not ignored by git. Add `.claude/settings.local.json` \
+ "[ai-memory] warning: {} is not ignored by git. Add `**/.claude/settings.local.json` \
to this repository's .gitignore (or your global excludes) so the machine-specific \
hook commands are never committed.",
path.display()
@@ -8662,9 +8753,10 @@ model = "gpt-5"
/// `--scope project` lands where Claude Code reads the file: the git root
/// of the checkout, even from a subdirectory. A plain directory is its own
- /// root.
+ /// root. On Windows, and when the repository root is the home directory,
+ /// Claude Code reads the launch directory instead.
#[test]
- fn project_claude_settings_local_resolves_to_the_repo_root_or_cwd() {
+ fn project_claude_settings_local_resolves_where_claude_code_reads_it() {
let tmp = TempDir::new().unwrap();
let repo = tmp.path().join("repo");
let sub = repo.join("crates").join("x");
@@ -8675,20 +8767,92 @@ model = "gpt-5"
.status()
.unwrap();
assert!(status.success(), "git init failed");
-
- let from_sub = project_claude_settings_local(&sub);
- assert!(from_sub.ends_with(Path::new(".claude").join("settings.local.json")));
+ let local = |dir: &Path| dir.join(".claude").join("settings.local.json");
+ let unrelated_home = tmp.path().join("home");
+ std::fs::create_dir_all(&unrelated_home).unwrap();
// libgit2 reports the real path; compare canonicalised so a
// /private/var vs /var prefix on macOS does not trip the assertion.
- let root = from_sub.parent().and_then(Path::parent).unwrap();
- assert_eq!(root.canonicalize().unwrap(), repo.canonicalize().unwrap());
+ let root_of = |file: PathBuf| {
+ assert!(file.ends_with(Path::new(".claude").join("settings.local.json")));
+ file.parent()
+ .and_then(Path::parent)
+ .unwrap()
+ .canonicalize()
+ .unwrap()
+ };
+ let repo_root = repo.canonicalize().unwrap();
+
+ assert_eq!(
+ root_of(project_claude_settings_local_for(
+ &sub,
+ false,
+ Some(&unrelated_home)
+ )),
+ repo_root
+ );
+ assert_eq!(
+ root_of(project_claude_settings_local_for(&sub, false, None)),
+ repo_root,
+ "an unknown home does not change the git-root rule"
+ );
+ assert_eq!(
+ project_claude_settings_local_for(&sub, true, Some(&unrelated_home)),
+ local(&sub),
+ "Windows reads the launch directory, not the git root"
+ );
+ assert_eq!(
+ project_claude_settings_local_for(&sub, false, Some(&repo)),
+ local(&sub),
+ "a repository rooted at home reads the launch directory"
+ );
let plain = tmp.path().join("plain");
std::fs::create_dir_all(&plain).unwrap();
+ for is_windows in [false, true] {
+ assert_eq!(
+ project_claude_settings_local_for(&plain, is_windows, Some(&unrelated_home)),
+ local(&plain)
+ );
+ }
+ }
+
+ /// A project settings backup lands under the data dir with a stem that
+ /// names the checkout, is a single safe file-name component, and keeps
+ /// checkouts that flatten to the same text apart.
+ #[test]
+ fn project_settings_backup_stays_under_the_data_dir_per_checkout() {
+ let data = Path::new("/data");
+ let settings = |checkout: &str| {
+ Path::new(checkout)
+ .join(".claude")
+ .join("settings.local.json")
+ };
+ let backup = project_settings_backup(data, &settings("/home/u/work/my repo"));
assert_eq!(
- project_claude_settings_local(&plain),
- plain.join(".claude").join("settings.local.json")
+ backup.dir,
+ data.join("backups").join("claude-settings-local")
+ );
+ assert!(
+ backup.stem.starts_with("home-u-work-my-repo-"),
+ "{}",
+ backup.stem
+ );
+ assert!(
+ backup
+ .stem
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_')),
+ "{}",
+ backup.stem
+ );
+ assert_ne!(
+ project_settings_backup(data, &settings("/a/b-c")).stem,
+ project_settings_backup(data, &settings("/a-b/c")).stem
);
+ let deep = format!("/{}/repo", "x".repeat(300));
+ let stem = project_settings_backup(data, &settings(&deep)).stem;
+ assert!(stem.len() <= 64 + 13, "{stem}");
+ assert!(stem.contains("repo-"), "the repository end is kept: {stem}");
}
/// `upgrade` and the `run` auto-wire use this to tell a `--scope project`
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index 8b518b90..9957418e 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -8,9 +8,9 @@
use crate::cli::McpClient;
use crate::cli::UninstallArgs;
-use crate::commands::apply_shared::apply_atomic;
use crate::commands::apply_shared::mutate_json;
use crate::commands::apply_shared::mutate_toml;
+use crate::commands::apply_shared::{PrivateBackup, apply_atomic_with_backup};
use crate::commands::path_util::{
agent_config_home, claude_config_dir, claude_config_paths, home_dir,
};
@@ -583,7 +583,12 @@ fn print_plan(plan: &[PlannedChange]) {
/// Re-run the planned strippers inside `apply_atomic` so the actual write is
/// atomic + backed up. Planning records exact operations per file, so shared
/// files such as `~/.gemini/settings.json` only apply the selected concerns.
-fn apply_change(change: &PlannedChange, name: Option<&str>, url: &str) -> anyhow::Result<()> {
+fn apply_change(
+ change: &PlannedChange,
+ private_backup: Option<&PrivateBackup>,
+ name: Option<&str>,
+ url: &str,
+) -> anyhow::Result<()> {
match change {
PlannedChange::DeleteFile { path, kind } => {
if !path.exists() {
@@ -604,7 +609,7 @@ fn apply_change(change: &PlannedChange, name: Option<&str>, url: &str) -> anyhow
}
}
PlannedChange::Rewrite { path, ops, .. } => {
- let outcome = apply_atomic(path, |existing| {
+ let outcome = apply_atomic_with_backup(path, private_backup, |existing| {
let mut out = existing.to_string();
for op in ops {
out = match *op {
@@ -677,6 +682,15 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {
let plan = build_plan(&args, &config.data_dir)?;
print_plan(&plan);
+ let hooks_removed = args.only.is_none() || args.only == Some(crate::cli::UninstallOnly::Hooks);
+ if hooks_removed {
+ // Only the current checkout's project file is reachable from here.
+ println!(
+ "note: run `ai-memory uninstall --only hooks --apply` inside every other checkout that \
+ used `install-hooks --scope project`; their .claude/settings.local.json keeps calling \
+ this binary and data dir."
+ );
+ }
if args.purge_data {
for path in data_purge::purge_preview(&config.data_dir) {
println!("would purge {}", path.display());
@@ -713,8 +727,20 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {
}
}
+ // The current checkout's `.claude/settings.local.json` keeps its backup
+ // under the data dir, as `install-hooks --scope project` does: a sibling
+ // `.bak-<ts>` would sit untracked in the repository.
+ let project_local = std::env::current_dir()
+ .ok()
+ .map(|cwd| install_hooks::project_claude_settings_local(&cwd));
for change in &plan {
- apply_change(change, name.as_deref(), &url)?;
+ let private_backup = match change {
+ PlannedChange::Rewrite { path, .. } if project_local.as_ref() == Some(path) => Some(
+ install_hooks::project_settings_backup(&config.data_dir, path),
+ ),
+ _ => None,
+ };
+ apply_change(change, private_backup.as_ref(), name.as_deref(), &url)?;
}
// Removing the hooks removes the only readers of the stored bearer, so
@@ -723,7 +749,6 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {
// 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}",
@@ -2457,6 +2482,7 @@ command = "'/usr/local/bin/ai-memory' hook --event stop --agent kimi-code --serv
removed: vec!["ai-memory".to_string()],
ops: vec![RewriteOp::McpJson(McpClient::KimiCode)],
},
+ None,
Some("ai-memory"),
"http://127.0.0.1:49374/mcp",
)
diff --git a/crates/ai-memory-cli/src/commands/upgrade.rs b/crates/ai-memory-cli/src/commands/upgrade.rs
index e71075bf..bb8fc511 100644
--- a/crates/ai-memory-cli/src/commands/upgrade.rs
+++ b/crates/ai-memory-cli/src/commands/upgrade.rs
@@ -831,9 +831,10 @@ fn apply_staged_agent_hooks(config: &Config, name: &str, agent: AgentChoice) {
&& let Some(settings) = claude_user_level_install_absent()
{
println!(
- " (no ai-memory hooks in {} — skipping the user-level re-apply; a \
- `--scope project` install keeps pointing at the staged scripts, so those are \
- refreshed here)",
+ " (no ai-memory hooks in {} — skipping the user-level re-apply; the staged \
+ scripts are refreshed, but `--scope project` files are not rewritten: re-run \
+ `ai-memory install-hooks --agent {name} --scope project --apply` in each such \
+ checkout to pick up hook-command changes)",
settings.display()
);
match install_hooks::restage_claude_code_scripts(&config.data_dir, None) {
diff --git a/crates/ai-memory-cli/tests/suite/removal.rs b/crates/ai-memory-cli/tests/suite/removal.rs
index 8f4746dc..083c43a2 100644
--- a/crates/ai-memory-cli/tests/suite/removal.rs
+++ b/crates/ai-memory-cli/tests/suite/removal.rs
@@ -136,8 +136,9 @@ fn install_then_uninstall_round_trip_claude_hooks() {
}
/// `--scope project` writes the checkout's gitignored
-/// `.claude/settings.local.json` (at the git root, from any subdirectory) and
-/// leaves the user-level file alone. `uninstall` from inside the checkout
+/// `.claude/settings.local.json` (at the git root from any subdirectory; in
+/// the launch directory on Windows) and leaves the user-level file alone, and
+/// keeps its backup out of the checkout. `uninstall` from inside the checkout
/// sweeps exactly our entries; from anywhere else it leaves the file untouched.
#[test]
fn project_scope_install_then_uninstall_round_trip_claude_hooks() {
@@ -152,7 +153,14 @@ fn project_scope_install_then_uninstall_round_trip_claude_hooks() {
assert!(status.success(), "git init failed");
let sub = project.path().join("crates").join("x");
std::fs::create_dir_all(&sub).unwrap();
- let local = project.path().join(".claude").join("settings.local.json");
+ // Claude Code reads the launch directory on Windows, the git root elsewhere.
+ let local = if cfg!(windows) {
+ sub.as_path()
+ } else {
+ project.path()
+ }
+ .join(".claude")
+ .join("settings.local.json");
// Pre-seed a third-party hook we must NOT touch.
write_file(
&local,
@@ -194,11 +202,40 @@ fn project_scope_install_then_uninstall_round_trip_claude_hooks() {
!home.path().join(".claude").join("settings.json").exists(),
"project scope must not touch the user-level settings"
);
+ // The pre-seeded file was updated, so a backup exists, and it must sit
+ // under the data dir: Claude Code's ignore rule does not cover a sibling
+ // `.bak-<ts>`, which would carry the hook commands into `git status`.
+ let backups = home
+ .path()
+ .join(".ai-memory-data")
+ .join("backups")
+ .join("claude-settings-local");
+ let no_backup_in_checkout = |when: &str| {
+ let leaked: Vec<_> = std::fs::read_dir(local.parent().unwrap())
+ .unwrap()
+ .flatten()
+ .map(|entry| entry.file_name().to_string_lossy().into_owned())
+ .filter(|name| name.contains(".bak-"))
+ .collect();
+ assert!(
+ leaked.is_empty(),
+ "{when}: backup left in the checkout: {leaked:?}"
+ );
+ };
+ no_backup_in_checkout("install");
+ let saved: Vec<_> = std::fs::read_dir(&backups).unwrap().flatten().collect();
+ assert_eq!(saved.len(), 1, "one backup under {}", backups.display());
+ assert!(
+ std::fs::read_to_string(saved[0].path())
+ .unwrap()
+ .contains("/usr/bin/n.sh"),
+ "the backup holds the prior file"
+ );
// With an ignore rule in place the warning goes away.
write_file(
&project.path().join(".gitignore"),
- ".claude/settings.local.json\n",
+ "**/.claude/settings.local.json\n",
);
let output = install(&sub);
let stderr = String::from_utf8_lossy(&output.stderr);
@@ -235,6 +272,11 @@ fn project_scope_install_then_uninstall_round_trip_claude_hooks() {
"uninstall failed: {}",
String::from_utf8_lossy(&output.stderr)
);
+ no_backup_in_checkout("uninstall");
+ assert!(
+ String::from_utf8_lossy(&output.stdout).contains("used `install-hooks --scope project`"),
+ "uninstall must point at the checkouts it cannot reach"
+ );
let swept: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&local).unwrap()).unwrap();
assert!(
diff --git a/docs/cookbook.md b/docs/cookbook.md
index 0a2a206c..415a87ae 100644
--- a/docs/cookbook.md
+++ b/docs/cookbook.md
@@ -251,8 +251,10 @@ per repository instead, run from inside the checkout:
ai-memory install-hooks --agent claude-code --scope project --apply
```
-This writes the repository's gitignored `.claude/settings.local.json` (at the
-git root, where Claude Code reads it) and leaves the user-level file alone.
+This writes the repository's gitignored `.claude/settings.local.json` where
+Claude Code reads it (the git root; the current directory on Windows or when
+the repository root is your home directory) and leaves the user-level file
+alone. Backups of an updated file go under the data dir, not the checkout.
Pick one scope per machine: Claude Code merges project and user hooks. The
installer warns when the file is not git-ignored, and `ai-memory uninstall
--only hooks --apply` from inside the checkout removes the entries again.
diff --git a/docs/install.md b/docs/install.md
index f6a83213..782ce273 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -102,19 +102,30 @@ ai-memory install-hooks --agent claude-code --scope project --apply
This writes the repository's gitignored `.claude/settings.local.json` at the
git root (the main checkout's root from a worktree), which is where Claude Code
reads that file even when launched from a subdirectory — see
-[where Claude Code looks for each file](https://code.claude.com/docs/en/settings#where-claude-code-looks-for-each-file);
-on Windows it reads the launch directory instead, so launch from the root
-there. The user-level file is left alone. Claude Code merges the project
-file's hooks with any user-level ones, so pick one scope per machine.
-The installer warns when the file is not ignored by git (Claude Code adds it
-to your global excludes only when it creates the file itself) and refuses to
-embed a bearer token in it when the token cannot be persisted under the data
-dir. `ai-memory uninstall --only hooks --apply` run from inside the checkout
+[where Claude Code looks for each file](https://code.claude.com/docs/en/settings#where-claude-code-looks-for-each-file).
+On Windows, and when the repository root is your home directory, Claude Code
+reads the launch directory instead, so the installer writes to the current
+directory there: run it, and launch Claude Code, from the same directory.
+The user-level file is left alone. Claude Code merges the project file's
+hooks with any user-level ones, so pick one scope per machine; the installer
+notes when the other scope already carries ai-memory hooks.
+The installer warns when the file is not ignored by git (Claude Code adds
+`**/.claude/settings.local.json` to your global excludes only when it creates
+the file itself) and refuses to embed a bearer token in it when the token
+cannot be persisted under the data dir. When it updates an existing file, the
+backup goes to `<data_dir>/backups/claude-settings-local/` (owner-only), not
+next to the file, so nothing new appears in `git status`.
+`ai-memory uninstall --only hooks --apply` run from inside the checkout
removes the entries again; run elsewhere it does not reach into the
-repository. `upgrade` and the `ai-memory run` auto-wire leave the user-level
-file alone while a project-scoped install is the only one present.
-`setup-agent` and `backup-agents` only know the user-level file. Claude Code
-only; other agents keep their user-level hook files.
+repository, so run it in every project-scoped checkout before removing
+ai-memory — those files otherwise keep calling the removed binary and data
+dir. `upgrade` and the `ai-memory run` auto-wire leave the user-level file
+alone while a project-scoped install is the only one present. `upgrade`
+replaces the binary the hook commands call but does not rewrite project
+files; re-run `install-hooks --scope project --apply` in each checkout to pick
+up hook-command changes. `setup-agent` and `backup-agents` only know the
+user-level file. Claude Code only; other agents keep their user-level hook
+files.
`--session-aware` is an optional Claude Code MCP mode: