Skip to content

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

Rust

fix(cli): read CODEX_HOME and COPILOT_HOME from the captured environment

AkitaOnRails4e1f969b1e53
diff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rs
index 93bb032f..13fc1435 100644
--- a/crates/ai-memory-cli/src/commands/doctor.rs
+++ b/crates/ai-memory-cli/src/commands/doctor.rs
@@ -624,7 +624,7 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {
});
let native_memory = native_memory_reports(&home, &cwd);
- let codex_hooks = codex_hook_trust(&cwd).await;
+ let codex_hooks = codex_hook_trust(&config.runtime_env, &cwd).await;
let repo_root =
ai_memory_consolidate::discover_main_repo_root(&cwd).unwrap_or_else(|_| cwd.clone());
let agentmemory_residue = super::agentmemory_residue::scan(
@@ -680,8 +680,11 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {
/// The trust state of the installed ai-memory Codex hooks, when there are
/// any: asking Codex starts it, so a machine without ai-memory's Codex hooks
/// is left alone.
-async fn codex_hook_trust(cwd: &Path) -> Option<super::codex_hook_trust::CodexHookTrust> {
- let hooks_file = super::install_hooks::codex_hooks_path().ok()?;
+async fn codex_hook_trust(
+ env: &crate::config::RuntimeEnv,
+ cwd: &Path,
+) -> Option<super::codex_hook_trust::CodexHookTrust> {
+ let hooks_file = super::install_hooks::codex_hooks_path(env).ok()?;
let installed = std::fs::read_to_string(&hooks_file).ok()?;
if !installed.contains("ai-memory") {
return None;
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 34ce6718..5e2117bc 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -272,8 +272,10 @@ pub(crate) fn restage_claude_code_scripts(
/// honors the variable when it resolves that Codex's transcripts
/// (`ManagedHarness::Codex` in `ai-memory-workstream`), so ignoring it here left
/// one half of the same install pointing somewhere the other half did not.
-pub(crate) fn codex_hooks_path() -> anyhow::Result<std::path::PathBuf> {
- codex_hooks_path_in(std::env::var_os("CODEX_HOME"))
+pub(crate) fn codex_hooks_path(
+ env: &crate::config::RuntimeEnv,
+) -> anyhow::Result<std::path::PathBuf> {
+ codex_hooks_path_in(env.var_os("CODEX_HOME"))
}
/// The env value comes in as a parameter so tests can exercise both branches
@@ -308,7 +310,7 @@ pub(crate) fn copilot_cli_hooks_path() -> anyhow::Result<std::path::PathBuf> {
/// [`copilot_cli_hooks_path`] with the `COPILOT_HOME` value passed in. Resolves
/// through the same config dir as `install-mcp --client copilot-cli`
/// ([`install_mcp::copilot_home_in`]), so the two halves of one install agree.
-fn copilot_cli_hooks_path_in(
+pub(crate) fn copilot_cli_hooks_path_in(
env_override: Option<std::ffi::OsString>,
) -> anyhow::Result<std::path::PathBuf> {
Ok(install_mcp::copilot_home_in(env_override)?
@@ -792,6 +794,12 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(
// `--capture-assistant` still forces it on; this only fills in the unset case
// from what is already installed. Gated to the agents where assistant capture
// is allowed (Claude Code, Codex), whose configs share the nested-hooks shape.
+ // Codex's default hooks file depends on CODEX_HOME. Resolve it from the
+ // captured environment once, into `args` like the project strategy below,
+ // so every reader of the existing install and the writer agree on it.
+ if args.apply && args.agent == AgentChoice::Codex && args.config_file.is_none() {
+ args.config_file = Some(codex_hooks_path(&config.runtime_env)?);
+ }
if args.apply
&& !args.capture_assistant
&& capture_assistant_allowed(args.agent)
@@ -1272,7 +1280,8 @@ fn existing_agent_config(args: &InstallHooksArgs) -> Option<String> {
} else {
match args.agent {
AgentChoice::ClaudeCode => claude_settings_target(args).ok()?,
- AgentChoice::Codex => codex_hooks_path().ok()?,
+ // `run` resolves it into `args.config_file` before any caller.
+ AgentChoice::Codex => return None,
AgentChoice::CommandCode => command_code_settings_path().ok()?,
AgentChoice::Cursor => cursor_hooks_path().ok()?,
AgentChoice::GeminiCli => gemini_settings_path().ok()?,
@@ -2658,10 +2667,10 @@ fn apply_to_codex_settings_with_payload(
payload: serde_json::Value,
args: &InstallHooksArgs,
) -> Result<()> {
- let path = match &args.config_file {
- Some(p) => p.clone(),
- None => codex_hooks_path()?,
- };
+ let path = args
+ .config_file
+ .clone()
+ .context("internal: the Codex hooks path is resolved before apply")?;
let outcome = merge_codex_payload(payload, &path)?;
println!(
"✓ {} {} ({})",
@@ -9872,6 +9881,35 @@ model = "gpt-5"
/// `--auth-token <token>` for native hooks — so it sat in the agent's
/// config file *and* in `/proc/<pid>/cmdline` for the lifetime of every
/// hook, on every tool call.
+ /// `install-hooks --agent codex --apply` writes to the CODEX_HOME that
+ /// `Config::load` captured, not one re-read from the live process
+ /// (invariant #1): an injected value decides the file.
+ #[test]
+ fn codex_apply_writes_under_the_captured_codex_home() {
+ let home = TempDir::new().unwrap();
+ let codex_home = TempDir::new().unwrap();
+ let mut config =
+ crate::config::Config::load(None, Some(home.path().to_path_buf())).unwrap();
+ config.runtime_env = crate::config::RuntimeEnv::with_process_env_for_tests(&[(
+ "CODEX_HOME",
+ codex_home.path().to_str().unwrap(),
+ )]);
+ let args = InstallHooksArgs {
+ agent: AgentChoice::Codex,
+ apply: true,
+ server_url: Some("http://127.0.0.1:49374".to_string()),
+ hooks_dir: Some(
+ std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../hooks"),
+ ),
+ ..default_hook_args()
+ };
+
+ run(&config, args).expect("apply should succeed");
+
+ let written = std::fs::read_to_string(codex_home.path().join("hooks.json")).unwrap();
+ assert!(written.contains("ai-memory"), "{written}");
+ }
+
#[test]
fn apply_persists_the_bearer_and_keeps_it_out_of_the_agent_config() {
let home = TempDir::new().unwrap();
diff --git a/crates/ai-memory-cli/src/commands/install_instructions.rs b/crates/ai-memory-cli/src/commands/install_instructions.rs
index 126f9ed0..c7937ab1 100644
--- a/crates/ai-memory-cli/src/commands/install_instructions.rs
+++ b/crates/ai-memory-cli/src/commands/install_instructions.rs
@@ -39,15 +39,22 @@ const LEGACY_ORPHAN_TAIL_CRLF: &str =
/// # Errors
/// Returns an error if the target path can't be written or if the
/// existing file isn't valid UTF-8.
-pub fn run(_config: &Config, args: InstallInstructionsArgs) -> Result<()> {
- run_inner(args, true)
+pub fn run(config: &Config, args: InstallInstructionsArgs) -> Result<()> {
+ run_inner(args, &config.runtime_env, true)
}
-pub(super) fn run_quiet(args: InstallInstructionsArgs) -> Result<()> {
- run_inner(args, false)
+pub(super) fn run_quiet(
+ args: InstallInstructionsArgs,
+ env: &crate::config::RuntimeEnv,
+) -> Result<()> {
+ run_inner(args, env, false)
}
-fn run_inner(args: InstallInstructionsArgs, report: bool) -> Result<()> {
+fn run_inner(
+ args: InstallInstructionsArgs,
+ env: &crate::config::RuntimeEnv,
+ report: bool,
+) -> Result<()> {
let block = if args.compact {
compact_block()
} else {
@@ -62,7 +69,7 @@ fn run_inner(args: InstallInstructionsArgs, report: bool) -> Result<()> {
let prepared_skills = if !args.print {
skill_args
.as_ref()
- .map(install_skills::prepare_install)
+ .map(|args| install_skills::prepare_install(args, env))
.transpose()?
} else {
None
diff --git a/crates/ai-memory-cli/src/commands/install_skills.rs b/crates/ai-memory-cli/src/commands/install_skills.rs
index 5f079a0a..cf29eee8 100644
--- a/crates/ai-memory-cli/src/commands/install_skills.rs
+++ b/crates/ai-memory-cli/src/commands/install_skills.rs
@@ -48,22 +48,25 @@ pub(super) struct PreparedInstall {
/// Returns an error when target roots cannot be resolved, an unmanaged
/// same-name skill would be overwritten without `--force`, or a skill
/// file cannot be written.
-pub fn run(_config: &Config, args: InstallSkillsArgs) -> Result<()> {
- let roots = resolve_target_roots_from_env(&args)?;
+pub fn run(config: &Config, args: InstallSkillsArgs) -> Result<()> {
+ let roots = resolve_target_roots_from_env(&args, &config.runtime_env)?;
if args.print {
print_install_plan(&roots, grok_handoff_rule_path_for(&args)?);
return Ok(());
}
- let prepared = prepare_install(&args)?;
+ let prepared = prepare_install(&args, &config.runtime_env)?;
print_reports(apply_prepared_install(prepared)?);
Ok(())
}
-pub(super) fn prepare_install(args: &InstallSkillsArgs) -> Result<PreparedInstall> {
- let roots = resolve_target_roots_from_env(args)?;
+pub(super) fn prepare_install(
+ args: &InstallSkillsArgs,
+ env: &crate::config::RuntimeEnv,
+) -> Result<PreparedInstall> {
+ let roots = resolve_target_roots_from_env(args, env)?;
let plans = skill_file_plans(&roots);
let grok_handoff_rule = grok_handoff_rule_path_for(args)?;
validate_overwrite_safety(&plans, args.force)?;
@@ -178,20 +181,27 @@ fn print_reports(reports: Vec<InstallReport>) {
}
}
-fn resolve_target_roots_from_env(args: &InstallSkillsArgs) -> Result<Vec<TargetRoot>> {
+/// The harness homes come from the environment `Config::load` captured, not
+/// the live process (invariant #1).
+fn resolve_target_roots_from_env(
+ args: &InstallSkillsArgs,
+ env: &crate::config::RuntimeEnv,
+) -> Result<Vec<TargetRoot>> {
let cwd = std::env::current_dir().context("getting CWD for install-skills target")?;
let home = home_dir();
- let appdata = std::env::var_os("APPDATA").map(PathBuf::from);
+ let appdata = env.var_os("APPDATA").map(PathBuf::from);
// Grok and Copilot CLI relocate their whole config home, global skills
// included, through GROK_HOME / COPILOT_HOME.
let agent_home = match (args.scope, args.agent) {
- (InstallSkillsScope::Global, InstallSkillsAgent::Grok) => Some(install_mcp::grok_home()?),
- (InstallSkillsScope::Global, InstallSkillsAgent::CopilotCli) => Some(
- install_mcp::copilot_home_in(std::env::var_os("COPILOT_HOME"))?,
- ),
+ (InstallSkillsScope::Global, InstallSkillsAgent::Grok) => {
+ Some(install_mcp::grok_home_in(env.var_os("GROK_HOME"))?)
+ }
+ (InstallSkillsScope::Global, InstallSkillsAgent::CopilotCli) => {
+ Some(install_mcp::copilot_home_in(env.var_os("COPILOT_HOME"))?)
+ }
_ => None,
};
- let claude_config_dir = claude_config_dir(std::env::var_os("CLAUDE_CONFIG_DIR"));
+ let claude_config_dir = claude_config_dir(env.var_os("CLAUDE_CONFIG_DIR"));
resolve_target_roots_for_platform(
args,
&cwd,
@@ -708,6 +718,31 @@ mod tests {
assert_eq!(root_names(&roots), ["/custom/grok/skills"]);
}
+ /// COPILOT_HOME and GROK_HOME come from the captured environment, never
+ /// the live process: an injected value decides the global root.
+ #[test]
+ fn global_harness_homes_come_from_the_captured_environment() {
+ let env = crate::config::RuntimeEnv::with_process_env_for_tests(&[
+ ("COPILOT_HOME", "/injected/copilot"),
+ ("GROK_HOME", "/injected/grok"),
+ ]);
+ let copilot = resolve_target_roots_from_env(
+ &args(InstallSkillsScope::Global, InstallSkillsAgent::CopilotCli),
+ &env,
+ )
+ .unwrap();
+ assert_eq!(
+ copilot[0].path,
+ Path::new("/injected/copilot").join(SKILLS_DIR)
+ );
+ let grok = resolve_target_roots_from_env(
+ &args(InstallSkillsScope::Global, InstallSkillsAgent::Grok),
+ &env,
+ )
+ .unwrap();
+ assert_eq!(grok[0].path, Path::new("/injected/grok").join(SKILLS_DIR));
+ }
+
#[test]
fn copilot_cli_skill_roots_split_project_github_and_global_copilot_home() {
let cwd = Path::new("/repo");
diff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rs
index 7ecfda74..231647dd 100644
--- a/crates/ai-memory-cli/src/commands/run_autowire.rs
+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs
@@ -1537,7 +1537,10 @@ mod tests {
AgentChoice::ClaudeCode,
install_hooks::claude_settings_path(),
),
- (AgentChoice::Codex, install_hooks::codex_hooks_path()),
+ (
+ AgentChoice::Codex,
+ install_hooks::codex_hooks_path(&crate::config::RuntimeEnv::from_process()),
+ ),
(AgentChoice::OpenCode, install_hooks::opencode_plugin_path()),
(
AgentChoice::OpenCode2,
diff --git a/crates/ai-memory-cli/src/commands/show.rs b/crates/ai-memory-cli/src/commands/show.rs
index a21aa073..ba960c75 100644
--- a/crates/ai-memory-cli/src/commands/show.rs
+++ b/crates/ai-memory-cli/src/commands/show.rs
@@ -214,7 +214,7 @@ pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {
let (target, workspace, project) = if let Some(name) = new_project {
let workspace = args.workspace.as_deref().unwrap_or(DEFAULT_WORKSPACE);
- let target = create_project(&root, &name, workspace, harness)?;
+ let target = create_project(&root, &name, workspace, harness, &config.runtime_env)?;
(target, workspace.to_owned(), name)
} else {
let candidate = &candidates[project_index - 1];
@@ -565,9 +565,10 @@ fn create_project(
name: &str,
workspace: &str,
harness: RunHarnessChoice,
+ env: &crate::config::RuntimeEnv,
) -> Result<PathBuf> {
create_project_with_initializer(parent, name, workspace, |staging| {
- install_context_files(harness, staging)
+ install_context_files(harness, staging, env)
})
}
@@ -611,7 +612,11 @@ fn create_project_with_initializer(
Ok(target)
}
-fn install_context_files(harness: RunHarnessChoice, path: &Path) -> Result<()> {
+fn install_context_files(
+ harness: RunHarnessChoice,
+ path: &Path,
+ env: &crate::config::RuntimeEnv,
+) -> Result<()> {
let (instruction, agent, skill_root) = match harness {
RunHarnessChoice::Claude => (
"CLAUDE.md",
@@ -624,16 +629,19 @@ fn install_context_files(harness: RunHarnessChoice, path: &Path) -> Result<()> {
path.join(".agents/skills"),
),
};
- install_instructions::run_quiet(InstallInstructionsArgs {
- target: Some(path.join(instruction)),
- print: false,
- no_skills: false,
- compact: false,
- skills_scope: None,
- skills_agent: Some(agent),
- skills_target_dir: Some(skill_root),
- skills_force: false,
- })
+ install_instructions::run_quiet(
+ InstallInstructionsArgs {
+ target: Some(path.join(instruction)),
+ print: false,
+ no_skills: false,
+ compact: false,
+ skills_scope: None,
+ skills_agent: Some(agent),
+ skills_target_dir: Some(skill_root),
+ skills_force: false,
+ },
+ env,
+ )
}
fn humanize_age(timestamp: Option<&str>) -> String {
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index 7630f6f6..e42d1a0b 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -179,13 +179,21 @@ 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, data_dir: &Path) -> anyhow::Result<Vec<PlannedChange>> {
+///
+/// Harness homes (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `COPILOT_HOME`,
+/// `GROK_HOME`, `APPDATA`) come
+/// from `env`, the environment `Config::load` captured (invariant #1).
+fn build_plan(
+ args: &UninstallArgs,
+ data_dir: &Path,
+ env: &crate::config::RuntimeEnv,
+) -> 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 claude_config_dir = claude_config_dir(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())
@@ -216,11 +224,11 @@ fn build_plan(args: &UninstallArgs, data_dir: &Path) -> anyhow::Result<Vec<Plann
// Copilot CLI's standalone file keeps flat entries under the usual
// `hooks` key next to its `version: 1`, like Cursor's.
(
- install_hooks::copilot_cli_hooks_path()?,
+ install_hooks::copilot_cli_hooks_path_in(env.var_os("COPILOT_HOME"))?,
HookConfigShape::NestedHooksKey,
),
(
- install_hooks::codex_hooks_path()?,
+ install_hooks::codex_hooks_path(env)?,
HookConfigShape::NestedHooksKey,
),
(
@@ -438,7 +446,7 @@ fn build_plan(args: &UninstallArgs, data_dir: &Path) -> anyhow::Result<Vec<Plann
// 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(),
+ agent_config_home(env.var_os("CODEX_HOME")).as_deref(),
Path::new(".codex/config.toml"),
Path::new("config.toml"),
)
@@ -496,9 +504,9 @@ fn build_plan(args: &UninstallArgs, data_dir: &Path) -> anyhow::Result<Vec<Plann
// ---- Managed Agent Skills (project + global roots) ----
if want(crate::cli::UninstallOnly::Skills) {
let cwd = std::env::current_dir().context("getting CWD for skill removal")?;
- let appdata = std::env::var_os("APPDATA").map(PathBuf::from);
- let grok_home = install_mcp::grok_home().ok();
- let copilot_home = install_mcp::copilot_home_in(std::env::var_os("COPILOT_HOME")).ok();
+ let appdata = env.var_os("APPDATA").map(PathBuf::from);
+ let grok_home = install_mcp::grok_home_in(env.var_os("GROK_HOME")).ok();
+ let copilot_home = install_mcp::copilot_home_in(env.var_os("COPILOT_HOME")).ok();
for root in skill_roots(
&cwd,
home.as_deref(),
@@ -727,7 +735,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, &config.data_dir)?;
+ let plan = build_plan(&args, &config.data_dir, &config.runtime_env)?;
print_plan(&plan);
// The marketplace plugins carry hooks, MCP and skills together, so only a
// full uninstall removes them; the harness's own CLI does the removal.
@@ -1841,6 +1849,42 @@ mod tests {
);
}
+ /// The skill sweep finds a global Copilot CLI skill under the COPILOT_HOME
+ /// `Config::load` captured (invariant #1), not one re-read from the live
+ /// process.
+ #[test]
+ fn skill_sweep_uses_the_captured_copilot_home() {
+ let copilot_home = tempfile::tempdir().unwrap();
+ let skill = copilot_home
+ .path()
+ .join(SKILLS_DIR)
+ .join(MANAGED_SKILLS[0].relative_path);
+ std::fs::create_dir_all(skill.parent().unwrap()).unwrap();
+ std::fs::write(&skill, MANAGED_SKILLS[0].content).unwrap();
+ let env = crate::config::RuntimeEnv::with_process_env_for_tests(&[(
+ "COPILOT_HOME",
+ copilot_home.path().to_str().unwrap(),
+ )]);
+ let args = UninstallArgs {
+ apply: false,
+ purge_data: false,
+ only: Some(crate::cli::UninstallOnly::Skills),
+ mcp_name: None,
+ mcp_url: String::new(),
+ yes: false,
+ profile: None,
+ };
+ let data = tempfile::tempdir().unwrap();
+ let plan = build_plan(&args, data.path(), &env).unwrap();
+ assert!(
+ plan.iter().any(|change| matches!(
+ change,
+ PlannedChange::DeleteFile { path, .. } if *path == skill
+ )),
+ "{plan:?}"
+ );
+ }
+
/// Each installed plugin is removed through its own harness CLI, and one
/// failure does not stop the next.
#[test]
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index 4bfae0f0..86c1fed5 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -807,6 +807,19 @@ impl RuntimeEnv {
&self.process_env.0
}
+ /// One variable of the captured process environment. Third-party harness
+ /// homes (`CODEX_HOME`, `COPILOT_HOME`, ...) are read through here so a
+ /// command never re-reads the live environment (invariant #1) and tests
+ /// can inject them.
+ #[must_use]
+ pub(crate) fn var_os(&self, name: &str) -> Option<OsString> {
+ self.process_env
+ .0
+ .iter()
+ .find(|(key, _)| key.as_os_str() == name)
+ .map(|(_, value)| value.clone())
+ }
+
/// Whether this invocation delegates native capture to an external producer.
#[must_use]
pub fn capture_owner_active(&self) -> bool {
@@ -852,6 +865,19 @@ impl RuntimeEnv {
}
}
+ #[cfg(test)]
+ pub fn with_process_env_for_tests(pairs: &[(&str, &str)]) -> Self {
+ Self {
+ process_env: CapturedProcessEnv(
+ pairs
+ .iter()
+ .map(|(key, value)| (OsString::from(key), OsString::from(value)))
+ .collect(),
+ ),
+ ..Self::default()
+ }
+ }
+
#[cfg(test)]
pub fn with_openai_api_key_for_tests(api_key: impl Into<String>) -> Self {
Self {