Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(run): wire hooks and MCP where the launch environment points
Éverton Toffanetto6295dd814ba0
diff --git a/AGENTS.md b/AGENTS.mdindex eb36ae4c..c878a31d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -582,8 +582,9 @@ Additional boundary rules:- [`docs/install.md`](docs/install.md) — installation cookbook for everysupported agent client.- [`docs/cookbook.md`](docs/cookbook.md) — task-oriented cheat sheet: "I want- to do X" → how (recall, durable rules, importing a knowledge base, two agents- working together).+ to do X" → how (recall, durable rules and must-read docs, importing a+ knowledge base, retention, two agents working together, several accounts or+ an external launcher via `run --env`, the Mac app, CLI, troubleshooting).- [`docs/comparison.md`](docs/comparison.md) — fair, user-facing comparisonagainst other memory tools (camps, migration notes, how the field validatesthe file-first/pages-over-facts approach). Analysis behind it:diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 653feca1..9595d4ab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,10 +14,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0callers who previously had to wrap the launch in `env KEY=VAL harness`.Both flags are wrapper-owned like `--yolo`/`--executable` and must precedethe harness name; a `--env` entry overrides a same-key `--env-file` line.- The resolved environment reaches both the spawned process and ai-memory's- own native-session resolution, so the two agree on where a- `CLAUDE_CONFIG_DIR`-style override points the session store. See- `docs/managed-workstreams.md`. (#820)+ The resolved environment reaches the spawned process, ai-memory's own+ native-session resolution, first-launch auto-wire and the global Crush+ config the managed context packet is layered onto, so the session store,+ hooks and MCP all follow a `CLAUDE_CONFIG_DIR`-style override, and+ auto-wire warns when the override puts Pi and OMP in one extensions+ directory. See `docs/managed-workstreams.md`. (#820)- `contradiction_band_min` / `contradiction_band_max` config keys (env:`AI_MEMORY_CONTRADICTION_BAND_MIN` / `AI_MEMORY_CONTRADICTION_BAND_MAX`)make `memory_lint`'s A5 zero-LLM contradiction-detection cosine-similarity@@ -99,6 +101,80 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0capture suppression, like the other context-delivery events. (#840)### 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)+- OMP paths now follow OMP's own profile rules. A named profile (`--profile`,+ `OMP_PROFILE`, or the legacy `PI_PROFILE`, previously ignored) owns+ `~/.omp/profiles/<name>/agent` and ignores `PI_CODING_AGENT_DIR`, as OMP+ does; `install-hooks` wrote the extension into `PI_CODING_AGENT_DIR`+ instead, where that OMP never loads it. An empty, whitespace or `default`+ profile selects the default profile rather than a `profiles/default` or+ blank-named directory, a `PI_CODING_AGENT_DIR` a parent OMP derived for its+ profile no longer leaks into the default profile, and a name OMP refuses is+ refused. `install-mcp+ --client omp` and auto-wire write `mcp.json` into the same agent dir instead+ of always `~/.omp/agent`; `ai-memory run omp` imports sessions from it and+ honors `PI_CODING_AGENT_SESSION_DIR` and a leading native `--profile`; `uninstall`+ sweeps the active, default-profile and `~/.omp/agent` locations and no+ longer aborts every agent's cleanup on an invalid profile name. ai-memory+ also follows OMP's `PI_CONFIG_DIR`, which renames the `~/.omp` root (joined+ under the home, as OMP joins it), for profiles, the extension, `mcp.json`,+ session import and the `uninstall` sweep, which still covers the `~/.omp`+ locations earlier releases wrote to; and on Linux and macOS `ai-memory run+ omp`, `backfill` and `doctor` read sessions from `$XDG_DATA_HOME/omp/sessions`+ (`$XDG_DATA_HOME/omp/profiles/<name>/sessions` for a named profile) when+ that OMP directory exists and the agent dir is not relocated, as OMP does.+ (#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. Crush's managed+ context likewise read a whitespace-only `CRUSH_GLOBAL_CONFIG` or+ `XDG_CONFIG_HOME` as a directory, and now falls back to the default global+ config. (#820)+- `ai-memory uninstall` left `ai-memory run`'s auto-wire sentinels in+ `<data_dir>/autowire-state/`, so after the hooks were removed the next+ managed launch of that harness on the same binary version skipped wiring and+ captured nothing. Removing hooks or MCP (a full uninstall, `--only hooks` or+ `--only mcp`) now deletes every sentinel and lists them in the dry-run plan.+ `--only mcp`, `--only instructions` and `--only skills` also no longer delete+ the stored hook bearer that the still-installed hooks read. (#820)+- A managed Crush launch with a context packet dropped the `CRUSH.md` and+ `AGENTS.md` Crush loads by default: Crush only adds them while+ `global_context_paths` is empty, and the packet filled it. The launcher now+ adds them first when the user's config lists none, and no longer refuses to+ start over a global `crush.json` Crush accepts (an empty file, `null`, or+ `null` options), read from the path cleaned as Crush cleans it. The global+ `crushrc` beside that config, which Crush stopped reading once the config+ dir moved, is now sourced from its own directory as well. (#820)+- Two fresh managed launches in one checkout could import each other's+ transcript: after exit, `ai-memory run` took the newest session there even+ when a hook in the child had already linked the run's own session. The+ hook-linked session now wins when this checkout's store holds it (a process+ the child starts inherits the run id). Crush, which has no hooks, claims only the+ one top-level session created during a fresh run and imports nothing, with+ a warning, when another launch created one too; its title and sub-agent+ sessions are no longer taken for the conversation, and in a data directory+ outside the project only a session that edited a file in the project is+ claimed. (#820)+- `ai-memory run crush`, `backfill` and `doctor` looked for Crush sessions only+ in `<cwd>/.crush/crush.db`, so a launch from a project subdirectory, or a+ project whose Crush config sets `options.data_directory`, imported nothing.+ They now find the store as Crush does: `options.data_directory` from Crush's+ JSON configs, else the closest `.crush` up to the git worktree root (not one+ directly in the home), else `<cwd>/.crush`. (#820)+- A Kiro v3 resume that falls back to the default session store drops+ `KIRO_HOME` from the child, but auto-wire still installed hooks and MCP+ under `KIRO_HOME`; it now wires the default home that resume reads. (#820)- `memory_query`'s vector stream called the generic `Embedder::embed`instead of `embed_query` on the configured embedder, so aquery/document-asymmetric embedder (Google's task-typed embeddings, ordiff --git a/Cargo.lock b/Cargo.lockindex 8c08bbf3..cb412005 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -60,6 +60,7 @@ dependencies = ["reqwest 0.12.28","rmcp","rstest",+ "rusqlite","rustls","secrecy","serde",diff --git a/README.md b/README.mdindex b251315e..5b328f54 100644--- a/README.md+++ b/README.md@@ -344,7 +344,8 @@ way to launch: the first time it runs a harness it auto-installs that harness'sai-memory hooks + MCP if they are missing (so capture and recall just work —no separate `install-hooks`/`install-mcp` step to forget), it wires the rightproject scope by construction, and it adds cross-harness *session* continuity on-top of shared memory. Everything is idempotent and one-time per harness.+top of shared memory. Everything is idempotent and one-time per harness and+config home.```bashai-memory run claude@@ -358,7 +359,9 @@ Auto-wiring is on by default; opt out with `ai-memory run --no-autowire` or`ai-memory run`).`ai-memory uninstall --apply` removes everything ai-memory installed,-and only what it installed. Install commands are idempotent and write+and only what it installed. It also clears `ai-memory run`'s auto-wire+record, so the next managed launch wires that harness again; to keep it+unwired, launch with `--no-autowire` or set `AI_MEMORY_RUN_AUTOWIRE=false`. Install commands are idempotent and writetimestamped backups next to any file they touch.## Everyday usediff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.tomlindex 0bb989a9..a2bf90ca 100644--- a/crates/ai-memory-cli/Cargo.toml+++ b/crates/ai-memory-cli/Cargo.toml@@ -93,6 +93,7 @@ tempfile.workspace = trueai-memory-test-support.workspace = truetempfile.workspace = truerstest.workspace = true+rusqlite.workspace = truetower.workspace = truetokio = { workspace = true, features = ["test-util"] }diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 94eb1d9f..38b0ac78 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -263,15 +263,16 @@ pub struct RunArgs {pub no_autowire: bool,/// Extra environment variable for the spawned harness, `KEY=VALUE`./// Repeatable; wrapper-owned like `--yolo`/`--executable`, so it must- /// precede `harness`. Reaches both the spawned process and ai-memory's own- /// native-session resolution (e.g. `CLAUDE_CONFIG_DIR`), so the two agree- /// on where the harness's session lives. A later `--env` wins over an- /// earlier one and over a same-key `--env-file` entry.+ /// precede `harness`. Reaches the spawned process, ai-memory's own+ /// native-session resolution and first-launch auto-wire (e.g.+ /// `CLAUDE_CONFIG_DIR`), so session store, hooks and MCP agree on one+ /// config home. A later `--env` wins over an earlier one and over a+ /// same-key `--env-file` entry.#[arg(long = "env", value_parser = parse_env_kv, value_name = "KEY=VALUE")]pub env: Vec<(String, String)>,/// Read `KEY=VALUE` lines from this file (blank lines and `#` comments- /// skipped) and merge them into the spawned harness's environment before- /// `--env` entries, which override a same-key line here.+ /// skipped) and merge them into the launch environment (same reach as+ /// `--env`) before `--env` entries, which override a same-key line here.#[arg(long = "env-file", value_name = "PATH")]pub env_file: Option<PathBuf>,/// Agent harness to launch. When omitted, continue the newest managed or@@ -994,8 +995,9 @@ pub struct UninstallArgs {/// Skip the interactive confirmation when a TTY is attached.#[arg(long)]pub yes: bool,- /// Profile to use for OMP extensions, which relocates the path to- /// `~/.omp/profiles/<profile>/agent/extensions/`.+ /// OMP profile whose extension and MCP entry to remove, as `omp+ /// --profile` names it. Beats `OMP_PROFILE` and `PI_PROFILE`; the default+ /// profile's files are swept as well.#[arg(long)]pub profile: Option<String>,}@@ -1648,8 +1650,9 @@ pub enum AgentChoice {/// lifecycle capture and bridges ai-memory's HTTP MCP tools into Pi.Pi,/// Oh My Pi (`omp`) — TypeScript extension- /// under `~/.omp/agent/extensions/`. `--apply` writes the extension- /// file directly; restart `omp` for it to load.+ /// under `~/.omp/agent/extensions/`, or the active profile's agent dir.+ /// `--apply` writes the extension file directly; restart `omp` for it to+ /// load.#[value(alias = "oh-my-pi")]Omp,/// OpenClaw personal AI gateway — native plugin package with@@ -1887,7 +1890,7 @@ impl SchemaFlavor {pub enum McpClient {/// Anthropic Claude Code — `claude mcp add`.ClaudeCode,- /// OpenAI Codex CLI — `~/.codex/config.toml`.+ /// OpenAI Codex CLI — `$CODEX_HOME/config.toml` (default `~/.codex/config.toml`).Codex,/// OpenCode — `opencode.json`. Accepts `opencode` (no hyphen) as/// an alias for symmetry with `AgentChoice` and the on-disk@@ -1913,7 +1916,8 @@ pub enum McpClient {/// Real Pi coding agent. Uses ai-memory's generated bridge extension/// because Pi has no native MCP config.Pi,- /// Oh My Pi (`omp`) — `~/.omp/agent/mcp.json`.+ /// Oh My Pi (`omp`) — `~/.omp/agent/mcp.json`, or the active profile's+ /// agent dir.#[value(alias = "oh-my-pi")]Omp,/// Google Antigravity CLI (`agy`) — `~/.gemini/config/mcp_config.json`.@@ -2416,8 +2420,9 @@ pub struct InstallHooksArgs {/// `--no-capture-prompts` install. Only valid for Claude Code.#[arg(long, conflicts_with = "no_capture_prompts")]pub capture_prompts: bool,- /// Profile to use for OMP extensions, which relocates the path to- /// `~/.omp/profiles/<profile>/agent/extensions/`.+ /// OMP profile to install into, as `omp --profile` names it:+ /// `~/.omp/profiles/<profile>/agent/extensions/`. Beats `OMP_PROFILE` and+ /// `PI_PROFILE`; `default` selects the default profile.#[arg(long)]pub profile: Option<String>,}diff --git a/crates/ai-memory-cli/src/commands/backfill.rs b/crates/ai-memory-cli/src/commands/backfill.rsindex 4d322719..e8a3aede 100644--- a/crates/ai-memory-cli/src/commands/backfill.rs+++ b/crates/ai-memory-cli/src/commands/backfill.rs@@ -40,8 +40,8 @@ use serde::{Deserialize, Serialize};use ai_memory_core::{NewWorkstreamEvent, WorkstreamEventKind};use ai_memory_workstream::{- ManagedHarness, build_launch_plan, export_transcript, list_native_sessions,- wait_for_transcript_flush,+ LaunchRoots, ManagedHarness, build_launch_plan_with_env, export_transcript,+ list_native_sessions, wait_for_transcript_flush,};use super::doctor::SCANNED_HARNESSES;@@ -270,9 +270,11 @@ async fn collect_local_sessions() -> Vec<SessionRef> {let mut out = Vec::new();for &harness in SCANNED_HARNESSES {- let session_dir = build_launch_plan(harness, None, Vec::new(), None)- .ok()- .and_then(|plan| plan.session_dir);+ let roots = LaunchRoots { home, cwd };+ let session_dir =+ build_launch_plan_with_env(harness, None, Vec::new(), None, &[], Some(roots))+ .ok()+ .and_then(|plan| plan.session_dir);let Ok(sessions) = list_native_sessions(harness,home,@@ -328,9 +330,11 @@ async fn import_one(cwd: &Path,session: &SessionRef,) -> Result<usize> {- let session_dir = build_launch_plan(session.harness, None, Vec::new(), None)- .ok()- .and_then(|plan| plan.session_dir);+ let roots = LaunchRoots { home, cwd };+ let session_dir =+ build_launch_plan_with_env(session.harness, None, Vec::new(), None, &[], Some(roots))+ .ok()+ .and_then(|plan| plan.session_dir);// These are historical sessions, so the flush wait is a quick no-op; ignore// its result and read whatever is on disk.let _ = wait_for_transcript_flush(diff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rsindex 97c5d81b..785e14e0 100644--- a/crates/ai-memory-cli/src/commands/doctor.rs+++ b/crates/ai-memory-cli/src/commands/doctor.rs@@ -27,7 +27,9 @@ use anyhow::{Context, Result};use serde::{Deserialize, Serialize};use ai_memory_core::AgentKind;-use ai_memory_workstream::{ManagedHarness, build_launch_plan, list_native_sessions};+use ai_memory_workstream::{+ LaunchRoots, ManagedHarness, build_launch_plan_with_env, list_native_sessions,+};use crate::config::Config;use crate::http_client::{ServerEndpoint, get_json};@@ -181,9 +183,11 @@ pub(crate) async fn scan_local(home: &Path, cwd: &Path, since_days: u32) -> Vec<// Honor harness home relocations (CODEX_HOME, KIMI_CODE_HOME, …) via the// same launch-plan resolver `ai-memory run` uses; fall back to the// default $HOME-relative store when a probe plan cannot be built.- let session_dir = build_launch_plan(harness, None, Vec::new(), None)- .ok()- .and_then(|plan| plan.session_dir);+ let roots = LaunchRoots { home, cwd };+ let session_dir =+ build_launch_plan_with_env(harness, None, Vec::new(), None, &[], Some(roots))+ .ok()+ .and_then(|plan| plan.session_dir);let Ok(sessions) =list_native_sessions(harness, home, cwd, session_dir.as_deref(), SCAN_LIMIT).awaitelse {diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 7e35448b..6862416d 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -188,7 +188,14 @@ pub(crate) fn antigravity_hooks_path() -> anyhow::Result<std::path::PathBuf> {/// `~/.grok/hooks/ai-memory.json` — Grok Build CLI lifecycle hooks.pub(crate) fn grok_hooks_path() -> anyhow::Result<std::path::PathBuf> {- Ok(install_mcp::grok_home()?+ grok_hooks_path_in(std::env::var_os("GROK_HOME"))+}++/// [`grok_hooks_path`] with the `GROK_HOME` value passed in.+fn grok_hooks_path_in(+ env_override: Option<std::ffi::OsString>,+) -> anyhow::Result<std::path::PathBuf> {+ Ok(install_mcp::grok_home_in(env_override)?.join("hooks").join("ai-memory.json"))}@@ -245,56 +252,31 @@ pub(crate) fn opencode_plugin_path() -> anyhow::Result<std::path::PathBuf> {.join("ai-memory.ts"))}-/// `$PI_CODING_AGENT_DIR/extensions/ai-memory.ts` when the var is set, else-/// `~/.omp/agent/extensions/ai-memory.ts` — OMP lifecycle extension.+/// OMP lifecycle extension at `<agent dir>/extensions/ai-memory-omp.ts`. The+/// agent dir is OMP's own ([`ai_memory_workstream::omp_agent_dir`]):+/// `~/.omp/profiles/<name>/agent` for a named profile (`--profile`, then+/// `OMP_PROFILE`, then `PI_PROFILE`), else `$PI_CODING_AGENT_DIR`, else+/// `~/.omp/agent`, with `~/.omp` renamed by `PI_CONFIG_DIR`. XDG never moves+/// it: OMP only relocates sessions there.///-/// `PI_CODING_AGENT_DIR` relocates OMP's whole agent config home-/// (`~/.omp/agent`), so extensions written to the default path are never-/// loaded by an OMP configured that way: capture silently does nothing, with-/// a successful-looking install. ai-memory already honors the variable when-/// it resolves OMP transcripts (`ManagedHarness::Omp` in-/// `ai-memory-workstream`), so ignoring it here left one half of the same-/// install pointing somewhere the other half did not.+/// OMP loads extensions only from that directory, so an extension written+/// anywhere else is never loaded: capture silently does nothing, with a+/// successful-looking install. Session import resolves OMP transcripts through+/// the same agent dir, so both halves of an install agree on it.pub(crate) fn omp_extension_path(profile: Option<&str>) -> anyhow::Result<std::path::PathBuf> {- // Bind the OsString before borrowing from it: `var_os(..).as_ref()` in a- // single expression drops the temporary at the end of the statement.- let env_profile = std::env::var_os("OMP_PROFILE");- let profile = profile.or_else(|| env_profile.as_ref().and_then(|s| s.to_str()));- omp_extension_path_in(std::env::var_os("PI_CODING_AGENT_DIR"), profile)+ omp_extension_path_with(profile, &|name| std::env::var_os(name))}-/// The env value comes in as a parameter so tests can exercise both branches-/// without mutating process env (mirrors [`codex_hooks_path_in`]).-fn omp_extension_path_in(- env_override: Option<std::ffi::OsString>,+/// The env comes in as a parameter so tests can exercise every branch without+/// mutating process env (mirrors [`codex_hooks_path_in`]).+fn omp_extension_path_with(profile: Option<&str>,+ env: &dyn Fn(&str) -> Option<std::ffi::OsString>,) -> anyhow::Result<std::path::PathBuf> {- // Precedence: `PI_CODING_AGENT_DIR` wins over `--profile`.- //- // OMP documents each separately — the variable "can override the agent- // directory", and `--profile <name>` moves it to- // `~/.omp/profiles/<name>/agent` — but does not define what happens when- // both are set. Rather than guess at a composition (an earlier revision- // derived `$DIR/profiles/<name>/agent`, and re-rooted differently- // depending on whether the path's last component happened to be named- // "agent", so the result changed with the directory's *name*), this- // takes the reading each is documented to have: the variable names the- // agent directory outright, so when it is set that is the agent- // directory. The profile then has nothing left to relocate, and the- // caller says so instead of silently picking one.- let base_dir = if let Some(dir) = crate::commands::path_util::agent_config_home(env_override) {- dir- } else {- let root = home_dir()- .context("could not locate $HOME for ~/.omp")?- .join(".omp");- if let Some(profile_name) = profile {- root.join("profiles").join(profile_name).join("agent")- } else {- root.join("agent")- }- };- Ok(base_dir.join("extensions").join("ai-memory-omp.ts"))+ let home = home_dir().context("could not locate $HOME for ~/.omp")?;+ Ok(ai_memory_workstream::omp_agent_dir(&home, profile, env)?+ .join("extensions")+ .join("ai-memory-omp.ts"))}/// `$PI_CODING_AGENT_DIR/extensions/ai-memory-pi.ts` when the var is set, else@@ -327,7 +309,8 @@ fn pi_extension_path_in(.join("ai-memory-pi.ts"))}-/// `$KIMI_CODE_HOME/config.toml` when set, else `~/.kimi-code/config.toml`.+/// `$KIMI_CODE_HOME/config.toml` when set and not blank, else+/// `~/.kimi-code/config.toml`./// Kimi Code keeps hooks as `[[hooks]]` entries inside the same/// config.toml that stores the user's providers/model, so the apply/// path merges TOML-aware instead of rewriting the file.@@ -341,8 +324,8 @@ pub(crate) fn kimi_code_config_path() -> anyhow::Result<std::path::PathBuf> {fn kimi_code_config_path_in(env_override: Option<std::ffi::OsString>,) -> anyhow::Result<std::path::PathBuf> {- if let Some(dir) = env_override.filter(|value| !value.is_empty()) {- return Ok(PathBuf::from(dir).join("config.toml"));+ if let Some(dir) = crate::commands::path_util::agent_config_home(env_override) {+ return Ok(dir.join("config.toml"));}Ok(home_dir().context("could not locate $HOME for ~/.kimi-code/config.toml")?@@ -375,8 +358,8 @@ fn kiro_cli_home_join(env_override: Option<std::ffi::OsString>,child: &str,) -> anyhow::Result<std::path::PathBuf> {- if let Some(dir) = env_override.filter(|value| !value.is_empty()) {- return Ok(PathBuf::from(dir).join(child));+ if let Some(dir) = crate::commands::path_util::agent_config_home(env_override) {+ return Ok(dir.join(child));}Ok(home_dir().context("could not locate $HOME for ~/.kiro")?@@ -1171,6 +1154,17 @@ fn apply_base_path_to_hook_url(url: &str, base_path: &str) -> String {}}+/// The first readable TOML MCP config among `paths` that registers ai-memory.+fn infer_first_toml_mcp_config(+ paths: impl IntoIterator<Item = PathBuf>,+) -> Option<InferredMcpConfig> {+ paths.into_iter().find_map(|path| {+ fs::read_to_string(path)+ .ok()+ .and_then(|content| infer_toml_mcp_config(&content))+ })+}+fn infer_installed_mcp_config(agent: AgentChoice) -> Result<Option<InferredMcpConfig>> {if agent == AgentChoice::Grok {let cwd = std::env::current_dir()@@ -1187,6 +1181,14 @@ fn infer_installed_mcp_config(agent: AgentChoice) -> Result<Option<InferredMcpCoreturn Ok(None);};let path = install_mcp::mcp_config_path(client)?;+ if matches!(client, McpClient::Codex) {+ // An entry written before `install-mcp` honored CODEX_HOME still sits+ // in ~/.codex/config.toml; keep inferring from it until it is rewritten.+ let legacy = home_dir().map(|home| home.join(".codex").join("config.toml"));+ return Ok(infer_first_toml_mcp_config(+ std::iter::once(path).chain(legacy),+ ));+ }let Ok(content) = fs::read_to_string(path) else {return Ok(None);};@@ -1354,6 +1356,40 @@ pub(crate) fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {}}+/// The hook config `--apply` writes for an agent that `ai-memory run`+/// auto-wires, with the relocation variables read through `env` rather than+/// ai-memory's own environment. It is the default each installer picks when no+/// `--config-file` is given; for Kiro CLI v2 that default is the agents+/// directory whose configs receive the hooks, not a single file.+///+/// # Errors+/// When `$HOME` cannot be located, or for an agent `run` does not auto-wire.+pub(crate) fn hook_config_target_with(+ agent: AgentChoice,+ env: &dyn Fn(&str) -> Option<std::ffi::OsString>,+) -> Result<PathBuf> {+ match agent {+ AgentChoice::ClaudeCode => claude_settings_path_in(env("CLAUDE_CONFIG_DIR")),+ AgentChoice::Codex => codex_hooks_path_in(env("CODEX_HOME")),+ AgentChoice::OpenCode => opencode_plugin_path(),+ AgentChoice::OpenCode2 => opencode2_plugin_path(),+ AgentChoice::Pi => pi_extension_path_in(env("PI_CODING_AGENT_DIR")),+ AgentChoice::Omp => omp_extension_path_with(None, env),+ AgentChoice::KimiCode => kimi_code_config_path_in(env("KIMI_CODE_HOME")),+ AgentChoice::CommandCode => command_code_settings_path(),+ AgentChoice::KiroCli => kiro_cli_home_join(env("KIRO_HOME"), "agents"),+ AgentChoice::KiroCliV3 => {+ Ok(kiro_cli_home_join(env("KIRO_HOME"), "hooks")?.join("ai-memory.json"))+ }+ AgentChoice::Grok => grok_hooks_path_in(env("GROK_HOME")),+ AgentChoice::AntigravityCli => antigravity_hooks_path(),+ other => anyhow::bail!(+ "{} is not auto-wired by `ai-memory run`",+ other.kind().as_str()+ ),+ }+}+fn infer_json_mcp_config(content: &str,entry_path: &[&str],@@ -3943,12 +3979,13 @@ export default AiMemoryHooks;add_hook_spooling(body).expect("generated TS integration lost its hook-spool anchors")}-/// Warn when Pi and OMP resolve to the same extensions directory.+/// The extensions directory Pi and OMP would share, when `this_agent`'s+/// extension at `this_path` sits beside the other agent's under `env`.////// Agent-distinct filenames stop the two installs from overwriting each/// other, but they do not make sharing a directory safe. OMP discovers/// **every** direct `*.ts` under its extensions directory, so with both-/// files present each agent loads both extensions — and since the Pi+/// files present each agent loads both extensions, and since the Pi/// extension is the OMP one with `const AGENT` swapped, and neither guards/// on its host, every lifecycle event is captured twice under two different/// agent identities.@@ -3956,29 +3993,45 @@ export default AiMemoryHooks;/// That is not a regression this installer can fix by itself: both agents/// honour the same `PI_CODING_AGENT_DIR`, so the collision is upstream. What/// it can do is refuse to be silent about it, and name the two ways out.-fn warn_if_agents_share_extensions_dir(this_agent: &str, this_path: &Path) {+/// `env` is a parameter because `ai-memory run` resolves the other agent+/// through its launch environment, not ai-memory's own.+pub(crate) fn shared_extensions_dir(+ this_agent: AgentChoice,+ this_path: &Path,+ env: &dyn Fn(&str) -> Option<std::ffi::OsString>,+) -> Option<PathBuf> {let other = match this_agent {- "pi" => omp_extension_path(None),- "omp" => pi_extension_path(),- _ => return,+ AgentChoice::Pi => AgentChoice::Omp,+ AgentChoice::Omp => AgentChoice::Pi,+ _ => return None,};- let Ok(other_path) = other else { return };- let (Some(a), Some(b)) = (this_path.parent(), other_path.parent()) else {- return;- };- if a != b {- return;- }+ let other_path = hook_config_target_with(other, env).ok()?;+ let dir = this_path.parent()?;+ (other_path.parent() == Some(dir)).then(|| dir.to_path_buf())+}++/// Print the Pi/OMP double-capture warning for `dir`; see+/// [`shared_extensions_dir`].+pub(crate) fn warn_agents_share_extensions_dir(dir: &Path) {eprintln!(- "warning: Pi and OMP both resolve to {} — they share PI_CODING_AGENT_DIR.\n\+ "warning: Pi and OMP both resolve to {}, an agent dir they share\n\+ \x20 (PI_CODING_AGENT_DIR, or OMP's PI_CONFIG_DIR).\n\\x20 Each agent loads every *.ts in that directory, so installing both\n\\x20 captures each event twice, once as `pi` and once as `omp`.\n\- \x20 Give them separate homes, or scope OMP to a profile:\n\- \x20 ai-memory install-hooks --agent omp --profile <name> --apply",- a.display()+ \x20 Give them separate homes, or move OMP to a named profile, which\n\+ \x20 ignores PI_CODING_AGENT_DIR (OMP_PROFILE=<name>, or `--profile <name>`\n\+ \x20 on both `omp` and `ai-memory install-hooks --agent omp`).",+ dir.display());}+fn warn_if_agents_share_extensions_dir(this_agent: AgentChoice, this_path: &Path) {+ if let Some(dir) = shared_extensions_dir(this_agent, this_path, &|name| std::env::var_os(name))+ {+ warn_agents_share_extensions_dir(&dir);+ }+}+/// Remove a pre-rename `ai-memory.ts` sitting beside the new agent-distinct/// file, so the agent does not load both.///@@ -4026,10 +4079,11 @@ fn remove_legacy_extension(new_path: &Path, agent: &str) {}}-/// Generate an Oh My Pi extension at `~/.omp/agent/extensions/ai-memory-omp.ts`.+/// Generate an Oh My Pi extension at `<agent dir>/extensions/ai-memory-omp.ts`+/// (see [`omp_extension_path`]).///-/// OMP discovers direct `*.ts` / `*.js` files under `~/.omp/agent/extensions/`-/// at startup, so no separate settings merge is needed. The extension uses OMP's+/// OMP discovers direct `*.ts` / `*.js` files under its agent dir's+/// `extensions/` at startup, so no separate settings merge is needed. The extension uses OMP's/// lifecycle API for capture and `before_agent_start` for handoff injection.fn apply_to_omp_extension(server_url: &str,@@ -4053,13 +4107,14 @@ fn apply_to_omp_extension(});- warn_if_agents_share_extensions_dir("omp", &path);+ warn_if_agents_share_extensions_dir(AgentChoice::Omp, &path);remove_legacy_extension(&path, "omp");if !matches!(outcome, ApplyOutcome::NoOp) {println!();println!(- "OMP auto-loads direct TypeScript extensions from ~/.omp/agent/extensions/ on next start."+ "OMP auto-loads direct TypeScript extensions from {} on next start.",+ path.parent().unwrap_or(&path).display());println!("If you're already inside an `omp` session, restart it for the");println!("new extension to take effect.");@@ -4067,23 +4122,21 @@ fn apply_to_omp_extension(Ok(())}-fn omp_extension_hint_in(- env_override: Option<std::ffi::OsString>,+/// Where `--apply` would write the OMP extension. Without a `$HOME` the hint+/// still names the layout, rooted at a literal `~`.+fn omp_extension_hint_with(profile: Option<&str>,-) -> String {- omp_extension_path_in(env_override, profile).map_or_else(- |_| {- if let Some(name) = profile {- format!("~/.omp/profiles/{}/agent/extensions/ai-memory-omp.ts", name)- } else {- "~/.omp/agent/extensions/ai-memory-omp.ts".to_string()- }- },- |p| p.display().to_string(),- )+ env: &dyn Fn(&str) -> Option<std::ffi::OsString>,+) -> Result<String> {+ let home = home_dir().unwrap_or_else(|| PathBuf::from("~"));+ Ok(ai_memory_workstream::omp_agent_dir(&home, profile, env)?+ .join("extensions")+ .join("ai-memory-omp.ts")+ .display()+ .to_string())}-/// See [`omp_extension_hint_in`]; same reasoning for Pi.+/// Where `--apply` would write the Pi extension; see [`omp_extension_hint_with`].fn pi_extension_hint_in(env_override: Option<std::ffi::OsString>) -> String {pi_extension_path_in(env_override).map_or_else(|_| "~/.pi/agent/extensions/ai-memory-pi.ts".to_string(),@@ -4100,7 +4153,7 @@ fn render_omp_extension() -> Result<()> {println!("// Oh My Pi / OMP extension — write to {}",- omp_extension_hint_in(std::env::var_os("PI_CODING_AGENT_DIR"), profile)+ omp_extension_hint_with(profile, &|name| std::env::var_os(name))?);println!("// Or re-run with `--apply` to install it automatically.");println!("// Restart OMP after changing extensions; config is loaded at startup.");@@ -4116,13 +4169,7 @@ fn resolve_omp_extension_path(args: &InstallHooksArgs) -> Result<PathBuf> {if let Some(p) = &args.config_file {return Ok(p.clone());}- // See `omp_extension_path`: bind before borrowing.- let env_profile = std::env::var_os("OMP_PROFILE");- let profile = args- .profile- .as_deref()- .or_else(|| env_profile.as_ref().and_then(|s| s.to_str()));- omp_extension_path(profile)+ omp_extension_path(args.profile.as_deref())}fn apply_to_pi_extension(@@ -4147,7 +4194,7 @@ fn apply_to_pi_extension(});- warn_if_agents_share_extensions_dir("pi", &path);+ warn_if_agents_share_extensions_dir(AgentChoice::Pi, &path);remove_legacy_extension(&path, "pi");if !matches!(outcome, ApplyOutcome::NoOp) {@@ -7466,6 +7513,51 @@ Authorization = "Bearer secret-token"assert_eq!(inferred.auth_token.as_deref(), Some("secret-token"));}+ /// With CODEX_HOME set, the MCP entry may still live in the legacy+ /// ~/.codex/config.toml from before install-mcp honored the variable.+ #[test]+ fn codex_mcp_inference_prefers_the_relocated_config_then_the_legacy_one() {+ let dir = tempfile::tempdir().unwrap();+ let relocated = dir.path().join("relocated.toml");+ let legacy = dir.path().join("legacy.toml");+ let entry = |url: &str| {+ format!(+ "[mcp_servers.ai-memory]\nurl = \"{url}/mcp\"\n\n\+ [mcp_servers.ai-memory.http_headers]\nAuthorization = \"Bearer t\"\n"+ )+ };+ let candidates = || [relocated.clone(), legacy.clone()];++ assert!(infer_first_toml_mcp_config(candidates()).is_none());++ std::fs::write(&legacy, entry("http://legacy:49374")).unwrap();+ assert_eq!(+ infer_first_toml_mcp_config(candidates())+ .and_then(|inferred| inferred.hook_server_url)+ .as_deref(),+ Some("http://legacy:49374"),+ "a missing relocated config falls back to the legacy entry"+ );++ std::fs::write(&relocated, "[mcp_servers.other]\nurl = \"http://x\"\n").unwrap();+ assert_eq!(+ infer_first_toml_mcp_config(candidates())+ .and_then(|inferred| inferred.hook_server_url)+ .as_deref(),+ Some("http://legacy:49374"),+ "a relocated config without ai-memory still falls back"+ );++ std::fs::write(&relocated, entry("http://relocated:49374")).unwrap();+ assert_eq!(+ infer_first_toml_mcp_config(candidates())+ .and_then(|inferred| inferred.hook_server_url)+ .as_deref(),+ Some("http://relocated:49374"),+ "the relocated entry wins once it exists"+ );+ }+#[test]fn grok_mcp_inference_accepts_headers_key() {let inferred = infer_toml_mcp_config(@@ -8828,7 +8920,10 @@ model = "gpt-5"let env = || Some(std::ffi::OsString::from(custom));for hint in [- omp_extension_hint_in(env(), None),+ omp_extension_hint_with(None, &|name| {+ (name == "PI_CODING_AGENT_DIR").then(env).flatten()+ })+ .unwrap(),pi_extension_hint_in(env()),] {assert!(@@ -8850,7 +8945,7 @@ model = "gpt-5"(".omp","ai-memory-omp.ts",- omp_extension_hint_in(None, None),+ omp_extension_hint_with(None, &|_| None).unwrap(),),(".pi", "ai-memory-pi.ts", pi_extension_hint_in(None)),] {@@ -8864,58 +8959,271 @@ model = "gpt-5"}}- /// Precedence must not depend on what the override directory is *named*.- /// An earlier revision re-rooted only when the last component happened to- /// be "agent", so `/custom/agent` and `/custom/pi-agent` behaved- /// differently for the same inputs.+ fn env_of(+ pairs: &[(&'static str, &'static str)],+ ) -> impl Fn(&str) -> Option<std::ffi::OsString> + use<> {+ let pairs = pairs.to_vec();+ move |name| {+ pairs+ .iter()+ .find(|(key, _)| *key == name)+ .map(|(_, value)| std::ffi::OsString::from(value))+ }+ }++ fn omp_profile_extension(profile: &str) -> PathBuf {+ [+ ".omp",+ "profiles",+ profile,+ "agent",+ "extensions",+ "ai-memory-omp.ts",+ ]+ .iter()+ .collect()+ }++ fn omp_default_extension() -> PathBuf {+ [".omp", "agent", "extensions", "ai-memory-omp.ts"]+ .iter()+ .collect()+ }++ /// OMP gives a named profile its own agent dir and ignores+ /// `PI_CODING_AGENT_DIR` for it (`DirResolver` in OMP 18.2.5 drops the+ /// override whenever a profile is active). Installing into the override+ /// instead put the extension where that OMP never looks.#[test]- fn omp_profile_precedence_is_independent_of_the_override_dir_name() {- let a = omp_extension_path_in(- Some(std::ffi::OsString::from("/custom/agent")),- Some("work"),- )- .unwrap();- let b = omp_extension_path_in(- Some(std::ffi::OsString::from("/custom/pi-agent")),- Some("work"),- )- .unwrap();+ fn omp_named_profile_ignores_pi_coding_agent_dir() {+ for custom in ["/custom/agent", "/custom/pi-agent"] {+ let env = env_of(&[("PI_CODING_AGENT_DIR", custom)]);+ let explicit = omp_extension_path_with(Some("work"), &env).unwrap();+ assert!(+ explicit.ends_with(omp_profile_extension("work")),+ "got {explicit:?}"+ );- // The override names the agent dir in both cases; the profile does- // not re-root it, and neither result invents a `profiles/` segment.- assert!(- a.ends_with("agent/extensions/ai-memory-omp.ts"),- "got {a:?}"- );- assert!(- b.ends_with("pi-agent/extensions/ai-memory-omp.ts"),- "got {b:?}"- );- for p in [&a, &b] {+ let env = env_of(&[("PI_CODING_AGENT_DIR", custom), ("OMP_PROFILE", "work")]);+ let from_env = omp_extension_path_with(None, &env).unwrap();+ assert_eq!(from_env, explicit);+ }+ }++ /// Profile names go through OMP's own normalization: `--profile` beats+ /// `OMP_PROFILE`, a set `OMP_PROFILE` (even empty) masks `PI_PROFILE`,+ /// names are trimmed, empty/whitespace/`default` select the default+ /// profile, and a name OMP refuses is refused here too.+ #[test]+ fn omp_extension_path_normalizes_profile_like_omp() {+ let default = omp_default_extension();+ let work = omp_profile_extension("work");+ type Case<'a> = (+ Option<&'a str>,+ &'a [(&'static str, &'static str)],+ &'a PathBuf,+ );+ let cases: &[Case] = &[+ (None, &[("OMP_PROFILE", "")], &default),+ (None, &[("OMP_PROFILE", " ")], &default),+ (None, &[("OMP_PROFILE", "default")], &default),+ (None, &[("OMP_PROFILE", " work ")], &work),+ (None, &[("PI_PROFILE", "work")], &work),+ (+ None,+ &[("OMP_PROFILE", ""), ("PI_PROFILE", "work")],+ &default,+ ),+ (Some("work"), &[("OMP_PROFILE", "other")], &work),+ (Some("default"), &[("OMP_PROFILE", "other")], &default),+ ];+ for (explicit, pairs, expected) in cases {+ let path = omp_extension_path_with(*explicit, &env_of(pairs)).unwrap();+ assert!(+ path.ends_with(expected),+ "{explicit:?} {pairs:?} -> {path:?}"+ );+ }++ for (explicit, pairs) in [+ (None, &[("OMP_PROFILE", "Work")][..]),+ (None, &[("OMP_PROFILE", "../x")][..]),+ (None, &[("OMP_PROFILE", "work.")][..]),+ (None, &[("PI_PROFILE", "con")][..]),+ (Some(""), &[][..]),+ ] {assert!(- !p.to_string_lossy().contains("profiles"),- "PI_CODING_AGENT_DIR names the agent dir outright: {p:?}"+ omp_extension_path_with(explicit, &env_of(pairs)).is_err(),+ "{explicit:?} {pairs:?} must be refused");}}+ /// The preview names the file `--apply` writes, so it follows+ /// `OMP_PROFILE` even when `--profile` is absent.+ #[test]+ fn omp_preview_hint_follows_omp_profile() {+ let hint = omp_extension_hint_with(None, &env_of(&[("OMP_PROFILE", "work")])).unwrap();+ assert!(+ hint.ends_with(&omp_profile_extension("work").display().to_string()),+ "got {hint}"+ );+ }++ /// `PI_CONFIG_DIR` renames OMP's `~/.omp` root, extensions included, while+ /// an XDG data dir moves only OMP's sessions.+ #[test]+ fn omp_extension_path_follows_pi_config_dir_but_not_xdg() {+ let renamed: PathBuf = [".omp-alt", "agent", "extensions", "ai-memory-omp.ts"]+ .iter()+ .collect();+ let path =+ omp_extension_path_with(None, &env_of(&[("PI_CONFIG_DIR", ".omp-alt")])).unwrap();+ assert!(path.ends_with(&renamed), "{path:?}");+ let profiled: PathBuf = [+ ".omp-alt",+ "profiles",+ "work",+ "agent",+ "extensions",+ "ai-memory-omp.ts",+ ]+ .iter()+ .collect();+ let path = omp_extension_path_with(Some("work"), &env_of(&[("PI_CONFIG_DIR", ".omp-alt")]))+ .unwrap();+ assert!(path.ends_with(&profiled), "{path:?}");++ let xdg = tempfile::tempdir().unwrap();+ std::fs::create_dir(xdg.path().join("omp")).unwrap();+ let xdg_value = xdg.path().to_string_lossy().into_owned();+ let path = omp_extension_path_with(None, &|name: &str| {+ (name == "XDG_DATA_HOME").then(|| std::ffi::OsString::from(&xdg_value))+ })+ .unwrap();+ assert!(path.ends_with(omp_default_extension()), "{path:?}");+ }+/// With no override, `--profile` relocates to the documented/// `~/.omp/profiles/<name>/agent/extensions`.#[test]fn omp_profile_relocates_when_no_override_is_set() {- let path = omp_extension_path_in(None, Some("work")).unwrap();+ let path = omp_extension_path_with(Some("work"), &|_| None).unwrap();assert!(- path.ends_with(".omp/profiles/work/agent/extensions/ai-memory-omp.ts"),+ path.ends_with(omp_profile_extension("work")),"got {path:?}");- let plain = omp_extension_path_in(None, None).unwrap();- assert!(- plain.ends_with(".omp/agent/extensions/ai-memory-omp.ts"),- "got {plain:?}"+ let plain = omp_extension_path_with(None, &|_| None).unwrap();+ assert!(plain.ends_with(omp_default_extension()), "got {plain:?}");+ }++ /// `run` resolves the other Pi-family agent through its launch env, so+ /// the shared-directory check must use the env it is given, not+ /// ai-memory's own.+ #[test]+ fn shared_extensions_dir_follows_the_supplied_env() {+ let root = if cfg!(windows) {+ r"C:\relocated"+ } else {+ "/relocated"+ };+ let env = env_of(&[("PI_CODING_AGENT_DIR", root)]);+ let extensions = Path::new(root).join("extensions");+ for (agent, file) in [+ (AgentChoice::Pi, "ai-memory-pi.ts"),+ (AgentChoice::Omp, "ai-memory-omp.ts"),+ ] {+ let this_path = extensions.join(file);+ assert_eq!(+ shared_extensions_dir(agent, &this_path, &env),+ Some(extensions.clone())+ );+ assert_eq!(shared_extensions_dir(agent, &this_path, &|_| None), None);+ }+ assert_eq!(+ shared_extensions_dir(+ AgentChoice::ClaudeCode,+ &extensions.join("ai-memory-pi.ts"),+ &env+ ),+ None+ );+ // A named profile moves OMP off the shared directory.+ let profiled = env_of(&[("PI_CODING_AGENT_DIR", root), ("OMP_PROFILE", "work")]);+ assert_eq!(+ shared_extensions_dir(+ AgentChoice::Pi,+ &extensions.join("ai-memory-pi.ts"),+ &profiled+ ),+ None);}+ /// A blank relocation variable is unset for every auto-wired agent's hook+ /// target, the same rule `path_util::agent_config_home` and native session+ /// import use; otherwise the installer wrote into `<cwd>/ /`.+ #[test]+ fn hook_config_target_with_treats_blank_relocation_as_unset() {+ let home = home_dir().unwrap();+ let cases: &[(AgentChoice, &str, &[&str])] = &[+ (+ AgentChoice::ClaudeCode,+ "CLAUDE_CONFIG_DIR",+ &[".claude", "settings.json"],+ ),+ (AgentChoice::Codex, "CODEX_HOME", &[".codex", "hooks.json"]),+ (+ AgentChoice::Pi,+ "PI_CODING_AGENT_DIR",+ &[".pi", "agent", "extensions", "ai-memory-pi.ts"],+ ),+ (+ AgentChoice::Omp,+ "PI_CODING_AGENT_DIR",+ &[".omp", "agent", "extensions", "ai-memory-omp.ts"],+ ),+ (+ AgentChoice::Omp,+ "OMP_PROFILE",+ &[".omp", "agent", "extensions", "ai-memory-omp.ts"],+ ),+ (+ AgentChoice::Omp,+ "PI_CONFIG_DIR",+ &[".omp", "agent", "extensions", "ai-memory-omp.ts"],+ ),+ (+ AgentChoice::KimiCode,+ "KIMI_CODE_HOME",+ &[".kimi-code", "config.toml"],+ ),+ (AgentChoice::KiroCli, "KIRO_HOME", &[".kiro", "agents"]),+ (+ AgentChoice::KiroCliV3,+ "KIRO_HOME",+ &[".kiro", "hooks", "ai-memory.json"],+ ),+ (+ AgentChoice::Grok,+ "GROK_HOME",+ &[".grok", "hooks", "ai-memory.json"],+ ),+ ];+ for (agent, variable, tail) in cases {+ let expected: PathBuf = tail.iter().fold(home.clone(), |path, part| path.join(part));+ for blank in ["", " ", "\t", " \n"] {+ let env = |name: &str| (name == *variable).then(|| std::ffi::OsString::from(blank));+ assert_eq!(+ hook_config_target_with(*agent, &env).unwrap(),+ expected,+ "{agent:?} with {variable}={blank:?}"+ );+ }+ }+ }+/// `remove_legacy_extension` must delete only what this tool generated./// `uninstall` gates every delete on the same marker/// (`uninstall_omp_extension_deletes_only_generated_file`), so an@@ -9017,7 +9325,8 @@ model = "gpt-5"} else {"/custom/omp-agent"};- let path = omp_extension_path_in(Some(std::ffi::OsString::from(custom)), None).unwrap();+ let path =+ omp_extension_path_with(None, &env_of(&[("PI_CODING_AGENT_DIR", custom)])).unwrap();assert_eq!(path,Path::new(custom)@@ -9026,7 +9335,12 @@ model = "gpt-5");for env in [None, Some(std::ffi::OsString::new())] {- let path = omp_extension_path_in(env, None).unwrap();+ let path = omp_extension_path_with(None, &|name| {+ (name == "PI_CODING_AGENT_DIR")+ .then(|| env.clone())+ .flatten()+ })+ .unwrap();assert!(path.ends_with(Path::new(".omp")@@ -9042,7 +9356,7 @@ model = "gpt-5"#[test]fn omp_extension_path_honours_profile() {- let path = omp_extension_path_in(None, Some("my-profile")).unwrap();+ let path = omp_extension_path_with(Some("my-profile"), &|_| None).unwrap();assert!(path.ends_with(Path::new(".omp")@@ -9255,15 +9569,17 @@ model = "gpt-5"match alias {"opencode" => assert!(stdout.contains("install-hooks --agent opencode --apply")),"openclaw" => assert!(stdout.contains("install-hooks --agent openclaw --apply")),+ // The agent-distinct names the installers write, not the+ // pre-rename `ai-memory.ts`."omp" | "oh-my-pi" => {assert!(stdout.contains("install-hooks --agent omp --apply"));- assert!(stdout.contains("~/.omp/agent/extensions/ai-memory.ts"));+ assert!(stdout.contains("~/.omp/agent/extensions/ai-memory-omp.ts"));}"pi" => {assert!(stdout.contains("install-hooks --agent pi --apply"));- assert!(stdout.contains("~/.pi/agent/extensions/ai-memory.ts"));+ assert!(stdout.contains("~/.pi/agent/extensions/ai-memory-pi.ts"));assert!(stdout.contains("MCP tools come through the same generated bridge"));- assert!(!stdout.contains("~/.omp/agent/extensions/ai-memory.ts"));+ assert!(!stdout.contains("~/.omp/agent/extensions"));}_ => unreachable!(),}diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex d954f53f..df8e5f71 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -11,8 +11,9 @@//! community-standard `npx mcp-remote` stdio shim so the same HTTP//! endpoint still works.//!-//! OMP uses a native `~/.omp/agent/mcp.json` file with the same-//! `mcpServers` root as several other clients.+//! OMP uses a native `mcp.json` in its agent dir (`~/.omp/agent`, a named+//! profile's `~/.omp/profiles/<name>/agent`, or `$PI_CODING_AGENT_DIR`) with+//! the same `mcpServers` root as several other clients.use std::path::{Path, PathBuf};@@ -160,14 +161,27 @@ fn validate_kiro_remote_url(server_url: &str) -> Result<()> {/// Returns an error for `Pi` (no MCP config), for Claude Desktop on/// unsupported OSes, or when `$HOME` can't be resolved.pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf> {+ mcp_config_path_with(client, &|name| std::env::var_os(name))+}++/// [`mcp_config_path`] with the relocation variables (`CLAUDE_CONFIG_DIR`,+/// `CODEX_HOME`, `GROK_HOME`, `KIMI_CODE_HOME`, `KIRO_HOME`, and OMP's+/// `OMP_PROFILE`, `PI_PROFILE`, `PI_CODING_AGENT_DIR` and `PI_CONFIG_DIR`) read+/// through `env`,+/// so `ai-memory run --env` can point auto-wire at the same config home+/// it launches the harness with.+pub(crate) fn mcp_config_path_with(+ client: crate::cli::McpClient,+ env: &dyn Fn(&str) -> Option<std::ffi::OsString>,+) -> Result<PathBuf> {use crate::cli::McpClient;let home = || home_dir().context("could not locate $HOME for config-file auto-detect");Ok(match client {- McpClient::ClaudeCode => claude_code_config_path_in(std::env::var_os("CLAUDE_CONFIG_DIR"))?,- McpClient::Codex => home()?.join(".codex").join("config.toml"),+ McpClient::ClaudeCode => claude_code_config_path_in(env("CLAUDE_CONFIG_DIR"))?,+ McpClient::Codex => codex_config_path_in(env("CODEX_HOME"))?,// Project scope is `.grok/config.toml` under cwd/repo; pass// --config-file for that case rather than inventing a second default.- McpClient::Grok => grok_home()?.join("config.toml"),+ McpClient::Grok => grok_home_in(env("GROK_HOME"))?.join("config.toml"),McpClient::OpenCode => home()?.join(".config").join("opencode")@@ -212,7 +226,11 @@ pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf>McpClient::Pi => bail!("Pi has no native mcp.json; use `ai-memory install-hooks --agent pi --apply` to install the generated MCP bridge extension."),- McpClient::Omp => home()?.join(".omp").join("agent").join("mcp.json"),+ // OMP reads mcp.json from its agent dir, the one its extensions live+ // in, so a profile, PI_CODING_AGENT_DIR or PI_CONFIG_DIR moves it too.+ McpClient::Omp => {+ ai_memory_workstream::omp_agent_dir(&home()?, None, env)?.join("mcp.json")+ }McpClient::AntigravityCli => home()?.join(".gemini").join("config")@@ -229,8 +247,8 @@ pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf>// Kimi Code keeps its data dir at $KIMI_CODE_HOME when set,// falling back to ~/.kimi-code; MCP servers live in mcp.json at// that root.- McpClient::KimiCode => kimi_code_home(std::env::var_os("KIMI_CODE_HOME"))?.join("mcp.json"),- McpClient::KiroCli => kiro_home(std::env::var_os("KIRO_HOME"))?+ McpClient::KimiCode => kimi_code_home(env("KIMI_CODE_HOME"))?.join("mcp.json"),+ McpClient::KiroCli => kiro_home(env("KIRO_HOME"))?.join("settings").join("mcp.json"),McpClient::CommandCode => home()?.join(".commandcode").join("mcp.json"),@@ -386,23 +404,41 @@ fn claude_code_config_path_in(env_override: Option<std::ffi::OsString>) -> Resul.join(".claude.json"))}-/// Kimi Code's data dir: `$KIMI_CODE_HOME` when set (non-empty), else+/// Codex's user config, where its MCP servers live: `$CODEX_HOME/config.toml`+/// when the var is set, else `~/.codex/config.toml`. Codex keeps its whole+/// config home under `CODEX_HOME`, which `install-hooks` already honors for+/// `hooks.json`; writing the MCP entry to the default path left a relocated+/// Codex with hooks but no ai-memory server. Blank counts as unset, as it does+/// for the hooks path. The env value comes in as a parameter so tests can+/// exercise both branches without mutating process env.+fn codex_config_path_in(env_override: Option<std::ffi::OsString>) -> Result<PathBuf> {+ if let Some(dir) = crate::commands::path_util::agent_config_home(env_override) {+ return Ok(dir.join("config.toml"));+ }+ Ok(home_dir()+ .context("could not locate $HOME for ~/.codex/config.toml")?+ .join(".codex")+ .join("config.toml"))+}++/// Kimi Code's data dir: `$KIMI_CODE_HOME` when set and not blank, else/// `~/.kimi-code`. The env value comes in as a parameter so tests can/// exercise both branches without mutating process env.fn kimi_code_home(env_override: Option<std::ffi::OsString>) -> Result<PathBuf> {- if let Some(dir) = env_override.filter(|value| !value.is_empty()) {- return Ok(PathBuf::from(dir));+ if let Some(dir) = crate::commands::path_util::agent_config_home(env_override) {+ return Ok(dir);}Ok(home_dir().context("could not locate $HOME for config-file auto-detect")?.join(".kimi-code"))}-/// Kiro CLI's global configuration root: `$KIRO_HOME` when set, otherwise-/// `~/.kiro`. The override is injected to keep path tests process-local.+/// Kiro CLI's global configuration root: `$KIRO_HOME` when set and not+/// blank, otherwise `~/.kiro`. The override is injected to keep path tests+/// process-local.fn kiro_home(env_override: Option<std::ffi::OsString>) -> Result<PathBuf> {- if let Some(dir) = env_override.filter(|value| !value.is_empty()) {- return Ok(PathBuf::from(dir));+ if let Some(dir) = crate::commands::path_util::agent_config_home(env_override) {+ return Ok(dir);}Ok(home_dir().context("could not locate $HOME for Kiro configuration")?@@ -412,8 +448,14 @@ fn kiro_home(env_override: Option<std::ffi::OsString>) -> Result<PathBuf> {/// Resolve Grok Build CLI's user configuration root. Grok honours/// `GROK_HOME`; otherwise it uses `~/.grok`.pub(crate) fn grok_home() -> Result<PathBuf> {- if let Some(path) = std::env::var_os("GROK_HOME").filter(|path| !path.is_empty()) {- return Ok(PathBuf::from(path));+ grok_home_in(std::env::var_os("GROK_HOME"))+}++/// [`grok_home`] with the `GROK_HOME` value passed in, so auto-wire can resolve+/// it from `ai-memory run --env` and tests stay process-local.+pub(crate) fn grok_home_in(env_override: Option<std::ffi::OsString>) -> Result<PathBuf> {+ if let Some(dir) = crate::commands::path_util::agent_config_home(env_override) {+ return Ok(dir);}Ok(home_dir().context("could not locate $HOME for Grok configuration")?@@ -1113,7 +1155,7 @@ fn render_codex(args: &InstallMcpArgs) -> String {// and NOT a `[mcp_servers.<name>.headers]` sub-table (the key// is `http_headers`, with the `http_` prefix).let mut out = format!(- "# Codex CLI — append to ~/.codex/config.toml\n\+ "# Codex CLI — append to $CODEX_HOME/config.toml (default ~/.codex/config.toml)\n\#\n\[mcp_servers.{name}]\n\url = \"{url}\"\n\@@ -1335,7 +1377,10 @@ fn hook_server_url_from_mcp_url(url: &str) -> String {fn render_omp(args: &InstallMcpArgs) -> Result<String> {Ok(format!(- "# Oh My Pi / OMP — merge into ~/.omp/agent/mcp.json:\n\+ "# Oh My Pi / OMP — merge into mcp.json in OMP's agent dir:\n\+ # ~/.omp/agent/mcp.json by default, ~/.omp/profiles/<name>/agent/mcp.json\n\+ # under a named profile (OMP_PROFILE), or $PI_CODING_AGENT_DIR/mcp.json\n\+ # when that variable relocates the default profile.\n\#\n\# The current Oh My Pi package exposes the `omp` binary and native\n\# `.omp` config directories. Restart `omp` after changing MCP config.\n\@@ -1622,6 +1667,134 @@ mod tests {}}+ #[test]+ fn codex_config_path_honours_codex_home() {+ let custom = if cfg!(windows) {+ r"C:\custom\codex"+ } else {+ "/custom/codex"+ };+ let path = codex_config_path_in(Some(std::ffi::OsString::from(custom))).unwrap();+ assert_eq!(path, std::path::Path::new(custom).join("config.toml"));++ // Unset, empty and blank all fall back to ~/.codex/config.toml, the+ // same reading `install-hooks` gives CODEX_HOME for hooks.json.+ for env in [+ None,+ Some(std::ffi::OsString::new()),+ Some(std::ffi::OsString::from(" ")),+ ] {+ let path = codex_config_path_in(env).unwrap();+ assert!(+ path.ends_with(std::path::Path::new(".codex").join("config.toml")),+ "default must be ~/.codex/config.toml, got {}",+ path.display()+ );+ }+ }++ /// Auto-wire resolves MCP targets through `run --env`; every relocatable+ /// client must read its variable from the supplied lookup, not the process.+ #[test]+ fn mcp_config_path_with_reads_relocation_from_the_supplied_env() {+ let root = if cfg!(windows) {+ std::path::Path::new(r"C:\relocated")+ } else {+ std::path::Path::new("/relocated")+ };+ for (client, var, relative) in [+ (McpClient::ClaudeCode, "CLAUDE_CONFIG_DIR", ".claude.json"),+ (McpClient::Codex, "CODEX_HOME", "config.toml"),+ (McpClient::Grok, "GROK_HOME", "config.toml"),+ (McpClient::KimiCode, "KIMI_CODE_HOME", "mcp.json"),+ (McpClient::KiroCli, "KIRO_HOME", "settings/mcp.json"),+ (McpClient::Omp, "PI_CODING_AGENT_DIR", "mcp.json"),+ ] {+ let env = |name: &str| (name == var).then(|| root.as_os_str().to_owned());+ assert_eq!(+ mcp_config_path_with(client, &env).unwrap(),+ root.join(relative),+ "{client:?} must follow {var}"+ );+ }+ }++ /// OMP's MCP file lives in the same agent dir as its extensions: a named+ /// profile owns it and ignores `PI_CODING_AGENT_DIR`, as OMP does.+ #[test]+ fn omp_mcp_config_follows_the_profile_agent_dir() {+ let home = home_dir().unwrap();+ let profile = home+ .join(".omp")+ .join("profiles")+ .join("work")+ .join("agent")+ .join("mcp.json");+ for pairs in [+ &[("OMP_PROFILE", "work")][..],+ &[("OMP_PROFILE", "work"), ("PI_CODING_AGENT_DIR", "/custom")][..],+ &[("PI_PROFILE", "work")][..],+ ] {+ let env = |name: &str| {+ pairs+ .iter()+ .find(|(key, _)| *key == name)+ .map(|(_, value)| std::ffi::OsString::from(value))+ };+ assert_eq!(+ mcp_config_path_with(McpClient::Omp, &env).unwrap(),+ profile,+ "{pairs:?}"+ );+ }+ let invalid = |name: &str| (name == "OMP_PROFILE").then(|| "Work".into());+ assert!(mcp_config_path_with(McpClient::Omp, &invalid).is_err());+ let renamed = |name: &str| (name == "PI_CONFIG_DIR").then(|| ".omp-alt".into());+ assert_eq!(+ mcp_config_path_with(McpClient::Omp, &renamed).unwrap(),+ home.join(".omp-alt").join("agent").join("mcp.json"),+ "PI_CONFIG_DIR renames OMP's root"+ );+ }++ /// A blank relocation variable is unset, the rule every installer and+ /// native session import share; otherwise the MCP entry, bearer token+ /// included, landed in a whitespace-named directory under the cwd.+ #[test]+ fn mcp_config_path_with_treats_blank_relocation_as_unset() {+ let home = home_dir().unwrap();+ for (client, var, relative) in [+ (McpClient::ClaudeCode, "CLAUDE_CONFIG_DIR", ".claude.json"),+ (McpClient::Codex, "CODEX_HOME", ".codex/config.toml"),+ (McpClient::Grok, "GROK_HOME", ".grok/config.toml"),+ (McpClient::KimiCode, "KIMI_CODE_HOME", ".kimi-code/mcp.json"),+ (McpClient::KiroCli, "KIRO_HOME", ".kiro/settings/mcp.json"),+ (McpClient::Omp, "PI_CODING_AGENT_DIR", ".omp/agent/mcp.json"),+ (McpClient::Omp, "OMP_PROFILE", ".omp/agent/mcp.json"),+ (McpClient::Omp, "PI_CONFIG_DIR", ".omp/agent/mcp.json"),+ ] {+ for blank in ["", " ", "\t", " \n"] {+ let env = |name: &str| (name == var).then(|| std::ffi::OsString::from(blank));+ assert_eq!(+ mcp_config_path_with(client, &env).unwrap(),+ home.join(relative),+ "{client:?} with {var}={blank:?}"+ );+ }+ }+ }++ /// The snippet names CODEX_HOME rather than a resolved path: it is often+ /// rendered inside the Docker image, whose paths mean nothing on the host.+ #[test]+ fn codex_render_names_codex_home() {+ let out = render_codex(&args_for(McpClient::Codex));+ assert!(+ out.contains("$CODEX_HOME/config.toml"),+ "render must point a relocated Codex at its config home:\n{out}"+ );+ }+#[test]fn zed_config_path_uses_platform_conventions() {for (target_os, root, expected) in [@@ -2188,7 +2361,14 @@ mod tests {let grok_token = render_with_token(McpClient::Grok);assert!(grok_token.contains("[mcp_servers.ai-memory.headers]"));assert!(!grok_token.contains("http_headers"));- assert!(render_for_test(McpClient::Omp).contains("~/.omp/agent/mcp.json"));+ let omp = render_for_test(McpClient::Omp);+ for location in [+ "~/.omp/agent/mcp.json",+ "~/.omp/profiles/<name>/agent/mcp.json",+ "$PI_CODING_AGENT_DIR/mcp.json",+ ] {+ assert!(omp.contains(location), "{location} missing from:\n{omp}");+ }let pi = render_pi(&args_for(McpClient::Pi)).unwrap();assert!(pi.contains("Pi has no native mcp.json"));assert!(pi.contains("install-hooks --agent pi --apply"));diff --git a/crates/ai-memory-cli/src/commands/path_util.rs b/crates/ai-memory-cli/src/commands/path_util.rsindex c8430342..eb572f41 100644--- a/crates/ai-memory-cli/src/commands/path_util.rs+++ b/crates/ai-memory-cli/src/commands/path_util.rs@@ -20,18 +20,16 @@ pub(crate) fn home_dir() -> Option<PathBuf> {////// Blank is treated as unset on purpose: an exported-but-empty variable is far/// more often an unset shell expansion than a deliberate request to install-/// into the filesystem root.+/// into the filesystem root. The rule lives in+/// [`ai_memory_workstream::env_dir_override`] so native session import applies+/// the same one and never reads a store the installers did not wire.////// The env value comes in as a parameter so tests can exercise both branches/// without mutating process env — which is not merely inconvenient here but/// forbidden: `std::env::set_var` is `unsafe` under edition 2024 and this/// workspace forbids `unsafe_code`.pub(crate) fn agent_config_home(env_override: Option<std::ffi::OsString>) -> Option<PathBuf> {- let value = env_override?;- if value.to_str().is_some_and(|s| s.trim().is_empty()) {- return None;- }- Some(PathBuf::from(value))+ ai_memory_workstream::env_dir_override(env_override)}/// Claude Code's relocated config root: `$CLAUDE_CONFIG_DIR` when set, elsediff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex 34cd1b9c..95be42d0 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -12,12 +12,14 @@ use ai_memory_core::{PrepareManagedRunResponse,};use ai_memory_workstream::{- ExportedTranscript, LaunchMode, LaunchPlan, ManagedHarness, NativeSessionCandidate,- allows_native_session_adoption, apply_yolo, build_launch_plan, build_launch_plan_with_env,+ AmbiguousNativeSession, ExportedTranscript, LaunchMode, LaunchPlan, LaunchRoots,+ ManagedHarness, NativeSessionCandidate, allows_native_session_adoption, apply_yolo,+ build_launch_plan, build_launch_plan_with_env, crush_global_config_path,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, wait_for_transcript_flush,+ list_native_sessions, native_session_exists, native_session_in_checkout, omp_profile_flag,+ omp_profile_flag_env, store_override_vars, wait_for_transcript_flush,};use anyhow::{Context as _, Result, anyhow};use tokio::process::Command;@@ -99,8 +101,7 @@ pub(super) async fn run_from(config: &Config, args: RunArgs, cwd: &Path) -> Resu/// installers resolve their real per-agent paths — behavior is byte-identical to/// the inlined call this replaced. The overrides exist only so the `run` →/// autowire → child-spawn seam can be exercised without writing to the-/// developer's real `$HOME`, mirroring the `ensure_wired` / `ensure_wired_with`-/// split.+/// developer's real `$HOME`.pub(super) async fn run_from_with_wiring(config: &Config,args: RunArgs,@@ -241,14 +242,6 @@ pub(super) async fn run_from_with_wiring(resolved_harness};acquired_try!(ensure_executable_available(harness, executable.as_deref()));- // Auto-wire this harness's ai-memory hooks + MCP the first time it launches- // here, so managed launch "just works" for capture and recall without a- // manual install step. One-time, idempotent, best-effort (it never blocks or- // fails the launch); opt out with `--no-autowire` or AI_MEMORY_RUN_AUTOWIRE=false.- // Runs before the child spawns so the harness picks up the fresh hooks.- if config.run_autowire && !no_autowire {- super::run_autowire::ensure_wired_with(config, harness, wire_overrides);- }let native_grok_rules = user_supplied_grok_rules(&native_args);let (mut plan, orphaned_session) = acquired_try!(build_preflighted_launch_plan(harness,@@ -291,6 +284,10 @@ pub(super) async fn run_from_with_wiring(native_args.clone(),Some(&candidate.session.native_session_id),&run_env,+ Some(LaunchRoots {+ home: &home,+ cwd: &repository.cwd,+ }),));eprintln!("ai-memory: continuing newest checkout-local {} session {}",@@ -334,6 +331,10 @@ pub(super) async fn run_from_with_wiring(native_args,Some(&native_session_id),&run_env,+ Some(LaunchRoots {+ home: &home,+ cwd: &repository.cwd,+ }),));}Ok(None) => {}@@ -382,6 +383,31 @@ pub(super) async fn run_from_with_wiring("ai-memory: Kiro v3 stored this session under the default home despite custom KIRO_HOME; using the default home for this resume");}+ // Auto-wire this harness's ai-memory hooks + MCP the first time it launches+ // here, so managed launch "just works" for capture and recall without a+ // manual install step. One-time, idempotent, best-effort (it never blocks or+ // fails the launch); opt out with `--no-autowire` or AI_MEMORY_RUN_AUTOWIRE=false.+ // Runs once the session and its store are settled, so it wires the config+ // home the child will read, and before the child spawns so the harness+ // picks up the fresh hooks.+ // The environment the child runs with: `--env` over ai-memory's own.+ let launch_env = |name: &str| {+ run_env+ .iter()+ .find(|(key, _)| key == name)+ .map(|(_, value)| OsString::from(value))+ .or_else(|| std::env::var_os(name))+ };+ if config.run_autowire && !no_autowire {+ let wire_env = autowire_env(+ harness,+ &run_env,+ &plan.args,+ remove_kiro_home.then(|| home.join(".kiro")).as_deref(),+ &launch_env,+ );+ super::run_autowire::ensure_wired_with(config, harness, wire_overrides, &wire_env);+ }if plan.mode == LaunchMode::Session&& let Some(native_session_id) = &plan.expected_session_id{@@ -399,7 +425,8 @@ pub(super) async fn run_from_with_wiring(}let crush_context = if harness == ManagedHarness::Crush && plan.mode == LaunchMode::Session {- acquired_try!(prepare_crush_context(&endpoint, &run_path, &home).await)+ let source = crush_context_source(&home, &repository.cwd, launch_env);+ acquired_try!(prepare_crush_context(&endpoint, &run_path, &source).await)} else {None};@@ -451,6 +478,13 @@ pub(super) async fn run_from_with_wiring(.stdin(Stdio::inherit()).stdout(Stdio::inherit()).stderr(Stdio::inherit());+ // A blank home override is unset for session import, auto-wire and the+ // Crush context config; drop it from the child as well, or the harness+ // would read a blank-named directory under the checkout that nothing else+ // follows.+ for name in blank_home_overrides(harness, &launch_env) {+ command.env_remove(name);+ }if remove_kiro_home {command.env_remove("KIRO_HOME");}@@ -534,6 +568,7 @@ pub(super) async fn run_from_with_wiring(&home,&repository.cwd,started_at,+ prepared.native_session_id.as_deref(),server_status.as_ref(),).await@@ -644,12 +679,16 @@ async fn cancel_managed_run_after_failure(endpoint: &ServerEndpoint, run_path: &}}+/// The native session this run used. `prepared_session` is the session the+/// run was prepared with, which the server reports until a hook in the child+/// links another.async fn resolve_native_session_after_run(plan: &LaunchPlan,harness: ManagedHarness,home: &Path,cwd: &Path,started_at: SystemTime,+ prepared_session: Option<&str>,server_status: Option<&ManagedRunStatus>,) -> Result<Option<String>> {if plan.mode == LaunchMode::Passthrough {@@ -658,10 +697,47 @@ async fn resolve_native_session_after_run(if let Some(native_session_id) = &plan.expected_session_id {return Ok(Some(native_session_id.clone()));}- let discovered =- discover_native_session(harness, home, cwd, plan.session_dir.as_deref(), started_at)- .await?;- Ok(discovered.or_else(|| server_status.and_then(|status| status.native_session_id.clone())))+ let reported = server_status.and_then(|status| status.native_session_id.as_deref());+ // A hook links its session under this run's id, which a concurrent launch+ // in the same checkout cannot do; discovery only sees the newest session.+ // A descendant process inherits the id too, so the session must also be+ // this checkout's.+ let linked = reported.filter(|linked| Some(*linked) != prepared_session);+ if let Some(linked) = linked+ && native_session_in_checkout(harness, home, cwd, plan.session_dir.as_deref(), linked)+ .unwrap_or(false)+ {+ return Ok(Some(linked.to_string()));+ }+ let fresh = !has_native_session_selector(harness, &plan.args);+ let discovered = match discover_native_session(+ harness,+ home,+ cwd,+ plan.session_dir.as_deref(),+ started_at,+ fresh,+ )+ .await+ {+ Ok(discovered) => discovered,+ // The session the run was prepared with is no evidence either: this+ // launch may not have touched it while another one did.+ Err(error) if error.is::<AmbiguousNativeSession>() => {+ eprintln!(+ "ai-memory: {error}, so its transcript was not imported; resume the session with its native selector to link it"+ );+ return Ok(None);+ }+ Err(error) => return Err(error),+ };+ // A linked session set aside above belongs to another checkout, so it is+ // no fallback either.+ Ok(discovered.or_else(|| {+ reported+ .filter(|reported| Some(*reported) != linked)+ .map(str::to_string)+ }))}async fn list_auto_sessions(home: &Path, cwd: &Path) -> Result<Vec<AutoSessionCandidate>> {@@ -867,6 +943,60 @@ fn upsert_env(entries: &mut Vec<(String, String)>, key: String, value: String) {}}+/// The environment auto-wire resolves install targets from: the launch's own+/// `--env` entries, adjusted where the child runs with something else. OMP+/// ranks `--profile` above `OMP_PROFILE`, so the flag is passed on through the+/// profile variables (see [`omp_profile_flag_env`], which reads the launch+/// environment `launch_env`); a Kiro v3 resume from the default store drops+/// `KIRO_HOME` from the child, so its hooks and MCP belong under+/// `default_kiro_home`.+fn autowire_env(+ harness: ManagedHarness,+ run_env: &[(String, String)],+ native_args: &[OsString],+ default_kiro_home: Option<&Path>,+ launch_env: &dyn Fn(&str) -> Option<OsString>,+) -> Vec<(String, String)> {+ let mut env = run_env.to_vec();+ let mut set = |name: &str, value: String| {+ env.retain(|(key, _)| key != name);+ env.push((name.to_string(), value));+ };+ if harness == ManagedHarness::Omp+ && let Some(profile) = omp_profile_flag(native_args).filter(|name| !name.is_empty())+ {+ for (name, value) in omp_profile_flag_env(&profile, launch_env) {+ set(&name, value);+ }+ }+ if let Some(kiro_home) = default_kiro_home {+ set("KIRO_HOME", kiro_home.display().to_string());+ }+ env+}++/// The launched harness's home variables (its store overrides, plus the+/// config home Crush's managed context is built from) that are set but blank+/// in the launch environment.+fn blank_home_overrides(+ harness: ManagedHarness,+ get: &dyn Fn(&str) -> Option<OsString>,+) -> Vec<&'static str> {+ let crush_config: &[&'static str] = match harness {+ ManagedHarness::Crush => &["CRUSH_GLOBAL_CONFIG", "XDG_CONFIG_HOME"],+ _ => &[],+ };+ store_override_vars(harness)+ .iter()+ .chain(crush_config)+ .copied()+ .filter(|name| {+ let value = get(name);+ value.is_some() && ai_memory_workstream::env_dir_override(value).is_none()+ })+ .collect()+}+#[allow(clippy::too_many_arguments)]fn build_preflighted_launch_plan(harness: ManagedHarness,@@ -891,6 +1021,7 @@ fn build_preflighted_launch_plan(native_args.clone(),linked_session_id,env_overrides,+ Some(LaunchRoots { home, cwd }),)?;let Some(linked_session_id) = linked_session_id else {return Ok((plan, None));@@ -907,7 +1038,14 @@ fn build_preflighted_launch_plan() {Ok(true) => Ok((plan, None)),Ok(false) => Ok((- build_launch_plan_with_env(harness, executable, native_args, None, env_overrides)?,+ build_launch_plan_with_env(+ harness,+ executable,+ native_args,+ None,+ env_overrides,+ Some(LaunchRoots { home, cwd }),+ )?,Some(linked_session_id.to_string()),)),Err(error) => {@@ -1036,7 +1174,7 @@ async fn fetch_grok_context(endpoint: &ServerEndpoint, run_path: &str) -> Resultasync fn prepare_crush_context(endpoint: &ServerEndpoint,run_path: &str,- home: &Path,+ source: &Path,) -> Result<Option<tempfile::TempDir>> {let response: ManagedRunContextResponse = post_json(endpoint,@@ -1049,7 +1187,19 @@ async fn prepare_crush_context(return Ok(None);};- write_crush_context_config(&crush_global_config_path(home), &context).map(Some)+ write_crush_context_config(source, &context).map(Some)+}++/// The global `crush.json` the launched Crush reads. Crush takes a relative+/// `CRUSH_GLOBAL_CONFIG` from its working directory, and the generated config+/// dir (and its `crushrc`) must name the user's files absolutely because the+/// child reads them from elsewhere.+fn crush_context_source(+ home: &Path,+ cwd: &Path,+ get: impl Fn(&str) -> Option<OsString>,+) -> PathBuf {+ cwd.join(crush_global_config_path(home, get))}fn write_crush_context_config(source: &Path, context: &str) -> Result<tempfile::TempDir> {@@ -1060,27 +1210,61 @@ fn write_crush_context_config(source: &Path, context: &str) -> Result<tempfile::let context_path = temp.path().join("managed-workstream.md");write_private(&context_path, context.as_bytes())?;- let mut config = if source.is_file() {- let raw = std::fs::read(source)- .with_context(|| format!("reading Crush config {}", source.display()))?;+ // Crush cleans the path (`filepath.Join`) before reading it, so a `..`+ // after a missing directory still reaches the file.+ let source = ai_memory_workstream::clean_path(source);+ let raw = if source.is_file() {+ std::fs::read(&source)+ .with_context(|| format!("reading Crush config {}", source.display()))?+ } else {+ Vec::new()+ };+ // Crush skips an empty file and reads `null` as unset; do the same rather+ // than refuse a config Crush itself accepts.+ let mut config = if raw.is_empty() {+ serde_json::Value::Null+ } else {serde_json::from_slice::<serde_json::Value>(&raw).with_context(|| format!("parsing Crush config {}", source.display()))?- } else {- serde_json::json!({})};+ if config.is_null() {+ config = serde_json::json!({});+ }let root = config.as_object_mut().context("Crush global config must be a JSON object")?;- let options = root- .entry("options")- .or_insert_with(|| serde_json::json!({}))+ let options = root.entry("options").or_insert(serde_json::Value::Null);+ if options.is_null() {+ *options = serde_json::json!({});+ }+ let options = options.as_object_mut().context("Crush global config `options` must be a JSON object")?;let paths = options.entry("global_context_paths")- .or_insert_with(|| serde_json::json!([]))+ .or_insert(serde_json::Value::Null);+ if paths.is_null() {+ *paths = serde_json::json!([]);+ }+ let paths = paths.as_array_mut().context("Crush `options.global_context_paths` must be an array")?;+ // Crush fills an empty list with `CRUSH.md` beside its global config and+ // `AGENTS.md` one level up, but only while the list is empty, and it would+ // resolve them against this temp dir. Seed the user's own ones first so+ // the packet does not replace them.+ if paths.is_empty()+ && let Some(config_dir) = source.parent()+ {+ paths.push(serde_json::Value::String(+ config_dir.join("CRUSH.md").to_string_lossy().into_owned(),+ ));+ if let Some(parent) = config_dir.parent() {+ paths.push(serde_json::Value::String(+ parent.join("AGENTS.md").to_string_lossy().into_owned(),+ ));+ }+ }let context_path = context_path.to_string_lossy().into_owned();if !paths.iter()@@ -1090,17 +1274,23 @@ fn write_crush_context_config(source: &Path, context: &str) -> Result<tempfile::}let rendered = serde_json::to_vec_pretty(&config).context("rendering Crush config")?;write_private(&temp.path().join("crush.json"), &rendered)?;- Ok(temp)-}--fn crush_global_config_path(home: &Path) -> PathBuf {- if let Some(dir) = std::env::var_os("CRUSH_GLOBAL_CONFIG").filter(|value| !value.is_empty()) {- return PathBuf::from(dir).join("crush.json");- }- if let Some(dir) = std::env::var_os("XDG_CONFIG_HOME").filter(|value| !value.is_empty()) {- return PathBuf::from(dir).join("crush/crush.json");+ // Crush also runs the `crushrc` beside its global config, and with the+ // config dir moved here it would look for one in this dir. Source the+ // user's own from the directory Crush runs it in, so its relative paths+ // and `source` lines still resolve. Its settings merge over the JSON+ // above and lists concatenate, so the packet stays loaded. Unlike Crush,+ // the default context files above are seeded even when the script adds+ // paths of its own.+ if let Some(config_dir) = source.parent() {+ let crushrc = config_dir.join("crushrc");+ if crushrc.is_file() {+ let quote =+ |path: &Path| format!("'{}'", path.to_string_lossy().replace('\'', r"'\''"));+ let wrapper = format!("cd {} && source {}\n", quote(config_dir), quote(&crushrc));+ write_private(&temp.path().join("crushrc"), wrapper.as_bytes())?;+ }}- home.join(".config/crush/crush.json")+ Ok(temp)}fn write_private(path: &Path, content: &[u8]) -> Result<()> {@@ -2295,9 +2485,15 @@ mod tests {"CLAUDE_CONFIG_DIR".to_string(),"/accounts/work".to_string(),)];- let plan =- build_launch_plan_with_env(ManagedHarness::Claude, None, Vec::new(), None, &overrides)- .unwrap();+ let plan = build_launch_plan_with_env(+ ManagedHarness::Claude,+ None,+ Vec::new(),+ None,+ &overrides,+ None,+ )+ .unwrap();assert_eq!(plan.session_dir.as_deref(),Some(Path::new("/accounts/work/projects"))@@ -2547,6 +2743,7 @@ mod tests {&cwd,started_at,None,+ None,).await.unwrap()@@ -2562,6 +2759,7 @@ mod tests {&cwd,started_at,None,+ None,).await.unwrap()@@ -2570,6 +2768,168 @@ mod tests {);}+ /// A hook links the run's own session under its run id, so a newer+ /// session another launch made in the same checkout does not replace it.+ /// A report that only repeats the session the run was prepared with is no+ /// link, and discovery still decides.+ #[tokio::test]+ async fn hook_linked_session_wins_over_a_newer_concurrent_session() {+ let temp = tempfile::tempdir().unwrap();+ let cwd = temp.path().join("repo");+ let session_root = temp.path().join(".codex/sessions/2026/01/01");+ std::fs::create_dir_all(&cwd).unwrap();+ std::fs::create_dir_all(&session_root).unwrap();+ let started_at = SystemTime::now();+ let rollout = |name: &str, id: &str, cwd: &Path| {+ std::fs::write(+ session_root.join(format!("rollout-{name}.jsonl")),+ format!(+ "{}\n",+ serde_json::json!({+ "type": "session_meta",+ "payload": {"id": id, "cwd": cwd}+ })+ ),+ )+ .unwrap();+ };+ rollout("linked", "hook-linked", &cwd);+ // A descendant process in another checkout inherits the run id.+ rollout("nested", "nested", &temp.path().join("other-checkout"));+ rollout("concurrent", "concurrent-newer", &cwd);+ let plan = build_launch_plan(ManagedHarness::Codex, None, Vec::new(), None).unwrap();+ let status = |native: &str| ManagedRunStatus {+ run_id: ManagedRunId::new(),+ workstream_id: WorkstreamId::new(),+ agent: AgentKind::Codex,+ native_session_id: Some(native.to_string()),+ context_delivered: true,+ state: "active".to_string(),+ };+ let resolve = async |native: &str, prepared: Option<&str>| {+ resolve_native_session_after_run(+ &plan,+ ManagedHarness::Codex,+ temp.path(),+ &cwd,+ started_at,+ prepared,+ Some(&status(native)),+ )+ .await+ .unwrap()+ };+ assert_eq!(+ resolve("hook-linked", None).await.as_deref(),+ Some("hook-linked")+ );+ assert_eq!(+ resolve("hook-linked", Some("earlier")).await.as_deref(),+ Some("hook-linked")+ );+ assert_eq!(+ resolve("hook-linked", Some("hook-linked")).await.as_deref(),+ Some("concurrent-newer")+ );+ assert_eq!(+ resolve("nested", Some("earlier")).await.as_deref(),+ Some("concurrent-newer")+ );+ // With nothing to discover here, the other checkout's session is not+ // taken as a fallback either; the prepared session still is.+ let empty = temp.path().join("empty-checkout");+ std::fs::create_dir_all(&empty).unwrap();+ for (prepared, expected) in [(Some("earlier"), None), (Some("nested"), Some("nested"))] {+ assert_eq!(+ resolve_native_session_after_run(+ &plan,+ ManagedHarness::Codex,+ temp.path(),+ &empty,+ started_at,+ prepared,+ Some(&status("nested")),+ )+ .await+ .unwrap()+ .as_deref(),+ expected,+ "prepared={prepared:?}"+ );+ }+ }++ /// Two new Crush sessions in one store cannot be told apart, and that is+ /// reported without cancelling the finished run or falling back to the+ /// session the run was prepared with, which another launch may have+ /// moved. With no ambiguity a fresh run that created nothing keeps that+ /// session, and `--continue` claims the session it resumed.+ #[tokio::test]+ async fn ambiguous_crush_discovery_keeps_the_run() {+ let temp = tempfile::tempdir().unwrap();+ let cwd = temp.path().join("repo");+ std::fs::create_dir_all(&cwd).unwrap();+ let started = 1_900_000_000_i64;+ let started_at = SystemTime::UNIX_EPOCH + Duration::from_secs(started as u64);+ let store = |name: &str, sessions: &[(&str, i64, i64)]| {+ // Inside the checkout: a store only this project uses.+ let data = cwd.join(name);+ std::fs::create_dir_all(&data).unwrap();+ let connection = rusqlite::Connection::open(data.join("crush.db")).unwrap();+ connection+ .execute_batch(+ "CREATE TABLE sessions(id TEXT PRIMARY KEY, parent_session_id TEXT, \+ updated_at INTEGER NOT NULL, created_at INTEGER NOT NULL);",+ )+ .unwrap();+ for (id, created, updated) in sessions {+ connection+ .execute(+ "INSERT INTO sessions VALUES (?1, NULL, ?2, ?3)",+ rusqlite::params![id, started + updated, started + created],+ )+ .unwrap();+ }+ data+ };+ let crowded = store(+ "crowded",+ &[("continued", -1_000, 30), ("a", 5, 20), ("b", 8, 10)],+ );+ let quiet = store("quiet", &[("continued", -1_000, 30)]);+ let status = ManagedRunStatus {+ run_id: ManagedRunId::new(),+ workstream_id: WorkstreamId::new(),+ agent: AgentKind::Crush,+ native_session_id: Some("prepared".to_string()),+ context_delivered: false,+ state: "active".to_string(),+ };+ let resolve = async |data: &Path, extra: &[&str]| {+ let mut args = vec![OsString::from("--data-dir"), data.as_os_str().to_owned()];+ args.extend(extra.iter().map(OsString::from));+ let plan = build_launch_plan(ManagedHarness::Crush, None, args, None).unwrap();+ resolve_native_session_after_run(+ &plan,+ ManagedHarness::Crush,+ temp.path(),+ &cwd,+ started_at,+ Some("prepared"),+ Some(&status),+ )+ .await+ .unwrap()+ };+ assert_eq!(resolve(&crowded, &[]).await, None);+ assert_eq!(resolve(&crowded, &["--continue"]).await, None);+ assert_eq!(resolve(&quiet, &[]).await.as_deref(), Some("prepared"));+ assert_eq!(+ resolve(&quiet, &["--continue"]).await.as_deref(),+ Some("continued")+ );+ }+#[test]fn crush_context_config_preserves_user_settings_and_adds_packet() {let source_dir = tempfile::tempdir().unwrap();@@ -2601,7 +2961,7 @@ mod tests {/// The `ai-memory run` -> autowire -> child-spawn seam: driving the launcher/// entry point (`run_from_with_wiring`) must run auto-wire *before* the child/// starts, so the harness's ai-memory hooks + MCP are installed and the- /// per-(agent, version) sentinel is written as a side effect of `run` itself.+ /// auto-wire sentinel is written as a side effect of `run` itself./// The autowire path injections keep it off the developer's real `$HOME`, the/// child is a harmless `exit 0` script launched in passthrough mode/// (`--version`), and a mock server stands in for the workstream endpoints, so@@ -2674,6 +3034,7 @@ mod tests {hooks_dir: Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../hooks")),hooks_config_file: Some(settings.clone()),mcp_config_file: Some(mcp.clone()),+ ..WireOverrides::default()};let args = || RunArgs {workspace: Some("ws".into()),@@ -2715,10 +3076,12 @@ mod tests {mcp_json.contains("ai-memory"),"run must auto-install the ai-memory MCP server before spawning: {mcp_json}");- let sentinels = std::fs::read_dir(data.path().join("autowire-state"))- .expect("autowire-state dir created by the run")- .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())- .collect::<Vec<_>>();+ let sentinels = std::fs::read_dir(crate::commands::run_autowire::autowire_state_dir(+ data.path(),+ ))+ .expect("autowire-state dir created by the run")+ .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())+ .collect::<Vec<_>>();assert!(sentinels.iter()@@ -2746,4 +3109,587 @@ mod tests {server.abort();}++ /// A mock workstream server for launches driven through `run_from`: it+ /// prepares a run, linked to `native_session_id` when one is given, and+ /// accepts the link and the finish.+ async fn mock_workstream_server(+ native_session_id: Option<&'static str>,+ ) -> (std::net::SocketAddr, tokio::task::JoinHandle<()>) {+ let app = Router::new()+ .route(+ "/workstream/runs",+ post(move || async move {+ axum::Json(PrepareManagedRunResponse {+ workstream_id: WorkstreamId::new(),+ workstream_name: "default".into(),+ run_id: ManagedRunId::new(),+ resolved_agent: None,+ native_session_id: native_session_id.map(str::to_owned),+ source_cursor: None,+ sync_after: 0,+ sync_through: 0,+ may_adopt_existing_session: false,+ })+ }),+ )+ .route(+ "/workstream/runs/{run_id}/link",+ post(|| async { StatusCode::NO_CONTENT }),+ )+ .route(+ "/workstream/runs/{run_id}/finish",+ post(|| async {+ axum::Json(FinishManagedRunResponse {+ imported_events: 0,+ latest_sequence: 0,+ })+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ (address, server)+ }++ #[cfg(unix)]+ fn capture_env_script(dir: &Path, variable: &str) -> (PathBuf, PathBuf) {+ use std::os::unix::fs::PermissionsExt as _;++ let captured = dir.join("captured-env");+ let script = dir.join("capture-env-harness");+ std::fs::write(+ &script,+ format!(+ "#!/bin/sh\nprintf '%s' \"${{{variable}-unset}}\" > {}\nexit 0\n",+ captured.display()+ ),+ )+ .unwrap();+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();+ (script, captured)+ }++ fn launch_config(home: &Path, data: &Path, address: std::net::SocketAddr) -> Config {+ let mut config = Config::load(None, Some(home.to_path_buf())).unwrap();+ config.data_dir = data.to_path_buf();+ config.home_dir = Some(home.to_string_lossy().into_owned());+ config.server_url = format!("http://{address}");+ config.run_autowire = true;+ config+ }++ fn run_args(+ harness: RunHarnessChoice,+ executable: PathBuf,+ env: Vec<(String, String)>,+ native_args: &[&str],+ ) -> RunArgs {+ RunArgs {+ workspace: Some("ws".into()),+ project: Some("proj".into()),+ workstream: None,+ new_workstream: None,+ executable: Some(executable),+ yolo: false,+ fresh: false,+ no_autowire: false,+ env,+ env_file: None,+ harness: Some(harness),+ native_args: native_args.iter().map(OsString::from).collect(),+ }+ }++ /// `run` must hand its `--env` to auto-wire, or a relocated config home+ /// launches without hooks or MCP. The guard refuses every install outside+ /// the test's data dir, so if `run` dropped the env nothing is written at+ /// all, least of all to the real home.+ #[cfg(unix)]+ #[tokio::test]+ async fn run_entry_point_passes_run_env_to_autowire() {+ use crate::commands::run_autowire::WireOverrides;++ let (address, server) = mock_workstream_server(None).await;+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let repo = tempfile::tempdir().unwrap();+ let (script, captured) = capture_env_script(repo.path(), "CLAUDE_CONFIG_DIR");+ let claude_home = data.path().join("claude-home");+ std::fs::create_dir_all(&claude_home).unwrap();++ let config = launch_config(home.path(), data.path(), address);+ let overrides = WireOverrides {+ hooks_dir: Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../hooks")),+ confine_to: Some(data.path().to_path_buf()),+ ..WireOverrides::default()+ };+ let env = vec![(+ "CLAUDE_CONFIG_DIR".to_string(),+ claude_home.display().to_string(),+ )];+ let exit = run_from_with_wiring(+ &config,+ run_args(RunHarnessChoice::Claude, script, env, &["--version"]),+ repo.path(),+ &overrides,+ )+ .await+ .expect("managed passthrough run completes");+ assert_eq!(exit, 0);+ assert_eq!(+ std::fs::read_to_string(&captured).unwrap(),+ claude_home.display().to_string()+ );++ let settings = claude_home.join("settings.json");+ assert!(+ std::fs::read_to_string(&settings)+ .is_ok_and(|s| s.contains("ai-memory") || s.contains("ai_memory")),+ "hooks missing in {}",+ settings.display()+ );+ let mcp = claude_home.join(".claude.json");+ assert!(+ std::fs::read_to_string(&mcp).is_ok_and(|s| s.contains("ai-memory")),+ "MCP missing in {}",+ mcp.display()+ );++ server.abort();+ }++ /// A Kiro v3 session stored under the default home is resumed with+ /// `KIRO_HOME` removed from the child, so auto-wire must wire that default+ /// home. Wiring the `--env` home instead left the resumed session with no+ /// hooks and no MCP.+ #[cfg(unix)]+ #[tokio::test]+ async fn kiro_v3_default_store_resume_autowires_the_home_the_child_reads() {+ use crate::commands::run_autowire::WireOverrides;++ const SESSION: &str = "sess_c3774f9d-269e-40d1-aa02-2bb0c0817b4e";+ let (address, server) = mock_workstream_server(Some(SESSION)).await;+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let repo = tempfile::tempdir().unwrap();+ let (script, captured) = capture_env_script(repo.path(), "KIRO_HOME");++ let session_dir = home+ .path()+ .join(".kiro/sessions/checkout-fixture")+ .join(SESSION);+ std::fs::create_dir_all(&session_dir).unwrap();+ std::fs::write(+ session_dir.join("session.json"),+ serde_json::json!({+ "schemaVersion": "1.0.0",+ "dataModelVersion": 1,+ "id": SESSION,+ "workspacePaths": [repo.path()],+ "createdAt": "2026-08-06T10:00:00Z",+ "lastModifiedAt": "2026-08-06T10:05:00Z",+ "agentMode": "vibe",+ "status": "idle"+ })+ .to_string(),+ )+ .unwrap();+ std::fs::write(session_dir.join("messages.jsonl"), "{}\n").unwrap();+ let custom = home.path().join("custom-kiro");+ std::fs::create_dir_all(custom.join("sessions")).unwrap();++ let config = launch_config(home.path(), data.path(), address);+ let overrides = WireOverrides {+ hooks_dir: Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../hooks")),+ confine_to: Some(home.path().to_path_buf()),+ ..WireOverrides::default()+ };+ let env = vec![("KIRO_HOME".to_string(), custom.display().to_string())];+ let exit = run_from_with_wiring(+ &config,+ run_args(RunHarnessChoice::Kiro, script, env, &["--v3"]),+ repo.path(),+ &overrides,+ )+ .await+ .expect("managed Kiro v3 resume completes");+ assert_eq!(exit, 0);+ assert_eq!(+ std::fs::read_to_string(&captured).unwrap(),+ "unset",+ "the default-store resume must drop KIRO_HOME from the child"+ );++ let kiro_default = home.path().join(".kiro");+ let hooks = kiro_default.join("hooks").join("ai-memory.json");+ assert!(+ std::fs::read_to_string(&hooks).is_ok_and(|s| s.contains("ai-memory")),+ "hooks missing in {}",+ hooks.display()+ );+ let mcp = kiro_default.join("settings").join("mcp.json");+ assert!(+ std::fs::read_to_string(&mcp).is_ok_and(|s| s.contains("ai-memory")),+ "MCP missing in {}",+ mcp.display()+ );+ assert!(+ !custom.join("hooks").exists() && !custom.join("settings").exists(),+ "the KIRO_HOME the child no longer reads must stay untouched"+ );++ server.abort();+ }++ #[test]+ fn blank_home_overrides_names_only_blank_home_variables() {+ let env = |pairs: &'static [(&'static str, &'static str)]| {+ move |name: &str| {+ pairs+ .iter()+ .find(|(key, _)| *key == name)+ .map(|(_, value)| OsString::from(value))+ }+ };+ assert_eq!(+ blank_home_overrides(ManagedHarness::Claude, &env(&[("CLAUDE_CONFIG_DIR", " ")])),+ ["CLAUDE_CONFIG_DIR"]+ );+ assert!(+ blank_home_overrides(ManagedHarness::Claude, &env(&[("CLAUDE_CONFIG_DIR", "/x")]))+ .is_empty()+ );+ assert!(blank_home_overrides(ManagedHarness::Claude, &env(&[])).is_empty());+ assert!(+ blank_home_overrides(ManagedHarness::Codex, &env(&[("CLAUDE_CONFIG_DIR", "")]))+ .is_empty(),+ "only the launched harness's own variables"+ );+ assert_eq!(+ blank_home_overrides(+ ManagedHarness::Omp,+ &env(&[+ ("PI_CODING_AGENT_SESSION_DIR", ""),+ ("PI_CODING_AGENT_DIR", "/x")+ ])+ ),+ ["PI_CODING_AGENT_SESSION_DIR"]+ );+ assert_eq!(+ blank_home_overrides(+ ManagedHarness::Omp,+ &env(&[("PI_CONFIG_DIR", " "), ("XDG_DATA_HOME", "")])+ ),+ ["PI_CONFIG_DIR", "XDG_DATA_HOME"]+ );+ assert_eq!(+ blank_home_overrides(+ ManagedHarness::Crush,+ &env(&[("CRUSH_GLOBAL_CONFIG", " "), ("XDG_CONFIG_HOME", "/x")])+ ),+ ["CRUSH_GLOBAL_CONFIG"]+ );+ assert!(+ blank_home_overrides(ManagedHarness::Claude, &env(&[("XDG_CONFIG_HOME", "")]))+ .is_empty(),+ "Crush's config home is Crush's alone"+ );+ }++ /// The managed Crush context layers onto the global config the child+ /// would read: `--env` over ai-memory's own environment, blank as unset.+ /// A relative `CRUSH_GLOBAL_CONFIG` is read from the launch directory, as+ /// Crush reads it, so the generated config and `crushrc` do not point at+ /// paths the child would resolve from its temporary config dir.+ #[test]+ fn crush_context_source_is_anchored_at_the_launch_dir() {+ let home = Path::new("/home/user");+ let cwd = Path::new("/work/repo");+ let env = |pairs: &'static [(&'static str, &'static str)]| {+ move |name: &str| {+ pairs+ .iter()+ .find(|(key, _)| *key == name)+ .map(|(_, value)| OsString::from(value))+ }+ };+ assert_eq!(+ crush_context_source(home, cwd, env(&[("CRUSH_GLOBAL_CONFIG", "cfg")])),+ cwd.join("cfg").join("crush.json")+ );+ assert_eq!(+ crush_context_source(home, cwd, env(&[])),+ home.join(".config").join("crush").join("crush.json")+ );+ }++ #[test]+ fn crush_global_config_path_follows_the_launch_env() {+ let env = |pairs: &'static [(&'static str, &'static str)]| {+ move |name: &str| {+ pairs+ .iter()+ .find(|(key, _)| *key == name)+ .map(|(_, value)| OsString::from(value))+ }+ };+ let home = Path::new("/home/me");+ let default = home.join(".config").join("crush").join("crush.json");+ assert_eq!(+ crush_global_config_path(+ home,+ env(&[+ ("CRUSH_GLOBAL_CONFIG", "/team/crush"),+ ("XDG_CONFIG_HOME", "/xdg")+ ])+ ),+ Path::new("/team/crush").join("crush.json")+ );+ assert_eq!(+ crush_global_config_path(home, env(&[("XDG_CONFIG_HOME", "/xdg")])),+ Path::new("/xdg").join("crush").join("crush.json")+ );+ assert_eq!(+ crush_global_config_path(+ home,+ env(&[("CRUSH_GLOBAL_CONFIG", " "), ("XDG_CONFIG_HOME", "")])+ ),+ default,+ "blank counts as unset"+ );+ assert_eq!(crush_global_config_path(home, env(&[])), default);+ }++ /// Crush skips an empty config and reads `null` as unset, so neither may+ /// stop a managed launch.+ #[test]+ fn crush_context_config_accepts_what_crush_accepts() {+ let root = tempfile::tempdir().unwrap();+ for (name, content) in [+ ("empty", ""),+ ("null-options", r#"{"options": null}"#),+ (+ "null-paths",+ r#"{"options": {"global_context_paths": null}}"#,+ ),+ ("null", "null"),+ ] {+ let dir = root.path().join(name);+ std::fs::create_dir_all(&dir).unwrap();+ let source = dir.join("crush.json");+ std::fs::write(&source, content).unwrap();+ let generated = write_crush_context_config(&source, "managed packet")+ .unwrap_or_else(|error| panic!("{name}: {error:#}"));+ let config: serde_json::Value = serde_json::from_slice(+ &std::fs::read(generated.path().join("crush.json")).unwrap(),+ )+ .unwrap();+ assert_eq!(+ config["options"]["global_context_paths"]+ .as_array()+ .map(Vec::len),+ Some(3),+ "{name}: {config}"+ );+ }+ }++ /// Crush cleans the config path before reading it and deriving its default+ /// context files, so a `..` in `CRUSH_GLOBAL_CONFIG` moves neither.+ #[test]+ fn crush_default_context_files_follow_the_cleaned_config_path() {+ let root = tempfile::tempdir().unwrap();+ let config_dir = root.path().join("cfg");+ std::fs::create_dir_all(&config_dir).unwrap();+ std::fs::write(config_dir.join("crush.json"), r#"{"marker": 1}"#).unwrap();+ // `missing` does not exist: only a cleaned path reaches the file.+ let source = config_dir.join("missing").join("..").join("crush.json");++ let generated = write_crush_context_config(&source, "managed packet").unwrap();+ let config: serde_json::Value =+ serde_json::from_slice(&std::fs::read(generated.path().join("crush.json")).unwrap())+ .unwrap();+ let paths: Vec<&str> = config["options"]["global_context_paths"]+ .as_array()+ .unwrap()+ .iter()+ .map(|value| value.as_str().unwrap())+ .collect();+ assert_eq!(Path::new(paths[0]), config_dir.join("CRUSH.md"));+ assert_eq!(Path::new(paths[1]), root.path().join("AGENTS.md"));+ assert_eq!(config["marker"], 1, "the user's config was read");+ }++ /// Crush only fills in its default `CRUSH.md` / `AGENTS.md` while+ /// `global_context_paths` is empty, so the packet must not displace the+ /// user's own files.+ #[test]+ fn crush_context_config_keeps_crush_default_context_files() {+ let root = tempfile::tempdir().unwrap();+ let config_dir = root.path().join("config").join("crush");+ std::fs::create_dir_all(&config_dir).unwrap();+ let source = config_dir.join("crush.json");+ std::fs::write(&source, r#"{"options": {"debug": true}}"#).unwrap();++ let generated = write_crush_context_config(&source, "managed packet").unwrap();+ let config: serde_json::Value =+ serde_json::from_slice(&std::fs::read(generated.path().join("crush.json")).unwrap())+ .unwrap();+ let paths: Vec<&str> = config["options"]["global_context_paths"]+ .as_array()+ .unwrap()+ .iter()+ .map(|value| value.as_str().unwrap())+ .collect();+ assert_eq!(paths.len(), 3, "{paths:?}");+ assert_eq!(Path::new(paths[0]), config_dir.join("CRUSH.md"));+ assert_eq!(+ Path::new(paths[1]),+ root.path().join("config").join("AGENTS.md")+ );+ assert_eq!(std::fs::read_to_string(paths[2]).unwrap(), "managed packet");+ }++ /// Crush runs the `crushrc` beside its global config, and moving the+ /// config dir for the context packet would drop the user's. The generated+ /// dir sources it from its own directory, so relative `source` lines keep+ /// working, whatever the path contains.+ #[cfg(unix)]+ #[test]+ fn crush_context_config_carries_the_global_crushrc() {+ let root = tempfile::tempdir().unwrap();+ let root = std::fs::canonicalize(root.path()).unwrap();+ let config_dir = root.join("it's my crush");+ std::fs::create_dir_all(&config_dir).unwrap();+ let source = config_dir.join("crush.json");++ let generated = write_crush_context_config(&source, "managed packet").unwrap();+ assert!(!generated.path().join("crushrc").exists());++ std::fs::write(config_dir.join("crushrc"), "source ./extra\n").unwrap();+ std::fs::write(config_dir.join("extra"), "pwd > \"$OUT\"\n").unwrap();+ let generated = write_crush_context_config(&source, "managed packet").unwrap();+ let out = root.join("out");+ // Crush runs a crushrc from its own directory.+ let status = std::process::Command::new("bash")+ .arg(generated.path().join("crushrc"))+ .current_dir(generated.path())+ .env("OUT", &out)+ .status()+ .unwrap();+ assert!(status.success());+ assert_eq!(+ std::fs::read_to_string(&out).unwrap().trim_end(),+ config_dir.to_str().unwrap()+ );+ }++ /// The launched harness must not see a blank store override that session+ /// import and auto-wire treat as unset, or it reads a blank-named+ /// directory nothing else follows.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_blank_store_override_is_dropped_from_the_child() {+ use crate::commands::run_autowire::WireOverrides;++ let (address, server) = mock_workstream_server(None).await;+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let repo = tempfile::tempdir().unwrap();+ let (script, captured) = capture_env_script(repo.path(), "CLAUDE_CONFIG_DIR");+ let config = launch_config(home.path(), data.path(), address);+ let mut args = run_args(+ RunHarnessChoice::Claude,+ script,+ vec![("CLAUDE_CONFIG_DIR".to_string(), " ".to_string())],+ &["--version"],+ );+ args.no_autowire = true;+ let exit = run_from_with_wiring(&config, args, repo.path(), &WireOverrides::default())+ .await+ .expect("managed passthrough run completes");+ assert_eq!(exit, 0);+ assert_eq!(std::fs::read_to_string(&captured).unwrap(), "unset");++ server.abort();+ }++ /// OMP ranks `--profile` above `OMP_PROFILE`, and a Kiro v3 default-store+ /// resume drops `KIRO_HOME`, so auto-wire sees what the child will run+ /// with; everything else in `--env` passes through untouched.+ #[test]+ fn autowire_env_follows_what_the_child_runs_with() {+ let run_env = vec![+ ("OMP_PROFILE".to_string(), "other".to_string()),+ ("KIRO_HOME".to_string(), "/custom".to_string()),+ ("FOO".to_string(), "x".to_string()),+ ];+ let lookup = |env: &[(String, String)], name: &str| {+ let values: Vec<_> = env+ .iter()+ .filter(|(key, _)| key == name)+ .map(|(_, value)| value.clone())+ .collect();+ values+ };+ // Only the run_env: no process environment leaks into the test.+ let only = |env: Vec<(String, String)>| {+ move |name: &str| {+ env.iter()+ .find(|(key, _)| key == name)+ .map(|(_, value)| OsString::from(value))+ }+ };+ let launch = only(run_env.clone());++ let args = [OsString::from("--profile"), OsString::from("work")];+ let omp = autowire_env(ManagedHarness::Omp, &run_env, &args, None, &launch);+ assert_eq!(lookup(&omp, "OMP_PROFILE"), ["work"]);+ assert_eq!(lookup(&omp, "KIRO_HOME"), ["/custom"]);+ assert_eq!(lookup(&omp, "FOO"), ["x"]);+ assert_eq!(+ autowire_env(ManagedHarness::Pi, &run_env, &args, None, &launch),+ run_env,+ "only OMP reads --profile"+ );+ assert_eq!(+ autowire_env(ManagedHarness::Omp, &run_env, &[], None, &launch),+ run_env+ );++ // `--profile default` under an environment a profiled parent OMP+ // exported: OMP drops the inherited agent dir, and so must auto-wire.+ let home = Path::new("/home/me");+ let inherited = vec![+ ("OMP_PROFILE".to_string(), "work".to_string()),+ (+ "PI_CODING_AGENT_DIR".to_string(),+ "/home/me/.omp/profiles/work/agent".to_string(),+ ),+ ("PI_CONFIG_DIR".to_string(), String::new()),+ ];+ let default_args = [OsString::from("--profile"), OsString::from("default")];+ let wired = autowire_env(+ ManagedHarness::Omp,+ &inherited,+ &default_args,+ None,+ &only(inherited.clone()),+ );+ assert_eq!(+ ai_memory_workstream::omp_agent_dir(home, None, only(wired)).unwrap(),+ home.join(".omp").join("agent")+ );++ let kiro = autowire_env(+ ManagedHarness::KiroV3,+ &run_env,+ &[],+ Some(Path::new("/home/me/.kiro")),+ &launch,+ );+ assert_eq!(lookup(&kiro, "KIRO_HOME"), ["/home/me/.kiro"]);+ assert_eq!(lookup(&kiro, "OMP_PROFILE"), ["other"]);+ }}diff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rsindex 495abde9..56c76051 100644--- a/crates/ai-memory-cli/src/commands/run_autowire.rs+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs@@ -7,18 +7,25 @@//! user ran `ai-memory run kimi` and nothing was captured because the Kimi hooks//! and MCP had never been installed.//!-//! This runs at most once per (harness, binary version): a per-agent sentinel-//! under `<data_dir>/autowire-state/` keeps the run hot-path fast on every-//! subsequent launch, while keying on the version means an upgrade re-stages the-//! fresh hook bundle. Both installs are idempotent (they no-op when already up-//! to date), and the whole step is best-effort — a failure warns and the harness-//! still launches. Opt out with `run --no-autowire` or `AI_MEMORY_RUN_AUTOWIRE=false`.+//! This runs at most once per (harness, binary version, install location): a+//! sentinel under `<data_dir>/autowire-state/` keeps the run hot-path fast on+//! every subsequent launch, keying on the version means an upgrade re-stages the+//! fresh hook bundle, and keying on where the hook and MCP configs resolve means+//! a second config home (another `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, ...) gets+//! its own first launch instead of being skipped. Those locations follow+//! `run --env` / `--env-file` first, then ai-memory's own environment. Both+//! installs are idempotent (they no-op when already up to date), and the whole+//! step is best-effort — a failure warns and the harness still launches. Opt out+//! with `run --no-autowire` or `AI_MEMORY_RUN_AUTOWIRE=false`.-use std::path::{Path, PathBuf};+use std::cell::Cell;+use std::ffi::OsString;+use std::path::{Component, Path, PathBuf};use ai_memory_workstream::ManagedHarness;+use sha2::{Digest as _, Sha256};-use crate::cli::{AgentChoice, InstallHooksArgs, InstallMcpArgs};+use crate::cli::{AgentChoice, InstallHooksArgs, InstallMcpArgs, McpClient};use crate::config::Config;use super::{install_hooks, install_mcp};@@ -45,12 +52,25 @@ pub(crate) fn agent_choice_for_harness(harness: ManagedHarness) -> Option<AgentC})}-/// Per-(agent, version) sentinel marking that auto-wire already ran for this-/// harness on this machine with this binary. Keyed by the agent's stable kebab-/// name plus the crate version so an upgrade re-wires the fresh hook bundle.-fn sentinel_path(data_dir: &Path, agent: AgentChoice) -> PathBuf {- let name = format!("{}-{}", agent.kind().as_str(), env!("CARGO_PKG_VERSION"));- data_dir.join("autowire-state").join(name)+/// Sentinel marking that auto-wire already ran for this agent, binary version+/// and install location. The version re-wires the fresh hook bundle after an+/// upgrade; the hashed hook and MCP config locations give each config home its+/// own first launch.+/// Where auto-wire records its sentinels. `uninstall` clears it whenever it+/// removes hooks or MCP, so the next managed launch wires again.+pub(crate) fn autowire_state_dir(data_dir: &Path) -> PathBuf {+ data_dir.join("autowire-state")+}++fn sentinel_path(data_dir: &Path, agent: AgentChoice, targets: &[String]) -> PathBuf {+ let digest = format!("{:x}", Sha256::digest(targets.join("\n").as_bytes()));+ let name = format!(+ "{}-{}-{}",+ agent.kind().as_str(),+ env!("CARGO_PKG_VERSION"),+ &digest[..16]+ );+ autowire_state_dir(data_dir).join(name)}fn write_sentinel(path: &Path) {@@ -73,11 +93,285 @@ pub(crate) struct WireOverrides {pub hooks_config_file: Option<PathBuf>,/// Destination agent MCP-config file (else the agent's real path).pub mcp_config_file: Option<PathBuf>,+ /// Refuse every install whose target is not an explicit path under this+ /// directory, instead of letting it reach the real `$HOME` (an installer+ /// default, or a relocation that resolved back to the home). Lets a test+ /// drive `run` without injected targets and still never write outside+ /// its temp dirs.+ pub confine_to: Option<PathBuf>,+}++/// `path` with every existing part resolved through symlinks, so+/// `<root>/link/settings.json` with `link` pointing elsewhere is not under+/// `<root>`; the missing tail is folded lexically. `None` for a relative path+/// or a dangling link, which cannot be placed.+fn resolve_through_links(path: &Path) -> Option<PathBuf> {+ for existing in path.ancestors() {+ match std::fs::canonicalize(existing) {+ Ok(resolved) => {+ let rest = path.strip_prefix(existing).ok()?;+ let joined = ai_memory_workstream::clean_path(&resolved.join(rest));+ // Folding `missing/../link` lands on a part that exists, and+ // creating `missing` lets the write follow `link`: resolve+ // again from there.+ return if rest.components().any(|part| part == Component::ParentDir) {+ resolve_through_links(&joined)+ } else {+ Some(joined)+ };+ }+ // A link whose target is missing would be written through.+ Err(_) if std::fs::symlink_metadata(existing).is_ok() => return None,+ Err(_) => {}+ }+ }+ None+}++/// Reads the relocation variables for auto-wire: `run --env` / `--env-file`+/// entries first, then ai-memory's own environment. That is the order the+/// launch plan resolves the native session store in, so hooks, MCP and+/// transcript import agree on one config home. It also records whether any+/// value it handed out came from `--env`.+struct LaunchEnv<'a> {+ run_env: &'a [(String, String)],+ from_run_env: Cell<bool>,+}++impl<'a> LaunchEnv<'a> {+ fn new(run_env: &'a [(String, String)]) -> Self {+ Self {+ run_env,+ from_run_env: Cell::new(false),+ }+ }++ fn var_os(&self, name: &str) -> Option<OsString> {+ if let Some((_, value)) = self.run_env.iter().find(|(key, _)| key == name) {+ self.from_run_env.set(true);+ return Some(OsString::from(value));+ }+ std::env::var_os(name)+ }+}++/// Where this launch's auto-wire installs, resolved without touching the disk.+struct WireTargets {+ agent: AgentChoice,+ sentinel: PathBuf,+ hook_target: anyhow::Result<PathBuf>,+ /// Whether any relocation variable behind the hook target came from `--env`.+ hook_relocated: bool,+ mcp_client: Option<McpClient>,+ mcp_target: Option<anyhow::Result<PathBuf>>,+ mcp_relocated: bool,+ /// The extensions directory Pi and OMP share under the launch env, when+ /// the installer's own check (which reads ai-memory's environment) would+ /// miss it.+ shared_extensions_dir: Option<PathBuf>,}-/// Ensure the launched harness has ai-memory hooks + MCP installed. Best-effort-/// and one-time; never blocks or fails the launch.+fn wire_targets(+ config: &Config,+ harness: ManagedHarness,+ overrides: &WireOverrides,+ run_env: &[(String, String)],+) -> Option<WireTargets> {+ let agent = agent_choice_for_harness(harness)?;+ let hook_env = LaunchEnv::new(run_env);+ let hook_target = install_hooks::hook_config_target_with(agent, &|name| hook_env.var_os(name));+ let mcp_client = install_hooks::mcp_client_for_agent(agent);+ let mcp_env = LaunchEnv::new(run_env);+ let mcp_target = mcp_client+ .map(|client| install_mcp::mcp_config_path_with(client, &|name| mcp_env.var_os(name)));+ let sentinel = sentinel_path(+ &config.data_dir,+ agent,+ &[+ target_key(overrides.hooks_config_file.as_deref(), Some(&hook_target)),+ target_key(overrides.mcp_config_file.as_deref(), mcp_target.as_ref()),+ ],+ );+ let shared_extensions_dir = match (&overrides.hooks_config_file, &hook_target) {+ (None, Ok(target)) => {+ let launch = LaunchEnv::new(run_env);+ let process = LaunchEnv::new(&[]);+ install_hooks::shared_extensions_dir(agent, target, &|name| launch.var_os(name)).filter(+ |_| {+ install_hooks::shared_extensions_dir(agent, target, &|name| {+ process.var_os(name)+ })+ .is_none()+ },+ )+ }+ _ => None,+ };+ Some(WireTargets {+ agent,+ sentinel,+ hook_target,+ hook_relocated: hook_env.from_run_env.get(),+ mcp_client,+ mcp_target,+ mcp_relocated: mcp_env.from_run_env.get(),+ shared_extensions_dir,+ })+}++/// One sentinel component: the injected path, else the resolved one. A+/// relative `--env` value is made absolute against the directory the installer+/// writes from, so the same relative name in two checkouts keys two sentinels.+fn target_key(injected: Option<&Path>, resolved: Option<&anyhow::Result<PathBuf>>) -> String {+ let key = |path: &Path| {+ std::path::absolute(path)+ .unwrap_or_else(|_| path.to_path_buf())+ .display()+ .to_string()+ };+ match (injected, resolved) {+ (Some(path), _) => key(path),+ (None, Some(Ok(path))) => key(path),+ (None, Some(Err(_))) => "unresolved".to_string(),+ (None, None) => "none".to_string(),+ }+}++/// The installer calls one auto-wire makes. A test override always wins;+/// otherwise a target is pinned only when `--env` moved it, so a launch without+/// `--env` installs exactly where the installers pick on their own.+struct WireInstalls {+ /// One hook install, or one per agent config for a Kiro CLI v2 home that+ /// `--env` relocated.+ hooks: Vec<InstallHooksArgs>,+ /// Why no hook install could be planned, reported like an install failure.+ hooks_skipped: Option<String>,+ mcp: Option<InstallMcpArgs>,+ /// Why the MCP install was not planned, reported like an install failure.+ mcp_skipped: Option<String>,+ shared_extensions_dir: Option<PathBuf>,+}++fn wire_installs(config: &Config, targets: WireTargets, overrides: &WireOverrides) -> WireInstalls {+ let WireTargets {+ agent,+ hook_target,+ hook_relocated,+ mcp_client,+ mcp_target,+ mcp_relocated,+ shared_extensions_dir,+ ..+ } = targets;+ let server_url = Some(config.server_url.clone());+ let auth_token = config.auth.bearer_token.clone();+ let hook_install = |config_file: Option<PathBuf>| InstallHooksArgs {+ agent,+ hooks_dir: overrides.hooks_dir.clone(),+ server_url: server_url.clone(),+ auth_token: auth_token.clone(),+ as_user: None,+ apply: true,+ config_file,+ project_strategy: None,+ capture_assistant: false,+ capture_mode: None,+ no_capture_prompts: false,+ capture_prompts: false,+ profile: None,+ };+ let (hooks, hooks_skipped) = match (&overrides.hooks_config_file, hook_target) {+ (Some(file), _) => (vec![hook_install(Some(file.clone()))], None),+ // Kiro CLI v2 keeps hooks inside each agent config. The installer lists+ // them only under its own KIRO_HOME, and its --config-file names a single+ // config, so a relocated agents directory is expanded here.+ (None, Ok(agents_dir)) if hook_relocated && agent == AgentChoice::KiroCli => {+ match install_hooks::list_kiro_cli_agent_configs(&agents_dir) {+ Ok(files) if !files.is_empty() => (+ files+ .into_iter()+ .map(|file| hook_install(Some(file)))+ .collect(),+ None,+ ),+ Ok(_) => (+ Vec::new(),+ Some(format!(+ "no Kiro CLI agent configs found in {}",+ agents_dir.display()+ )),+ ),+ Err(error) => (Vec::new(), Some(format!("{error:#}"))),+ }+ }+ (None, Ok(target)) if hook_relocated => (vec![hook_install(Some(target))], None),+ // `--env` set a value the resolver refused (an OMP profile OMP itself+ // rejects). The installer would fall back to ai-memory's own+ // environment and wire a home this launch does not use.+ (None, Err(error)) if hook_relocated => (Vec::new(), Some(format!("{error:#}"))),+ (None, _) => (vec![hook_install(None)], None),+ };+ let outside_confinement = |file: Option<&PathBuf>| {+ overrides.confine_to.as_deref().is_some_and(|root| {+ let root = std::fs::canonicalize(root)+ .unwrap_or_else(|_| ai_memory_workstream::clean_path(root));+ !file+ .and_then(|file| resolve_through_links(file))+ .is_some_and(|file| file.starts_with(root))+ })+ };+ let confinement_refusal = || {+ overrides+ .confine_to+ .as_deref()+ .map_or_else(String::new, |root| {+ format!("refused a target outside {}", root.display())+ })+ };+ let (hooks, hooks_skipped) = if hooks+ .iter()+ .any(|args| outside_confinement(args.config_file.as_ref()))+ {+ (Vec::new(), Some(confinement_refusal()))+ } else {+ (hooks, hooks_skipped)+ };+ let (mcp_file, mcp_error) = match (&overrides.mcp_config_file, mcp_target) {+ (Some(file), _) => (Some(file.clone()), None),+ (None, Some(Ok(target))) if mcp_relocated => (Some(target), None),+ (None, Some(Err(error))) if mcp_relocated => (None, Some(format!("{error:#}"))),+ _ => (None, None),+ };+ let mcp_skipped = mcp_client.and(+ mcp_error.or_else(|| outside_confinement(mcp_file.as_ref()).then(confinement_refusal)),+ );+ let mcp = mcp_client+ .filter(|_| mcp_skipped.is_none())+ .map(|client| InstallMcpArgs {+ client,+ server_url: server_url.clone(),+ name: "ai-memory".to_string(),+ auth_token: auth_token.clone(),+ apply: true,+ config_file: mcp_file,+ session_aware: false,+ flavor: None,+ });+ WireInstalls {+ hooks,+ hooks_skipped,+ mcp,+ mcp_skipped,+ shared_extensions_dir,+ }+}++/// Ensure the launched harness has ai-memory hooks + MCP installed where this+/// launch's harness will look for them. Best-effort and one-time per install+/// location; never blocks or fails the launch.///+/// `run_env` is the resolved `--env` / `--env-file` list, so a relocated config+/// home (`--env CLAUDE_CONFIG_DIR=...`) is wired where the harness will read it./// Production launches pass [`WireOverrides::default()`] (via/// [`run_from`](super::run::run_from)); the overrides exist only so the seam can/// be exercised without writing to the developer's real `$HOME`.@@ -85,14 +379,16 @@ pub(crate) fn ensure_wired_with(config: &Config,harness: ManagedHarness,overrides: &WireOverrides,+ run_env: &[(String, String)],) {- let Some(agent) = agent_choice_for_harness(harness) else {+ let Some(targets) = wire_targets(config, harness, overrides, run_env) else {return;};- let sentinel = sentinel_path(&config.data_dir, agent);- if sentinel.exists() {+ if targets.sentinel.exists() {return;}+ let agent = targets.agent;+ let sentinel = targets.sentinel.clone();eprintln!("ai-memory: first managed launch of {} here — wiring its ai-memory hooks + MCP so \@@ -100,54 +396,40 @@ pub(crate) fn ensure_wired_with(harness.as_str());- let server_url = Some(config.server_url.clone());- let auth_token = config.auth.bearer_token.clone();-- if let Err(error) = install_hooks::run(- config,- InstallHooksArgs {- agent,- hooks_dir: overrides.hooks_dir.clone(),- server_url: server_url.clone(),- auth_token: auth_token.clone(),- as_user: None,- apply: true,- config_file: overrides.hooks_config_file.clone(),- project_strategy: None,- capture_assistant: false,- capture_mode: None,- no_capture_prompts: false,- capture_prompts: false,- profile: None,- },- ) {+ let installs = wire_installs(config, targets, overrides);+ let warn_hooks = |reason: &str| {eprintln!(- "ai-memory: could not auto-install {} hooks ({error:#}); continuing launch. \+ "ai-memory: could not auto-install {} hooks ({reason}); continuing launch. \Wire them manually with `ai-memory install-hooks --agent {} --apply`.",harness.as_str(),agent.kind().as_str());+ };+ for args in installs.hooks {+ match install_hooks::run(config, args) {+ Ok(()) => {+ if let Some(dir) = &installs.shared_extensions_dir {+ install_hooks::warn_agents_share_extensions_dir(dir);+ }+ }+ Err(error) => warn_hooks(&format!("{error:#}")),+ }+ }+ if let Some(reason) = &installs.hooks_skipped {+ warn_hooks(reason);}// 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 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,- },- )- {+ let mcp_failure = match installs.mcp {+ 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 ({error:#}); continuing \+ "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()@@ -156,7 +438,9 @@ pub(crate) fn ensure_wired_with(// Record the attempt even on partial failure: re-applying an idempotent// install on every launch would nag and churn config. A user who wants a- // retry can re-run install-hooks manually or clear the sentinel.+ // retry can re-run install-hooks manually or delete this sentinel under+ // `<data_dir>/autowire-state/`; `ai-memory uninstall` clears them all when+ // it removes hooks or MCP.write_sentinel(&sentinel);}@@ -209,23 +493,669 @@ mod tests {}#[test]- fn sentinel_is_agent_and_version_specific() {+ fn sentinel_keys_on_agent_version_and_install_targets() {let dir = Path::new("/data");- let claude = sentinel_path(dir, AgentChoice::ClaudeCode);- let codex = sentinel_path(dir, AgentChoice::Codex);+ let targets = |hooks: &str| vec![hooks.to_string(), "/cfg/.claude.json".to_string()];+ let claude = sentinel_path(dir, AgentChoice::ClaudeCode, &targets("/a/settings.json"));+ let codex = sentinel_path(dir, AgentChoice::Codex, &targets("/a/settings.json"));assert_ne!(claude, codex, "different agents get distinct sentinels");+ assert_eq!(+ claude,+ sentinel_path(dir, AgentChoice::ClaudeCode, &targets("/a/settings.json")),+ "the same install targets reuse the sentinel"+ );+ assert_ne!(+ claude,+ sentinel_path(dir, AgentChoice::ClaudeCode, &targets("/b/settings.json")),+ "another config home gets its own first launch"+ );assert!(claude.starts_with("/data/autowire-state/"));+ let prefix = format!("claude-code-{}-", env!("CARGO_PKG_VERSION"));assert!(claude.file_name().and_then(|n| n.to_str())- .is_some_and(- |n| n.starts_with("claude-code-") && n.ends_with(env!("CARGO_PKG_VERSION"))+ .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,+ ),+ (+ ManagedHarness::Omp,+ "PI_CODING_AGENT_DIR",+ "extensions/ai-memory-omp.ts",+ Some("mcp.json"),+ ),+ (+ 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 named OMP profile owns its agent dir and ignores+ /// `PI_CODING_AGENT_DIR`, as OMP does, so both the extension and the MCP+ /// file move there.+ #[test]+ fn run_env_omp_profile_moves_extension_and_mcp() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ let run_env = [+ (+ "PI_CODING_AGENT_DIR".to_string(),+ data.path().join("pi-family").display().to_string(),+ ),+ ("OMP_PROFILE".to_string(), "work".to_string()),+ // Blank masks a PI_CONFIG_DIR the developer's shell may export.+ ("PI_CONFIG_DIR".to_string(), String::new()),+ ];+ let installs = planned_installs(&config, ManagedHarness::Omp, &run_env);+ let agent_dir: PathBuf = [".omp", "profiles", "work", "agent"].iter().collect();+ let extension = installs.hooks[0].config_file.clone().unwrap();+ assert!(+ extension.ends_with(agent_dir.join("extensions").join("ai-memory-omp.ts")),+ "{}",+ extension.display()+ );+ let mcp = installs.mcp.and_then(|args| args.config_file).unwrap();+ assert!(+ mcp.ends_with(agent_dir.join("mcp.json")),+ "{}",+ mcp.display()+ );+ }++ /// `--env PI_CONFIG_DIR` renames OMP's root for this launch, so both the+ /// extension and `mcp.json` follow it.+ #[test]+ fn run_env_pi_config_dir_moves_extension_and_mcp() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ let run_env = [+ ("PI_CONFIG_DIR".to_string(), ".omp-alt".to_string()),+ ("PI_CODING_AGENT_DIR".to_string(), String::new()),+ ("OMP_PROFILE".to_string(), String::new()),+ ];+ let installs = planned_installs(&config, ManagedHarness::Omp, &run_env);+ let agent_dir: PathBuf = [".omp-alt", "agent"].iter().collect();+ let extension = installs.hooks[0].config_file.clone().unwrap();+ assert!(+ extension.ends_with(agent_dir.join("extensions").join("ai-memory-omp.ts")),+ "{}",+ extension.display()+ );+ let mcp = installs.mcp.and_then(|args| args.config_file).unwrap();+ assert!(+ mcp.ends_with(agent_dir.join("mcp.json")),+ "{}",+ mcp.display()+ );+ }++ /// Clearing the auto-wire state (what `uninstall` does) makes the next+ /// launch wire again; `uninstall` and the gate must agree on the directory.+ #[test]+ fn clearing_autowire_state_rewires_the_next_launch() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ let settings = data.path().join("claude-settings.json");+ let mcp = data.path().join("claude.json");+ let user_settings = r#"{"existingUserKey":1}"#;+ let user_mcp = r#"{"existingMcpKey":1}"#;+ std::fs::write(&settings, user_settings).unwrap();+ std::fs::write(&mcp, user_mcp).unwrap();+ 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, &[]);++ // The wiring is removed by hand; the sentinel alone keeps it that way.+ std::fs::write(&settings, user_settings).unwrap();+ std::fs::write(&mcp, user_mcp).unwrap();+ ensure_wired_with(&config, ManagedHarness::Claude, &overrides, &[]);+ assert_eq!(std::fs::read_to_string(&mcp).unwrap(), user_mcp);++ // Moving the state aside is, for the gate, the same as clearing it.+ std::fs::rename(+ autowire_state_dir(data.path()),+ data.path().join("cleared-autowire-state"),+ )+ .unwrap();+ ensure_wired_with(&config, ManagedHarness::Claude, &overrides, &[]);+ assert!(+ std::fs::read_to_string(&settings)+ .is_ok_and(|s| s.contains("ai-memory") || s.contains("ai_memory"))+ );+ assert!(std::fs::read_to_string(&mcp).is_ok_and(|s| s.contains("ai-memory")));+ }++ /// 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_SESSION_DIR",+ "PI_CODING_AGENT_DIR",+ "OMP_PROFILE",+ "PI_CONFIG_DIR",+ "XDG_DATA_HOME",+ ][..],+ ),+ (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"+ );+ if let Some(client) = install_hooks::mcp_client_for_agent(agent) {+ 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,+ Some(ai_memory_workstream::LaunchRoots {+ home: home.path(),+ cwd: home.path(),+ }),+ )+ .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:?}"+ );+ let profiled = [+ (+ "PI_CODING_AGENT_DIR".to_string(),+ root.display().to_string(),),- "sentinel keys on agent + version: {claude:?}"+ ("OMP_PROFILE".to_string(), "work".to_string()),+ ];+ assert_eq!(shared(&profiled), None, "{harness:?} with an OMP profile");+ }+ 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());+ }++ /// A profile OMP refuses, set through `--env`, is reported instead of+ /// letting the installers resolve again from ai-memory's own environment+ /// and wire a profile this launch does not use.+ #[test]+ fn run_env_invalid_omp_profile_is_reported_not_rerouted() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ let run_env = [("OMP_PROFILE".to_string(), "Work".to_string())];+ let installs = planned_installs(&config, ManagedHarness::Omp, &run_env);+ assert!(installs.hooks.is_empty());+ assert!(installs.mcp.is_none());+ for reason in [&installs.hooks_skipped, &installs.mcp_skipped] {+ assert!(+ reason+ .as_deref()+ .is_some_and(|reason| reason.contains("Invalid OMP profile")),+ "{reason:?}"+ );+ }+ }++ /// 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"+ );+ }+ }+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();@@ -255,8 +1185,9 @@ mod tests {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 hooks_json = std::fs::read_to_string(&settings).unwrap();assert!(@@ -277,14 +1208,17 @@ mod tests {"the ai-memory MCP server must be installed: {mcp_json}");assert!(- sentinel_path(&config.data_dir, AgentChoice::ClaudeCode).exists(),+ wire_targets(&config, ManagedHarness::Claude, &overrides, &[])+ .unwrap()+ .sentinel+ .exists(),"the attempt must be recorded");// Second launch: the sentinel gates it, so the files are byte-identical.let before_hooks = std::fs::read(&settings).unwrap();let before_mcp = std::fs::read(&mcp).unwrap();- ensure_wired_with(&config, ManagedHarness::Claude, &overrides);+ ensure_wired_with(&config, ManagedHarness::Claude, &overrides, &[]);assert_eq!(std::fs::read(&settings).unwrap(),before_hooks,@@ -304,9 +1238,14 @@ mod tests {let home = tempfile::tempdir().unwrap();let data = tempfile::tempdir().unwrap();let config = test_config(home.path(), data.path());- ensure_wired_with(&config, ManagedHarness::Crush, &WireOverrides::default());+ ensure_wired_with(+ &config,+ ManagedHarness::Crush,+ &WireOverrides::default(),+ &[],+ );assert!(- !data.path().join("autowire-state").exists(),+ !autowire_state_dir(data.path()).exists(),"an unsupported harness must not create autowire state");}@@ -318,25 +1257,32 @@ mod tests {let home = tempfile::tempdir().unwrap();let data = tempfile::tempdir().unwrap();let config = test_config(home.path(), data.path());- let sentinel = sentinel_path(&config.data_dir, AgentChoice::ClaudeCode);+ let settings = data.path().join("claude-settings.json");+ std::fs::write(&settings, r#"{"existingUserKey":1}"#).unwrap();+ let mcp = data.path().join("claude.json");+ std::fs::write(&mcp, r#"{"existingMcpKey":1}"#).unwrap();+ let overrides = WireOverrides {+ hooks_dir: Some(repo_hooks()),+ hooks_config_file: Some(settings.clone()),+ mcp_config_file: Some(mcp.clone()),+ ..WireOverrides::default()+ };+ let sentinel = wire_targets(&config, ManagedHarness::Claude, &overrides, &[])+ .unwrap()+ .sentinel;std::fs::create_dir_all(sentinel.parent().unwrap()).unwrap();std::fs::write(&sentinel, b"").unwrap();- let settings = data.path().join("claude-settings.json");- std::fs::write(&settings, r#"{"existingUserKey":1}"#).unwrap();- ensure_wired_with(- &config,- ManagedHarness::Claude,- &WireOverrides {- hooks_dir: Some(repo_hooks()),- hooks_config_file: Some(settings.clone()),- mcp_config_file: None,- },- );+ ensure_wired_with(&config, ManagedHarness::Claude, &overrides, &[]);assert_eq!(std::fs::read_to_string(&settings).unwrap(),r#"{"existingUserKey":1}"#,"a present sentinel must short-circuit before any install");+ assert_eq!(+ std::fs::read_to_string(&mcp).unwrap(),+ r#"{"existingMcpKey":1}"#,+ "a present sentinel must short-circuit before the MCP install"+ );}}diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex fa293f7e..ea8f1bf0 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -11,7 +11,9 @@ 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::path_util::{claude_config_dir, claude_config_paths, home_dir};+use crate::commands::path_util::{+ agent_config_home, claude_config_dir, claude_config_paths, home_dir,+};use crate::commands::{data_purge, install_hooks, install_mcp, openclaw_plugin};use crate::config::Config;use ai_memory_core::routing_skills::{@@ -72,6 +74,7 @@ enum DeleteKind {OpenClawEntrypoint,KiroCliV3Hooks,ManagedSkill,+ AutowireSentinel,}impl DeleteKind {@@ -86,6 +89,7 @@ impl DeleteKind {Self::OpenClawEntrypoint => "OpenClaw plugin entrypoint",Self::KiroCliV3Hooks => "Kiro CLI v3 hook file",Self::ManagedSkill => "managed Agent Skill",+ Self::AutowireSentinel => "auto-wire sentinel",}}}@@ -130,6 +134,38 @@ fn push_rewrite(plan: &mut Vec<PlannedChange>, path: PathBuf, removed: Vec<Strin});}+/// The OMP agent dirs an ai-memory install may have written to, active first:+/// the one OMP loads now (`--profile`, `OMP_PROFILE`, `PI_PROFILE`, else+/// `PI_CODING_AGENT_DIR`), the default profile's, where earlier releases put+/// the extension whenever `PI_CODING_AGENT_DIR` was set, the active one as+/// earlier releases resolved it (they ignored `PI_CONFIG_DIR` and wrote under+/// `~/.omp`), and `~/.omp/agent`, where `install-mcp` always wrote the MCP+/// entry. A profile name OMP refuses is reported and skipped instead of+/// aborting every other agent's cleanup.+fn omp_agent_dirs(home: Option<&Path>, profile: Option<&str>) -> Vec<PathBuf> {+ let Some(home) = home else {+ return Vec::new();+ };+ let env = |name: &str| std::env::var_os(name);+ let without_config_dir = |name: &str| (name != "PI_CONFIG_DIR").then(|| env(name)).flatten();+ let mut dirs = Vec::with_capacity(4);+ match ai_memory_workstream::omp_agent_dir(home, profile, env) {+ Ok(dir) => dirs.push(dir),+ Err(error) => eprintln!("warning: skipping the active OMP profile: {error:#}"),+ }+ let fallbacks = [+ ai_memory_workstream::omp_agent_dir(home, Some("default"), env).ok(),+ ai_memory_workstream::omp_agent_dir(home, profile, without_config_dir).ok(),+ Some(home.join(".omp").join("agent")),+ ];+ for dir in fallbacks.into_iter().flatten() {+ if !dirs.contains(&dir) {+ dirs.push(dir);+ }+ }+ dirs+}+fn push_generated_delete(plan: &mut Vec<PlannedChange>, path: PathBuf, kind: DeleteKind) {if generated_file_is_ours(&path, kind) {plan.push(PlannedChange::DeleteFile { path, kind });@@ -139,13 +175,19 @@ fn push_generated_delete(plan: &mut Vec<PlannedChange>, path: PathBuf, kind: Del/// Build the full removal plan by reading each existing config file and/// running the matching pure stripper. Missing files / no-matches/// produce no entry. `name`/`url` identify the MCP server.-fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {+fn build_plan(args: &UninstallArgs, data_dir: &Path) -> anyhow::Result<Vec<PlannedChange>> {let mut plan = Vec::new();let want = |k: crate::cli::UninstallOnly| args.only.is_none() || args.only == Some(k);let name = args.mcp_name.as_deref();let url = args.mcp_url.as_str();let home = home_dir();let claude_config_dir = claude_config_dir(std::env::var_os("CLAUDE_CONFIG_DIR"));+ let omp_dirs = if want(crate::cli::UninstallOnly::Hooks) || want(crate::cli::UninstallOnly::Mcp)+ {+ omp_agent_dirs(home.as_deref(), args.profile.as_deref())+ } else {+ Vec::new()+ };// ---- Hooks (JSON configs) ----if want(crate::cli::UninstallOnly::Hooks) {@@ -299,12 +341,10 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {let plugin2 = install_hooks::opencode2_plugin_path()?;push_generated_delete(&mut plan, plugin2, DeleteKind::OpenCode2Plugin);- let omp_profile = args.profile.as_deref();- let omp = install_hooks::omp_extension_path(omp_profile)?;- push_generated_delete(&mut plan, omp.clone(), DeleteKind::OmpExtension);-- let legacy_omp = omp.with_file_name("ai-memory.ts");- if legacy_omp != omp {+ for dir in &omp_dirs {+ let omp = dir.join("extensions").join("ai-memory-omp.ts");+ let legacy_omp = omp.with_file_name("ai-memory.ts");+ push_generated_delete(&mut plan, omp, DeleteKind::OmpExtension);push_generated_delete(&mut plan, legacy_omp, DeleteKind::OmpExtension);}@@ -367,6 +407,17 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {Path::new(".claude.json"),Path::new(".claude.json"),)+ } else if matches!(client, Codex) {+ // Older installs wrote the Codex MCP entry to ~/.codex/config.toml+ // even with CODEX_HOME set, so sweep that file too.+ claude_config_paths(+ home.as_deref(),+ agent_config_home(std::env::var_os("CODEX_HOME")).as_deref(),+ Path::new(".codex/config.toml"),+ Path::new("config.toml"),+ )+ } else if matches!(client, Omp) {+ omp_dirs.iter().map(|dir| dir.join("mcp.json")).collect()} else {let Ok(path) = install_mcp::mcp_config_path(client) else {continue;@@ -438,6 +489,24 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {}}+ // ---- Auto-wire sentinels (ai-memory's own state) ----+ // `ai-memory run` skips wiring while a sentinel exists, so one left behind+ // would stop the next managed launch from reinstalling what this removes.+ // All of them go: one keyed on a config home this environment cannot see+ // costs only an idempotent re-apply.+ if want(crate::cli::UninstallOnly::Hooks) || want(crate::cli::UninstallOnly::Mcp) {+ let dir = crate::commands::run_autowire::autowire_state_dir(data_dir);+ let mut sentinels: Vec<PathBuf> = std::fs::read_dir(&dir)+ .into_iter()+ .flatten()+ .filter_map(|entry| entry.ok().map(|entry| entry.path()))+ .collect();+ sentinels.sort();+ for path in sentinels {+ push_generated_delete(&mut plan, path, DeleteKind::AutowireSentinel);+ }+ }+Ok(plan)}@@ -599,7 +668,7 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {let name = args.mcp_name.clone();let url = args.mcp_url.clone();- let plan = build_plan(&args)?;+ let plan = build_plan(&args, &config.data_dir)?;print_plan(&plan);if args.purge_data {for path in data_purge::purge_preview(&config.data_dir) {@@ -642,9 +711,13 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {}// Removing the hooks removes the only readers of the stored bearer, so- // leaving it on disk would strand a live credential (#552). Best-effort:- // an unremovable file must not fail a teardown that otherwise succeeded.- if let Err(error) = crate::config::clear_hook_auth_token(&config.data_dir) {+ // leaving it on disk would strand a live credential (#552). An uninstall+ // that keeps the hooks (`--only mcp|instructions|skills`) keeps it: the+ // 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}",config.data_dir.display()@@ -1051,6 +1124,9 @@ fn generated_file_is_ours(path: &Path, kind: DeleteKind) -> bool {content.contains("Auto-generated by `ai-memory install-hooks --agent omp --apply`")&& content.contains("const AGENT = \"omp\";")}+ // Auto-wire writes its sentinels empty; anything else in that+ // directory is not one of them.+ DeleteKind::AutowireSentinel => content.is_empty(),DeleteKind::PiExtension => {content.contains("Auto-generated by `ai-memory install-hooks --agent pi --apply`")&& content.contains("const AGENT = \"pi\";")diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 9efebbca..ce606026 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -392,11 +392,11 @@ pub struct Config {/// false`; `ai-memory backfill` remains available to run it by hand.pub backfill_on_start: bool,/// On by default. The first time `ai-memory run <harness>` launches a- /// harness (per harness + binary version), it auto-installs that harness's- /// ai-memory lifecycle hooks and MCP server if they are not already wired,- /// so managed launches capture and can query memory without a manual- /// `install-hooks` / `install-mcp` step. Idempotent and one-time per- /// harness. Turn off with `AI_MEMORY_RUN_AUTOWIRE=false` /+ /// harness (per harness, binary version and config home), it auto-installs+ /// that harness's ai-memory lifecycle hooks and MCP server if they are not+ /// already wired, so managed launches capture and can query memory without+ /// a manual `install-hooks` / `install-mcp` step. Idempotent and one-time+ /// per harness and config home. Turn off with `AI_MEMORY_RUN_AUTOWIRE=false` //// `run_autowire = false`, or per launch with `ai-memory run --no-autowire`.pub run_autowire: bool,/// Strip root-level `anyOf`/`oneOf`/`allOf` from MCP tool inputdiff --git a/crates/ai-memory-cli/tests/suite/backfill_e2e.rs b/crates/ai-memory-cli/tests/suite/backfill_e2e.rsindex 1a0123b8..2473da11 100644--- a/crates/ai-memory-cli/tests/suite/backfill_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/backfill_e2e.rs@@ -34,14 +34,11 @@mod slow {use std::fs;use std::path::{Path, PathBuf};- use std::process::Stdio;use std::time::{Duration, Instant};use serde_json::{Value, json};- use crate::e2e_support::{- ServerGuard, free_port, hermetic, run_cli, session_count, write_jsonl,- };+ use crate::e2e_support::{hermetic, run_cli, session_count, start_serve, write_jsonl};const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");const WORKSPACE: &str = "backfill-e2e-ws";@@ -162,51 +159,28 @@ mod slow {// Start the real server (loopback, no auth, hermetic: no embedder, no// wiki watcher — a machine-global inotify instance concurrent server// children can exhaust, #745).- let port = free_port();- let base = format!("http://127.0.0.1:{port}");- let server = ServerGuard(- hermetic(BIN)- .args([- "serve",- "--transport",- "http",- "--bind",- &format!("127.0.0.1:{port}"),- "--workspace",- WORKSPACE,- "--project",- PROJECT,- "--no-watcher",- ])- .current_dir(&cwd)- .env("AI_MEMORY_DATA_DIR", data_dir.path())- .env("AI_MEMORY_HOME", home.path())- .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")- .env("RUST_LOG", "off")- .stdin(Stdio::null())- .stdout(Stdio::null())- .stderr(Stdio::null())- .spawn()- .expect("spawn serve"),- );-let client = reqwest::Client::new();-- // Wait for the server to accept connections.- let deadline = Instant::now() + Duration::from_secs(30);- loop {- if client- .get(format!("{base}/mcp"))- .timeout(Duration::from_secs(2))- .send()- .await- .is_ok()- {- break;- }- assert!(Instant::now() < deadline, "server never became reachable");- tokio::time::sleep(Duration::from_millis(150)).await;- }+ let (server, base) = start_serve(&client, &data_dir.path().join("serve.log"), |port| {+ let mut cmd = hermetic(BIN);+ cmd.args([+ "serve",+ "--transport",+ "http",+ "--bind",+ &format!("127.0.0.1:{port}"),+ "--workspace",+ WORKSPACE,+ "--project",+ PROJECT,+ "--no-watcher",+ ])+ .env("AI_MEMORY_DATA_DIR", data_dir.path())+ .env("AI_MEMORY_HOME", home.path())+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none");+ cmd.current_dir(&cwd);+ cmd+ })+ .await;// Phase 1 — the store is empty before backfill.assert_eq!(diff --git a/crates/ai-memory-cli/tests/suite/doctor_e2e.rs b/crates/ai-memory-cli/tests/suite/doctor_e2e.rsindex cf373863..74846569 100644--- a/crates/ai-memory-cli/tests/suite/doctor_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/doctor_e2e.rs@@ -36,14 +36,11 @@/// lives in the slow tier (`cargo tf` / CI), not the everyday loop.mod slow {use std::fs;- use std::process::Stdio;use std::time::{Duration, Instant};use serde_json::{Value, json};- use crate::e2e_support::{- ServerGuard, free_port, hermetic, run_cli, session_count, write_jsonl,- };+ use crate::e2e_support::{hermetic, run_cli, session_count, start_serve, write_jsonl};const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");const WORKSPACE: &str = "doctor-e2e-ws";@@ -98,51 +95,28 @@ mod slow {// Start the real server (loopback, no auth, hermetic: no embedder, no// wiki watcher — a machine-global inotify instance concurrent server// children can exhaust, #745).- let port = free_port();- let base = format!("http://127.0.0.1:{port}");- let server = ServerGuard(- hermetic(BIN)- .args([- "serve",- "--transport",- "http",- "--bind",- &format!("127.0.0.1:{port}"),- "--workspace",- WORKSPACE,- "--project",- PROJECT,- "--no-watcher",- ])- .current_dir(&cwd)- .env("AI_MEMORY_DATA_DIR", data_dir.path())- .env("AI_MEMORY_HOME", home.path())- .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")- .env("RUST_LOG", "off")- .stdin(Stdio::null())- .stdout(Stdio::null())- .stderr(Stdio::null())- .spawn()- .expect("spawn serve"),- );-let client = reqwest::Client::new();-- // Wait for the server to accept connections.- let deadline = Instant::now() + Duration::from_secs(30);- loop {- if client- .get(format!("{base}/mcp"))- .timeout(Duration::from_secs(2))- .send()- .await- .is_ok()- {- break;- }- assert!(Instant::now() < deadline, "server never became reachable");- tokio::time::sleep(Duration::from_millis(150)).await;- }+ let (server, base) = start_serve(&client, &data_dir.path().join("serve.log"), |port| {+ let mut cmd = hermetic(BIN);+ cmd.args([+ "serve",+ "--transport",+ "http",+ "--bind",+ &format!("127.0.0.1:{port}"),+ "--workspace",+ WORKSPACE,+ "--project",+ PROJECT,+ "--no-watcher",+ ])+ .env("AI_MEMORY_DATA_DIR", data_dir.path())+ .env("AI_MEMORY_HOME", home.path())+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none");+ cmd.current_dir(&cwd);+ cmd+ })+ .await;// Precondition: nothing captured yet for this scope.assert_eq!(diff --git a/crates/ai-memory-cli/tests/suite/e2e_support.rs b/crates/ai-memory-cli/tests/suite/e2e_support.rsindex d8dc0a03..ec74aa5f 100644--- a/crates/ai-memory-cli/tests/suite/e2e_support.rs+++ b/crates/ai-memory-cli/tests/suite/e2e_support.rs@@ -3,8 +3,8 @@//! `backfill_e2e`, `doctor_e2e`, and `message_e2e` each drive the shipped//! `ai-memory` binary against a real `ai-memory serve` child, exactly as an//! operator would. These are the pieces they all share: a hermetic `Command`,-//! the server-lifetime guard, ephemeral port allocation, the `by-agent`-//! session count, and the subcommand runner.+//! the server start and lifetime guard, ephemeral port allocation, the+//! `by-agent` session count, and the subcommand runner.//!//! Kept deliberately cfg-agnostic (no `#![cfg(unix)]`) so the non-unix//! `message_e2e` can use it too. The genuinely POSIX-specific fixtures — the@@ -14,7 +14,8 @@use std::fs;use std::net::TcpListener;use std::path::Path;-use std::process::{Child, Command};+use std::process::{Child, Command, Stdio};+use std::time::{Duration, Instant};use serde_json::Value;@@ -44,8 +45,8 @@ impl Drop for ServerGuard {}}-/// A free loopback port. The brief unbind→rebind race is acceptable for a-/// slow-tier test and is the same approach the shell smoke test uses.+/// A free loopback port. It is released before the caller binds it; a spawned+/// server goes through [`start_serve`], which survives losing that race.pub fn free_port() -> u16 {TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port")@@ -54,6 +55,81 @@ pub fn free_port() -> u16 {.port()}+/// What `serve` logs once its HTTP listener is bound, with the address.+const SERVE_READY: &str = "MCP HTTP server ready";++/// Start `ai-memory serve` on a free loopback port and wait until it answers+/// HTTP. `command` builds the configured serve command for a port; the+/// child's stderr goes to `log`, with the serve module's log turned on.+///+/// [`free_port`] releases the port before the server binds it, and under a+/// parallel test load another socket can take it in between. The server then+/// exits at once and a bare readiness loop only times out, hiding why; and+/// another test's server there would answer the probe. So the child must log+/// that it bound the port before an answer counts. A child that failed to+/// bind is restarted on a fresh port; any other exit, or no answer within the+/// deadline, panics with the child's stderr.+pub async fn start_serve(+ client: &reqwest::Client,+ log: &Path,+ command: impl Fn(u16) -> Command,+) -> (ServerGuard, String) {+ start_serve_on(client, log, command, free_port).await+}++async fn start_serve_on(+ client: &reqwest::Client,+ log: &Path,+ command: impl Fn(u16) -> Command,+ mut next_port: impl FnMut() -> u16,+) -> (ServerGuard, String) {+ const ATTEMPTS: usize = 5;+ let output = || fs::read_to_string(log).unwrap_or_default();+ for _ in 0..ATTEMPTS {+ let port = next_port();+ let addr = format!("127.0.0.1:{port}");+ let base = format!("http://{addr}");+ let stderr = fs::File::create(log).expect("create serve log");+ let mut server = ServerGuard(+ command(port)+ .env("RUST_LOG", "ai_memory_cli::commands::serve=info")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(stderr)+ .spawn()+ .expect("spawn serve"),+ );+ let deadline = Instant::now() + Duration::from_secs(30);+ loop {+ let bound = output()+ .lines()+ .any(|line| line.contains(SERVE_READY) && line.contains(&addr));+ // Bounded so a stalled answer cannot hide the child's exit.+ let answered = bound+ && client+ .get(format!("{base}/mcp"))+ .timeout(Duration::from_secs(2))+ .send()+ .await+ .is_ok();+ match server.0.try_wait().expect("poll serve") {+ None if answered => return (server, base),+ None => {}+ // `serve` reports a failed bind as `binding <addr>`.+ Some(_) if output().contains(&format!("binding {addr}")) => break,+ Some(status) => panic!("serve exited ({status}) before answering:\n{}", output()),+ }+ assert!(+ Instant::now() < deadline,+ "serve never answered on {base}:\n{}",+ output()+ );+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ }+ panic!("serve could not bind a free port in {ATTEMPTS} attempts");+}+/// Write the JSONL lines (each already a `Value`) as one transcript file.////// Only the POSIX-gated fixtures plant transcripts, so this is unused on@@ -133,3 +209,68 @@ pub fn run_cli();String::from_utf8(out.stdout).expect("stdout utf8")}++mod slow {+ use super::*;++ fn serve(root: &Path, port: u16) -> Command {+ let mut cmd = hermetic(BIN);+ cmd.env("HOME", root)+ .env("USERPROFILE", root)+ .env("AI_MEMORY_HOME", root)+ .env("AI_MEMORY_DATA_DIR", root.join("data"))+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")+ .env("AI_MEMORY_BACKFILL_ON_START", "false")+ .env("AI_MEMORY_AUTO_IMPROVE__SCHEDULER__ENABLED", "false")+ .env("RUST_LOG", "off")+ .current_dir(root)+ .args(["serve", "--transport", "http", "--bind"])+ .arg(format!("127.0.0.1:{port}"))+ .arg("--no-watcher");+ cmd+ }++ /// A port taken between [`free_port`] and the server's bind makes the+ /// server exit at once; the start moves to a fresh port instead of+ /// waiting out the readiness deadline, and does not take the answer of+ /// whatever holds the port for its own.+ #[tokio::test]+ async fn start_serve_moves_off_a_port_taken_before_the_bind() {+ use std::io::{Read as _, Write as _};++ let root = tempfile::tempdir().unwrap().keep();+ let taken = TcpListener::bind("127.0.0.1:0").unwrap();+ let busy = taken.local_addr().unwrap().port();+ std::thread::spawn(move || {+ for mut stream in taken.incoming().flatten() {+ let _ = stream.read(&mut [0; 1024]);+ let _ = stream.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n");+ }+ });+ let mut ports = [busy].into_iter();+ let client = reqwest::Client::new();+ let started = Instant::now();+ let (_server, base) = start_serve_on(+ &client,+ &root.join("serve.log"),+ |port| serve(&root, port),+ || ports.next().unwrap_or_else(free_port),+ )+ .await;+ assert_ne!(base, format!("http://127.0.0.1:{busy}"));+ assert!(started.elapsed() < Duration::from_secs(20));+ }++ /// Any other early exit fails at once with the server's own error.+ #[tokio::test]+ #[should_panic(expected = "serve exited")]+ async fn start_serve_reports_an_early_exit() {+ let root = tempfile::tempdir().unwrap().keep();+ start_serve(&reqwest::Client::new(), &root.join("serve.log"), |port| {+ let mut cmd = serve(&root, port);+ cmd.arg("--no-such-flag");+ cmd+ })+ .await;+ }+}diff --git a/crates/ai-memory-cli/tests/suite/external_capture.rs b/crates/ai-memory-cli/tests/suite/external_capture.rsindex 8ecbd93a..6ebca1e1 100644--- a/crates/ai-memory-cli/tests/suite/external_capture.rs+++ b/crates/ai-memory-cli/tests/suite/external_capture.rs@@ -109,13 +109,13 @@ fn capture_inspection_reports_external_ownership_without_side_effects() {mod slow {use super::*;use std::process::Command;- use std::time::{Duration, Instant};+ use std::time::Duration;use ai_memory_core::SessionId;use ai_memory_store::ReaderPool;use sha2::{Digest, Sha256};- use crate::e2e_support::{ServerGuard, free_port};+ use crate::e2e_support::{ServerGuard, start_serve};const TOKEN: &str = "external-capture-local-test-token";const MARKER: &str = "external_capture_handoff_marker";@@ -163,46 +163,27 @@ mod slow {"workspace = \"external-test\"\nproject = \"capture-test\"\n",).unwrap();- let port = free_port();- let base = format!("http://127.0.0.1:{port}");- let server = ServerGuard(- command(root.as_path())- .args([- "serve",- "--transport",- "http",- "--bind",- &format!("127.0.0.1:{port}"),- "--workspace",- "external-test",- "--project",- "capture-test",- "--no-watcher",- ])- .stdin(Stdio::null())- .stdout(Stdio::null())- .stderr(Stdio::null())- .spawn()- .unwrap(),- );let client = reqwest::Client::builder().timeout(Duration::from_secs(15)).build().unwrap();- let deadline = Instant::now() + Duration::from_secs(30);- loop {- if client- .get(format!("{base}/mcp"))- .bearer_auth(TOKEN)- .send()- .await- .is_ok()- {- break;- }- assert!(Instant::now() < deadline, "server readiness timeout");- tokio::time::sleep(Duration::from_millis(50)).await;- }+ let (server, base) = start_serve(&client, &root.as_path().join("serve.log"), |port| {+ let mut cmd = command(root.as_path());+ cmd.args([+ "serve",+ "--transport",+ "http",+ "--bind",+ &format!("127.0.0.1:{port}"),+ "--workspace",+ "external-test",+ "--project",+ "capture-test",+ "--no-watcher",+ ]);+ cmd+ })+ .await;let reader = ReaderPool::new(&root.as_path().join("data/db/memory.sqlite"), 2).unwrap();Self {_server: server,diff --git a/crates/ai-memory-cli/tests/suite/external_capture_ts.rs b/crates/ai-memory-cli/tests/suite/external_capture_ts.rsindex 0ac6db37..ee7174fe 100644--- a/crates/ai-memory-cli/tests/suite/external_capture_ts.rs+++ b/crates/ai-memory-cli/tests/suite/external_capture_ts.rs@@ -104,7 +104,14 @@ const server = createServer((req, res) => {res.writeHead(404);res.end();});-await new Promise<void>((resolve) => server.listen(port, "127.0.0.1", () => resolve()));+await new Promise<void>((resolve, reject) => {+ server.once("error", reject);+ server.listen(port, "127.0.0.1", () => resolve());+}).catch((error) => {+ // Taken before Node could bind it; nothing has run yet, so the test retries.+ if (error?.code === "EADDRINUSE") process.exit(75);+ throw error;+});const hooks: any = await (AiMemoryHooks as any)({ directory });await hooks.event({ event: { type: "session.created", properties: { info: { id: "s1", directory } } } });@@ -124,7 +131,7 @@ console.log(JSON.stringify({ events, handoffs, system: transformed.system }));/// `GIT_CONFIG_*` leaking in from the harness would point it somewhere/// outside the fixture. `PATH` and the rest of the environment stay so/// Node and git still resolve.- fn run_plugin(dir: &Path, port: u16, owner: Option<&str>) -> Value {+ fn run_plugin(dir: &Path, port: u16, owner: Option<&str>) -> Option<Value> {let mut command = hermetic("node");for (key, _) in std::env::vars_os() {if key.to_string_lossy().starts_with("GIT_") {@@ -146,13 +153,41 @@ console.log(JSON.stringify({ events, handoffs, system: transformed.system }));command.env("AI_MEMORY_CAPTURE_OWNER", owner);}let output = command.output().expect("run generated plugin");+ if output.status.code() == Some(PORT_TAKEN) {+ return None;+ }assert!(output.status.success(),"generated plugin run failed (owner={owner:?})\nstdout:\n{}\nstderr:\n{}",String::from_utf8_lossy(&output.stdout),String::from_utf8_lossy(&output.stderr),);- serde_json::from_slice(&output.stdout).expect("harness JSON")+ Some(serde_json::from_slice(&output.stdout).expect("harness JSON"))+ }++ /// The harness's exit code when its port was taken before it could bind.+ const PORT_TAKEN: i32 = 75;++ /// Writes the plugin, rendered for `port`, and the harness into `dir`.+ fn write_fixture(dir: &Path, port: u16) {+ let plugin = render_opencode_plugin(dir, &format!("http://127.0.0.1:{port}"));+ std::fs::write(dir.join("ai-memory.ts"), &plugin).unwrap();+ std::fs::write(dir.join("harness.ts"), HARNESS).unwrap();+ }++ /// One plugin run on `port`. The plugin names its server at render time,+ /// and [`free_port`] releases the port before Node binds it, so under a+ /// parallel test load another socket can take it first. The harness then+ /// stops before the plugin runs and the fixture moves to a fresh port.+ fn run_on_free_port(dir: &Path, port: &mut u16, owner: Option<&str>) -> Value {+ for _ in 0..5 {+ if let Some(run) = run_plugin(dir, *port, owner) {+ return run;+ }+ *port = free_port();+ write_fixture(dir, *port);+ }+ panic!("the harness could not bind a free port in 5 attempts");}fn spooled_entries(dir: &Path) -> usize {@@ -187,12 +222,10 @@ console.log(JSON.stringify({ events, handoffs, system: transformed.system }));return;}let dir = fixture_root();- let port = free_port();- let plugin = render_opencode_plugin(&dir, &format!("http://127.0.0.1:{port}"));- std::fs::write(dir.join("ai-memory.ts"), &plugin).unwrap();- std::fs::write(dir.join("harness.ts"), HARNESS).unwrap();+ let mut port = free_port();+ write_fixture(&dir, port);- let owned = run_plugin(&dir, port, Some("orchestrator-a"));+ let owned = run_on_free_port(&dir, &mut port, Some("orchestrator-a"));assert!(delivered_events(&owned).is_empty(),"owned run must POST nothing: {owned}"@@ -206,7 +239,7 @@ console.log(JSON.stringify({ events, handoffs, system: transformed.system }));// plugin and harness must capture normally. Without them the// assertions above could pass on a harness that never delivers.for (label, owner) in [("unset", None), ("whitespace", Some(" \t\n"))] {- let captured = run_plugin(&dir, port, owner);+ let captured = run_on_free_port(&dir, &mut port, owner);let events = delivered_events(&captured);for expected in ["session-start", "user-prompt", "session-end"] {assert!(@@ -221,4 +254,21 @@ console.log(JSON.stringify({ events, handoffs, system: transformed.system })););}}++ /// A port taken before Node binds it moves the fixture to a fresh one+ /// instead of failing the run.+ #[test]+ fn generated_plugin_fixture_moves_off_a_taken_port() {+ if !node_strip_types_available() {+ return;+ }+ let dir = fixture_root();+ let taken = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let busy = taken.local_addr().unwrap().port();+ let mut port = busy;+ write_fixture(&dir, port);+ let run = run_on_free_port(&dir, &mut port, None);+ assert_ne!(port, busy);+ assert!(delivered_events(&run).contains(&"session-start"), "{run}");+ }}diff --git a/crates/ai-memory-cli/tests/suite/message_e2e.rs b/crates/ai-memory-cli/tests/suite/message_e2e.rsindex d344e408..605478b7 100644--- a/crates/ai-memory-cli/tests/suite/message_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/message_e2e.rs@@ -29,12 +29,11 @@/// lives in the slow tier (`cargo tf` / CI), not the everyday loop.mod slow {use std::path::Path;- use std::process::Stdio;use std::time::{Duration, Instant};use serde_json::{Value, json};- use crate::e2e_support::{ServerGuard, free_port, hermetic, run_cli, session_count};+ use crate::e2e_support::{hermetic, run_cli, session_count, start_serve};const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");const WORKSPACE: &str = "message-e2e-ws";@@ -149,50 +148,27 @@ mod slow {// Start the real server (loopback, no auth, hermetic: no embedder, no// wiki watcher — a machine-global inotify instance concurrent server// children can exhaust, #745).- let port = free_port();- let base = format!("http://127.0.0.1:{port}");- let server = ServerGuard(- hermetic(BIN)- .args([- "serve",- "--transport",- "http",- "--bind",- &format!("127.0.0.1:{port}"),- "--workspace",- WORKSPACE,- "--project",- SENDER,- "--no-watcher",- ])- .env("AI_MEMORY_DATA_DIR", data_dir.path())- .env("AI_MEMORY_HOME", home.path())- .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")- .env("RUST_LOG", "off")- .stdin(Stdio::null())- .stdout(Stdio::null())- .stderr(Stdio::null())- .spawn()- .expect("spawn serve"),- );-let client = reqwest::Client::new();-- // Wait for the server to accept connections.- let deadline = Instant::now() + Duration::from_secs(30);- loop {- if client- .get(format!("{base}/mcp"))- .timeout(Duration::from_secs(2))- .send()- .await- .is_ok()- {- break;- }- assert!(Instant::now() < deadline, "server never became reachable");- tokio::time::sleep(Duration::from_millis(150)).await;- }+ let (server, base) = start_serve(&client, &data_dir.path().join("serve.log"), |port| {+ let mut cmd = hermetic(BIN);+ cmd.args([+ "serve",+ "--transport",+ "http",+ "--bind",+ &format!("127.0.0.1:{port}"),+ "--workspace",+ WORKSPACE,+ "--project",+ SENDER,+ "--no-watcher",+ ])+ .env("AI_MEMORY_DATA_DIR", data_dir.path())+ .env("AI_MEMORY_HOME", home.path())+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none");+ cmd+ })+ .await;// A send is rejected unless the recipient project already exists, so make// all three projects real by "running an agent" in each once.diff --git a/crates/ai-memory-cli/tests/suite/removal.rs b/crates/ai-memory-cli/tests/suite/removal.rsindex c2b0e4f7..2791a897 100644--- a/crates/ai-memory-cli/tests/suite/removal.rs+++ b/crates/ai-memory-cli/tests/suite/removal.rs@@ -45,7 +45,16 @@ fn command_with_home(home: &Path) -> Command {.env_remove("KIRO_HOME")// Keep Claude installer/removal tests inside their temp HOME unless a// test explicitly opts into a relocated config root.- .env_remove("CLAUDE_CONFIG_DIR");+ .env_remove("CLAUDE_CONFIG_DIR")+ // Codex's hooks.json and MCP config.toml both follow CODEX_HOME, and+ // uninstall also resolves Grok, Pi and OMP targets from their own+ // variables, so none of them may point outside the sandbox.+ .env_remove("CODEX_HOME")+ .env_remove("GROK_HOME")+ .env_remove("PI_CODING_AGENT_DIR")+ .env_remove("OMP_PROFILE")+ .env_remove("PI_PROFILE")+ .env_remove("PI_CONFIG_DIR");command}@@ -223,6 +232,253 @@ fn relocated_claude_uninstall_sweeps_active_and_legacy_installs() {}}+/// Older installs wrote the Codex MCP entry to `~/.codex/config.toml` even with+/// `CODEX_HOME` set. A relocated install now lands in `$CODEX_HOME/config.toml`,+/// and uninstall sweeps both.+#[test]+fn relocated_codex_uninstall_sweeps_active_and_legacy_mcp() {+ let _guard = cli_test_lock();+ let project = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ let relocated = home.path().join("codex-work");+ std::fs::create_dir_all(&relocated).unwrap();++ let run = |relocate: bool, args: &[&str]| {+ let mut command = command_with_home(home.path());+ if relocate {+ command.env("CODEX_HOME", &relocated);+ }+ command+ .args(args)+ .current_dir(project.path())+ .output()+ .unwrap()+ };++ for relocate in [false, true] {+ let output = run(relocate, &["install-mcp", "--client", "codex", "--apply"]);+ assert!(+ output.status.success(),+ "install failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ }++ let legacy = home.path().join(".codex/config.toml");+ let active = relocated.join("config.toml");+ for path in [&legacy, &active] {+ let content = std::fs::read_to_string(path)+ .unwrap_or_else(|error| panic!("installer did not create {}: {error}", path.display()));+ assert!(+ content.contains("ai-memory"),+ "Codex MCP entry missing in {}: {content}",+ path.display()+ );+ }++ let output = run(true, &["uninstall", "--only", "mcp", "--apply", "--yes"]);+ assert!(+ output.status.success(),+ "uninstall failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ for path in [&legacy, &active] {+ let content = std::fs::read_to_string(path).unwrap();+ assert!(+ !content.contains("ai-memory"),+ "Codex MCP entry survived in {}: {content}",+ path.display()+ );+ }+}++/// `ai-memory run` skips auto-wire while its sentinel exists, so an uninstall+/// that leaves one makes the next managed launch skip wiring and capture+/// nothing. Hooks or MCP in scope clear every sentinel, even with no other+/// wiring left; instructions and skills leave them alone.+#[test]+fn uninstall_clears_autowire_sentinels_with_hooks_or_mcp() {+ let _guard = cli_test_lock();+ for only in [+ None,+ Some("hooks"),+ Some("mcp"),+ Some("instructions"),+ Some("skills"),+ ] {+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();+ let state = home.path().join(".ai-memory-data/autowire-state");+ std::fs::create_dir_all(&state).unwrap();+ let sentinels = [+ state.join(format!(+ "claude-code-{}-0123456789abcdef",+ env!("CARGO_PKG_VERSION")+ )),+ // An older release's name, before the location hash.+ state.join("codex-2.3.1"),+ ];+ for path in &sentinels {+ std::fs::write(path, b"").unwrap();+ }+ let foreign = state.join("notes.txt");+ std::fs::write(&foreign, "not a sentinel").unwrap();+ let clears = matches!(only, None | Some("hooks" | "mcp"));+ let uninstall = |extra: &[&str]| {+ let mut args = vec!["uninstall"];+ if let Some(only) = only {+ args.extend(["--only", only]);+ }+ args.extend_from_slice(extra);+ let output = command_with_home(home.path())+ .args(&args)+ .current_dir(project.path())+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{args:?}: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ String::from_utf8_lossy(&output.stdout).into_owned()+ };+ let plan = uninstall(&[]);+ assert_eq!(+ plan.contains("auto-wire sentinel"),+ clears,+ "{only:?}: {plan}"+ );+ assert!(+ sentinels.iter().all(|path| path.exists()),+ "a dry run must not delete"+ );+ uninstall(&["--apply", "--yes"]);+ for path in &sentinels {+ assert_eq!(path.exists(), !clears, "{only:?}: {}", path.display());+ }+ assert!(+ foreign.exists(),+ "a file auto-wire did not write must survive"+ );+ }+}++/// The stored hook bearer is read by the hooks, so only an uninstall that+/// removes them may delete it.+#[test]+fn uninstall_keeps_the_hook_bearer_unless_hooks_are_removed() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();+ let run = |args: &[&str]| {+ let output = command_with_home(home.path())+ .args(args)+ .current_dir(project.path())+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{args:?}: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ };+ run(&["install-mcp", "--client", "claude-code", "--apply"]);+ run(&["install-hooks", "--agent", "claude-code", "--apply"]);+ let data = home.path().join(".ai-memory-data");+ let bearer = [data.join("auth-token"), data.join("auth-header")];+ for path in &bearer {+ std::fs::write(path, "secret\n").unwrap();+ }++ run(&["uninstall", "--only", "mcp", "--apply", "--yes"]);+ for path in &bearer {+ assert!(path.exists(), "--only mcp removed {}", path.display());+ }+ run(&["uninstall", "--only", "hooks", "--apply", "--yes"]);+ for path in &bearer {+ assert!(+ !path.exists(),+ "removing the hooks keeps {}",+ path.display()+ );+ }+}++/// `PI_CONFIG_DIR` renames OMP's `~/.omp` root for the extension and+/// `mcp.json` (an XDG data dir moves only sessions), and uninstall also sweeps+/// the `~/.omp` locations earlier releases wrote whatever the variable said.+#[test]+fn omp_install_and_uninstall_follow_pi_config_dir() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();+ let xdg_omp = home.path().join(".local/share/omp");+ std::fs::create_dir_all(&xdg_omp).unwrap();+ let run = |args: &[&str]| {+ let output = command_with_home(home.path())+ .env("PI_CONFIG_DIR", ".omp-alt")+ .args(args)+ .current_dir(project.path())+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{args:?}: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ };+ run(&["install-mcp", "--client", "omp", "--apply"]);+ run(&[+ "install-hooks",+ "--agent",+ "omp",+ "--apply",+ "--server-url",+ "http://127.0.0.1:49374",+ ]);+ let renamed = home.path().join(".omp-alt/agent");+ let mcp = renamed.join("mcp.json");+ let extension = renamed.join("extensions/ai-memory-omp.ts");+ assert!(std::fs::read_to_string(&mcp).is_ok_and(|s| s.contains("ai-memory")));+ assert!(extension.exists(), "{}", extension.display());+ assert!(+ std::fs::read_dir(&xdg_omp).unwrap().next().is_none(),+ "XDG never receives the extension or mcp.json"+ );+ assert!(!home.path().join(".omp").exists());++ // What an earlier release left under ~/.omp, which ignored PI_CONFIG_DIR.+ let generated = "// Auto-generated by `ai-memory install-hooks --agent omp --apply`.\nconst AGENT = \"omp\";\n";+ let legacy = [+ home.path().join(".omp/agent/extensions/ai-memory-omp.ts"),+ home.path()+ .join(".omp/profiles/work/agent/extensions/ai-memory-omp.ts"),+ ];+ for path in &legacy {+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(path, generated).unwrap();+ }++ run(&[+ "uninstall",+ "--only",+ "hooks",+ "--profile",+ "work",+ "--apply",+ "--yes",+ ]);+ run(&["uninstall", "--only", "mcp", "--apply", "--yes"]);+ for path in legacy.iter().chain([&extension]) {+ assert!(+ !path.exists(),+ "OMP extension survived at {}",+ path.display()+ );+ }+ assert!(!std::fs::read_to_string(&mcp).unwrap().contains("ai-memory"));+}+#[test]fn uninstall_apply_is_idempotent() {let _guard = cli_test_lock();@@ -368,6 +624,128 @@ fn uninstall_omp_extension_deletes_only_generated_file() {assert!(!extension.exists(), "generated extension should be deleted");}+/// A named OMP profile owns its agent dir, extension and `mcp.json` alike.+/// Uninstall sweeps it, the default profile's dir (where earlier releases put+/// the extension whenever `PI_CODING_AGENT_DIR` was set) and `~/.omp/agent`+/// (where `install-mcp` always wrote the MCP entry).+#[test]+fn profiled_omp_uninstall_sweeps_profile_default_and_legacy() {+ let _guard = cli_test_lock();+ let project = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ let pcad = home.path().join("pi-family");++ let run = |env: &[(&str, &Path)], args: &[&str]| {+ let mut command = command_with_home(home.path());+ for (name, value) in env {+ command.env(name, value);+ }+ let output = command+ .args(args)+ .current_dir(project.path())+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{args:?} failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ };+ let work = Path::new("work");+ let install_hooks = [+ "install-hooks",+ "--agent",+ "omp",+ "--apply",+ "--server-url",+ "http://127.0.0.1:49374",+ ];+ let install_mcp = ["install-mcp", "--client", "omp", "--apply"];+ run(&[], &install_mcp);+ run(&[("OMP_PROFILE", work)], &install_mcp);+ run(&[("OMP_PROFILE", work)], &install_hooks);+ run(&[("PI_CODING_AGENT_DIR", &pcad)], &install_hooks);++ let profile = home.path().join(".omp/profiles/work/agent");+ let legacy = home.path().join(".omp/agent");+ let installed = [+ legacy.join("mcp.json"),+ profile.join("mcp.json"),+ profile.join("extensions/ai-memory-omp.ts"),+ pcad.join("extensions/ai-memory-omp.ts"),+ ];+ for path in &installed {+ let content = std::fs::read_to_string(path)+ .unwrap_or_else(|error| panic!("installer did not create {}: {error}", path.display()));+ assert!(content.contains("ai-memory"), "{}", path.display());+ }++ let env: &[(&str, &Path)] = &[("OMP_PROFILE", work), ("PI_CODING_AGENT_DIR", &pcad)];+ run(env, &["uninstall", "--only", "hooks", "--apply", "--yes"]);+ run(env, &["uninstall", "--only", "mcp", "--apply", "--yes"]);+ for path in &installed[..2] {+ let content = std::fs::read_to_string(path).unwrap();+ assert!(+ !content.contains("ai-memory"),+ "OMP MCP entry survived in {}: {content}",+ path.display()+ );+ }+ for path in &installed[2..] {+ assert!(+ !path.exists(),+ "OMP extension survived at {}",+ path.display()+ );+ }+}++/// A profile name OMP refuses must not abort the cleanup of every other+/// agent: uninstall warns, skips that profile and sweeps the rest.+#[test]+fn uninstall_survives_an_invalid_omp_profile() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let claude = home.path().join(".claude");+ std::fs::create_dir_all(&claude).unwrap();+ let settings = claude.join("settings.json");+ std::fs::write(+ &settings,+ r#"{"hooks":{"Stop":[{"matcher":"","hooks":[{"type":"command","command":"AI_MEMORY_HOOK_URL=http://h /x/stop.sh"}]}]}}"#,+ )+ .unwrap();+ let extensions = home.path().join(".omp/agent/extensions");+ std::fs::create_dir_all(&extensions).unwrap();+ let extension = extensions.join("ai-memory-omp.ts");+ std::fs::write(+ &extension,+ "// Auto-generated by `ai-memory install-hooks --agent omp --apply`.\nconst AGENT = \"omp\";\n",+ )+ .unwrap();++ let output = command_with_home(home.path())+ .env("OMP_PROFILE", "Work")+ .args(["uninstall", "--apply", "--only", "hooks", "--yes"])+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(output.status.success(), "uninstall failed: {stderr}");+ assert!(+ stderr.contains("skipping the active OMP profile"),+ "the invalid profile must be reported: {stderr}"+ );+ assert!(+ !std::fs::read_to_string(&settings)+ .unwrap()+ .contains("AI_MEMORY_HOOK_URL"),+ "the Claude hook must still be removed"+ );+ assert!(+ !extension.exists(),+ "the default OMP extension must be swept"+ );+}+#[test]fn uninstall_pi_extension_deletes_only_generated_bridge_file() {let _guard = cli_test_lock();diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rsindex 4cff9451..c7ba5903 100644--- a/crates/ai-memory-workstream/src/harness.rs+++ b/crates/ai-memory-workstream/src/harness.rs@@ -1,10 +1,10 @@//! Native command planning without filtering harness arguments.use std::ffi::OsString;-use std::path::PathBuf;+use std::path::{Component, Path, PathBuf};use ai_memory_core::AgentKind;-use anyhow::Result;+use anyhow::{Result, anyhow, bail};use uuid::Uuid;/// Harnesses with native-session and transcript adapters.@@ -203,7 +203,24 @@ pub fn build_launch_plan(native_args: Vec<OsString>,linked_session_id: Option<&str>,) -> Result<LaunchPlan> {- build_launch_plan_with_env(harness, executable, native_args, linked_session_id, &[])+ build_launch_plan_with_env(+ harness,+ executable,+ native_args,+ linked_session_id,+ &[],+ None,+ )+}++/// Where a launch runs: the home the harness resolves `~` against and the+/// directory it starts in.+#[derive(Debug, Clone, Copy)]+pub struct LaunchRoots<'a> {+ /// The native home.+ pub home: &'a Path,+ /// The harness's working directory.+ pub cwd: &'a Path,}/// [`build_launch_plan`] with `--env`/`--env-file` overrides layered in front@@ -215,28 +232,49 @@ pub fn build_launch_plan(/// this same variable, so a caller-scoped override that only reached the/// child process would make the two disagree about where the session lives/// (see the `CLAUDE_CONFIG_DIR` note in `docs/managed-workstreams.md`).+///+/// `roots` name the native home and the launch directory. OMP needs the home+/// (a named profile, `PI_CONFIG_DIR`, or an XDG data dir) and Crush both (its+/// data directory is found from the launch directory, see+/// [`crush_data_dir`]); without them those stores fall back to the adapter's+/// default root.pub fn build_launch_plan_with_env(harness: ManagedHarness,executable: Option<OsString>,native_args: Vec<OsString>,linked_session_id: Option<&str>,env_overrides: &[(String, String)],+ roots: Option<LaunchRoots<'_>>,) -> Result<LaunchPlan> {let program = executable.unwrap_or_else(|| OsString::from(harness.executable()));let mut args = native_args;+ let get = |name: &str| {+ env_overrides+ .iter()+ .find(|(key, _)| key == name)+ .map(|(_, value)| OsString::from(value))+ .or_else(|| std::env::var_os(name))+ };let session_dir = match harness {ManagedHarness::Pi | ManagedHarness::Omp => flag_path(&args, &["--session-dir"]),ManagedHarness::Crush => flag_path(&args, &["--data-dir", "-D"]),_ => None,}.or_else(|| {- environment_session_dir_with(harness, |name| {- env_overrides- .iter()- .find(|(key, _)| key == name)- .map(|(_, value)| OsString::from(value))- .or_else(|| std::env::var_os(name))- })+ let omp_profile = match harness {+ ManagedHarness::Omp => omp_profile_flag(&args),+ _ => None,+ };+ environment_session_dir_with(+ harness,+ roots.map(|roots| roots.home),+ omp_profile.as_deref(),+ get,+ )+ })+ .or_else(|| match (harness, roots) {+ (ManagedHarness::Crush, Some(roots)) => Some(crush_data_dir(roots.cwd, roots.home, get)),+ _ => None,});let mut expected = explicit_session_id(harness, &args);let mode = launch_mode(harness, &args);@@ -917,15 +955,517 @@ fn flag_path(args: &[OsString], names: &[&str]) -> Option<PathBuf> {None}-fn environment_session_dir_with(- harness: ManagedHarness,+/// A harness home variable's directory, or `None` when it is unset or blank.+///+/// Blank (empty or whitespace-only) counts as unset on purpose: an+/// exported-but-empty variable is far more often an unset shell expansion than+/// a request to use the filesystem root or a directory named by whitespace.+/// Session import and the hook/MCP installers share this one rule, so a blank+/// override never sends one to the default home and the other to `<cwd>/ /`.+pub fn env_dir_override(value: Option<OsString>) -> Option<PathBuf> {+ let value = value?;+ if value.to_str().is_some_and(|text| text.trim().is_empty()) {+ return None;+ }+ Some(PathBuf::from(value))+}++/// The profile an OMP command line selects with a leading `--profile` (after+/// an optional `launch` or `acp`), which OMP ranks above `OMP_PROFILE`.+///+/// Only the leading position is read. OMP stops extracting global flags at a+/// subcommand (`omp grep --profile x` greps for `--profile`) and at `--`, and a+/// string flag such as `--system-prompt` takes a following `--profile` as its+/// value; telling those apart later in the line needs OMP's own flag tables.+/// A `--profile` anywhere else is left to the environment instead of guessed,+/// and so is a leading one that a later `--profile` might override.+pub fn omp_profile_flag(args: &[OsString]) -> Option<String> {+ let args: Vec<&str> = args.iter().map(|arg| arg.to_str()).collect::<Option<_>>()?;+ let mut rest = match args.first() {+ Some(&"launch" | &"acp") => &args[1..],+ _ => &args[..],+ };+ let mut profile = None;+ loop {+ match rest {+ [flag, value, tail @ ..] if *flag == "--profile" => {+ profile = Some(*value);+ rest = tail;+ }+ [flag, tail @ ..] if flag.starts_with("--profile=") => {+ profile = flag.strip_prefix("--profile=");+ rest = tail;+ }+ _ => break,+ }+ }+ let is_profile_flag = |arg: &&str| *arg == "--profile" || arg.starts_with("--profile=");+ if rest.iter().any(is_profile_flag) {+ return None;+ }+ profile+ .filter(|value| !value.is_empty() && !value.starts_with('-'))+ .map(str::to_owned)+}++/// The variables that relocate a harness's native store, the ones+/// [`build_launch_plan_with_env`] resolves its session directory from.+pub fn store_override_vars(harness: ManagedHarness) -> &'static [&'static str] {+ match harness {+ ManagedHarness::Claude => &["CLAUDE_CONFIG_DIR"],+ ManagedHarness::Codex => &["CODEX_HOME"],+ ManagedHarness::OpenCode | ManagedHarness::OpenCode2 => &["XDG_DATA_HOME"],+ ManagedHarness::Pi => &["PI_CODING_AGENT_SESSION_DIR", "PI_CODING_AGENT_DIR"],+ ManagedHarness::Omp => &[+ "PI_CODING_AGENT_SESSION_DIR",+ "PI_CODING_AGENT_DIR",+ "PI_CONFIG_DIR",+ "XDG_DATA_HOME",+ ],+ ManagedHarness::Kimi => &["KIMI_CODE_HOME"],+ ManagedHarness::Kiro | ManagedHarness::KiroV3 => &["KIRO_HOME"],+ ManagedHarness::Grok => &["GROK_HOME"],+ ManagedHarness::Crush | ManagedHarness::CommandCode | ManagedHarness::Antigravity => &[],+ }+}++/// OMP's active profile, resolved the way OMP resolves it+/// (`normalizeProfileName` and `resolveProfileEnv` in its+/// `pi-utils/src/dirs.ts`, checked against 18.2.5): an explicit `--profile`+/// wins, then `OMP_PROFILE` whenever it is set, even to an empty value, and+/// only then the legacy `PI_PROFILE`. The name is trimmed, and an empty,+/// whitespace-only or `default` name selects the default profile (`None`).+///+/// # Errors+/// Returns an error for a name OMP itself refuses, so ai-memory never wires a+/// profile directory OMP will not load.+fn omp_profile(+ explicit: Option<&str>,get: impl Fn(&str) -> Option<OsString>,-) -> Option<PathBuf> {- let value = |name| {+) -> Result<Option<String>> {+ let raw = match explicit {+ Some("") => bail!("--profile requires a profile name"),+ Some(name) => name.to_owned(),+ None => match get("OMP_PROFILE").or_else(|| get("PI_PROFILE")) {+ Some(value) => value+ .into_string()+ .map_err(|value| anyhow!("Invalid OMP profile {value:?}: not valid UTF-8"))?,+ None => return Ok(None),+ },+ };+ normalize_omp_profile(&raw)+}++/// OMP's `normalizeProfileName`: trimmed, with empty and `default` meaning the+/// default profile.+fn normalize_omp_profile(raw: &str) -> Result<Option<String>> {+ let name = raw.trim();+ if name.is_empty() || name == "default" {+ return Ok(None);+ }+ if !is_valid_omp_profile_name(name) {+ bail!(+ "Invalid OMP profile \"{raw}\". Profile names must match ^[a-z0-9][a-z0-9._-]{{0,63}}$, \+ cannot be \".\" or \"..\", cannot end with \".\", and cannot be a Windows reserved \+ device name (CON, PRN, AUX, NUL, COM0-9, LPT0-9, or any of those with an extension)."+ );+ }+ Ok(Some(name.to_owned()))+}++fn is_valid_omp_profile_name(name: &str) -> bool {+ let bytes = name.as_bytes();+ let lower_alnum = |byte: &u8| byte.is_ascii_lowercase() || byte.is_ascii_digit();+ let base = name.split('.').next().unwrap_or(name);+ let reserved = matches!(base, "con" | "prn" | "aux" | "nul")+ || (base.len() == 4+ && (base.starts_with("com") || base.starts_with("lpt"))+ && base.as_bytes()[3].is_ascii_digit());+ (1..=64).contains(&bytes.len())+ && lower_alnum(&bytes[0])+ && bytes[1..]+ .iter()+ .all(|byte| lower_alnum(byte) || matches!(byte, b'.' | b'_' | b'-'))+ && !name.ends_with('.')+ && !reserved+}++/// OMP's agent directory, where it loads extensions and `mcp.json` (and keeps+/// sessions unless XDG moves them, see [`omp_sessions_dir`]). A named profile+/// owns `<root>/profiles/<name>/agent` and ignores `PI_CODING_AGENT_DIR`; the+/// default profile honors a non-blank `PI_CODING_AGENT_DIR`, else+/// `<root>/agent`. `<root>` is `<home>/.omp`, renamed by `PI_CONFIG_DIR`.+///+/// # Errors+/// Returns the [`omp_profile`] error for a profile name OMP refuses.+pub fn omp_agent_dir(+ home: &Path,+ explicit_profile: Option<&str>,+ get: impl Fn(&str) -> Option<OsString>,+) -> Result<PathBuf> {+ Ok(match omp_profile(explicit_profile, &get)? {+ Some(profile) => omp_profile_agent_dir(home, &profile, &get),+ None => omp_default_agent_dir_override(home, &get)+ .unwrap_or_else(|| omp_config_root(home, &get).join("agent")),+ })+}++/// OMP's config root: `<home>/.omp`, or `<home>/<PI_CONFIG_DIR>` when that+/// variable renames it. OMP joins the value under the home with Node's+/// `path.join`, so an absolute value stays under the home and `..` walks up+/// from it, where `PathBuf::join` would replace the home instead.+fn omp_config_root(home: &Path, get: impl Fn(&str) -> Option<OsString>) -> PathBuf {+ let name = env_dir_override(get("PI_CONFIG_DIR")).unwrap_or_else(|| PathBuf::from(".omp"));+ let mut root = home.to_path_buf();+ for component in name.components() {+ match component {+ Component::Normal(part) => root.push(part),+ Component::ParentDir => {+ root.pop();+ }+ // Node's `path.win32.join` keeps a drive or UNC prefix as plain+ // segments under the home (`C:\Users\me\server\share\omp`).+ // Appended as text: pushing `D:` would make it a new prefix.+ Component::Prefix(prefix) => {+ let text = prefix.as_os_str().to_string_lossy().into_owned();+ for part in text.split(['\\', '/']).filter(|part| !part.is_empty()) {+ let path = root.as_mut_os_string();+ if !path.to_string_lossy().ends_with(['\\', '/']) {+ path.push(std::path::MAIN_SEPARATOR_STR);+ }+ path.push(part);+ }+ }+ Component::RootDir | Component::CurDir => {}+ }+ }+ root+}++/// `path` with `.` dropped and `..` folded lexically, without touching the+/// filesystem: Go's `filepath.Clean`, and the normalizing half of Node's+/// `path.resolve`. A `..` that would climb above the root is dropped.+pub fn clean_path(path: &Path) -> PathBuf {+ let mut clean = PathBuf::new();+ for component in path.components() {+ match component {+ Component::CurDir => {}+ Component::ParentDir => match clean.components().next_back() {+ Some(Component::Normal(_)) => {+ clean.pop();+ }+ Some(Component::RootDir | Component::Prefix(_)) => {}+ _ => clean.push(".."),+ },+ other => clean.push(other.as_os_str()),+ }+ }+ if clean.as_os_str().is_empty() {+ clean.push(".");+ }+ clean+}++/// Crush's global `crush.json`, resolved as Crush's `GlobalConfig()` does:+/// `$CRUSH_GLOBAL_CONFIG/crush.json`, else `$XDG_CONFIG_HOME/crush/crush.json`,+/// else `~/.config/crush/crush.json`. `get` is the launch environment, and a+/// blank value counts as unset, as for every other harness home; a managed+/// launch drops such a value from Crush too.+pub fn crush_global_config_path(home: &Path, get: impl Fn(&str) -> Option<OsString>) -> PathBuf {+ let dir = |name| env_dir_override(get(name));+ if let Some(dir) = dir("CRUSH_GLOBAL_CONFIG") {+ return dir.join("crush.json");+ }+ dir("XDG_CONFIG_HOME")+ .unwrap_or_else(|| home.join(".config"))+ .join("crush")+ .join("crush.json")+}++/// The directory Crush keeps `crush.db` in when no `--data-dir` is given,+/// resolved as Crush's `setDefaults` does: the last `options.data_directory`+/// among its JSON configs, else the closest `.crush` from `cwd` up to the git+/// worktree root (not one directly in the home, and the walk stops at an+/// entry another user owns), else `<cwd>/.crush`. A relative value is taken+/// against `cwd`. `get` is the launch environment.+///+/// A `crushrc` can set the option as well, but reading it means running the+/// user's shell script, so a data directory set only there is not seen; pass+/// `--data-dir` to name it.+pub fn crush_data_dir(cwd: &Path, home: &Path, get: impl Fn(&str) -> Option<OsString>) -> PathBuf {+ let cwd = clean_path(&std::path::absolute(cwd).unwrap_or_else(|_| cwd.to_path_buf()));+ let boundary = crate::repository::worktree_root(&cwd).unwrap_or_else(|| cwd.clone());+ // Crush gives up on both upward searches when it cannot stat the start.+ let walk = path_owner(&cwd)+ .ok()+ .map(|owner| (owner, crush_walk_up(&cwd, &boundary)));+ let configured = crush_config_files(&cwd, home, walk.as_ref(), &get)+ .iter()+ .fold(None, |value, file| {+ crush_config_data_directory(file).or(value)+ })+ .filter(|dir| !dir.is_empty())+ .map(PathBuf::from);+ let dir = configured+ .or_else(|| {+ let (owner, dirs) = walk.as_ref()?;+ crush_closest_data_dir(dirs, *owner, home)+ })+ .unwrap_or_else(|| cwd.join(".crush"));+ // Crush's `SmartJoin`: a path that starts with a slash is absolute on+ // Windows too.+ let rooted = cfg!(windows) && dir.to_string_lossy().starts_with(['/', '\\']);+ if dir.is_absolute() || rooted {+ clean_path(&dir)+ } else {+ clean_path(&cwd.join(dir))+ }+}++/// [`crush_data_dir`] against ai-memory's own environment, for a store no+/// launch plan named (automatic session discovery).+pub(crate) fn crush_process_data_dir(cwd: &Path, home: &Path) -> PathBuf {+ crush_data_dir(cwd, home, |name| std::env::var_os(name))+}++/// Crush's JSON configs in merge order, later ones winning: the system file,+/// the global config, the global data config, then the project's+/// `crush.json` and `.crush.json` from the walk's top down to `cwd`.+fn crush_config_files(+ cwd: &Path,+ home: &Path,+ walk: Option<&(Option<u32>, Vec<PathBuf>)>,+ get: &impl Fn(&str) -> Option<OsString>,+) -> Vec<PathBuf> {+ // Crush tests these with `!= ""` and reads a relative path from its+ // working directory.+ let set = |name: &str| {get(name).filter(|value| !value.is_empty()).map(PathBuf::from)};+ let global_data = if let Some(dir) = set("CRUSH_GLOBAL_DATA") {+ dir.join("crush.json")+ } else if let Some(dir) = set("XDG_DATA_HOME") {+ dir.join("crush").join("crush.json")+ } else if cfg!(windows) {+ set("LOCALAPPDATA")+ .unwrap_or_else(|| {+ PathBuf::from(get("USERPROFILE").unwrap_or_default())+ .join("AppData")+ .join("Local")+ })+ .join("crush")+ .join("crush.json")+ } else {+ home.join(".local")+ .join("share")+ .join("crush")+ .join("crush.json")+ };+ let mut files = Vec::new();+ if cfg!(not(windows)) {+ files.push(PathBuf::from("/etc/crush/crush.json"));+ }+ files.push(cwd.join(crush_global_config_path(home, get)));+ files.push(cwd.join(global_data));+ if let Some((owner, dirs)) = walk {+ for dir in dirs.iter().rev() {+ for name in ["crush.json", ".crush.json"] {+ let file = dir.join(name);+ if crush_probe(&file, *owner) == CrushProbe::Found {+ files.push(file);+ }+ }+ }+ }+ files+}++/// `options.data_directory` from one JSON config, when it sets one.+fn crush_config_data_directory(file: &Path) -> Option<String> {+ let raw = std::fs::read(file).ok()?;+ let config = serde_json::from_slice::<serde_json::Value>(&raw).ok()?;+ config+ .get("options")?+ .get("data_directory")?+ .as_str()+ .map(str::to_owned)+}++/// Crush's `LookupClosestBounded(cwd, boundary, ".crush")` over `dirs`.+fn crush_closest_data_dir(dirs: &[PathBuf], owner: Option<u32>, home: &Path) -> Option<PathBuf> {+ for dir in dirs {+ let candidate = dir.join(".crush");+ match crush_probe(&candidate, owner) {+ CrushProbe::Missing => continue,+ CrushProbe::Refused => return None,+ CrushProbe::Found => return (dir != home).then_some(candidate),+ }+ }+ None+}++/// `cwd` and each parent up to `boundary`, compared with symlinks resolved,+/// or up to the filesystem root when `boundary` is not above `cwd` (Crush's+/// `traverseUpBounded`).+fn crush_walk_up(cwd: &Path, boundary: &Path) -> Vec<PathBuf> {+ let resolved = |path: &Path| std::fs::canonicalize(path).unwrap_or_else(|_| clean_path(path));+ let stop = resolved(boundary);+ let mut dirs = Vec::new();+ let mut dir = Some(cwd);+ while let Some(current) = dir {+ dirs.push(current.to_path_buf());+ if resolved(current) == stop {+ break;+ }+ dir = current.parent();+ }+ dirs+}++#[derive(Debug, PartialEq, Eq)]+enum CrushProbe {+ Found,+ Missing,+ Refused,+}++/// Crush's `probeEnt`: an entry owned by someone other than the walk's+/// owner, or one it cannot stat, is refused.+fn crush_probe(path: &Path, owner: Option<u32>) -> CrushProbe {+ match std::fs::metadata(path) {+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => CrushProbe::Missing,+ Err(_) => CrushProbe::Refused,+ Ok(metadata) if owner.is_none_or(|owner| metadata_owner(&metadata) == Some(owner)) => {+ CrushProbe::Found+ }+ Ok(_) => CrushProbe::Refused,+ }+}++/// The uid Crush compares while walking up (`fsext.Owner`); `None` on+/// Windows, where Crush skips the check.+fn path_owner(path: &Path) -> std::io::Result<Option<u32>> {+ std::fs::metadata(path).map(|metadata| metadata_owner(&metadata))+}++#[cfg(unix)]+fn metadata_owner(metadata: &std::fs::Metadata) -> Option<u32> {+ use std::os::unix::fs::MetadataExt as _;+ Some(metadata.uid())+}++#[cfg(not(unix))]+fn metadata_owner(_metadata: &std::fs::Metadata) -> Option<u32> {+ None+}++/// Where OMP keeps sessions when nothing names the session dir: its agent+/// dir's `sessions`, except that on Linux and macOS an agent dir at its+/// default location moves them under `$XDG_DATA_HOME/omp` (a named profile+/// under `$XDG_DATA_HOME/omp/profiles/<name>`) once that directory exists+/// (`DirResolver` in OMP's `dirs.ts`). Extensions and `mcp.json` never move.+fn omp_sessions_dir(+ home: &Path,+ explicit_profile: Option<&str>,+ get: impl Fn(&str) -> Option<OsString>,+ xdg_platform: bool,+ exists: impl Fn(&Path) -> bool,+) -> Result<PathBuf> {+ let profile = omp_profile(explicit_profile, &get)?;+ let agent_dir = omp_agent_dir(home, explicit_profile, &get)?;+ let default_location = match &profile {+ Some(name) => omp_profile_agent_dir(home, name, &get),+ None => omp_config_root(home, &get).join("agent"),+ };+ // OMP compares the override after `path.resolve`, so a relative or+ // `..`-laden spelling of the default location still counts as default.+ let resolved = std::path::absolute(&agent_dir)+ .map(|dir| clean_path(&dir))+ .unwrap_or_else(|_| agent_dir.clone());+ if xdg_platform+ && resolved == clean_path(&default_location)+ && let Some(data) = env_dir_override(get("XDG_DATA_HOME"))+ {+ let base = match &profile {+ Some(name) => data.join("omp").join("profiles").join(name),+ None => data.join("omp"),+ };+ if exists(&base) {+ return Ok(base.join("sessions"));+ }+ }+ Ok(agent_dir.join("sessions"))+}++/// The default profile's `PI_CODING_AGENT_DIR`, unless it is the agent dir a+/// parent OMP derived for its profile and exported to its children. OMP drops+/// such a value (`resolvePreProfileAgentDir` in `dirs.ts`), so a nested launch+/// back on the default profile uses `~/.omp/agent`, not the parent's profile.+fn omp_default_agent_dir_override(+ home: &Path,+ get: impl Fn(&str) -> Option<OsString>,+) -> Option<PathBuf> {+ let dir = env_dir_override(get("PI_CODING_AGENT_DIR"))?;+ match inherited_omp_profile(&get) {+ Some(profile) if dir == omp_profile_agent_dir(home, &profile, &get) => None,+ _ => Some(dir),+ }+}++/// The profile the environment names for OMP (`OMP_PROFILE`, else+/// `PI_PROFILE`), or failing that `PI_PROFILE` on its own: the one OMP checks+/// an inherited `PI_CODING_AGENT_DIR` against. Invalid names count as none,+/// as in OMP's `readProfileFromEnvSafe`.+fn inherited_omp_profile(get: impl Fn(&str) -> Option<OsString>) -> Option<String> {+ let normalized =+ |value: Option<OsString>| normalize_omp_profile(value?.to_str()?).ok().flatten();+ normalized(get("OMP_PROFILE").or_else(|| get("PI_PROFILE")))+ .or_else(|| normalized(get("PI_PROFILE")))+}++/// The `OMP_PROFILE` / `PI_PROFILE` values under which ai-memory's resolvers+/// see what `omp --profile <profile>` sees in the environment `get` reads. A+/// named profile needs only `OMP_PROFILE`. `default` selects the default+/// profile but must keep the profile the environment named, which OMP still+/// uses to drop a `PI_CODING_AGENT_DIR` inherited from that profile.+pub fn omp_profile_flag_env(+ profile: &str,+ get: impl Fn(&str) -> Option<OsString>,+) -> Vec<(String, String)> {+ match normalize_omp_profile(profile) {+ Ok(Some(name)) => vec![("OMP_PROFILE".to_string(), name)],+ Ok(None) => vec![+ ("OMP_PROFILE".to_string(), String::new()),+ (+ "PI_PROFILE".to_string(),+ inherited_omp_profile(&get).unwrap_or_default(),+ ),+ ],+ // OMP refuses to start with it; pass it on so auto-wire reports it.+ Err(_) => vec![("OMP_PROFILE".to_string(), profile.to_string())],+ }+}++fn omp_profile_agent_dir(+ home: &Path,+ profile: &str,+ get: impl Fn(&str) -> Option<OsString>,+) -> PathBuf {+ omp_config_root(home, get)+ .join("profiles")+ .join(profile)+ .join("agent")+}++fn environment_session_dir_with(+ harness: ManagedHarness,+ home: Option<&Path>,+ omp_profile_flag: Option<&str>,+ get: impl Fn(&str) -> Option<OsString>,+) -> Option<PathBuf> {+ let value = |name| env_dir_override(get(name));match harness {ManagedHarness::Claude => value("CLAUDE_CONFIG_DIR").map(|dir| dir.join("projects")),ManagedHarness::Codex => value("CODEX_HOME").map(|dir| dir.join("sessions")),@@ -937,7 +1477,25 @@ fn environment_session_dir_with(ManagedHarness::Pi => value("PI_CODING_AGENT_SESSION_DIR").or_else(|| value("PI_CODING_AGENT_DIR").map(|dir| dir.join("sessions"))),ManagedHarness::Crush => None,- ManagedHarness::Omp => value("PI_CODING_AGENT_DIR").map(|dir| dir.join("sessions")),+ // OMP reads `PI_CODING_AGENT_SESSION_DIR` as its `--session-dir`+ // default. A named profile needs the home to resolve, and an invalid+ // one makes OMP refuse to start, so neither has a store to point at.+ ManagedHarness::Omp => value("PI_CODING_AGENT_SESSION_DIR").or_else(|| match home {+ Some(home) => omp_sessions_dir(+ home,+ omp_profile_flag,+ &get,+ cfg!(any(target_os = "linux", target_os = "macos")),+ Path::exists,+ )+ .ok()+ // The adapter's default root already covers an unmoved store.+ .filter(|dir| *dir != home.join(".omp").join("agent").join("sessions")),+ None => match omp_profile(omp_profile_flag, &get) {+ Ok(None) => value("PI_CODING_AGENT_DIR").map(|dir| dir.join("sessions")),+ _ => None,+ },+ }),// Sessions live under `<KIMI_CODE_HOME>/sessions/<bucket>/<id>/`.ManagedHarness::Kimi => value("KIMI_CODE_HOME").map(|dir| dir.join("sessions")),// Command Code documents no session-root override. Its user store is@@ -1389,23 +1947,673 @@ mod tests {_ => None,};assert_eq!(- environment_session_dir_with(ManagedHarness::Claude, get).as_deref(),+ environment_session_dir_with(ManagedHarness::Claude, None, None, get).as_deref(),Some(std::path::Path::new("/stores/claude/projects")));assert_eq!(- environment_session_dir_with(ManagedHarness::Codex, get).as_deref(),+ environment_session_dir_with(ManagedHarness::Codex, None, None, get).as_deref(),Some(std::path::Path::new("/stores/codex/sessions")));assert_eq!(- environment_session_dir_with(ManagedHarness::OpenCode, get).as_deref(),+ environment_session_dir_with(ManagedHarness::OpenCode, None, None, get).as_deref(),Some(std::path::Path::new("/stores/xdg/opencode")));assert_eq!(- environment_session_dir_with(ManagedHarness::Omp, get).as_deref(),+ environment_session_dir_with(ManagedHarness::Omp, None, None, get).as_deref(),Some(std::path::Path::new("/stores/pi-family/sessions")));}+ fn git_init(dir: &Path) {+ let status = std::process::Command::new("git")+ .args(["init", "-q"])+ .arg(dir)+ .status()+ .unwrap();+ assert!(status.success());+ }++ /// Only Crush's global config names: the global JSON files under the temp+ /// root, never the developer's.+ fn crush_env(root: &Path) -> impl Fn(&str) -> Option<OsString> + use<> {+ let config = root.join("global-config").into_os_string();+ let data = root.join("global-data").into_os_string();+ move |name| match name {+ "CRUSH_GLOBAL_CONFIG" => Some(config.clone()),+ "CRUSH_GLOBAL_DATA" => Some(data.clone()),+ _ => None,+ }+ }++ /// Without `--data-dir` Crush keeps `crush.db` in the closest `.crush`+ /// between the working directory and the git worktree root, not always+ /// in `<cwd>/.crush`; outside a worktree it looks only in the cwd.+ #[test]+ fn crush_data_dir_takes_the_closest_crush_dir_in_the_worktree() {+ let root = tempfile::tempdir().unwrap();+ let root = std::fs::canonicalize(root.path()).unwrap();+ let home = root.join("home");+ let repo = root.join("repo");+ let cwd = repo.join("sub").join("deep");+ std::fs::create_dir_all(&cwd).unwrap();+ std::fs::create_dir_all(&home).unwrap();+ std::fs::create_dir(root.join(".crush")).unwrap();+ let resolve = |cwd: &Path| crush_data_dir(cwd, &home, crush_env(&root));++ // `<root>/.crush` is above the cwd but outside any worktree bound.+ assert_eq!(resolve(&cwd), cwd.join(".crush"));+ git_init(&repo);+ assert_eq!(+ resolve(&cwd),+ cwd.join(".crush"),+ "the walk stops at the worktree root"+ );+ std::fs::create_dir(repo.join(".crush")).unwrap();+ assert_eq!(resolve(&cwd), repo.join(".crush"));+ std::fs::create_dir(repo.join("sub").join(".crush")).unwrap();+ assert_eq!(resolve(&cwd), repo.join("sub").join(".crush"));+ }++ /// A `.crush` directly in the home is Crush's global state, never a+ /// project's data dir.+ #[test]+ fn crush_data_dir_skips_a_crush_dir_in_the_home() {+ let root = tempfile::tempdir().unwrap();+ let root = std::fs::canonicalize(root.path()).unwrap();+ let home = root.join("home");+ let cwd = home.join("project");+ std::fs::create_dir_all(&cwd).unwrap();+ git_init(&home);+ std::fs::create_dir(home.join(".crush")).unwrap();+ assert_eq!(+ crush_data_dir(&cwd, &home, crush_env(&root)),+ cwd.join(".crush")+ );+ }++ /// `options.data_directory` wins over the lookup. Later configs override+ /// earlier ones: the global JSON files, then the project's from the+ /// worktree root down, `.crush.json` over `crush.json` in one directory.+ /// A relative value is taken against the cwd and an empty one falls back+ /// to the lookup.+ #[test]+ fn crush_data_dir_follows_data_directory_in_crush_configs() {+ let root = tempfile::tempdir().unwrap();+ let root = std::fs::canonicalize(root.path()).unwrap();+ let home = root.join("home");+ let repo = root.join("repo");+ let cwd = repo.join("sub");+ std::fs::create_dir_all(&cwd).unwrap();+ std::fs::create_dir_all(&home).unwrap();+ git_init(&repo);+ let write = |file: &Path, dir: &str| {+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();+ std::fs::write(+ file,+ serde_json::json!({"options": {"data_directory": dir}}).to_string(),+ )+ .unwrap();+ };+ let resolve = || crush_data_dir(&cwd, &home, crush_env(&root));++ write(+ &root.join("global-config").join("crush.json"),+ "/from/global",+ );+ assert_eq!(resolve(), Path::new("/from/global"));+ write(&root.join("global-data").join("crush.json"), "/from/data");+ assert_eq!(resolve(), Path::new("/from/data"));+ write(&repo.join(".crush.json"), "/from/repo-hidden");+ write(&repo.join("crush.json"), "/from/repo");+ assert_eq!(resolve(), Path::new("/from/repo-hidden"));+ write(&cwd.join("crush.json"), "state/../store");+ assert_eq!(resolve(), cwd.join("store"));+ write(&cwd.join("crush.json"), "");+ std::fs::create_dir(repo.join(".crush")).unwrap();+ assert_eq!(resolve(), repo.join(".crush"));+ }++ /// The launch plan carries the resolved Crush store when it knows where+ /// the launch runs; `--data-dir` still wins.+ #[test]+ fn crush_launch_plan_resolves_the_data_dir_from_the_launch_dir() {+ let root = tempfile::tempdir().unwrap();+ let root = std::fs::canonicalize(root.path()).unwrap();+ let repo = root.join("repo");+ let cwd = repo.join("sub");+ std::fs::create_dir_all(&cwd).unwrap();+ git_init(&repo);+ std::fs::create_dir(repo.join(".crush")).unwrap();+ let env = [+ (+ "CRUSH_GLOBAL_CONFIG".to_string(),+ root.join("global-config").display().to_string(),+ ),+ (+ "CRUSH_GLOBAL_DATA".to_string(),+ root.join("global-data").display().to_string(),+ ),+ ];+ let plan = |args: Vec<OsString>| {+ build_launch_plan_with_env(+ ManagedHarness::Crush,+ None,+ args,+ None,+ &env,+ Some(LaunchRoots {+ home: &root,+ cwd: &cwd,+ }),+ )+ .unwrap()+ .session_dir+ };+ assert_eq!(plan(Vec::new()), Some(repo.join(".crush")));+ assert_eq!(+ plan(vec![+ OsString::from("--data-dir"),+ OsString::from("/pinned")+ ]),+ Some(PathBuf::from("/pinned"))+ );+ }++ fn env_of(pairs: &[(&'static str, &'static str)]) -> impl Fn(&str) -> Option<OsString> + use<> {+ let pairs = pairs.to_vec();+ move |name| {+ pairs+ .iter()+ .find(|(key, _)| *key == name)+ .map(|(_, value)| OsString::from(value))+ }+ }++ #[test]+ fn omp_profile_flag_reads_only_a_leading_profile() {+ let flag =+ |args: &[&str]| omp_profile_flag(&args.iter().map(OsString::from).collect::<Vec<_>>());+ assert_eq!(flag(&["--profile", "work"]).as_deref(), Some("work"));+ assert_eq!(+ flag(&["--profile=work", "--model", "x"]).as_deref(),+ Some("work")+ );+ assert_eq!(+ flag(&["launch", "--profile", "work"]).as_deref(),+ Some("work")+ );+ // OMP itself does not select a profile from any of these.+ assert_eq!(flag(&["grep", "--profile", "foo"]), None);+ assert_eq!(flag(&["--system-prompt", "--profile", "foo"]), None);+ assert_eq!(flag(&["--", "--profile", "foo"]), None);+ assert_eq!(flag(&["--profile", "--print"]), None);+ assert_eq!(flag(&["--profile="]), None);+ // Ambiguous without OMP's flag tables, so the environment decides.+ assert_eq!(flag(&["--model", "x", "--profile", "work"]), None);+ // OMP keeps the last `--profile`.+ assert_eq!(+ flag(&["--profile", "work", "--profile=personal"]).as_deref(),+ Some("personal")+ );+ assert_eq!(+ flag(&["--profile", "work", "--model", "x", "--profile", "b"]),+ None+ );+ }++ /// A `PI_CODING_AGENT_DIR` that a parent OMP derived for its profile is+ /// dropped once the default profile is back in charge, as OMP does; any+ /// other value is still honored.+ #[test]+ fn omp_default_profile_drops_a_profile_derived_agent_dir() {+ let home = Path::new("/home/me");+ let derived = "/home/me/.omp/profiles/work/agent";+ let default = home.join(".omp/agent");+ let dir = |explicit: Option<&str>, pairs: &[(&'static str, &'static str)]| {+ omp_agent_dir(home, explicit, env_of(pairs)).unwrap()+ };+ let inherited = [+ ("OMP_PROFILE", ""),+ ("PI_PROFILE", "work"),+ ("PI_CODING_AGENT_DIR", derived),+ ];+ assert_eq!(dir(None, &inherited), default);+ assert_eq!(+ dir(+ None,+ &[+ ("OMP_PROFILE", ""),+ ("PI_PROFILE", "work"),+ ("PI_CONFIG_DIR", ".cfg"),+ ("PI_CODING_AGENT_DIR", "/home/me/.cfg/profiles/work/agent")+ ]+ ),+ PathBuf::from("/home/me/.cfg/agent"),+ "the derived dir follows PI_CONFIG_DIR"+ );+ assert_eq!(+ dir(+ Some("default"),+ &[("OMP_PROFILE", "work"), ("PI_CODING_AGENT_DIR", derived)]+ ),+ default+ );+ assert_eq!(+ dir(+ None,+ &[+ ("OMP_PROFILE", ""),+ ("PI_PROFILE", "work"),+ ("PI_CODING_AGENT_DIR", "/custom")+ ]+ ),+ PathBuf::from("/custom")+ );+ assert_eq!(+ dir(None, &[("PI_CODING_AGENT_DIR", derived)]),+ PathBuf::from(derived),+ "without an inherited profile the override is the user's own"+ );+ assert_eq!(+ environment_session_dir_with(ManagedHarness::Omp, Some(home), None, env_of(&inherited)),+ None+ );+ }++ /// OMP keeps sessions in its agent dir: a named profile owns+ /// `~/.omp/profiles/<name>/agent` and ignores `PI_CODING_AGENT_DIR`,+ /// `--profile` beats `OMP_PROFILE`, and `PI_CODING_AGENT_SESSION_DIR`+ /// (OMP's `--session-dir` default) beats both.+ #[test]+ fn omp_session_dir_follows_profile_and_session_env() {+ let home = Path::new("/home/me");+ let profile = |name: &str| home.join(".omp/profiles").join(name).join("agent/sessions");+ let resolve = |flag: Option<&str>, pairs: &[(&'static str, &'static str)]| {+ environment_session_dir_with(ManagedHarness::Omp, Some(home), flag, env_of(pairs))+ };+ assert_eq!(+ resolve(None, &[("OMP_PROFILE", "work")]),+ Some(profile("work"))+ );+ assert_eq!(+ resolve(+ None,+ &[("OMP_PROFILE", "work"), ("PI_CODING_AGENT_DIR", "/x")]+ ),+ Some(profile("work"))+ );+ assert_eq!(+ resolve(None, &[("PI_PROFILE", "work")]),+ Some(profile("work"))+ );+ assert_eq!(+ resolve(Some("work"), &[("OMP_PROFILE", "other")]),+ Some(profile("work"))+ );+ assert_eq!(+ resolve(+ Some("default"),+ &[("OMP_PROFILE", "other"), ("PI_CODING_AGENT_DIR", "/x")]+ ),+ Some(PathBuf::from("/x/sessions"))+ );+ assert_eq!(+ resolve(+ None,+ &[+ ("PI_CODING_AGENT_SESSION_DIR", "/s"),+ ("OMP_PROFILE", "work")+ ]+ ),+ Some(PathBuf::from("/s"))+ );+ // No home, or a profile OMP refuses to start with: nothing to point at.+ assert_eq!(+ environment_session_dir_with(+ ManagedHarness::Omp,+ None,+ None,+ env_of(&[("OMP_PROFILE", "work")])+ ),+ None+ );+ assert_eq!(resolve(None, &[("OMP_PROFILE", "Work")]), None);++ let plan = build_launch_plan_with_env(+ ManagedHarness::Omp,+ None,+ vec![OsString::from("--profile"), OsString::from("work")],+ None,+ &[+ ("PI_CODING_AGENT_DIR".to_string(), "/x".to_string()),+ // Blank masks whatever the developer's shell exports.+ ("PI_CODING_AGENT_SESSION_DIR".to_string(), String::new()),+ ("PI_CONFIG_DIR".to_string(), String::new()),+ ("XDG_DATA_HOME".to_string(), String::new()),+ ],+ Some(LaunchRoots { home, cwd: home }),+ )+ .unwrap();+ assert_eq!(plan.session_dir, Some(profile("work")));+ }++ /// OMP joins `PI_CONFIG_DIR` under the home with Node's `path.join`: an+ /// absolute value stays under the home, `..` walks up, `~` is literal,+ /// and a blank value keeps `.omp`.+ #[test]+ fn omp_config_root_renames_like_node_path_join() {+ let home = Path::new("/home/me");+ for (value, expected) in [+ (".omp-alt", "/home/me/.omp-alt"),+ ("/abs/cfg", "/home/me/abs/cfg"),+ ("../sib", "/home/sib"),+ ("~/.x", "/home/me/~/.x"),+ ("./cfg/", "/home/me/cfg"),+ ("", "/home/me/.omp"),+ (" ", "/home/me/.omp"),+ ] {+ let env = |name: &str| (name == "PI_CONFIG_DIR").then(|| OsString::from(value));+ assert_eq!(+ omp_config_root(home, env),+ PathBuf::from(expected),+ "{value:?}"+ );+ assert_eq!(+ omp_agent_dir(home, Some("work"), env).unwrap(),+ PathBuf::from(expected).join("profiles/work/agent"),+ "{value:?}"+ );+ }+ assert_eq!(omp_config_root(home, |_| None), home.join(".omp"));+ assert_eq!(+ environment_session_dir_with(+ ManagedHarness::Omp,+ Some(home),+ None,+ env_of(&[("PI_CONFIG_DIR", ".cfg")])+ ),+ Some(PathBuf::from("/home/me/.cfg/agent/sessions"))+ );+ }++ #[test]+ fn clean_path_folds_like_go_filepath_clean() {+ for (raw, expected) in [+ ("/a/b/../c", "/a/c"),+ ("/a/./b/", "/a/b"),+ ("/..", "/"),+ ("a/../..", ".."),+ ("", "."),+ ("./", "."),+ ] {+ assert_eq!(+ clean_path(Path::new(raw)),+ PathBuf::from(expected),+ "{raw:?}"+ );+ }+ }++ /// `omp --profile default` keeps the profile the environment named, so+ /// an agent dir inherited from that profile is still dropped.+ #[test]+ fn omp_profile_flag_env_keeps_the_inherited_profile_for_default() {+ let home = Path::new("/home/me");+ let resolve = |pairs: Vec<(String, String)>| {+ let inherited = env_of(&[+ ("OMP_PROFILE", "work"),+ ("PI_CODING_AGENT_DIR", "/home/me/.omp/profiles/work/agent"),+ ]);+ let merged = move |name: &str| {+ pairs+ .iter()+ .find(|(key, _)| key == name)+ .map(|(_, value)| OsString::from(value))+ .or_else(|| inherited(name))+ };+ omp_agent_dir(home, None, merged).unwrap()+ };+ assert_eq!(+ resolve(omp_profile_flag_env(+ "default",+ env_of(&[("OMP_PROFILE", "work")])+ )),+ home.join(".omp/agent")+ );+ assert_eq!(+ resolve(omp_profile_flag_env("other", |_| None)),+ home.join(".omp/profiles/other/agent")+ );+ assert_eq!(+ omp_profile_flag_env("Bad", |_| None),+ vec![("OMP_PROFILE".to_string(), "Bad".to_string())],+ "an invalid name is passed on for the resolver to refuse"+ );+ }++ /// OMP resolves `PI_CODING_AGENT_DIR` before deciding whether it moved the+ /// agent dir, so `..` or a relative spelling of the default still counts+ /// as the default location and keeps XDG sessions.+ #[test]+ fn omp_xdg_sessions_compare_the_resolved_agent_dir() {+ let exists = |path: &Path| path == Path::new("/xdg/omp");+ let sessions = |pairs: &[(&'static str, &'static str)], home: &Path| {+ omp_sessions_dir(home, None, env_of(pairs), true, exists).unwrap()+ };+ let home = Path::new("/home/me");+ assert_eq!(+ sessions(+ &[+ ("XDG_DATA_HOME", "/xdg"),+ ("PI_CODING_AGENT_DIR", "/home/me/.omp/../.omp/agent")+ ],+ home+ ),+ PathBuf::from("/xdg/omp/sessions")+ );+ let cwd = std::env::current_dir().unwrap();+ assert_eq!(+ sessions(+ &[+ ("XDG_DATA_HOME", "/xdg"),+ ("PI_CODING_AGENT_DIR", ".omp/agent")+ ],+ &cwd+ ),+ PathBuf::from("/xdg/omp/sessions"),+ "a relative override resolves against the working directory"+ );+ }++ /// Node's `path.win32.join` keeps a drive or UNC prefix of `PI_CONFIG_DIR`+ /// as plain segments under the home.+ #[cfg(windows)]+ #[test]+ fn omp_config_root_keeps_windows_prefixes_like_node() {+ let home = Path::new(r"C:\Users\me");+ for (value, expected) in [+ (r"\\server\share\omp", r"C:\Users\me\server\share\omp"),+ (r"D:\cfg", r"C:\Users\me\D:\cfg"),+ ] {+ let env = |name: &str| (name == "PI_CONFIG_DIR").then(|| OsString::from(value));+ assert_eq!(+ omp_config_root(home, env),+ PathBuf::from(expected),+ "{value}"+ );+ }+ }++ /// On Linux and macOS, OMP moves sessions (only sessions) under+ /// `$XDG_DATA_HOME/omp` once that directory exists, unless+ /// `PI_CODING_AGENT_DIR` moved the agent dir away from its default.+ #[test]+ fn omp_sessions_dir_follows_xdg_data_home() {+ let home = Path::new("/home/me");+ let existing = ["/xdg/omp", "/xdg2/omp/profiles/work", "/xdg3/omp"];+ let exists = |path: &Path| existing.iter().any(|dir| path == Path::new(dir));+ let sessions =+ |explicit: Option<&str>, pairs: &[(&'static str, &'static str)], xdg_platform: bool| {+ omp_sessions_dir(home, explicit, env_of(pairs), xdg_platform, exists).unwrap()+ };+ let xdg = [("XDG_DATA_HOME", "/xdg")];+ assert_eq!(+ sessions(None, &xdg, true),+ PathBuf::from("/xdg/omp/sessions")+ );+ assert_eq!(+ sessions(None, &xdg, false),+ home.join(".omp/agent/sessions"),+ "Windows keeps the agent dir"+ );+ assert_eq!(+ sessions(None, &[("XDG_DATA_HOME", "/missing")], true),+ home.join(".omp/agent/sessions")+ );+ assert_eq!(+ sessions(None, &[], true),+ home.join(".omp/agent/sessions"),+ "no ~/.local/share fallback"+ );+ assert_eq!(+ sessions(Some("work"), &xdg, true),+ home.join(".omp/profiles/work/agent/sessions"),+ "a profile keys on its own XDG dir, not the app root"+ );+ assert_eq!(+ sessions(Some("work"), &[("XDG_DATA_HOME", "/xdg2")], true),+ PathBuf::from("/xdg2/omp/profiles/work/sessions")+ );+ assert_eq!(+ sessions(+ None,+ &[+ ("XDG_DATA_HOME", "/xdg"),+ ("PI_CODING_AGENT_DIR", "/custom")+ ],+ true+ ),+ PathBuf::from("/custom/sessions"),+ "a relocated agent dir keeps its sessions"+ );+ assert_eq!(+ sessions(+ None,+ &[+ ("XDG_DATA_HOME", "/xdg"),+ ("PI_CODING_AGENT_DIR", "/home/me/.omp/agent/")+ ],+ true+ ),+ PathBuf::from("/xdg/omp/sessions"),+ "an override naming the default location is not a relocation"+ );+ assert_eq!(+ sessions(+ None,+ &[("XDG_DATA_HOME", "/xdg3"), ("PI_CONFIG_DIR", ".cfg")],+ true+ ),+ PathBuf::from("/xdg3/omp/sessions"),+ "PI_CONFIG_DIR does not rename the XDG app dir"+ );+ let probed = std::cell::Cell::new(false);+ let _ = omp_sessions_dir(+ home,+ None,+ env_of(&[("XDG_DATA_HOME", " ")]),+ true,+ |_: &Path| {+ probed.set(true);+ true+ },+ );+ assert!(!probed.get(), "a blank XDG_DATA_HOME is unset");+ }++ /// The same rule through the launch plan, against the real filesystem.+ #[cfg(any(target_os = "linux", target_os = "macos"))]+ #[test]+ fn omp_session_import_reads_an_existing_xdg_data_dir() {+ let home = tempfile::tempdir().unwrap();+ let xdg = tempfile::tempdir().unwrap();+ let mut env = vec![(+ "XDG_DATA_HOME".to_string(),+ xdg.path().to_string_lossy().into_owned(),+ )];+ // Blank masks whatever the developer's shell exports.+ for name in [+ "PI_CODING_AGENT_SESSION_DIR",+ "PI_CODING_AGENT_DIR",+ "PI_CONFIG_DIR",+ "OMP_PROFILE",+ ] {+ env.push((name.to_string(), String::new()));+ }+ let plan = || {+ build_launch_plan_with_env(+ ManagedHarness::Omp,+ None,+ Vec::new(),+ None,+ &env,+ Some(LaunchRoots {+ home: home.path(),+ cwd: home.path(),+ }),+ )+ .unwrap()+ .session_dir+ };+ assert_eq!(plan(), None, "no XDG omp dir yet: the default store");+ std::fs::create_dir(xdg.path().join("omp")).unwrap();+ assert_eq!(plan(), Some(xdg.path().join("omp").join("sessions")));+ }++ /// Blank relocation values are unset, the same rule the hook and MCP+ /// installers apply; otherwise import read `<cwd>/ /...` while auto-wire+ /// installed into the default home.+ #[test]+ fn native_store_environment_overrides_treat_blank_as_unset() {+ for blank in ["", " ", "\t"] {+ for harness in [+ ManagedHarness::Claude,+ ManagedHarness::Codex,+ ManagedHarness::OpenCode,+ ManagedHarness::OpenCode2,+ ManagedHarness::Pi,+ ManagedHarness::Omp,+ ManagedHarness::Kimi,+ ManagedHarness::Kiro,+ ManagedHarness::KiroV3,+ ManagedHarness::Grok,+ ] {+ assert_eq!(+ environment_session_dir_with(+ harness,+ Some(Path::new("/home/me")),+ None,+ |_| Some(OsString::from(blank))+ ),+ None,+ "{harness:?} with {blank:?}"+ );+ }+ }+ assert_eq!(+ environment_session_dir_with(+ ManagedHarness::Pi,+ None,+ None,+ env_of(&[+ ("PI_CODING_AGENT_SESSION_DIR", " "),+ ("PI_CODING_AGENT_DIR", "/stores/pi")+ ])+ ),+ Some(PathBuf::from("/stores/pi/sessions"))+ );+ }+#[test]fn utility_subcommands_are_passed_through_without_resume_flags() {let plan = build_launch_plan(@@ -1626,7 +2834,7 @@ mod tests {fn grok_home_environment_override_points_at_sessions_root() {let get = |name: &str| (name == "GROK_HOME").then(|| OsString::from("/stores/grok"));assert_eq!(- environment_session_dir_with(ManagedHarness::Grok, get).as_deref(),+ environment_session_dir_with(ManagedHarness::Grok, None, None, get).as_deref(),Some(std::path::Path::new("/stores/grok/sessions")));}@@ -1636,7 +2844,7 @@ mod tests {let get =|name: &str| (name == "KIMI_CODE_HOME").then(|| OsString::from("/stores/kimi-code"));assert_eq!(- environment_session_dir_with(ManagedHarness::Kimi, get).as_deref(),+ environment_session_dir_with(ManagedHarness::Kimi, None, None, get).as_deref(),Some(std::path::Path::new("/stores/kimi-code/sessions")));}@@ -1849,12 +3057,12 @@ mod tests {fn kiro_home_override_points_at_the_cli_session_store() {let get = |name: &str| (name == "KIRO_HOME").then(|| OsString::from("/stores/kiro"));assert_eq!(- environment_session_dir_with(ManagedHarness::Kiro, get).as_deref(),+ environment_session_dir_with(ManagedHarness::Kiro, None, None, get).as_deref(),Some(std::path::Path::new("/stores/kiro/sessions/cli")));let get = |name: &str| (name == "KIRO_HOME").then(|| OsString::from("/stores/kiro"));assert_eq!(- environment_session_dir_with(ManagedHarness::KiroV3, get).as_deref(),+ environment_session_dir_with(ManagedHarness::KiroV3, None, None, get).as_deref(),Some(std::path::Path::new("/stores/kiro/sessions")));}diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rsindex 90a6e154..ae4895a1 100644--- a/crates/ai-memory-workstream/src/lib.rs+++ b/crates/ai-memory-workstream/src/lib.rs@@ -5,14 +5,17 @@ mod repository;mod transcript;pub use harness::{- LaunchMode, LaunchPlan, ManagedHarness, allows_native_session_adoption, apply_yolo,- build_launch_plan, build_launch_plan_with_env, has_native_session_selector,+ LaunchMode, LaunchPlan, LaunchRoots, ManagedHarness, allows_native_session_adoption,+ apply_yolo, build_launch_plan, build_launch_plan_with_env, clean_path, crush_data_dir,+ crush_global_config_path, env_dir_override, has_native_session_selector,kiro_explicit_session_id, kiro_selects_non_default_engine, kiro_selects_v2_engine,- kiro_selects_v3_engine,+ kiro_selects_v3_engine, omp_agent_dir, omp_profile_flag, omp_profile_flag_env,+ store_override_vars,};pub use repository::{RepositoryIdentity, inspect_repository};pub use transcript::{- ExportedTranscript, NativeSessionCandidate, discover_native_session, export_transcript,- kiro_harness_from_source_cursor, kiro_v3_resume_uses_default_store, list_native_sessions,- native_session_exists, wait_for_transcript_flush,+ AmbiguousNativeSession, ExportedTranscript, NativeSessionCandidate, discover_native_session,+ export_transcript, kiro_harness_from_source_cursor, kiro_v3_resume_uses_default_store,+ list_native_sessions, native_session_exists, native_session_in_checkout,+ wait_for_transcript_flush,};diff --git a/crates/ai-memory-workstream/src/repository.rs b/crates/ai-memory-workstream/src/repository.rsindex c1108238..11f18838 100644--- a/crates/ai-memory-workstream/src/repository.rs+++ b/crates/ai-memory-workstream/src/repository.rs@@ -78,6 +78,13 @@ fn checkpoint(cwd: &Path) -> WorkstreamCheckpoint {}}+/// The git worktree root above `cwd`, or `None` outside a worktree.+pub(crate) fn worktree_root(cwd: &Path) -> Option<PathBuf> {+ git(cwd, &["rev-parse", "--show-toplevel"])+ .filter(|root| !root.is_empty())+ .map(PathBuf::from)+}+fn git(cwd: &Path, args: &[&str]) -> Option<String> {let output = git_bytes(cwd, args)?;String::from_utf8(output)diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rsindex a77cf886..89562767 100644--- a/crates/ai-memory-workstream/src/transcript.rs+++ b/crates/ai-memory-workstream/src/transcript.rs@@ -16,7 +16,7 @@ use serde_json::{Value, json};use sha2::{Digest as _, Sha256};use uuid::Uuid;-use crate::ManagedHarness;+use crate::{ManagedHarness, clean_path};const MAX_SCAN_FILES: usize = 50_000;const MAX_EVENT_BYTES: usize = 128 * 1024;@@ -120,7 +120,7 @@ pub async fn export_transcript(return export_opencode2(home, session_dir, native_session_id, source_cursor);}if harness == ManagedHarness::Crush {- return export_crush(cwd, session_dir, native_session_id, source_cursor);+ return export_crush(home, cwd, session_dir, native_session_id, source_cursor);}if harness == ManagedHarness::Antigravity {// The conversation store keeps every step as an undocumented protobuf@@ -138,14 +138,48 @@ pub async fn export_transcript(export_jsonl(harness, &path, native_session_id, source_cursor)}+/// New sessions appeared in a store that records no launch identity and none+/// can be tied to this run, so a concurrent launch on the same store cannot+/// be told apart and none is claimed.+#[derive(Debug)]+pub struct AmbiguousNativeSession {+ harness: ManagedHarness,+ sessions: usize,+ /// For a store outside the project, how many of them edited a file in it.+ placed: Option<usize>,+}++impl std::fmt::Display for AmbiguousNativeSession {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let (sessions, harness) = (self.sessions, self.harness.as_str());+ match self.placed {+ None => write!(+ formatter,+ "{sessions} new {harness} sessions were created during this run and none records which launch made it"+ ),+ Some(placed) => write!(+ formatter,+ "{sessions} new {harness} session(s) were created during this run in a data directory outside this project, and {placed} of them edited a file here"+ ),+ }+ }+}++impl std::error::Error for AmbiguousNativeSession {}+/// Discover a session created after `started_at` when the harness could not be-/// assigned an id before launch and SessionStart did not link one.+/// assigned an id before launch and SessionStart did not link one. `fresh` is+/// whether the launch started a new native session rather than continuing the+/// newest one. Crush, which has no hooks to link its session, claims only the+/// one session the run created (or, continuing, the one it touched) and fails+/// with [`AmbiguousNativeSession`] when another launch did the same.pub async fn discover_native_session(harness: ManagedHarness,home: &Path,cwd: &Path,session_dir: Option<&Path>,started_at: SystemTime,+ fresh: bool,) -> Result<Option<String>> {if harness == ManagedHarness::OpenCode {return discover_opencode(home, session_dir, cwd, started_at);@@ -154,7 +188,7 @@ pub async fn discover_native_session(return discover_opencode2(home, session_dir, cwd, started_at);}if harness == ManagedHarness::Crush {- return discover_crush(cwd, session_dir, started_at);+ return discover_crush(home, cwd, session_dir, started_at, fresh);}let mut candidates = collect_session_files(harness, home, session_dir)?;candidates.sort_by(|left, right| {@@ -195,7 +229,7 @@ pub async fn list_native_sessions(return list_opencode2_sessions(home, session_dir, cwd, limit);}if harness == ManagedHarness::Crush {- return list_crush_sessions(cwd, session_dir, limit);+ return list_crush_sessions(home, cwd, session_dir, limit);}let mut files = collect_session_files(harness, home, session_dir)?;@@ -232,6 +266,36 @@ pub async fn list_native_sessions(Ok(sessions)}+/// Whether the native store holds `native_session_id` for this checkout.+/// [`native_session_exists`] answers for the store; OpenCode keeps every+/// checkout's sessions in one database, so there the recorded directory must+/// match `cwd` too.+pub fn native_session_in_checkout(+ harness: ManagedHarness,+ home: &Path,+ cwd: &Path,+ session_dir: Option<&Path>,+ native_session_id: &str,+) -> Result<bool> {+ let table = match harness {+ ManagedHarness::OpenCode => "session",+ ManagedHarness::OpenCode2 => "session_v2",+ _ => return native_session_exists(harness, home, cwd, session_dir, native_session_id),+ };+ let db = opencode_db(home, session_dir);+ if !db.is_file() {+ return Ok(false);+ }+ let connection = Connection::open_with_flags(+ &db,+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,+ )?;+ let mut statement = connection.prepare(&format!(+ "SELECT 1 FROM {table} WHERE id = ?1 AND directory = ?2"+ ))?;+ Ok(statement.exists(params![native_session_id, cwd.to_string_lossy()])?)+}+/// Check whether one exact native session still exists in the harness's/// read-only transcript store. `Ok(false)` means the resume target is/// definitely absent; store access or schema failures remain errors so callers@@ -250,7 +314,7 @@ pub fn native_session_exists(return Ok(opencode2_updated(home, session_dir, native_session_id)?.is_some());}if harness == ManagedHarness::Crush {- return Ok(crush_updated(cwd, session_dir, native_session_id)?.is_some());+ return Ok(crush_updated(home, cwd, session_dir, native_session_id)?.is_some());}Ok(locate_session_file(harness, home, cwd, session_dir, native_session_id)?.is_some())}@@ -300,7 +364,7 @@ pub async fn wait_for_transcript_flush(} else if harness == ManagedHarness::OpenCode2 {opencode2_updated(home, session_dir, native_session_id)?.map(|value| value.to_string())} else if harness == ManagedHarness::Crush {- crush_updated(cwd, session_dir, native_session_id)?.map(|value| value.to_string())+ crush_updated(home, cwd, session_dir, native_session_id)?.map(|value| value.to_string())} else {locate_session_file(harness, home, cwd, session_dir, native_session_id)?.and_then(|path| {@@ -1925,12 +1989,13 @@ fn export_opencode(}fn export_crush(+ home: &Path,cwd: &Path,session_dir: Option<&Path>,session: &str,source_cursor: Option<&str>,) -> Result<ExportedTranscript> {- let db = crush_db(cwd, session_dir);+ let db = crush_db(home, cwd, session_dir);let connection = Connection::open_with_flags(&db,OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,@@ -2829,22 +2894,115 @@ fn list_opencode_sessions(}fn discover_crush(+ home: &Path,cwd: &Path,session_dir: Option<&Path>,started_at: SystemTime,+ fresh: bool,) -> Result<Option<String>> {- Ok(list_crush_sessions(cwd, session_dir, 1)?- .into_iter()- .find(|candidate| candidate.updated_at + Duration::from_secs(2) >= started_at)- .map(|candidate| candidate.native_session_id))+ let db = crush_db(home, cwd, session_dir);+ if !db.is_file() {+ return Ok(None);+ }+ let connection = Connection::open_with_flags(+ &db,+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,+ )?;+ // Title and sub-agent sessions name their session as parent. A fresh+ // launch looks at what it created; `--continue` at what it resumed.+ let order = if fresh { "created_at" } else { "updated_at" };+ let mut statement = connection.prepare(&format!(+ "SELECT id, {order} FROM sessions WHERE parent_session_id IS NULL \+ ORDER BY {order} DESC LIMIT 64"+ ))?;+ let rows = statement.query_map([], |row| {+ Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))+ })?;+ let mut during_run = Vec::new();+ for row in rows {+ let (id, at) = row?;+ let Some(at) = native_timestamp(at) else {+ continue;+ };+ if at + Duration::from_secs(2) < started_at {+ break;+ }+ if valid_native_session_id(&id) {+ during_run.push(id);+ }+ }+ // A data directory outside the project (a global `data_directory`) holds+ // other projects' sessions too, and Crush keeps no directory per session.+ // What it does keep is the absolute path of each file a session edited;+ // only a session that edited a file here is known to be this project's.+ // (`read_files` paths are relative to each session's own directory, so+ // they place nothing.)+ let project = crate::repository::worktree_root(cwd).unwrap_or_else(|| cwd.to_path_buf());+ // Where the store really is: a `.crush` symlinked to a shared directory+ // is shared.+ let resolved = |path: &Path| fs::canonicalize(path).unwrap_or_else(|_| clean_path(path));+ let shared = db+ .parent()+ .is_some_and(|dir| !resolved(&cwd.join(dir)).starts_with(resolved(&project)));+ let placed = if shared {+ let mut placed = Vec::new();+ for id in &during_run {+ let edited = crush_edited_paths(&connection, id)?;+ if edited.iter().any(|path| path_within(path, &project)) {+ placed.push(id.clone());+ }+ }+ Some(placed)+ } else {+ None+ };+ let sessions = during_run.len();+ if sessions == 0 {+ return Ok(None);+ }+ let placed_count = placed.as_ref().map(Vec::len);+ let mut claimed = placed.unwrap_or(during_run);+ if claimed.len() == 1 {+ return Ok(claimed.pop());+ }+ Err(AmbiguousNativeSession {+ harness: ManagedHarness::Crush,+ sessions,+ placed: placed_count,+ }+ .into())+}++/// The files a Crush session edited, as the absolute paths its edit tools+/// record in `files`, including edits its sub-agent sessions made.+fn crush_edited_paths(connection: &Connection, session: &str) -> Result<Vec<PathBuf>> {+ let mut statement = connection.prepare(+ "WITH RECURSIVE tree(id) AS ( \+ SELECT ?1 UNION SELECT sessions.id FROM sessions \+ JOIN tree ON sessions.parent_session_id = tree.id) \+ SELECT path FROM files WHERE session_id IN (SELECT id FROM tree)",+ )?;+ let rows = statement.query_map([session], |row| row.get::<_, String>(0))?;+ rows.map(|row| Ok(PathBuf::from(row?))).collect()+}++/// Whether absolute `path` lies under `root`, compared both as written and+/// with symlinks resolved (Crush records the path it was given, which may go+/// through a symlinked `/var` or checkout). A relative path cannot be placed.+fn path_within(path: &Path, root: &Path) -> bool {+ let resolved = |path: &Path| fs::canonicalize(path).unwrap_or_else(|_| clean_path(path));+ path.is_absolute()+ && (clean_path(path).starts_with(clean_path(root))+ || resolved(path).starts_with(resolved(root)))}fn list_crush_sessions(+ home: &Path,cwd: &Path,session_dir: Option<&Path>,limit: usize,) -> Result<Vec<NativeSessionCandidate>> {- let db = crush_db(cwd, session_dir);+ let db = crush_db(home, cwd, session_dir);if !db.is_file() {return Ok(Vec::new());}@@ -2874,8 +3032,13 @@ fn list_crush_sessions(Ok(sessions)}-fn crush_updated(cwd: &Path, session_dir: Option<&Path>, session: &str) -> Result<Option<i64>> {- let db = crush_db(cwd, session_dir);+fn crush_updated(+ home: &Path,+ cwd: &Path,+ session_dir: Option<&Path>,+ session: &str,+) -> Result<Option<i64>> {+ let db = crush_db(home, cwd, session_dir);if !db.is_file() {return Ok(None);}@@ -2894,8 +3057,11 @@ fn crush_updated(cwd: &Path, session_dir: Option<&Path>, session: &str) -> Resul}}-fn crush_db(cwd: &Path, session_dir: Option<&Path>) -> PathBuf {- session_dir.unwrap_or(&cwd.join(".crush")).join("crush.db")+fn crush_db(home: &Path, cwd: &Path, session_dir: Option<&Path>) -> PathBuf {+ session_dir+ .map(Path::to_path_buf)+ .unwrap_or_else(|| crate::harness::crush_process_data_dir(cwd, home))+ .join("crush.db")}fn native_timestamp(value: i64) -> Option<SystemTime> {@@ -3745,6 +3911,271 @@ mod tests {);}+ /// Crush has no hooks to link its session, and a store can be shared by+ /// launches in several subdirectories. A fresh launch claims the one+ /// top-level session created while it ran (title and sub-agent sessions+ /// name a parent) and claims none when another launch created one too;+ /// `--continue` claims the one session it touched, on the same terms.+ #[tokio::test]+ async fn crush_discovery_claims_only_the_session_the_run_created() {+ let temp = tempfile::tempdir().unwrap();+ let cwd = temp.path().join("repo");+ fs::create_dir_all(cwd.join(".crush")).unwrap();+ let connection = Connection::open(cwd.join(".crush").join("crush.db")).unwrap();+ connection+ .execute_batch(+ "CREATE TABLE sessions(id TEXT PRIMARY KEY, parent_session_id TEXT, \+ updated_at INTEGER NOT NULL, created_at INTEGER NOT NULL);",+ )+ .unwrap();+ let started = 1_900_000_000_i64;+ let started_at = UNIX_EPOCH + Duration::from_secs(started as u64);+ let insert = |id: &str, parent: Option<&str>, created: i64, updated: i64| {+ connection+ .execute(+ "INSERT INTO sessions VALUES (?1, ?2, ?3, ?4)",+ params![id, parent, started + updated, started + created],+ )+ .unwrap();+ };+ let discover = |fresh: bool| discover_crush(temp.path(), &cwd, None, started_at, fresh);++ let ambiguous = |fresh: bool| {+ discover(fresh)+ .unwrap_err()+ .downcast::<AmbiguousNativeSession>()+ .unwrap()+ .sessions+ };+ insert("idle", None, -2_000, -1_000);+ insert("continued", None, -1_000, 30);+ insert("continued-task", Some("continued"), 3, 40);+ assert_eq!(discover(true).unwrap(), None);+ assert_eq!(discover(false).unwrap().as_deref(), Some("continued"));++ insert("mine", None, 5, 20);+ insert("mine-title", Some("mine"), 6, 25);+ assert_eq!(discover(true).unwrap().as_deref(), Some("mine"));+ assert_eq!(ambiguous(false), 2);++ insert("theirs", None, 8, 10);+ assert_eq!(ambiguous(true), 2);+ }++ /// A data directory outside the project can hold another project's+ /// sessions, and Crush records no directory per session. Only a session+ /// that edited a file here (an absolute path in `files`) is claimed, and+ /// only when it is the one; a read (`read_files` keeps paths relative to+ /// each session's own directory) or a file elsewhere places nothing. A+ /// store inside the project keeps the plain one-new-session rule.+ #[tokio::test]+ async fn crush_discovery_in_a_shared_store_claims_only_an_edit_here() {+ let temp = tempfile::tempdir().unwrap();+ let root = fs::canonicalize(temp.path()).unwrap();+ let repo = root.join("repo");+ fs::create_dir_all(repo.join("src")).unwrap();+ let status = std::process::Command::new("git")+ .args(["init", "-q"])+ .arg(&repo)+ .status()+ .unwrap();+ assert!(status.success());+ let started = 1_900_000_000_i64;+ let started_at = UNIX_EPOCH + Duration::from_secs(started as u64);+ let store = |name: &str, sessions: &[(&str, &[&str])]| {+ let dir = if name == ".crush" {+ repo.join(name)+ } else {+ root.join(name)+ };+ fs::create_dir_all(&dir).unwrap();+ let connection = Connection::open(dir.join("crush.db")).unwrap();+ connection+ .execute_batch(+ "CREATE TABLE sessions(id TEXT PRIMARY KEY, parent_session_id TEXT, \+ updated_at INTEGER NOT NULL, created_at INTEGER NOT NULL); \+ CREATE TABLE files(id TEXT PRIMARY KEY, session_id TEXT NOT NULL, \+ path TEXT NOT NULL); \+ CREATE TABLE read_files(session_id TEXT NOT NULL, path TEXT NOT NULL, \+ read_at INTEGER NOT NULL);",+ )+ .unwrap();+ for (nth, (id, paths)) in sessions.iter().enumerate() {+ let at = started + 5 + nth as i64;+ // `parent/child` is a sub-agent session of `parent`.+ let (parent, id) = match id.split_once('/') {+ Some((parent, child)) => (Some(parent), child),+ None => (None, *id),+ };+ connection+ .execute(+ "INSERT INTO sessions VALUES (?1, ?2, ?3, ?3)",+ params![id, parent, at],+ )+ .unwrap();+ for path in *paths {+ // `read:` marks a file the session only read.+ match path.strip_prefix("read:") {+ Some(read) => connection.execute(+ "INSERT INTO read_files VALUES (?1, ?2, 0)",+ params![id, read],+ ),+ None => connection.execute(+ "INSERT INTO files VALUES (?1, ?2, ?3)",+ params![format!("{id}-{path}"), id, path],+ ),+ }+ .unwrap();+ }+ }+ dir+ };+ let discover = |dir: &Path| discover_crush(&root, &repo, Some(dir), started_at, true);+ let placed = |dir: &Path| {+ discover(dir)+ .unwrap_err()+ .downcast::<AmbiguousNativeSession>()+ .unwrap()+ .placed+ };+ let here = repo.join("src").join("main.rs").display().to_string();+ let elsewhere = "/elsewhere/project-b/main.go";++ let dir = store("shared-foreign", &[("theirs", &[elsewhere])]);+ assert_eq!(placed(&dir), Some(0));++ let dir = store(+ "shared-mine",+ &[+ ("theirs", &[elsewhere]),+ ("chat", &[]),+ ("mine", &[elsewhere, &here]),+ ],+ );+ assert_eq!(discover(&dir).unwrap().as_deref(), Some("mine"));++ // Reads place nothing: Crush keeps them relative to each session's own+ // directory (absolute only when that fails), and neither does an edit+ // whose path cannot be placed.+ let read_here_absolute = format!("read:{here}");+ let dir = store(+ "shared-read",+ &[+ ("theirs", &["read:src/main.go", &read_here_absolute]),+ ("relative", &["src/main.go"]),+ ("chat", &[]),+ ],+ );+ assert_eq!(placed(&dir), Some(0));++ let dir = store("shared-both", &[("one", &[&here]), ("two", &[&here])]);+ assert_eq!(placed(&dir), Some(2));++ // An edit a sub-agent made places the session that ran it.+ let dir = store(+ "shared-task",+ &[+ ("theirs", &[elsewhere]),+ ("mine", &[]),+ ("mine/task", &[&here]),+ ],+ );+ assert_eq!(discover(&dir).unwrap().as_deref(), Some("mine"));++ let dir = store(".crush", &[("dotfiles", &[elsewhere])]);+ assert_eq!(discover(&dir).unwrap().as_deref(), Some("dotfiles"));++ // A project `.crush` that links to a shared store is shared.+ #[cfg(unix)]+ {+ let dir = store("shared-linked", &[("theirs", &[elsewhere])]);+ let linked = repo.join("linked-crush");+ std::os::unix::fs::symlink(&dir, &linked).unwrap();+ assert_eq!(placed(&linked), Some(0));+ }+ }++ /// Session discovery with no store named by a launch plan finds Crush's+ /// database where Crush keeps it: the closest `.crush` up to the worktree+ /// root, not only `<cwd>/.crush`.+ #[tokio::test]+ async fn crush_discovery_finds_the_store_above_the_cwd() {+ let temp = tempfile::tempdir().unwrap();+ let root = fs::canonicalize(temp.path()).unwrap();+ let repo = root.join("repo");+ let cwd = repo.join("sub");+ fs::create_dir_all(repo.join(".crush")).unwrap();+ fs::create_dir_all(&cwd).unwrap();+ let status = std::process::Command::new("git")+ .args(["init", "-q"])+ .arg(&repo)+ .status()+ .unwrap();+ assert!(status.success());+ let connection = Connection::open(repo.join(".crush").join("crush.db")).unwrap();+ connection+ .execute_batch(+ "CREATE TABLE sessions(id TEXT PRIMARY KEY, updated_at INTEGER NOT NULL);\n\+ INSERT INTO sessions VALUES ('above', 1800000000);",+ )+ .unwrap();++ let candidates = list_native_sessions(ManagedHarness::Crush, &root, &cwd, None, 8)+ .await+ .unwrap();+ assert_eq!(+ candidates+ .iter()+ .map(|candidate| candidate.native_session_id.as_str())+ .collect::<Vec<_>>(),+ ["above"]+ );+ }++ /// OpenCode keeps every checkout's sessions in one database, so a session+ /// is this checkout's only when its recorded directory matches; other+ /// harnesses answer as `native_session_exists` does.+ #[test]+ fn native_session_in_checkout_checks_the_opencode_directory() {+ let temp = tempfile::tempdir().unwrap();+ let cwd = temp.path().join("repo");+ let other = temp.path().join("other");+ let store = temp.path().join("opencode");+ fs::create_dir_all(&store).unwrap();+ let connection = Connection::open(store.join("opencode.db")).unwrap();+ connection+ .execute_batch(+ "CREATE TABLE session(id TEXT PRIMARY KEY, directory TEXT NOT NULL, \+ time_updated INTEGER NOT NULL); \+ CREATE TABLE session_v2(id TEXT PRIMARY KEY, directory TEXT NOT NULL, \+ time_updated INTEGER NOT NULL);",+ )+ .unwrap();+ for table in ["session", "session_v2"] {+ for (id, dir) in [("here", &cwd), ("elsewhere", &other)] {+ connection+ .execute(+ &format!("INSERT INTO {table} VALUES (?1, ?2, 1)"),+ params![id, dir.to_string_lossy()],+ )+ .unwrap();+ }+ }+ for harness in [ManagedHarness::OpenCode, ManagedHarness::OpenCode2] {+ let in_checkout = |id: &str| {+ native_session_in_checkout(harness, temp.path(), &cwd, Some(&store), id).unwrap()+ };+ assert!(in_checkout("here"), "{harness:?}");+ assert!(!in_checkout("elsewhere"), "{harness:?}");+ assert!(!in_checkout("missing"), "{harness:?}");+ assert!(+ native_session_exists(harness, temp.path(), &cwd, Some(&store), "elsewhere")+ .unwrap(),+ "{harness:?}: the store holds it"+ );+ }+ }+#[tokio::test]async fn crush_candidate_discovery_and_incremental_export_are_read_only() {let temp = tempfile::tempdir().unwrap();@@ -3797,7 +4228,7 @@ mod tests {.unwrap());- let first = export_crush(&cwd, None, "newer", None).unwrap();+ let first = export_crush(temp.path(), &cwd, None, "newer", None).unwrap();assert_eq!(first.events.len(), 1);assert_eq!(first.events[0].content, "visible");assert!(first.losses.iter().any(|loss| loss.contains("reasoning")));@@ -3808,7 +4239,14 @@ mod tests {[json!([{"type":"tool_result","data":{"name":"bash","content":"ok","is_error":false}}]).to_string()],).unwrap();- let second = export_crush(&cwd, None, "newer", first.source_cursor.as_deref()).unwrap();+ let second = export_crush(+ temp.path(),+ &cwd,+ None,+ "newer",+ first.source_cursor.as_deref(),+ )+ .unwrap();assert_eq!(second.events.len(), 1);assert_eq!(second.events[0].kind, WorkstreamEventKind::ToolResult);assert_eq!(second.events[0].content, "ok");diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 5ea92480..f3c47dbd 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -637,7 +637,8 @@ backfill_on_start = true # on first SessionStart in a brand-new (empty# backfill` runs it by hand.run_autowire = true # `ai-memory run <harness>` auto-installs that harness's# hooks + MCP on first launch if missing (idempotent,- # one-time per harness+version). Also `--no-autowire`.+ # one-time per harness+version+install location).+ # Also `--no-autowire`.[decay] # M8 retention paramslambda = 0.02 # ↓ to forget less aggressively (fallback λ)diff --git a/docs/competitive-parity.md b/docs/competitive-parity.mdindex 8d57e3e4..ea84e089 100644--- a/docs/competitive-parity.md+++ b/docs/competitive-parity.md@@ -140,7 +140,7 @@ implemented without a separate decision.** Ordered by leverage.wiki (push/pull the source-of-truth dir, rebuild the index) — a cleaner,file-first P2P story than an opaque KV LWW.5. **Close the setup-friction gap vs the built-in.** Our one honest structural- weakness for the solo user. Much is already done (`run --autowire`, `doctor`,+ weakness for the solo user. Much is already done (`run` auto-wire, `doctor`,`backfill`, `install-self-routing`); surface it as *the* onboarding path in theREADME hero, add a one-line `ai-memory run claude` quickstart, and ship a"coming from Claude built-in?" importer (the `~/.claude/.../memory/` format isdiff --git a/docs/cookbook.md b/docs/cookbook.mdindex 1058d24d..9f4e3d3d 100644--- a/docs/cookbook.md+++ b/docs/cookbook.md@@ -128,6 +128,30 @@ compacted or merged stays in git and the supersession chain, recoverable withadd the export endpoint" (`memory_message_send`), and over there "check myinbox" (`memory_message_pop`). See [`agent-messaging.md`](agent-messaging.md).+## Recipe: several accounts or an external launcher++Give each account or provider its own config home and pass it with `--env`, so+the harness, its hooks and MCP, and transcript import all use that one home:++```bash+ai-memory run --env CLAUDE_CONFIG_DIR="$HOME/.claude-work" claude+ai-memory run --env CODEX_HOME="$HOME/.codex-work" codex # the dir must exist+```++- `--env` and `--env-file` belong to `ai-memory run`, so they go before the+ harness name.+- A launcher or orchestrator that starts harnesses with its own environment+ (provider keys, an account's config dir) can write it to a file and pass+ `--env-file <path>`, one `KEY=VALUE` per line. Values are taken literally, so+ use absolute paths in the file.+- Auto-wire runs once per config home, so the second account gets its hooks ++ MCP on its own first launch. To wire one by hand, export the variable for the+ installers: `CLAUDE_CONFIG_DIR="$HOME/.claude-work" ai-memory install-hooks+ --agent claude-code --apply`, then the same for `install-mcp --client+ claude-code --apply`.++See [`managed-workstreams.md`](managed-workstreams.md).+## Recipe: run the server on a MacUse the menu bar app when you want one `.app` that starts the server and@@ -154,9 +178,12 @@ Memory stays in `~/Library/Application Support/ai-memory`. Replacing the## From the terminal (CLI)-Most people never need these — the agent does it — but they exist:+Your agent runs most of these for you; `run` and `continue` are how you start it:```bash+ai-memory run <harness> # launch a harness, hooks + MCP auto-wired+ai-memory continue # resume the newest managed checkout+ai-memory workstreams # list this checkout's managed workstreamsai-memory status # counts, paths, healthai-memory doctor # is every harness that ran here captured?ai-memory backfill # import prior local history into an empty store@@ -169,10 +196,13 @@ ai-memory serve # run the server## When it isn't doing what you expect-- **Nothing is being remembered**: hooks may not be installed. Easiest fix —- start the harness with `ai-memory run <harness>`, which auto-installs its- hooks + MCP on first launch; or wire it by hand with `ai-memory install-hooks- --agent <your-agent> --apply`. Then check `ai-memory status` / `ai-memory doctor`.+- **Nothing is being remembered**: hooks may not be installed. `ai-memory run+ <harness>` installs its hooks + MCP on the first launch per harness,+ ai-memory version and config home, and again after `ai-memory uninstall`. If that harness+ already launched through `run` and its hooks went missing another way+ (removed by hand, a failed first wire), install them by hand: `ai-memory+ install-hooks --agent <your-agent> --apply` and `ai-memory install-mcp+ --client <client> --apply`. Then check `ai-memory status` / `ai-memory doctor`.- **Only *some* agents are being remembered**: run `ai-memory doctor`. It listsevery harness that has local sessions in this project and whether the servercaptured them — so a harness you rotated in without installing its hook (adiff --git a/docs/install.md b/docs/install.mdindex 24ed2c76..4fa536eb 100644--- a/docs/install.md+++ b/docs/install.md@@ -799,7 +799,7 @@ including Pi and Zero, have lifecycle capture paths through `install-hooks`.### OpenAI Codex```bash-# MCP snippet (merge into ~/.codex/config.toml):+# MCP snippet (merge into $CODEX_HOME/config.toml, default ~/.codex/config.toml):docker run --rm akitaonrails/ai-memory:latest \install-mcp --client codex \--server-url "http://homelab:49374/mcp" \@@ -1313,19 +1313,27 @@ not interchangeable — only Pi's bridges MCP tools.#### OMP profiles`omp --profile <name>` relocates OMP's agent home to-`~/.omp/profiles/<name>/agent`. Point the installer at the same profile so-the extension lands where that profile loads it:+`~/.omp/profiles/<name>/agent`. Point the installers at the same profile so+the extension and the MCP entry land where that profile loads them:```bashai-memory install-hooks --agent omp --profile work --apply-# or set it once for the shell:+# or set it once for the shell, which install-mcp also reads:OMP_PROFILE=work ai-memory install-hooks --agent omp --apply+OMP_PROFILE=work ai-memory install-mcp --client omp --apply```-`--profile` takes precedence over `OMP_PROFILE`, and `uninstall --profile-<name>` removes the same file. `PI_CODING_AGENT_DIR` overrides **both** —-when it is set it names the agent directory outright, so no profile-subdirectory is derived from it.+The profile resolves the way OMP resolves it: `--profile` beats+`OMP_PROFILE`, which beats the legacy `PI_PROFILE` whenever it is set, even+to an empty value. Names are trimmed, an empty name or `default` selects the+default profile, and a name OMP refuses is refused here too. A named profile+ignores `PI_CODING_AGENT_DIR`, as OMP does; only the default profile honors+it. OMP's `PI_CONFIG_DIR` renames the `~/.omp` root (joined under your home,+as OMP joins it), and the extension and `mcp.json` follow it; an+`$XDG_DATA_HOME/omp` directory moves only OMP's sessions, never these files.+`uninstall --profile <name>` removes the same files, and also sweeps the+default profile's directory and the `~/.omp` locations earlier releases wrote+to, whatever `PI_CONFIG_DIR` says.```bashai-memory install-hooks --agent pi --apply \@@ -2050,7 +2058,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree| `setup-agent --agent --to --host-prefix` | `docker run --rm -v` | Extract bundled scripts + print config (one-shot) || `install-instructions [--target] [--print] [--no-skills]` | same host environment used for the agent prompt files | Install or update the slim CLAUDE.md / AGENTS.md routing block and, by default, the managed ai-memory Agent Skills || `install-skills [--scope] [--agent]` | same host environment used for the agent skill dirs | Install or update only the managed ai-memory Agent Skills |-| `uninstall --apply` | same host environment used for install | Remove only ai-memory-owned hooks, MCP entries, instruction blocks, managed skill files, and generated plugin files after content/marker validation. Use `--mcp-url` for custom MCP endpoints and `--mcp-name` only to narrow removal. |+| `uninstall --apply` | same host environment used for install | Remove only ai-memory-owned hooks, MCP entries, instruction blocks, managed skill files, and generated plugin files after content/marker validation. Removing hooks or MCP also deletes the `ai-memory run` auto-wire sentinels under `<data_dir>/autowire-state/`, so the next managed launch wires again. Use `--mcp-url` for custom MCP endpoints and `--mcp-name` only to narrow removal. || `llm-test --provider …` | `docker run --rm -e …` | Smoke-test an LLM provider || `completions <shell>` | `docker run --rm` or native binary | Print a bash/zsh/fish/PowerShell/elvish completion script; see [`shell-completions.md`](shell-completions.md) |diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex d56cf600..9a9e287d 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -13,7 +13,11 @@ harness it **auto-installs that harness's ai-memory hooks and MCP** if they arenot already wired, so capture and recall work without a separate `install-hooks`/ `install-mcp` step (a common footgun: `ai-memory run kimi` used to capturenothing if the Kimi hooks were never installed). Auto-wire is idempotent and-one-time per harness + binary version, preserves unrelated user config, runs+one-time per harness, binary version and install location (a second config home,+such as another `CLAUDE_CONFIG_DIR`, gets its own first launch; `ai-memory+uninstall` of hooks or MCP clears that record, so the next launch wires again),+preserves+unrelated user config, runsbefore the harness starts so it picks up the fresh hooks, and is best-effort —if an install fails it warns and still launches. Harnesses without installersupport (Crush) are skipped; Pi wires hooks but has no MCP client to write. Turn@@ -367,12 +371,12 @@ is labelled completed evidence and must never be replayed as a pending call.| OpenCode | native default creation | `--session <id>` | `~/.local/share/opencode/opencode.db` opened read-only || OpenCode 2 beta | native default creation | `--session <id>` | same `opencode.db` as v1 (the beta channel keeps v1's filename; the beta adds `session_v2`/`session_message` tables beside v1's); launched via the `opencode2` binary || Pi | generated `--session-id` | `--session <id>` | `~/.pi/agent/sessions/**/*.jsonl` |-| Crush | native default creation | `--session <id>` | `<project>/.crush/crush.db` opened read-only |+| Crush | native default creation | `--session <id>` | `<data dir>/crush.db` opened read-only: `options.data_directory` from Crush's JSON configs, else the closest `.crush` up to the git worktree root, else `<cwd>/.crush` || Kimi Code | native default creation | `--session <id>` | `$KIMI_CODE_HOME/sessions/*/*/agents/main/wire.jsonl` || Command Code | native default creation | `--session <uuid>` | `~/.commandcode/projects/*/<uuid>.jsonl` || Kiro CLI v2 | native default creation | `--resume-id <uuid>` | `$KIRO_HOME/sessions/cli/<uuid>.jsonl` (+ sibling `<uuid>.json` metadata) || Kiro CLI v3 | native default creation with `--v3` | `--v3 --resume-id <sess_uuid>` | `$KIRO_HOME/sessions/<checkout-bucket>/<sess_uuid>/messages.jsonl` (+ sibling `session.json` metadata) |-| OMP | native default creation | `--resume=<id>` | `~/.omp/agent/sessions/**/*.jsonl` |+| OMP | native default creation | `--resume=<id>` | `<agent dir>/sessions/**/*.jsonl`: `~/.omp/agent`, `~/.omp/profiles/<name>/agent` under a named profile, or `$PI_CODING_AGENT_DIR` for the default profile, with `~/.omp` renamed by `PI_CONFIG_DIR`; on Linux and macOS, `$XDG_DATA_HOME/omp/sessions` (`.../omp/profiles/<name>/sessions`) once that OMP directory exists and the agent dir is not relocated || Grok Build CLI | generated `--session-id` | `--resume <id>` | `$GROK_HOME/sessions/*/*/chat_history.jsonl` || Antigravity CLI | native default creation | `--conversation <id>` | `~/.gemini/antigravity-cli/conversations/<id>.db` metadata plus lifecycle-hook capture |@@ -393,17 +397,49 @@ An explicit native selector such as Claude's `--resume`, OpenCode's `--session`,Codex's `resume`, or Antigravity's `--conversation` / `--continue` wins.ai-memory links the selected native session and resets an unrelated adaptercursor rather than assuming it belongs to the old session.++When a fresh launch cannot name its session up front, the session a hook in+the child links under the run's `AI_MEMORY_RUN_ID` is the one imported when+the native store holds it for this checkout (a process the child starts+inherits that id too), so a concurrent launch in the same checkout cannot hand+it a different transcript. Only without such a link does ai-memory look for+the session after exit. A+hook that links the very session the run was prepared with, as when a native+picker resumes the workstream's current session without naming it, is not yet+told apart from no link, so the look after exit still decides there.+Crush has no hooks: a fresh Crush launch claims the one top-level session+created while it ran (its title and sub-agent sessions do not count), and+imports nothing, with a warning, when another launch on the same store created+one too; resume that session with `--session <id>` to link it. `--continue`+claims the one session it touched on the same terms. When the data directory+lies outside the project, as a global `data_directory` does, other projects'+sessions share it and Crush records no directory per session, so a run claims+only a session that edited a file in this project (its sub-agents' edits+count), and only when it is the one; otherwise it imports nothing, with the+same warning. The store's real location decides, so a `.crush` symlinked to a+shared directory is shared. Another project's session that edited a file here+still counts as this project's.Pi and OMP `--session-dir` values and Crush `--data-dir` values are passed-through unchanged and used as the read-only import root. Native store+through unchanged and used as the read-only import root. Without `--data-dir`,+ai-memory finds Crush's data directory as Crush does, except that it does not+run a `crushrc` to read one set only there; pass `--data-dir` in that case. Native storeenvironment overrides are also honored:`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `XDG_DATA_HOME`,`PI_CODING_AGENT_SESSION_DIR`, `PI_CODING_AGENT_DIR`, `KIMI_CODE_HOME`,-`KIRO_HOME`, and `GROK_HOME`.-Export these in the environment `ai-memory run` itself sees — not only inside a-harness wrapper script. `ai-memory run` resolves the native session directory-(and installs hooks) from its own environment; if the harness writes its-transcript under a custom `CLAUDE_CONFIG_DIR` that `ai-memory run` cannot see,-the two disagree and the native transcript import fails. When you use per-account+`KIRO_HOME`, and `GROK_HOME`, plus OMP's `PI_CONFIG_DIR` and profile (a+leading `--profile`, then `OMP_PROFILE`, then `PI_PROFILE`), which ignores+`PI_CODING_AGENT_DIR` as OMP does. A `--profile` later in the command line is+left to OMP; set+`OMP_PROFILE` (or `--env OMP_PROFILE=<name>`) when you need it there. A blank+value (empty or whitespace only) counts as unset everywhere: session import,+hooks and MCP all fall back to the default home, and `ai-memory run` removes+it from the launched harness's environment so the harness does too.+Export these in the environment `ai-memory run` itself sees, or pass them with+`--env` (below), not only inside a harness wrapper script. `ai-memory run`+resolves the native session directory, and auto-wires hooks and MCP, from that+environment; if the harness writes its transcript under a custom+`CLAUDE_CONFIG_DIR` that `ai-memory run` cannot see, the two disagree and the+native transcript import fails. When you use per-accountconfig directories, set the variable before invoking `ai-memory run` (or in thesame wrapper that also runs it), so hook installation and native-sessionresolution agree.@@ -412,12 +448,16 @@ A repeatable `ai-memory run --env KEY=VALUE <harness>` (and `--env-file<path>`, one `KEY=VALUE` per line, blank lines and `#` comments skipped) isthe first-class alternative to the `env KEY=VAL harness` wrapper-aliaspattern above: it is a wrapper-owned flag, so it must precede the harness-name, and the resolved environment reaches both the spawned harness process-*and* `ai-memory run`'s own native-session resolution — the same-`CLAUDE_CONFIG_DIR`-agreement requirement described above, satisfied without-having to export the variable into the invoking shell first. A later `--env`-overrides a same-key `--env-file` entry; neither expands nor interprets the-value.+name, and the resolved environment reaches the spawned harness process,+`ai-memory run`'s own native-session resolution, *and* first-launch auto-wire.+Hooks, MCP and transcript import then follow the same config home, which is the+`CLAUDE_CONFIG_DIR`-agreement requirement described above, without exporting the+variable into the invoking shell first. A later `--env` overrides a same-key+`--env-file` entry; neither expands nor interprets the value, so let the shell+expand `$HOME` on the command line and write absolute paths in an+`--env-file`. Manual `install-hooks` / `install-mcp` do not take `--env`; they+read their own environment.+The Pi-family adapteralso recognizes a complete `.jsonl.<nonce>.tmp` atomic-write file when a nativeprocess exits before renaming it; incomplete final JSONL records are never@@ -513,7 +553,8 @@ transparently. Kiro CLI 2.16.2 wrote v3 sessions below the defaultchecks the configured v3 root first and that default root as a compatibilityfallback. If a linked session exists only in the fallback, ai-memory removes`KIRO_HOME` for that one resume so Kiro can find the session; Kiro consequently-uses its default-home v3 settings/hooks for that process. Fresh launches and+uses its default-home v3 settings/hooks for that process, and first-launch+auto-wire wires that default home rather than `KIRO_HOME`. Fresh launches andversions that store the session below the configured root keep `KIRO_HOME`unchanged. Every candidate still needs exact id, schema, and checkout metadata.The v2 `--yolo` translation is `--trust-all-tools`; an explicit narrower@@ -562,9 +603,17 @@ Antigravity CLI v1.1.7. Antigravity is not part of the no-argumentauto-detection set; name it explicitly.Crush needs no ai-memory hook installation for managed mode. The launcher reads-its one-time context from the server, copies the existing global Crush JSON into-a private temporary directory, appends an ephemeral context path, and points the-child at that directory with `CRUSH_GLOBAL_CONFIG`. Delivery is acknowledged+its one-time context from the server, copies the global Crush JSON the launch+would read (`$CRUSH_GLOBAL_CONFIG/crush.json`, else+`$XDG_CONFIG_HOME/crush/crush.json`, else `~/.config/crush/crush.json`, with+`--env` entries first and a blank value counting as unset) into a private+temporary directory, appends an ephemeral context path, and points the child at+that directory with `CRUSH_GLOBAL_CONFIG`. When that JSON lists no+`global_context_paths`, the launcher first adds the `CRUSH.md` and `AGENTS.md`+Crush would have loaded by default, so the packet does not replace them. A+global `crushrc` next to that JSON is carried over by a generated `crushrc` in+the temporary directory that sources it from its own directory, where Crush+runs it. Delivery is acknowledgedonly after the child starts, so a spawn failure cannot lose the packet. Theoriginal config is not modified. ai-memory opens the project database read-only;the launched Crush process continues its normal native session writes.diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex ce5e1482..ad358e6b 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -1158,7 +1158,11 @@ OpenClaw distinguishes transports explicitly. Use`ai-memory install-hooks --agent omp --apply` (or `--agent oh-my-pi`).**Config file:**-- User: `~/.omp/agent/mcp.json`+- User: `mcp.json` in OMP's agent dir: `~/.omp/agent/mcp.json` by default,+ `~/.omp/profiles/<name>/agent/mcp.json` under a named profile+ (`OMP_PROFILE`, or the legacy `PI_PROFILE`), or+ `$PI_CODING_AGENT_DIR/mcp.json` when that variable relocates the default+ profile; OMP's `PI_CONFIG_DIR` renames the `~/.omp` root in each case- Project: `.omp/mcp.json`The current Oh My Pi package exposes the `omp` binary and native@@ -1186,20 +1190,19 @@ ai-memory install-hooks --agent omp --applyThis writes `~/.omp/agent/extensions/ai-memory-omp.ts`, which OMP discoversas a direct TypeScript extension on startup. Restart `omp` after-installing or changing the file. When `PI_CODING_AGENT_DIR` is set-(it relocates OMP's whole `~/.omp/agent` home), the extension is written-to `$PI_CODING_AGENT_DIR/extensions/ai-memory-omp.ts` instead, and-`--profile <name>` (or `OMP_PROFILE`) targets-`~/.omp/profiles/<name>/agent/extensions/` — note `PI_CODING_AGENT_DIR`-takes precedence over a profile, since it names the agent directory-outright.+installing or changing the file. `--profile <name>` (or `OMP_PROFILE`)+targets `~/.omp/profiles/<name>/agent/extensions/`, and a named profile+ignores `PI_CODING_AGENT_DIR`, as OMP does. For the default profile,+`PI_CODING_AGENT_DIR` relocates OMP's whole `~/.omp/agent` home, so the+extension and `mcp.json` move to `$PI_CODING_AGENT_DIR` instead.Pi and OMP honour the *same* `PI_CODING_AGENT_DIR`, and each agent loadsevery direct `*.ts` in its extensions directory. Pointing both at onedirectory therefore makes each load both extensions and capture every-event twice, once under each agent identity. `install-hooks` warns when it-detects this; give the two agents separate homes, or scope OMP to a-profile.+event twice, once under each agent identity. `install-hooks` and the+`ai-memory run` auto-wire warn when they detect this; give the two agents+separate homes, or put OMP on a named profile, which leaves+`PI_CODING_AGENT_DIR` to Pi.**Gotchas:**- OMP extensions are TypeScript modules, not shell hooks; stdout is notdiff --git a/docs/users.md b/docs/users.mdindex ada11cba..e4244337 100644--- a/docs/users.md+++ b/docs/users.md@@ -492,6 +492,10 @@ the data dir, both `0600` (the data dir itself is `0700`):| `<data_dir>/auth-token` | the native `ai-memory hook` command || `<data_dir>/auth-header` | the shell hooks, via `curl -H @<file>` |+`ai-memory uninstall` deletes both files when it removes the hooks (a full+uninstall or `--only hooks`); `--only mcp`, `--only instructions` and `--only+skills` keep them for the hooks still installed.+It is deliberately **not** written into the agent's own config any more. Before#552 it went onto the hook's command line — `--auth-token <token>` for nativehooks, an `AI_MEMORY_AUTH_TOKEN=` shell prefix for the script hooks — which putdiff --git a/scripts/install-hooks.sh b/scripts/install-hooks.shindex 76ea005f..cd3d6f14 100755--- a/scripts/install-hooks.sh+++ b/scripts/install-hooks.sh@@ -88,14 +88,16 @@ fiif [[ "$AGENT" == "omp" || "$AGENT" == "oh-my-pi" ]]; thenecho "OMP uses a generated TypeScript extension, not shell hook scripts."echo "Run: ai-memory install-hooks --agent omp --apply"- echo "Then restart OMP so it loads ~/.omp/agent/extensions/ai-memory.ts."+ echo "Then restart OMP so it loads the extension install-hooks reports"+ echo "(default ~/.omp/agent/extensions/ai-memory-omp.ts)."exit 0fiif [[ "$AGENT" == "pi" ]]; thenecho "Pi uses a generated TypeScript extension, not shell hook scripts."echo "Run: ai-memory install-hooks --agent pi --apply"- echo "Then restart Pi so it loads ~/.pi/agent/extensions/ai-memory.ts."+ echo "Then restart Pi so it loads the extension install-hooks reports"+ echo "(default ~/.pi/agent/extensions/ai-memory-pi.ts)."echo "MCP tools come through the same generated bridge extension."exit 0fi