Skip to content

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

Rust

fix(omp): follow OMP's profile rules, PI_CONFIG_DIR and XDG session dir

Éverton Toffanetto86f001c6bff7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8e1bdf65..ed5d849d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -203,6 +203,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
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
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 00d0ce97..c251d295 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -1002,8 +1002,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>,
}
@@ -1669,8 +1670,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
@@ -1934,7 +1936,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`.
@@ -2436,8 +2439,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/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index f0898eec..4c36edc4 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -252,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
@@ -1407,13 +1382,7 @@ pub(crate) fn hook_config_target_with(
AgentChoice::OpenCode => opencode_plugin_path(),
AgentChoice::OpenCode2 => opencode2_plugin_path(),
AgentChoice::Pi => pi_extension_path_in(env("PI_CODING_AGENT_DIR")),
- AgentChoice::Omp => {
- let profile = env("OMP_PROFILE");
- omp_extension_path_in(
- env("PI_CODING_AGENT_DIR"),
- profile.as_ref().and_then(|name| name.to_str()),
- )
- }
+ 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"),
@@ -4221,11 +4190,13 @@ pub(crate) fn shared_extensions_dir(
/// [`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",
+ \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()
);
}
@@ -4284,10 +4255,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,
@@ -4317,7 +4289,8 @@ fn apply_to_omp_extension(
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.");
@@ -4325,23 +4298,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(),
@@ -4358,7 +4329,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.");
@@ -4374,13 +4345,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(
@@ -9242,7 +9207,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!(
@@ -9264,7 +9232,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)),
] {
@@ -9290,56 +9258,151 @@ 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 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!(
- !p.to_string_lossy().contains("profiles"),
- "PI_CODING_AGENT_DIR names the agent dir outright: {p:?}"
+ 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!(
+ 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
@@ -9373,6 +9436,16 @@ model = "gpt-5"
),
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
@@ -9398,6 +9471,16 @@ model = "gpt-5"
"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",
@@ -9529,7 +9612,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)
@@ -9538,7 +9622,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")
@@ -9554,7 +9643,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")
@@ -9769,15 +9858,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.rs
index 2d98f05c..328d19c9 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};
@@ -164,8 +165,10 @@ pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf>
}
/// [`mcp_config_path`] with the relocation variables (`CLAUDE_CONFIG_DIR`,
-/// `CODEX_HOME`, `GROK_HOME`, `KIMI_CODE_HOME` and `KIRO_HOME`) read through
-/// `env`, so `ai-memory run --env` can point auto-wire at the same config home
+/// `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,
@@ -223,7 +226,11 @@ pub(crate) fn mcp_config_path_with(
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")
@@ -1411,7 +1418,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\
@@ -1739,6 +1749,7 @@ mod tests {
(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!(
@@ -1749,6 +1760,44 @@ mod tests {
}
}
+ /// 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.
@@ -1761,6 +1810,9 @@ mod tests {
(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));
@@ -2350,7 +2402,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/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index ee7eb998..c1cfb539 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -18,8 +18,8 @@ use ai_memory_workstream::{
discover_native_session, export_transcript, has_native_session_selector, inspect_repository,
kiro_explicit_session_id, kiro_harness_from_source_cursor, kiro_selects_non_default_engine,
kiro_selects_v2_engine, kiro_selects_v3_engine, kiro_v3_resume_uses_default_store,
- list_native_sessions, native_session_exists, native_session_in_checkout, store_override_vars,
- 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;
@@ -401,7 +401,7 @@ pub(super) async fn run_from_with_wiring(
if config.run_autowire && !no_autowire {
// A Kiro v3 resume from the default store drops `KIRO_HOME` from the
// child, so its hooks and MCP belong under the default home.
- let mut wire_env = run_env.clone();
+ let mut wire_env = autowire_env(harness, &run_env, &plan.args, &launch_env);
if remove_kiro_home {
upsert_env(
&mut wire_env,
@@ -942,6 +942,32 @@ 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`).
+fn autowire_env(
+ harness: ManagedHarness,
+ run_env: &[(String, String)],
+ native_args: &[OsString],
+ 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);
+ }
+ }
+ 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.
@@ -3330,7 +3356,7 @@ mod tests {
);
assert_eq!(
blank_home_overrides(
- ManagedHarness::Pi,
+ ManagedHarness::Omp,
&env(&[
("PI_CODING_AGENT_SESSION_DIR", ""),
("PI_CODING_AGENT_DIR", "/x")
@@ -3338,6 +3364,13 @@ mod tests {
),
["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,
@@ -3569,4 +3602,71 @@ mod tests {
server.abort();
}
+
+ /// OMP ranks `--profile` above `OMP_PROFILE`, 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, &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, &launch),
+ run_env,
+ "only OMP reads --profile"
+ );
+ assert_eq!(
+ autowire_env(ManagedHarness::Omp, &run_env, &[], &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,
+ &only(inherited.clone()),
+ );
+ assert_eq!(
+ ai_memory_workstream::omp_agent_dir(home, None, only(wired)).unwrap(),
+ home.join(".omp").join("agent")
+ );
+ }
}
diff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rs
index f1521fa5..d9a482ec 100644
--- a/crates/ai-memory-cli/src/commands/run_autowire.rs
+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs
@@ -305,9 +305,9 @@ fn wire_installs(config: &Config, targets: WireTargets, overrides: &WireOverride
}
}
(None, Ok(target)) if hook_relocated => (vec![hook_install(Some(target))], None),
- // `--env` relocated a target the resolver could not place. The
- // installer would fall back to ai-memory's own environment and wire a
- // home this launch does not use.
+ // `--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),
};
@@ -593,12 +593,11 @@ mod tests {
"extensions/ai-memory-pi.ts",
None,
),
- // OMP's `mcp.json` stays in `~/.omp/agent`, so nothing pins it.
(
ManagedHarness::Omp,
"PI_CODING_AGENT_DIR",
"extensions/ai-memory-omp.ts",
- None,
+ Some("mcp.json"),
),
(
ManagedHarness::Kimi,
@@ -654,6 +653,67 @@ mod tests {
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()
+ );
+ }
+
/// 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.
@@ -669,7 +729,16 @@ mod tests {
ManagedHarness::Pi,
&["PI_CODING_AGENT_SESSION_DIR", "PI_CODING_AGENT_DIR"][..],
),
- (ManagedHarness::Omp, &["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"][..]),
@@ -685,10 +754,7 @@ mod tests {
install_hooks::hook_config_target_with(agent, &|_| None).ok(),
"{harness:?} hooks"
);
- // OMP's `mcp.json` reads no relocation variable, so nothing pins it.
- if let Some(client) = install_hooks::mcp_client_for_agent(agent)
- && harness != ManagedHarness::Omp
- {
+ 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(),
@@ -701,7 +767,10 @@ mod tests {
Vec::new(),
None,
&run_env,
- None,
+ Some(ai_memory_workstream::LaunchRoots {
+ home: home.path(),
+ cwd: home.path(),
+ }),
)
.unwrap();
assert_eq!(plan.session_dir, None, "{harness:?} session store");
@@ -729,6 +798,14 @@ mod tests {
Some(root.join("extensions")),
"{harness:?}"
);
+ let profiled = [
+ (
+ "PI_CODING_AGENT_DIR".to_string(),
+ root.display().to_string(),
+ ),
+ ("OMP_PROFILE".to_string(), "work".to_string()),
+ ];
+ assert_eq!(shared(&profiled), None, "{harness:?} with an OMP profile");
}
assert_eq!(
wire_targets(
@@ -842,6 +919,28 @@ mod tests {
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]
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index b851ba76..ea8f1bf0 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -134,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 });
@@ -150,6 +182,12 @@ fn build_plan(args: &UninstallArgs, data_dir: &Path) -> anyhow::Result<Vec<Plann
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) {
@@ -303,12 +341,10 @@ fn build_plan(args: &UninstallArgs, data_dir: &Path) -> anyhow::Result<Vec<Plann
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);
}
@@ -380,6 +416,8 @@ fn build_plan(args: &UninstallArgs, data_dir: &Path) -> anyhow::Result<Vec<Plann
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;
diff --git a/crates/ai-memory-cli/tests/suite/removal.rs b/crates/ai-memory-cli/tests/suite/removal.rs
index dd289d12..0d24b9ac 100644
--- a/crates/ai-memory-cli/tests/suite/removal.rs
+++ b/crates/ai-memory-cli/tests/suite/removal.rs
@@ -52,7 +52,9 @@ fn command_with_home(home: &Path) -> Command {
.env_remove("CODEX_HOME")
.env_remove("GROK_HOME")
.env_remove("PI_CODING_AGENT_DIR")
- .env_remove("OMP_PROFILE");
+ .env_remove("OMP_PROFILE")
+ .env_remove("PI_PROFILE")
+ .env_remove("PI_CONFIG_DIR");
command
}
@@ -290,6 +292,81 @@ fn relocated_codex_uninstall_sweeps_active_and_legacy_mcp() {
}
}
+/// `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();
@@ -435,6 +512,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.rs
index 618830ac..b1c79845 100644
--- a/crates/ai-memory-workstream/src/harness.rs
+++ b/crates/ai-memory-workstream/src/harness.rs
@@ -4,7 +4,7 @@ use std::ffi::OsString;
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.
@@ -234,9 +234,9 @@ pub struct LaunchRoots<'a> {
/// (see the `CLAUDE_CONFIG_DIR` note in `docs/managed-workstreams.md`).
///
/// `roots` name the native home and the launch directory. Crush needs both
-/// (its data directory is found from the launch directory, see
-/// [`crush_data_dir`]); without them that store falls back to the adapter's
-/// default root.
+/// (see [`crush_data_dir`]); OMP needs the home for profiles, `PI_CONFIG_DIR`
+/// and XDG session storage. Without roots, these stores fall back to the
+/// adapter's default root.
pub fn build_launch_plan_with_env(
harness: ManagedHarness,
executable: Option<OsString>,
@@ -259,7 +259,18 @@ pub fn build_launch_plan_with_env(
ManagedHarness::Crush => flag_path(&args, &["--data-dir", "-D"]),
_ => None,
}
- .or_else(|| environment_session_dir_with(harness, get))
+ .or_else(|| {
+ 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,
@@ -958,6 +969,44 @@ pub fn env_dir_override(value: Option<OsString>) -> Option<PathBuf> {
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] {
@@ -966,7 +1015,12 @@ pub fn store_override_vars(harness: ManagedHarness) -> &'static [&'static str] {
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_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"],
@@ -974,6 +1028,119 @@ pub fn store_override_vars(harness: ManagedHarness) -> &'static [&'static str] {
}
}
+/// 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>,
+) -> 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.
@@ -1193,8 +1360,108 @@ 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));
@@ -1209,7 +1476,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
@@ -1661,19 +1946,19 @@ 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"))
);
}
@@ -1843,6 +2128,213 @@ mod tests {
}
}
+ #[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 [
@@ -1861,6 +2353,224 @@ mod tests {
}
}
+ /// `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.
+ #[cfg(unix)]
+ #[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.
+ #[cfg(unix)]
+ #[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.
@@ -1880,7 +2590,12 @@ mod tests {
ManagedHarness::Grok,
] {
assert_eq!(
- environment_session_dir_with(harness, |_| Some(OsString::from(blank))),
+ environment_session_dir_with(
+ harness,
+ Some(Path::new("/home/me")),
+ None,
+ |_| Some(OsString::from(blank))
+ ),
None,
"{harness:?} with {blank:?}"
);
@@ -1889,6 +2604,8 @@ mod tests {
assert_eq!(
environment_session_dir_with(
ManagedHarness::Pi,
+ None,
+ None,
env_of(&[
("PI_CODING_AGENT_SESSION_DIR", " "),
("PI_CODING_AGENT_DIR", "/stores/pi")
@@ -2118,7 +2835,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"))
);
}
@@ -2128,7 +2845,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"))
);
}
@@ -2341,12 +3058,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.rs
index 15e2886d..ae4895a1 100644
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@ -9,7 +9,8 @@ pub use harness::{
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, store_override_vars,
+ 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::{
diff --git a/docs/install.md b/docs/install.md
index 64a6df1f..27abb166 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -1338,19 +1338,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:
```bash
ai-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
-```
-
-`--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.
+OMP_PROFILE=work ai-memory install-mcp --client omp --apply
+```
+
+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.
```bash
ai-memory install-hooks --agent pi --apply \
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index 1efbfdfd..83090ab0 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -381,7 +381,7 @@ is labelled completed evidence and must never be replayed as a pending call.
| 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 |
@@ -422,7 +422,11 @@ run a `crushrc` to read one set only there; pass `--data-dir` in that case. Nati
environment 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`. A blank
+`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.
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index 42c7dc86..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 --apply
This writes `~/.omp/agent/extensions/ai-memory-omp.ts`, which OMP discovers
as 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 loads
every direct `*.ts` in its extensions directory. Pointing both at one
directory therefore makes each load both extensions and capture every
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 scope OMP to a profile.
+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 not
diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.sh
index 76ea005f..cd3d6f14 100755
--- a/scripts/install-hooks.sh
+++ b/scripts/install-hooks.sh
@@ -88,14 +88,16 @@ fi
if [[ "$AGENT" == "omp" || "$AGENT" == "oh-my-pi" ]]; then
echo "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 0
fi
if [[ "$AGENT" == "pi" ]]; then
echo "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 0
fi