Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(install-hooks): add --scope project for Claude Code hooks
Talysson de Oliveira Cassiano6e585d3a68f2
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 60810a7a..370e949d 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -1635,6 +1635,17 @@ pub enum InstallSkillsScope {Global,}+/// Where `install-hooks` writes Claude Code's hook configuration.+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]+pub enum HookInstallScope {+ /// The user-level settings file (`~/.claude/settings.json`, or+ /// `$CLAUDE_CONFIG_DIR/settings.json`): hooks fire in every project.+ Global,+ /// This repository's gitignored `.claude/settings.local.json`: hooks fire+ /// only for sessions started in this checkout.+ Project,+}+/// Agent skill directory family for `install-skills`.#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]pub enum InstallSkillsAgent {@@ -2905,6 +2916,19 @@ pub struct InstallHooksArgs {/// For OpenClaw, this is the generated plugin package directory.#[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.+ /// Claude Code only; ignores `CLAUDE_CONFIG_DIR`. Cannot be combined+ /// with `--config-file`, which names the target file directly.+ #[arg(+ long,+ value_enum,+ default_value_t = HookInstallScope::Global,+ conflicts_with = "config_file"+ )]+ pub scope: HookInstallScope,/// Default project strategy to bake into the installed hooks./// `repo-root` makes every session resolve its project from the main/// git repo root (collapsing subdirectories and worktrees) without a@@ -3688,6 +3712,45 @@ mod tests {}}+ #[test]+ fn install_hooks_scope_defaults_to_global_and_conflicts_with_config_file() {+ let cli =+ Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", "claude-code"]).unwrap();+ let Command::InstallHooks(args) = cli.command else {+ panic!("expected install-hooks command");+ };+ assert_eq!(args.scope, HookInstallScope::Global);++ let cli = Cli::try_parse_from([+ "ai-memory",+ "install-hooks",+ "--agent",+ "claude-code",+ "--scope",+ "project",+ ])+ .unwrap();+ let Command::InstallHooks(args) = cli.command else {+ panic!("expected install-hooks command");+ };+ assert_eq!(args.scope, HookInstallScope::Project);++ // Both name the target file; accepting them together would silently+ // pick one.+ let err = Cli::try_parse_from([+ "ai-memory",+ "install-hooks",+ "--agent",+ "claude-code",+ "--scope",+ "project",+ "--config-file",+ "settings.json",+ ])+ .unwrap_err();+ assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);+ }+#[test]fn antigravity_aliases_parse_to_same_variant() {for alias in ["antigravity-cli", "antigravity", "agy"] {diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 1f66f043..576ffbbe 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -20,7 +20,9 @@ use std::path::{Path, PathBuf};use anyhow::{Context, Result};-use crate::cli::{AgentChoice, CaptureModeArg, InstallHooksArgs, McpClient, ProjectStrategyArg};+use crate::cli::{+ AgentChoice, CaptureModeArg, HookInstallScope, InstallHooksArgs, McpClient, ProjectStrategyArg,+};use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json, mutate_toml};use crate::commands::install_mcp;use crate::commands::openclaw_plugin;@@ -63,6 +65,92 @@ fn claude_settings_path_in(.join("settings.json"))}+/// The Claude Code settings file this invocation renders for or writes. An+/// explicit `--config-file` wins; `--scope project` targets the checkout's+/// `.claude/settings.local.json`; otherwise the user-level file.+pub(crate) fn claude_settings_target(args: &InstallHooksArgs) -> Result<PathBuf> {+ if let Some(path) = &args.config_file {+ return Ok(path.clone());+ }+ match args.scope {+ HookInstallScope::Global => claude_settings_path(),+ HookInstallScope::Project => {+ let cwd = std::env::current_dir().context(+ "could not resolve current dir for the project-scoped Claude Code settings",+ )?;+ Ok(project_claude_settings_local(&cwd))+ }+ }+}++/// `<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.+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")+}++/// The `hooks` table of a Claude-shaped settings document (`hooks` → event →+/// entries) when at least one entry in it is ours; `None` means the document+/// is not an ai-memory install. Every "is this file one of ours" question+/// goes through here so the walk cannot drift between callers.+fn ai_memory_claude_hooks(+ document: &serde_json::Value,+) -> Option<&serde_json::Map<String, serde_json::Value>> {+ let hooks = document.get("hooks")?.as_object()?;+ hooks+ .values()+ .filter_map(serde_json::Value::as_array)+ .flatten()+ .any(is_ai_memory_hook_entry)+ .then_some(hooks)+}++/// Whether a parsed Claude-shaped settings document carries an ai-memory hook.+/// `upgrade` and the `run` auto-wire use it to tell a `--scope project`+/// install apart from a user-level one: both stage the same scripts, so the+/// staged dir alone no longer says which file was written.+pub(crate) fn document_carries_ai_memory_hooks(document: &serde_json::Value) -> bool {+ ai_memory_claude_hooks(document).is_some()+}++/// [`document_carries_ai_memory_hooks`] over raw file content; unparsable+/// content is not an install.+pub(crate) fn settings_carry_ai_memory_hooks(content: &str) -> bool {+ serde_json::from_str::<serde_json::Value>(content)+ .ok()+ .is_some_and(|document| document_carries_ai_memory_hooks(&document))+}++/// [`settings_carry_ai_memory_hooks`] over a file; a missing or unreadable+/// file is not an install.+pub(crate) fn settings_file_carries_ai_memory_hooks(path: &Path) -> bool {+ fs::read_to_string(path)+ .ok()+ .is_some_and(|content| settings_carry_ai_memory_hooks(&content))+}++/// 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.+pub(crate) fn restage_claude_code_scripts(+ data_dir: &Path,+ hooks_dir: Option<&Path>,+) -> Result<PathBuf> {+ let hooks_dir = resolve_hooks_dir(hooks_dir, AgentChoice::ClaudeCode, data_dir)?;+ stage_hook_scripts(&hooks_dir, "claude-code", data_dir)+}+/// Codex's hooks file — `$CODEX_HOME/hooks.json` when the var is set, else/// `~/.codex/hooks.json`.///@@ -373,6 +461,13 @@ fn kiro_cli_home_join(/// # Errors/// Returns an error if the hook script directory cannot be located.pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {+ if args.scope == HookInstallScope::Project && args.agent != AgentChoice::ClaudeCode {+ anyhow::bail!(+ "`--scope project` is only supported for `--agent claude-code`; ai-memory writes no \+ project-local hook file for {}",+ args.agent.kind().as_str()+ );+ }let inferred = if args.server_url.is_none() {infer_installed_mcp_config(args.agent)?} else {@@ -407,6 +502,17 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {// path back.match crate::config::store_hook_auth_token(&config.data_dir, token) {Ok(()) => true,+ // A project-local file sits inside a checkout where a commit could+ // publish it, so the inline fallback is refused there outright.+ Err(e) if args.scope == HookInstallScope::Project => {+ return Err(anyhow::Error::new(e).context(format!(+ "could not persist the hook auth token under {}; refusing to embed it in the \+ project-local .claude/settings.local.json instead. Install with a writable \+ host data dir (e.g. `AI_MEMORY_DATA_DIR=$HOME/.local/share/ai-memory` for \+ the docker wrapper) or a native `ai-memory` binary, or use `--scope global`",+ config.data_dir.display()+ )));+ }Err(e) => {eprintln!("[ai-memory] warning: could not persist the hook auth token under {} ({e}); \@@ -666,17 +772,17 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {AgentChoice::ClaudeCode => {let hooks_dir =resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent, &config.data_dir)?;- let settings_path = match &args.config_file {- Some(p) => p.clone(),- None => claude_settings_path()?,- };+ let settings_path = claude_settings_target(&args)?;render_claude_code(&hooks_dir,&server_url,auth,&config.data_dir,strategy,- &settings_path,+ ClaudeRenderTarget {+ settings_path: &settings_path,+ scope: args.scope,+ },ClaudeCaptureScope {assistant: args.capture_assistant,prompts: install_claude_prompt_capture(&args),@@ -871,15 +977,7 @@ fn install_claude_prompt_capture(args: &InstallHooksArgs) -> bool {/// `None` means this is not an existing ai-memory Claude Code install.fn baked_claude_prompt_capture(existing: &str) -> Option<bool> {let document: serde_json::Value = serde_json::from_str(existing).ok()?;- let hooks = document.get("hooks")?.as_object()?;- let has_ai_memory_hooks = hooks.values().any(|value| {- value- .as_array()- .is_some_and(|entries| entries.iter().any(is_ai_memory_hook_entry))- });- if !has_ai_memory_hooks {- return None;- }+ let hooks = ai_memory_claude_hooks(&document)?;Some(hooks.get(CLAUDE_PROMPT_EVENT)@@ -950,7 +1048,7 @@ fn existing_agent_config(args: &InstallHooksArgs) -> Option<String> {}} else {match args.agent {- AgentChoice::ClaudeCode => claude_settings_path().ok()?,+ AgentChoice::ClaudeCode => claude_settings_target(args).ok()?,AgentChoice::Codex => codex_hooks_path().ok()?,AgentChoice::CommandCode => command_code_settings_path().ok()?,AgentChoice::Cursor => cursor_hooks_path().ok()?,@@ -1679,9 +1777,6 @@ fn overlay_kiro_cli_event_hooks(map.insert(event.to_string(), serde_json::Value::Array(entries));}-/// Mutate `~/.claude/settings.json` in place: replace the hook entries-/// ai-memory cares about (`CLAUDE_CODE_EVENTS`); preserve every other hook the-/// user has wired up to other tools./// Whether `--capture-assistant` may take effect for this agent + platform/// (#196, #743): Claude Code, Codex and OpenCode 2 on a native hook platform./// OpenCode 2 forwards completed text through the same native Stop sanitizer.@@ -1713,6 +1808,9 @@ fn configure_claude_prompt_capture(payload}+/// Mutate the Claude Code settings file in place: replace the hook entries+/// ai-memory cares about (`CLAUDE_CODE_EVENTS`); preserve every other hook the+/// user has wired up to other tools.fn apply_to_claude_code_settings(hooks_dir: &Path,server_url: &str,@@ -1778,10 +1876,7 @@ fn apply_to_claude_code_settings_with_payload(args: &InstallHooksArgs,capture_prompts: bool,) -> Result<()> {- let path = match &args.config_file {- Some(p) => p.clone(),- None => claude_settings_path()?,- };+ let path = claude_settings_target(args)?;let our_hooks = payload.get("hooks").and_then(|v| v.as_object())@@ -1818,6 +1913,20 @@ fn apply_to_claude_code_settings_with_payload(ApplyOutcome::NoOp => "already up to date",});+ // 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+ // paths nobody wants committed.+ if args.scope == HookInstallScope::Project+ && ai_memory_consolidate::path_is_git_ignored(&path) == Some(false)+ {+ eprintln!(+ "[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()+ );+ }Ok(())}@@ -5391,19 +5500,35 @@ struct ClaudeCaptureScope {prompts: bool,}+/// The settings file a Claude Code preview is rendered for, and the scope that+/// chose it.+struct ClaudeRenderTarget<'a> {+ settings_path: &'a Path,+ scope: HookInstallScope,+}+fn render_claude_code(hooks_dir: &Path,server_url: &str,auth_token: Option<&str>,data_dir: &Path,project_strategy: Option<&str>,- settings_path: &Path,+ target: ClaudeRenderTarget<'_>,capture: ClaudeCaptureScope,) -> Result<()> {+ let ClaudeRenderTarget {+ settings_path,+ scope,+ } = target;let ClaudeCaptureScope {assistant: capture_assistant,prompts: capture_prompts,} = capture;+ // A preview never persists the bearer (#552), so it would land inline in+ // the snippet — and project scope tells the operator to paste that snippet+ // into a checkout. Withhold it there; `--apply` persists it instead.+ let token_withheld = scope == HookInstallScope::Project && auth_token.is_some();+ let auth_token = if token_withheld { None } else { auth_token };// Soft check: warn (don't bail) if a script is missing. The user// may be running this command inside docker against a host path// that exists only on the host's filesystem — bailing would@@ -5443,7 +5568,14 @@ fn render_claude_code();println!("# Hook scripts: {}", hooks_dir.display());println!("# AI-memory server URL: {server_url}");- if auth_token.is_some() {+ if token_withheld {+ println!("# Auth: a bearer token is configured but NOT embedded below: this file");+ println!("# lives inside a checkout. Re-run with --apply, which persists the");+ println!(+ "# token under {} (0600) where the hooks read it.",+ data_dir.display()+ );+ } else if auth_token.is_some() {println!("# Auth: AI_MEMORY_AUTH_TOKEN embedded in each hook command below.");println!("# Treat {} as sensitive (chmod 600).",@@ -6198,7 +6330,7 @@ fn render_pool_output(let mut out = String::new();out.push_str("# Pool (Poolside Agent CLI) hook config — merge into the repo-root\n");out.push_str("# .poolside/settings.yaml of each project Pool runs in. ai-memory\n");- out.push_str("# does not write project-local files, so paste this snippet manually\n");+ out.push_str("# does not write committed project files, so paste this snippet manually\n");out.push_str("# (re-run with --apply first to stage the scripts to a stable path).\n");out.push_str(&format!("# Hook scripts: {}\n", hooks_dir.display()));out.push_str(&format!("# AI-memory server URL: {server_url}\n"));@@ -6736,6 +6868,7 @@ mod tests {as_user: None,apply: true,config_file: None,+ scope: HookInstallScope::Global,project_strategy: Some(ProjectStrategyArg::Basename),}}@@ -7283,7 +7416,7 @@ command = "AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/aNone,);assert!(out.contains(".poolside/settings.yaml"));- assert!(out.contains("does not write project-local files"));+ assert!(out.contains("does not write committed project files"));assert!(out.contains("finalize-session --agent pool"));assert!(out.contains("memory_handoff_accept"));assert!(out.contains("hooks:\n"));@@ -8527,6 +8660,105 @@ 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.+ #[test]+ fn project_claude_settings_local_resolves_to_the_repo_root_or_cwd() {+ let tmp = TempDir::new().unwrap();+ let repo = tmp.path().join("repo");+ let sub = repo.join("crates").join("x");+ std::fs::create_dir_all(&sub).unwrap();+ let status = std::process::Command::new("git")+ .args(["init", "-q"])+ .current_dir(&repo)+ .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")));+ // 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 plain = tmp.path().join("plain");+ std::fs::create_dir_all(&plain).unwrap();+ assert_eq!(+ project_claude_settings_local(&plain),+ plain.join(".claude").join("settings.local.json")+ );+ }++ /// `upgrade` and the `run` auto-wire use this to tell a `--scope project`+ /// install from a user-level one; a third-party hook alone must not count.+ #[test]+ fn settings_carry_ai_memory_hooks_recognizes_only_our_entries() {+ let ours = r#"{"hooks":{"Stop":[{"matcher":"","hooks":[{"type":"command","command":"AI_MEMORY_HOOK_URL=http://127.0.0.1:49374 /home/u/.local/share/ai-memory/hooks/claude-code/stop.sh"}]}]}}"#;+ assert!(settings_carry_ai_memory_hooks(ours));+ let third_party = r#"{"hooks":{"Notification":[{"matcher":"","hooks":[{"type":"command","command":"/usr/bin/n.sh"}]}]}}"#;+ assert!(!settings_carry_ai_memory_hooks(third_party));+ assert!(!settings_carry_ai_memory_hooks(r#"{"permissions":{}}"#));+ assert!(!settings_carry_ai_memory_hooks("not json"));+ }++ /// Project scope names a Claude Code file; no other agent has a+ /// project-local hook file ai-memory writes, so the install must fail+ /// before it stages anything.+ #[test]+ fn project_scope_is_rejected_for_agents_without_a_project_file() {+ let home = TempDir::new().unwrap();+ let config = crate::config::Config::load(None, Some(home.path().to_path_buf())).unwrap();+ let args = InstallHooksArgs {+ agent: AgentChoice::Codex,+ scope: HookInstallScope::Project,+ server_url: Some("http://127.0.0.1:49374".to_string()),+ hooks_dir: Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../hooks")),+ // Unreachable from the CLI (clap rejects the pair); set only so a+ // regression writes into the temp dir, not the real ~/.codex.+ config_file: Some(home.path().join("hooks.json")),+ ..default_hook_args()+ };+ let err = run(&config, args).unwrap_err();+ assert!(err.to_string().contains("--scope project"), "{err:#}");+ assert!(+ !config+ .data_dir+ .join(crate::install_layout::HOOKS_DIR_NAME)+ .exists(),+ "nothing may be staged after a refused install"+ );+ }++ /// The inline-bearer fallback (F5 above) writes the token into the hook+ /// config. Inside a checkout that file can be committed, so project scope+ /// refuses the fallback instead of taking it.+ #[test]+ fn project_scope_refuses_the_inline_bearer_when_persisting_fails() {+ let home = TempDir::new().unwrap();+ let config = crate::config::Config::load(None, Some(home.path().to_path_buf())).unwrap();+ // Same EISDIR trick as the fallback test: only the secret write fails.+ std::fs::create_dir_all(crate::config::hook_auth_token_path_in(&config.data_dir)).unwrap();+ let settings = home.path().join("settings.local.json");+ let args = InstallHooksArgs {+ agent: AgentChoice::ClaudeCode,+ scope: HookInstallScope::Project,+ apply: true,+ server_url: Some("http://127.0.0.1:49374".to_string()),+ auth_token: Some("PROJECT-BEARER".to_string()),+ hooks_dir: Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../hooks")),+ // Unreachable from the CLI (clap rejects the pair); set only so a+ // regression writes into the temp dir, not this checkout.+ config_file: Some(settings.clone()),+ ..default_hook_args()+ };+ let err = run(&config, args).unwrap_err();+ assert!(format!("{err:#}").contains("refusing to embed"), "{err:#}");+ assert!(!settings.exists(), "no config may be written on refusal");+ assert_eq!(crate::config::read_hook_auth_token(&config.data_dir), None);+ }+fn claude_apply_args(settings: &std::path::Path,hooks_dir: &std::path::Path,@@ -9910,6 +10142,7 @@ model = "gpt-5"as_user: None,apply: true,config_file: Some(tmp.path().join("extensions").join("ai-memory-omp.ts")),+ scope: HookInstallScope::Global,project_strategy: Some(ProjectStrategyArg::Basename),profile: None,};@@ -9943,6 +10176,7 @@ model = "gpt-5"as_user: None,apply: true,config_file: Some(path.clone()),+ scope: HookInstallScope::Global,project_strategy: Some(ProjectStrategyArg::Basename),profile: None,};@@ -10536,6 +10770,7 @@ model = "gpt-5"server_url: Some("http://127.0.0.1:49374".to_string()),auth_token: None,config_file: Some(config_path.clone()),+ scope: HookInstallScope::Global,project_strategy: Some(ProjectStrategyArg::Basename),as_user: None,apply: false,@@ -11030,6 +11265,7 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessioserver_url: Some("http://127.0.0.1:49374".to_string()),auth_token: None,config_file: Some(config_path.clone()),+ scope: HookInstallScope::Global,project_strategy: Some(ProjectStrategyArg::Basename),as_user: None,apply: false,@@ -11592,6 +11828,7 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessioserver_url: Some("http://127.0.0.1:49374".to_string()),auth_token: None,config_file: Some(config_path.clone()),+ scope: HookInstallScope::Global,project_strategy: Some(crate::cli::ProjectStrategyArg::Basename),as_user: None,apply: false,@@ -11659,6 +11896,7 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessioserver_url: Some("http://127.0.0.1:49374".to_string()),auth_token: None,config_file: Some(config_path.clone()),+ scope: HookInstallScope::Global,project_strategy: Some(crate::cli::ProjectStrategyArg::Basename),as_user: None,apply: false,@@ -11715,6 +11953,7 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessioserver_url: Some("http://127.0.0.1:49374".to_string()),auth_token: None,config_file: Some(hooks_v1_path.clone()),+ scope: HookInstallScope::Global,project_strategy: Some(crate::cli::ProjectStrategyArg::Basename),as_user: None,apply: false,@@ -11764,6 +12003,7 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessioserver_url: Some("http://127.0.0.1:49374".to_string()),auth_token: None,config_file: Some(config_path.clone()),+ scope: HookInstallScope::Global,project_strategy: Some(crate::cli::ProjectStrategyArg::Basename),as_user: None,apply: false,@@ -11838,6 +12078,7 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessioserver_url: Some("http://127.0.0.1:49374".to_string()),auth_token: None,config_file: Some(config_path.clone()),+ scope: HookInstallScope::Global,project_strategy: Some(crate::cli::ProjectStrategyArg::Basename),as_user: None,apply: false,diff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rsindex d9a482ec..c4ac1ea4 100644--- a/crates/ai-memory-cli/src/commands/run_autowire.rs+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs@@ -273,6 +273,7 @@ fn wire_installs(config: &Config, targets: WireTargets, overrides: &WireOverrideas_user: None,apply: true,config_file,+ scope: crate::cli::HookInstallScope::Global,project_strategy: None,capture_assistant: false,capture_mode: None,diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex d2ee4b55..327cb164 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -408,7 +408,7 @@ fn emit_grok(emit_root: &Path, args: &SetupAgentArgs) -> Result<()> {fn emit_pool(emit_root: &Path, args: &SetupAgentArgs) {let snippet = build_pool_settings_yaml(emit_root, &args.server_url, args.auth_token.as_deref());println!("# Pool (Poolside Agent CLI) — merge into the repo-root .poolside/settings.yaml");- println!("# of each project Pool runs in; ai-memory does not write project-local files.");+ println!("# of each project Pool runs in; ai-memory does not write committed project files.");println!("# Hook scripts (must be reachable from the host that runs Pool):");println!("# {}", emit_root.display());println!("# AI-memory server: {}", args.server_url);diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex fe827220..8b518b90 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -200,6 +200,14 @@ fn build_plan(args: &UninstallArgs, data_dir: &Path) -> anyhow::Result<Vec<Plann.into_iter().map(|path| (path, HookConfigShape::NestedHooksKey)).collect();+ // A `--scope project` install lives in the checkout's gitignored+ // `.claude/settings.local.json`; sweep the one for the current+ // directory, as the Kiro project configs below are.+ let cwd = std::env::current_dir().context("getting CWD for hook removal")?;+ let project_local = install_hooks::project_claude_settings_local(&cwd);+ if !hook_files.iter().any(|(path, _)| *path == project_local) {+ hook_files.push((project_local, HookConfigShape::NestedHooksKey));+ }hook_files.extend([(install_hooks::codex_hooks_path()?,@@ -255,7 +263,6 @@ fn build_plan(args: &UninstallArgs, data_dir: &Path) -> anyhow::Result<Vec<Plannlet mut kiro_configs =install_hooks::list_kiro_cli_agent_configs(&install_hooks::kiro_cli_agents_dir()?)?;- let cwd = std::env::current_dir().context("getting CWD for Kiro hook removal")?;kiro_configs.extend(install_hooks::list_kiro_cli_agent_configs(&cwd.join(".kiro/agents"),)?);diff --git a/crates/ai-memory-cli/src/commands/upgrade.rs b/crates/ai-memory-cli/src/commands/upgrade.rsindex 0288853f..5dade4ed 100644--- a/crates/ai-memory-cli/src/commands/upgrade.rs+++ b/crates/ai-memory-cli/src/commands/upgrade.rs@@ -38,7 +38,7 @@ use flate2::read::GzDecoder;use sha2::{Digest, Sha256};use tracing::info;-use crate::cli::{AgentChoice, InstallHooksArgs, UpgradeArgs};+use crate::cli::{AgentChoice, HookInstallScope, InstallHooksArgs, UpgradeArgs};use crate::commands::install_hooks;use crate::config::Config;use crate::install_layout::{HOOKS_DIR_NAME, shipped_binary_name};@@ -844,6 +844,7 @@ fn apply_hooks_args(agent: AgentChoice) -> InstallHooksArgs {as_user: None,apply: true,config_file: None,+ scope: HookInstallScope::Global,project_strategy: None,capture_assistant: false,capture_mode: None,diff --git a/crates/ai-memory-cli/tests/suite/removal.rs b/crates/ai-memory-cli/tests/suite/removal.rsindex 0d24b9ac..8f4746dc 100644--- a/crates/ai-memory-cli/tests/suite/removal.rs+++ b/crates/ai-memory-cli/tests/suite/removal.rs@@ -135,6 +135,175 @@ 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+/// sweeps exactly our entries; from anywhere else it leaves the file untouched.+#[test]+fn project_scope_install_then_uninstall_round_trip_claude_hooks() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();+ let status = Command::new("git")+ .args(["init", "-q"])+ .current_dir(project.path())+ .status()+ .unwrap();+ 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");+ // Pre-seed a third-party hook we must NOT touch.+ write_file(+ &local,+ r#"{"hooks":{"Notification":[{"matcher":"","hooks":[{"type":"command","command":"/usr/bin/n.sh"}]}]}}"#,+ );+ let install = |cwd: &Path| {+ command_with_home(home.path())+ .args([+ "install-hooks",+ "--agent",+ "claude-code",+ "--scope",+ "project",+ "--apply",+ ])+ .current_dir(cwd)+ .output()+ .unwrap()+ };++ let output = install(&sub);+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(output.status.success(), "install-hooks failed: {stderr}");+ assert!(+ stderr.contains("is not ignored by git"),+ "no ignore rule exists yet, so the installer must warn: {stderr}"+ );+ let after: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&local).unwrap()).unwrap();+ assert!(+ after["hooks"]["Notification"].is_array(),+ "third-party hook must survive"+ );+ assert!(+ after["hooks"]["SessionStart"].is_array(),+ "our hooks must land in the project file: {after}"+ );+ assert!(+ !home.path().join(".claude").join("settings.json").exists(),+ "project scope must not touch the user-level settings"+ );++ // With an ignore rule in place the warning goes away.+ write_file(+ &project.path().join(".gitignore"),+ ".claude/settings.local.json\n",+ );+ let output = install(&sub);+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(output.status.success(), "re-apply failed: {stderr}");+ assert!(!stderr.contains("is not ignored by git"), "{stderr}");++ // Uninstall from an unrelated directory never reaches into this checkout.+ let elsewhere = tempfile::tempdir().unwrap();+ let output = run_uninstall(+ elsewhere.path(),+ home.path(),+ &["uninstall", "--apply", "--only", "hooks", "--yes"],+ );+ assert!(+ output.status.success(),+ "uninstall failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let untouched: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&local).unwrap()).unwrap();+ assert!(+ untouched["hooks"]["SessionStart"].is_array(),+ "uninstall elsewhere must leave the project file alone"+ );++ // From inside the checkout (any subdirectory) it sweeps exactly our entries.+ let output = run_uninstall(+ &sub,+ home.path(),+ &["uninstall", "--apply", "--only", "hooks", "--yes"],+ );+ assert!(+ output.status.success(),+ "uninstall failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let swept: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&local).unwrap()).unwrap();+ assert!(+ swept["hooks"]["Notification"].is_array(),+ "third-party hook must survive uninstall"+ );+ for ours in [+ "SessionStart",+ "SessionEnd",+ "PreToolUse",+ "PostToolUse",+ "Stop",+ "PreCompact",+ "UserPromptSubmit",+ ] {+ assert!(+ swept["hooks"].get(ours).is_none(),+ "{ours} should be removed: {swept}"+ );+ }+}++/// A print-only preview of a project-scoped install must not hand the operator+/// a bearer to paste into the checkout; the user-level preview still embeds it.+#[test]+fn project_scope_preview_withholds_the_bearer_token() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();+ let preview = |scope: &str| {+ let output = command_with_home(home.path())+ .args([+ "install-hooks",+ "--agent",+ "claude-code",+ "--scope",+ scope,+ "--auth-token",+ "SEKRIT-PREVIEW",+ ])+ .current_dir(project.path())+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "preview failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ String::from_utf8_lossy(&output.stdout).into_owned()+ };++ let project_scoped = preview("project");+ assert!(+ !project_scoped.contains("SEKRIT-PREVIEW"),+ "the project preview must not embed the bearer: {project_scoped}"+ );+ assert!(project_scoped.contains("NOT embedded"), "{project_scoped}");++ let global = preview("global");+ assert!(+ global.contains("SEKRIT-PREVIEW"),+ "control: the user-level preview embeds it as before: {global}"+ );+ assert!(+ !home.path().join(".claude").exists() && !project.path().join(".claude").exists(),+ "a preview writes nothing"+ );+}+#[test]fn relocated_claude_uninstall_sweeps_active_and_legacy_installs() {let _guard = cli_test_lock();diff --git a/crates/ai-memory-consolidate/src/bootstrap.rs b/crates/ai-memory-consolidate/src/bootstrap.rsindex 5a1ad0b4..53aa0f77 100644--- a/crates/ai-memory-consolidate/src/bootstrap.rs+++ b/crates/ai-memory-consolidate/src/bootstrap.rs@@ -742,6 +742,27 @@ pub fn discover_repo_root(start: &Path) -> Result<PathBuf, BootstrapError> {.ok_or_else(|| BootstrapError::NotARepo(start.to_path_buf()))}+/// Whether git ignores `path` in the repository containing it; `None`+/// outside any repository, or when the path cannot be related to the+/// repository's working directory. Lets an installer that writes a file+/// inside a checkout warn when a commit could pick it up. Honors the+/// repository's `.gitignore` files, `.git/info/exclude`, and the global+/// excludes file, like `git check-ignore`.+#[must_use]+pub fn path_is_git_ignored(path: &Path) -> Option<bool> {+ let parent = path.parent()?;+ let name = path.file_name()?;+ let repo = git2::Repository::discover(parent).ok()?;+ let workdir = repo.workdir()?;+ // libgit2 wants a workdir-relative path. Canonicalize both sides so a+ // symlinked prefix (`/var` vs `/private/var` on macOS) or Windows'+ // `\\?\` verbatim form on only one of them still strips.+ let dir = std::fs::canonicalize(parent).unwrap_or_else(|_| parent.to_path_buf());+ let workdir = std::fs::canonicalize(workdir).unwrap_or_else(|_| workdir.to_path_buf());+ let relative = dir.strip_prefix(&workdir).ok()?.join(name);+ repo.is_path_ignored(relative).ok()+}+/// URLs of the `upstream` and `origin` remotes of the repository containing/// `start`, for resolving its repository identity (#708).///@@ -2126,6 +2147,34 @@ mod tests {);}+ /// `path_is_git_ignored` answers like `git check-ignore`: `None` outside+ /// a repository, otherwise whether some ignore rule covers the path. The+ /// fixture file name is deliberately unlike anything a developer's global+ /// excludes would already list.+ #[test]+ fn path_is_git_ignored_follows_the_repository_rules() {+ let tmp = TempDir::new().unwrap();+ let repo = tmp.path().join("repo");+ let file = repo.join("notes").join("scratch.local");+ fs::create_dir_all(file.parent().unwrap()).unwrap();+ fs::write(&file, "x").unwrap();+ let status = std::process::Command::new("git")+ .args(["init", "-q", "-b", "main"])+ .current_dir(&repo)+ .status()+ .unwrap();+ assert!(status.success(), "git init failed");++ assert_eq!(path_is_git_ignored(&file), Some(false));+ fs::write(repo.join(".gitignore"), "notes/scratch.local\n").unwrap();+ assert_eq!(path_is_git_ignored(&file), Some(true));++ let plain = tmp.path().join("plain").join("scratch.local");+ fs::create_dir_all(plain.parent().unwrap()).unwrap();+ fs::write(&plain, "x").unwrap();+ assert_eq!(path_is_git_ignored(&plain), None);+ }+/// `MainRepoRoot` falls back to `Basename` semantics when no git/// repo lives at or above the path — never errors, never returns/// `("", None)`.diff --git a/crates/ai-memory-consolidate/src/lib.rs b/crates/ai-memory-consolidate/src/lib.rsindex 1156c977..91ff06e1 100644--- a/crates/ai-memory-consolidate/src/lib.rs+++ b/crates/ai-memory-consolidate/src/lib.rs@@ -56,7 +56,7 @@ pub use bootstrap::{Bootstrap, BootstrapConfig, BootstrapError, BootstrapOutcome, BootstrapSource,DEFAULT_CHUNK_INPUT_TOKENS, ProjectNameStrategy, SourceCounts, SourceKind, collect_sources,derive_project_name, discover_main_repo_root, discover_repo_root, effective_chunk_budget,- plan_bootstrap_chunks, prune_sources_to_budget, read_identity_remotes,+ path_is_git_ignored, plan_bootstrap_chunks, prune_sources_to_budget, read_identity_remotes,};pub use cold_cluster::{adaptive_eps, cosine_distance, dbscan};pub use compaction::build_compacted_markdown;