Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge remote-tracking branch 'upstream/release/2.5' into fix/autowire-run-env
Éverton Toffanetto407d55d0f875
diff --cc CHANGELOG.mdindex e28a61e6,044e8341..3493c199--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -154,22 -175,16 +176,31 @@@ and this project adheres to [Semantic Vcleanup; an explicit `session.moved` rebinds the live session to its newdirectory so its later end lands there. Checked against OpenCode 2.0.14. (#865)+ ### Changed+ - Quieted the default server log: the reconciliation-pass summary that fired+ every 30 s regardless of activity dropped from `info` to `debug`, and the+ default log filter now pins the external `rmcp` MCP SDK to `warn` (its+ per-request lifecycle logging at `info` was the other half of a near-empty+ server's log). Both are restorable through `log_level` (e.g.+ `"info,rmcp=info"` or `"debug"`) or `RUST_LOG`; the `tracing_appender=warn`+ feedback-loop guard stays non-overridable. (#894)+### Fixed+- `ai-memory run` auto-wired only the first config home per agent and+ version: its sentinel ignored where hooks and MCP were installed, so a second+ account (another exported `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, ...) was+ skipped. The sentinel now also keys on the resolved hook and MCP config+ paths. The Codex MCP entry ignored `CODEX_HOME`: `install-mcp` and auto-wire+ now write `$CODEX_HOME/config.toml`, matching `hooks.json`; `uninstall`+ sweeps the legacy `~/.codex/config.toml` too, and `install-hooks` still+ infers the server URL and token from it until the entry is rewritten. (#820)+- A whitespace-only `KIMI_CODE_HOME`, `KIRO_HOME` or `GROK_HOME` pointed+ installs at a blank-named directory under the working directory, and a+ whitespace-only relocation variable did the same for `ai-memory run`'s+ native session import. Blank now counts as unset everywhere, as it already+ did for the `CLAUDE_CONFIG_DIR`, `CODEX_HOME` and `PI_CODING_AGENT_DIR`+ installers, and `ai-memory run` drops such a value from the harness it+ launches so the harness uses its default home as well. (#820)- Native `ai-memory upgrade` no longer refuses every Linux install by probingthe running executable for write (Linux `ETXTBSY`); it only requires theparent directory to be writable for rename-based replace. (#802)diff --cc crates/ai-memory-cli/src/commands/run.rsindex 9b12e94f,7e53ceca..c3d78ca5--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@@ -17,7 -17,8 +17,8 @@@ use ai_memory_workstream::discover_native_session, export_transcript, has_native_session_selector, inspect_repository,kiro_explicit_session_id, kiro_harness_from_source_cursor, kiro_selects_non_default_engine,kiro_selects_v2_engine, kiro_selects_v3_engine, kiro_v3_resume_uses_default_store,- list_native_sessions, native_session_exists, store_override_vars, wait_for_transcript_flush,- list_native_sessions, native_session_exists, native_session_in_checkout,++ list_native_sessions, native_session_exists, native_session_in_checkout, store_override_vars,+ wait_for_transcript_flush,};use anyhow::{Context as _, Result, anyhow};use tokio::process::Command;diff --cc crates/ai-memory-cli/src/commands/run_autowire.rsindex 8fdcdeec,a6819a15..ffdefd50--- a/crates/ai-memory-cli/src/commands/run_autowire.rs+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs@@@ -420,19 -131,42 +420,39 @@@ pub(crate) fn ensure_wired_with// Not every hook-capable harness has an MCP client the installer can write// (e.g. Pi bridges MCP through its generated extension); skip those quietly.- if let Some(client) = install_hooks::mcp_client_for_agent(agent) {+ let mcp_failure = match installs.mcp {+ // The sentinel is version-keyed, so this whole step re-runs on every+ // upgrade. install-mcp replaces the `ai-memory` entry wholesale, so a+ // plain re-run would overwrite a session-aware Claude Code bridge the+ // user installed with `install-mcp --session-aware` back to static HTTP,- // silently disabling per_session for their MCP calls. Preserve it.- if install_mcp::existing_entry_is_session_aware(- client,- overrides.mcp_config_file.as_deref(),- "ai-memory",- ) {++ // silently disabling per_session for their MCP calls. Preserve it, in++ // the file this launch would write.++ Some(args)++ if install_mcp::existing_entry_is_session_aware(++ args.client,++ args.config_file.as_deref(),++ &args.name,++ ) =>++ {+ eprintln!(+ "ai-memory: keeping the existing session-aware {} MCP bridge; not \+ overwriting it with the static HTTP registration.",+ harness.as_str()+ );- } else if let Err(error) = install_mcp::run(- config,- InstallMcpArgs {- client,- server_url,- name: "ai-memory".to_string(),- auth_token,- apply: true,- config_file: overrides.mcp_config_file.clone(),- session_aware: false,- flavor: None,- },- ) {- eprintln!(- "ai-memory: could not auto-install the {} MCP server ({error:#}); continuing \- launch. Wire it manually with `ai-memory install-mcp --client {} --apply`.",- harness.as_str(),- agent.kind().as_str()- );++ None+ }+ Some(args) => install_mcp::run(config, args)+ .err()+ .map(|error| format!("{error:#}")),+ None => installs.mcp_skipped,+ };+ if let Some(reason) = mcp_failure {+ eprintln!(+ "ai-memory: could not auto-install the {} MCP server ({reason}); continuing \+ launch. Wire it manually with `ai-memory install-mcp --client {} --apply`.",+ harness.as_str(),+ agent.kind().as_str()+ );}// Record the attempt even on partial failure: re-applying an idempotent@@@ -513,506 -234,13 +533,516 @@@ mod testsclaude.file_name().and_then(|n| n.to_str())- .is_some_and(- |n| n.starts_with("claude-code-") && n.ends_with(env!("CARGO_PKG_VERSION"))- ),- "sentinel keys on agent + version: {claude:?}"+ .is_some_and(|n| n.starts_with(&prefix)),+ "sentinel names the agent and version first: {claude:?}"+ );+ }++ /// `--env CLAUDE_CONFIG_DIR=.claude-work` names a different home in each+ /// checkout, so the sentinel must key on the absolute path.+ #[test]+ fn a_relative_target_keys_on_its_absolute_path() {+ let relative = PathBuf::from(".claude-work").join("settings.json");+ let key = target_key(None, Some(&Ok(relative.clone())));+ assert!(Path::new(&key).is_absolute(), "{key}");+ assert!(Path::new(&key).ends_with(&relative), "{key}");+ }++ /// The planned installs for a launch, without running them.+ fn planned_installs(+ config: &Config,+ harness: ManagedHarness,+ run_env: &[(String, String)],+ ) -> WireInstalls {+ let overrides = WireOverrides::default();+ let targets = wire_targets(config, harness, &overrides, run_env).unwrap();+ wire_installs(config, targets, &overrides)+ }++ fn env_pair(name: &str, value: &Path) -> Vec<(String, String)> {+ vec![(name.to_string(), value.display().to_string())]+ }++ /// `run --env` moves a config home, so auto-wire must install where that+ /// harness will read. Only the plan is built: nothing is written, so a+ /// regression here cannot reach the developer's real config.+ #[test]+ fn run_env_points_hooks_and_mcp_at_the_relocated_config_home() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ let root = data.path().join("relocated");+ for (harness, var, hooks, mcp) in [+ (+ ManagedHarness::Claude,+ "CLAUDE_CONFIG_DIR",+ "settings.json",+ Some(".claude.json"),+ ),+ (+ ManagedHarness::Codex,+ "CODEX_HOME",+ "hooks.json",+ Some("config.toml"),+ ),+ (+ ManagedHarness::Pi,+ "PI_CODING_AGENT_DIR",+ "extensions/ai-memory-pi.ts",+ None,+ ),+ // OMP's `mcp.json` stays in `~/.omp/agent`, so nothing pins it.+ (+ ManagedHarness::Omp,+ "PI_CODING_AGENT_DIR",+ "extensions/ai-memory-omp.ts",+ None,+ ),+ (+ ManagedHarness::Kimi,+ "KIMI_CODE_HOME",+ "config.toml",+ Some("mcp.json"),+ ),+ (+ ManagedHarness::KiroV3,+ "KIRO_HOME",+ "hooks/ai-memory.json",+ Some("settings/mcp.json"),+ ),+ (+ ManagedHarness::Grok,+ "GROK_HOME",+ "hooks/ai-memory.json",+ Some("config.toml"),+ ),+ ] {+ let installs = planned_installs(&config, harness, &env_pair(var, &root));+ assert_eq!(installs.hooks.len(), 1, "{harness:?}");+ assert_eq!(+ installs.hooks[0].config_file,+ Some(root.join(hooks)),+ "{harness:?} hooks must follow --env {var}"+ );+ assert_eq!(+ installs.mcp.and_then(|args| args.config_file),+ mcp.map(|relative| root.join(relative)),+ "{harness:?} MCP must follow --env {var}"+ );+ }+ }++ /// `--env` wins over ai-memory's own environment, and an empty value still+ /// masks the process one, the same layering native-session resolution uses.+ #[test]+ fn launch_env_prefers_run_env_and_records_it() {+ let process_only = LaunchEnv::new(&[]);+ assert_eq!(process_only.var_os("PATH"), std::env::var_os("PATH"));+ assert!(!process_only.from_run_env.get());++ let run_env = [("PATH".to_string(), "/from-run-env".to_string())];+ let layered = LaunchEnv::new(&run_env);+ assert_eq!(+ layered.var_os("PATH"),+ Some(OsString::from("/from-run-env"))+ );+ assert!(layered.from_run_env.get());++ let empty = [("PATH".to_string(), String::new())];+ assert_eq!(LaunchEnv::new(&empty).var_os("PATH"), Some(OsString::new()));+ }++ /// A blank `--env` value masks the process one and counts as unset, so+ /// hooks, MCP and native session import all fall back to the defaults the+ /// installers pick on their own, never to a whitespace-named directory.+ #[test]+ fn blank_run_env_relocation_falls_back_to_defaults_everywhere() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ for (harness, vars) in [+ (ManagedHarness::Claude, &["CLAUDE_CONFIG_DIR"][..]),+ (ManagedHarness::Codex, &["CODEX_HOME"][..]),+ (+ ManagedHarness::Pi,+ &["PI_CODING_AGENT_SESSION_DIR", "PI_CODING_AGENT_DIR"][..],+ ),+ (ManagedHarness::Omp, &["PI_CODING_AGENT_DIR"][..]),+ (ManagedHarness::Kimi, &["KIMI_CODE_HOME"][..]),+ (ManagedHarness::KiroV3, &["KIRO_HOME"][..]),+ (ManagedHarness::Grok, &["GROK_HOME"][..]),+ ] {+ let run_env: Vec<_> = vars+ .iter()+ .map(|name| (name.to_string(), " ".to_string()))+ .collect();+ let agent = agent_choice_for_harness(harness).unwrap();+ let installs = planned_installs(&config, harness, &run_env);+ assert_eq!(+ installs.hooks[0].config_file,+ install_hooks::hook_config_target_with(agent, &|_| None).ok(),+ "{harness:?} hooks"+ );+ // OMP's `mcp.json` reads no relocation variable, so nothing pins it.+ if let Some(client) = install_hooks::mcp_client_for_agent(agent)+ && harness != ManagedHarness::Omp+ {+ assert_eq!(+ installs.mcp.and_then(|args| args.config_file),+ install_mcp::mcp_config_path_with(client, &|_| None).ok(),+ "{harness:?} MCP"+ );+ }+ let plan = ai_memory_workstream::build_launch_plan_with_env(+ harness,+ None,+ Vec::new(),+ None,+ &run_env,+ )+ .unwrap();+ assert_eq!(plan.session_dir, None, "{harness:?} session store");+ }+ }++ /// `run pi|omp --env PI_CODING_AGENT_DIR=...` can put both agents in one+ /// extensions directory that ai-memory's own environment never sees, so+ /// auto-wire must report the double capture itself.+ #[test]+ fn run_env_shared_pi_family_dir_is_reported() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ let root = data.path().join("pi-family");+ let overrides = WireOverrides::default();+ for harness in [ManagedHarness::Pi, ManagedHarness::Omp] {+ let shared = |run_env: &[(String, String)]| {+ wire_targets(&config, harness, &overrides, run_env)+ .unwrap()+ .shared_extensions_dir+ };+ assert_eq!(+ shared(&env_pair("PI_CODING_AGENT_DIR", &root)),+ Some(root.join("extensions")),+ "{harness:?}"+ );+ }+ assert_eq!(+ wire_targets(+ &config,+ ManagedHarness::Claude,+ &overrides,+ &env_pair("PI_CODING_AGENT_DIR", &root)+ )+ .unwrap()+ .shared_extensions_dir,+ None+ );+ }++ /// The test guard plans only installs whose target is an explicit path+ /// under its root, so a test that drives `run` without injected paths+ /// cannot reach the real home, including through a relocation that+ /// resolves back to it.+ #[test]+ fn confined_installs_refuse_targets_outside_the_root() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ let overrides = WireOverrides {+ confine_to: Some(data.path().to_path_buf()),+ ..WireOverrides::default()+ };+ let plan = |harness: ManagedHarness, run_env: &[(String, String)]| {+ let targets = wire_targets(&config, harness, &overrides, run_env).unwrap();+ wire_installs(&config, targets, &overrides)+ };+ let blank = [("CLAUDE_CONFIG_DIR".to_string(), " ".to_string())];+ let profiled = [("OMP_PROFILE".to_string(), "work".to_string())];+ let escaping = env_pair(+ "CLAUDE_CONFIG_DIR",+ &data.path().join("..").join("elsewhere"),+ );+ for (harness, run_env) in [+ (ManagedHarness::Claude, &[][..]),+ (ManagedHarness::Claude, &blank[..]),+ (ManagedHarness::Omp, &profiled[..]),+ (ManagedHarness::Claude, &escaping[..]),+ ] {+ let refused = plan(harness, run_env);+ assert!(refused.hooks.is_empty(), "{harness:?} {run_env:?}");+ assert!(refused.mcp.is_none(), "{harness:?} {run_env:?}");+ assert!(+ refused.hooks_skipped.is_some() && refused.mcp_skipped.is_some(),+ "{harness:?} {run_env:?}"+ );+ }++ let root = data.path().join("claude-home");+ let pinned = plan(+ ManagedHarness::Claude,+ &env_pair("CLAUDE_CONFIG_DIR", &root),+ );+ assert_eq!(pinned.hooks.len(), 1);+ assert_eq!(+ pinned.hooks[0].config_file,+ Some(root.join("settings.json"))+ );+ assert_eq!(+ pinned.mcp.and_then(|args| args.config_file),+ Some(root.join(".claude.json")));+ assert_eq!(pinned.hooks_skipped, None);+ assert_eq!(pinned.mcp_skipped, None);}+ /// A symlink under the root leads out of it, and a dangling one would be+ /// written through, so neither counts as inside.+ #[cfg(unix)]+ #[test]+ fn confined_installs_refuse_symlinks_out_of_the_root() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let outside = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ let overrides = WireOverrides {+ confine_to: Some(data.path().to_path_buf()),+ ..WireOverrides::default()+ };+ let linked = data.path().join("linked");+ std::os::unix::fs::symlink(outside.path(), &linked).unwrap();+ let dangling = data.path().join("dangling");+ std::os::unix::fs::symlink(outside.path().join("missing"), &dangling).unwrap();+ let inside = data.path().join("inside");+ std::fs::create_dir(&inside).unwrap();+ let looped = data.path().join("looped");+ std::os::unix::fs::symlink(&inside, &looped).unwrap();+ let plan = |dir: &Path| {+ let run_env = env_pair("CLAUDE_CONFIG_DIR", dir);+ let targets =+ wire_targets(&config, ManagedHarness::Claude, &overrides, &run_env).unwrap();+ wire_installs(&config, targets, &overrides)+ };+ let detour = data.path().join("missing").join("..").join("linked");+ for dir in [+ &linked,+ &dangling,+ &linked.join("..").join("elsewhere"),+ &detour,+ ] {+ let refused = plan(dir);+ assert!(refused.hooks.is_empty(), "{dir:?}");+ assert!(refused.mcp.is_none(), "{dir:?}");+ }+ let kept = plan(&looped);+ assert_eq!(kept.hooks.len(), 1);+ assert!(kept.mcp.is_some());+ }++ /// Without `--env` relocating anything, auto-wire leaves target selection to+ /// the installers, exactly as before `--env` reached it.+ #[test]+ fn without_a_relocating_run_env_the_installers_pick_their_own_targets() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ let unrelated = [("SOME_PROVIDER_KEY".to_string(), "x".to_string())];+ for run_env in [&[][..], &unrelated[..]] {+ for harness in [ManagedHarness::Claude, ManagedHarness::Codex] {+ let installs = planned_installs(&config, harness, run_env);+ assert_eq!(installs.hooks.len(), 1);+ assert_eq!(installs.hooks[0].config_file, None, "{harness:?}");+ assert_eq!(+ installs.mcp.and_then(|args| args.config_file),+ None,+ "{harness:?}"+ );+ }+ }+ }++ #[test]+ fn each_config_home_gets_its_own_sentinel() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ let overrides = WireOverrides::default();+ let sentinel = |dir: &str| {+ let run_env = env_pair("CLAUDE_CONFIG_DIR", &data.path().join(dir));+ wire_targets(&config, ManagedHarness::Claude, &overrides, &run_env)+ .unwrap()+ .sentinel+ };+ assert_eq!(sentinel("work"), sentinel("work"));+ assert_ne!(+ sentinel("work"),+ sentinel("personal"),+ "a second account must not reuse the first account's sentinel"+ );+ }++ /// The multi-account sentinel bug: wiring one config home used to mark the+ /// agent as wired for every other one. Both paths are injected, so the real+ /// installers run without leaving the temp dirs; how `--env` picks those+ /// paths is covered by the plan tests above.+ #[test]+ fn a_second_config_home_is_wired_after_the_first() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ let account = |name: &str| {+ let dir = data.path().join(name);+ std::fs::create_dir_all(&dir).unwrap();+ WireOverrides {+ hooks_dir: Some(repo_hooks()),+ hooks_config_file: Some(dir.join("settings.json")),+ mcp_config_file: Some(dir.join(".claude.json")),+ ..WireOverrides::default()+ }+ };+ let work = account("work");+ let personal = account("personal");+ ensure_wired_with(&config, ManagedHarness::Claude, &work, &[]);+ ensure_wired_with(&config, ManagedHarness::Claude, &personal, &[]);+ for overrides in [&work, &personal] {+ let settings = overrides.hooks_config_file.as_ref().unwrap();+ let mcp = overrides.mcp_config_file.as_ref().unwrap();+ assert!(+ std::fs::read_to_string(settings)+ .is_ok_and(|s| s.contains("ai-memory") || s.contains("ai_memory")),+ "hooks missing in {}",+ settings.display()+ );+ assert!(+ std::fs::read_to_string(mcp).is_ok_and(|s| s.contains("ai-memory")),+ "MCP missing in {}",+ mcp.display()+ );+ }+ }++ /// Kiro CLI v2 has no single hook file: a relocated home is expanded into one+ /// install per existing agent config, and an empty one is reported instead+ /// of silently wiring nothing.+ #[test]+ fn kiro_v2_relocated_by_run_env_wires_each_agent_config() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ let kiro_home = data.path().join("kiro");+ let agents = kiro_home.join("agents");+ std::fs::create_dir_all(&agents).unwrap();+ let run_env = env_pair("KIRO_HOME", &kiro_home);++ let empty = planned_installs(&config, ManagedHarness::Kiro, &run_env);+ assert!(empty.hooks.is_empty());+ assert!(+ empty+ .hooks_skipped+ .as_deref()+ .is_some_and(|reason| reason.contains("no Kiro CLI agent configs")),+ "an empty relocated agents dir must be reported: {:?}",+ empty.hooks_skipped+ );++ for name in ["default.json", "review.json"] {+ std::fs::write(agents.join(name), "{}").unwrap();+ }+ std::fs::write(agents.join("notes.txt"), "not an agent").unwrap();+ let installs = planned_installs(&config, ManagedHarness::Kiro, &run_env);+ let mut files: Vec<_> = installs+ .hooks+ .iter()+ .filter_map(|args| args.config_file.clone())+ .collect();+ files.sort();+ assert_eq!(+ files,+ vec![agents.join("default.json"), agents.join("review.json")]+ );+ assert_eq!(installs.hooks_skipped, None);+ assert_eq!(+ installs.mcp.and_then(|args| args.config_file),+ Some(kiro_home.join("settings").join("mcp.json"))+ );+ }++ /// The autowire target table must agree with the default each installer+ /// resolves on its own, or the sentinel would key on a path nothing writes.+ #[test]+ fn every_auto_wired_agent_resolves_its_installer_default() {+ let process_env = |name: &str| std::env::var_os(name);+ for (agent, installer_default) in [+ (+ AgentChoice::ClaudeCode,+ install_hooks::claude_settings_path(),+ ),+ (AgentChoice::Codex, install_hooks::codex_hooks_path()),+ (AgentChoice::OpenCode, install_hooks::opencode_plugin_path()),+ (+ AgentChoice::OpenCode2,+ install_hooks::opencode2_plugin_path(),+ ),+ (AgentChoice::Pi, install_hooks::pi_extension_path()),+ (AgentChoice::Omp, install_hooks::omp_extension_path(None)),+ (+ AgentChoice::KimiCode,+ install_hooks::kimi_code_config_path(),+ ),+ (+ AgentChoice::CommandCode,+ install_hooks::command_code_settings_path(),+ ),+ (AgentChoice::KiroCli, install_hooks::kiro_cli_agents_dir()),+ (+ AgentChoice::KiroCliV3,+ install_hooks::kiro_cli_v3_hooks_path(),+ ),+ (AgentChoice::Grok, install_hooks::grok_hooks_path()),+ (+ AgentChoice::AntigravityCli,+ install_hooks::antigravity_hooks_path(),+ ),+ ] {+ assert_eq!(+ install_hooks::hook_config_target_with(agent, &process_env).ok(),+ installer_default.ok(),+ "{agent:?}"+ );+ }+ for harness in [+ ManagedHarness::Claude,+ ManagedHarness::Codex,+ ManagedHarness::OpenCode,+ ManagedHarness::OpenCode2,+ ManagedHarness::Pi,+ ManagedHarness::Omp,+ ManagedHarness::Kimi,+ ManagedHarness::CommandCode,+ ManagedHarness::Kiro,+ ManagedHarness::KiroV3,+ ManagedHarness::Grok,+ ManagedHarness::Antigravity,+ ] {+ let agent = agent_choice_for_harness(harness).unwrap();+ assert!(+ install_hooks::hook_config_target_with(agent, &|_| None).is_ok()+ || crate::commands::path_util::home_dir().is_none(),+ "{harness:?} is auto-wired but has no hook target"+ );+ }+ }+++ const SESSION_AWARE_BRIDGE: &str = r#"{++ "mcpServers": {++ "ai-memory": {++ "type": "stdio",++ "command": "ai-memory",++ "args": ["mcp-bridge", "--server-url", "http://127.0.0.1:49374/mcp"]++ }++ }++}"#;++fn test_config(home: &Path, data_dir: &Path) -> Config {let mut config = Config::load(None, Some(home.to_path_buf())).unwrap();config.data_dir = data_dir.to_path_buf();@@@ -1088,6 -312,59 +1118,93 @@@);}+ /// Auto-wire must not downgrade a deliberately-installed session-aware+ /// bridge to static HTTP. The sentinel is version-keyed, so this step+ /// re-runs on every upgrade; without the guard that re-run rewrites the+ /// Claude Code MCP entry wholesale, silently disabling the per_session+ /// isolation the user opted into with `install-mcp --session-aware`.+ #[test]+ fn wiring_preserves_an_existing_session_aware_bridge() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let settings = data.path().join("claude-settings.json");+ std::fs::write(&settings, "{}").unwrap();+ let mcp = data.path().join("claude.json");- let bridge = r#"{- "mcpServers": {- "ai-memory": {- "type": "stdio",- "command": "ai-memory",- "args": ["mcp-bridge", "--server-url", "http://127.0.0.1:49374/mcp"]- }- }-}"#;- std::fs::write(&mcp, bridge).unwrap();++ std::fs::write(&mcp, SESSION_AWARE_BRIDGE).unwrap();++ let config = test_config(home.path(), data.path());+ let overrides = WireOverrides {+ hooks_dir: Some(repo_hooks()),+ hooks_config_file: Some(settings.clone()),+ mcp_config_file: Some(mcp.clone()),++ ..WireOverrides::default()+ };- ensure_wired_with(&config, ManagedHarness::Claude, &overrides);++ ensure_wired_with(&config, ManagedHarness::Claude, &overrides, &[]);++ let mcp_json = std::fs::read_to_string(&mcp).unwrap();+ let entry: serde_json::Value = serde_json::from_str(&mcp_json).unwrap();+ let server = &entry["mcpServers"]["ai-memory"];+ assert_eq!(+ server["type"].as_str(),+ Some("stdio"),+ "auto-wire must keep the session-aware bridge, not downgrade it to http: {mcp_json}"+ );+ assert!(+ server["args"]+ .as_array()+ .is_some_and(|args| args.iter().any(|arg| arg == "mcp-bridge")),+ "the preserved entry must still be the mcp-bridge: {mcp_json}"+ );+ // The hooks still install, and the attempt is still recorded, so a plain+ // re-launch stays gated.+ assert!(- sentinel_path(&config.data_dir, AgentChoice::ClaudeCode).exists(),++ wire_targets(&config, ManagedHarness::Claude, &overrides, &[])++ .unwrap()++ .sentinel++ .exists(),+ "the attempt must be recorded even when the MCP bridge is preserved"+ );+ }+++ /// Under `--env CLAUDE_CONFIG_DIR` the guard reads the relocated++ /// `.claude.json` this launch writes, not the default one, so a bridge++ /// installed for that account is kept too.++ #[test]++ fn wiring_preserves_a_session_aware_bridge_in_the_relocated_home() {++ let home = tempfile::tempdir().unwrap();++ let data = tempfile::tempdir().unwrap();++ let root = data.path().join("claude-home");++ std::fs::create_dir_all(&root).unwrap();++ let mcp = root.join(".claude.json");++ std::fs::write(&mcp, SESSION_AWARE_BRIDGE).unwrap();++++ let config = test_config(home.path(), data.path());++ let overrides = WireOverrides {++ hooks_dir: Some(repo_hooks()),++ confine_to: Some(data.path().to_path_buf()),++ ..WireOverrides::default()++ };++ ensure_wired_with(++ &config,++ ManagedHarness::Claude,++ &overrides,++ &env_pair("CLAUDE_CONFIG_DIR", &root),++ );++++ let mcp_json = std::fs::read_to_string(&mcp).unwrap();++ let entry: serde_json::Value = serde_json::from_str(&mcp_json).unwrap();++ assert_eq!(++ entry["mcpServers"]["ai-memory"]["type"].as_str(),++ Some("stdio"),++ "the relocated session-aware bridge must be kept: {mcp_json}"++ );++ assert!(++ std::fs::read_to_string(root.join("settings.json"))++ .is_ok_and(|s| s.contains("ai-memory") || s.contains("ai_memory")),++ "the hooks still install in the relocated home"++ );++ }++/// A harness with no installer support (Crush) is skipped before anything is/// written — no config touched, no sentinel churn.#[test]