Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(run): launch the wrapper named by a claude* harness spelling
Carlos Daniel404f06be4dc7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 63b5437f..55862899 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,12 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]### Fixed+- Launched the wrapper executable named by a `claude*` harness spelling+ (`ai-memory run claude-glm`) when it is on the launch `PATH` and no+ `--executable` is given, instead of silently starting plain `claude` on the+ wrong account. When no such executable exists, `run` now prints a warning+ and still starts `claude`. An explicit `--executable` still wins.+ ([#NNN](https://github.com/akitaonrails/ai-memory/pull/NNN))- Ignored a UTF-8 byte-order mark at the start of `run --env-file` input sothe first environment variable keeps its intended name.([#1465](https://github.com/akitaonrails/ai-memory/pull/1465))diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 2f6e53d4..07528099 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -3,7 +3,7 @@use std::ffi::OsString;use std::path::PathBuf;-use clap::{Args, Parser, Subcommand};+use clap::{Args, FromArgMatches, Parser, Subcommand};use clap_complete::Shell;/// Parse the process argv while making the documented `run` boundary real:@@ -26,7 +26,21 @@ where{let mut args = args.into_iter().map(Into::into).collect::<Vec<_>>();delimit_run_native_args(&mut args);- Cli::try_parse_from(args)+ let matches = <Cli as clap::CommandFactory>::command().try_get_matches_from(args)?;+ let mut cli = Cli::from_arg_matches(&matches)?;+ if let Command::Run(run) = &mut cli.command {+ // The value parser collapses every `claude*` spelling onto+ // `RunHarnessChoice::Claude`; keep the typed spelling so `run` can+ // prefer a same-named wrapper executable.+ run.claude_wrapper = matches+ .subcommand_matches("run")+ .and_then(|run_matches| run_matches.get_raw("harness"))+ .and_then(|mut raw| raw.next())+ .and_then(std::ffi::OsStr::to_str)+ .and_then(claude_wrapper_spelling)+ .map(str::to_owned);+ }+ Ok(cli)}fn delimit_run_native_args(args: &mut Vec<OsString>) {@@ -486,9 +500,16 @@ pub struct RunArgs {/// Agent harness to launch. When omitted, continue the newest managed or/// checkout-local session among the auto-detected harnesses. Any value/// starting with `claude` (e.g. `claude-corp`, `claude-personal`) also- /// selects the Claude harness — see `parse_run_harness_choice`.+ /// selects the Claude harness — see `parse_run_harness_choice` — and, when+ /// no `--executable` is given and an executable with that exact name is on+ /// `PATH`, launches it instead of plain `claude`.#[arg(value_parser = parse_run_harness_choice)]pub harness: Option<RunHarnessChoice>,+ /// The `claude*` spelling typed as `harness` when it is a wrapper name+ /// rather than a fixed alias (`claude`, `claude-code`). Filled by+ /// [`try_parse_from`]; `run` uses it as the default `--executable`.+ #[arg(skip)]+ pub claude_wrapper: Option<String>,/// Native harness arguments, forwarded byte-for-byte and in order.#[arg(allow_hyphen_values = true, trailing_var_arg = true)]pub native_args: Vec<OsString>,@@ -552,13 +573,13 @@ pub enum RunHarnessChoice {/// `PATH`-visible wrapper script per account (a plain shell `alias` is/// invisible to us — `ai-memory run` execs directly, without going through/// an interactive shell). Naming those wrappers `claude-corp` /-/// `claude-personal` and then passing `--executable claude-corp` (bare names-/// resolve through `PATH` just like the default) already selects the right-/// binary; this parser just stops the harness argument itself from being-/// rejected as an unknown value, so `ai-memory run claude-corp --executable-/// claude-corp` (or any other `claude*` spelling used consistently) reads-/// naturally instead of forcing every account onto the literal `claude`-/// token.+/// `claude-personal` makes the spelling itself readable in shell history, and+/// this parser stops it being rejected as an unknown value.+///+/// The typed spelling is kept (see [`RunArgs::claude_wrapper`]): when it names+/// an executable on the launch `PATH` and `--executable` is absent, `run`+/// launches that wrapper. Before, the spelling was dropped here and plain+/// `claude` started on the wrong account without any hint.fn parse_run_harness_choice(value: &str) -> Result<RunHarnessChoice, String> {use clap::ValueEnum as _;if let Ok(choice) = RunHarnessChoice::from_str(value, true) {@@ -578,6 +599,15 @@ fn parse_run_harness_choice(value: &str) -> Result<RunHarnessChoice, String> {))}+/// The wrapper name behind a `claude*` harness spelling, or `None` for the+/// fixed names (`claude`, `claude-code`, any case) and non-Claude values.+fn claude_wrapper_spelling(value: &str) -> Option<&str> {+ use clap::ValueEnum as _;+ (RunHarnessChoice::from_str(value, true).is_err()+ && parse_run_harness_choice(value) == Ok(RunHarnessChoice::Claude))+ .then_some(value)+}+/// Parse one `KEY=VALUE` entry for `--env` (also reused for `--env-file`/// lines). The value is taken literally — no expansion, no interpretation —/// so a caller-supplied value reaches the harness exactly as written.@@ -4469,6 +4499,47 @@ mod tests {}}+ #[test]+ fn claude_wrapper_spelling_is_kept_only_for_non_fixed_names() {+ let wrapper = |name: &str| {+ let cli = crate::cli::try_parse_from(["ai-memory", "run", name]).unwrap();+ let Command::Run(args) = cli.command else {+ panic!("expected run for {name}");+ };+ args.claude_wrapper+ };+ assert_eq!(wrapper("claude-glm").as_deref(), Some("claude-glm"));+ assert_eq!(wrapper("CLAUDE-WORK").as_deref(), Some("CLAUDE-WORK"));+ assert_eq!(wrapper("claudex").as_deref(), Some("claudex"));+ for fixed in [+ "claude",+ "CLAUDE",+ "Claude-Code",+ "claude-code",+ "codex",+ "kiro",+ ] {+ assert_eq!(wrapper(fixed), None, "{fixed}");+ }++ // Wrapper-owned flags before the harness, native args after it.+ let cli = crate::cli::try_parse_from([+ "ai-memory",+ "run",+ "--executable",+ "/opt/claude-x",+ "claude-glm",+ "--model",+ "opus",+ ])+ .unwrap();+ let Command::Run(args) = cli.command else {+ panic!("expected run");+ };+ assert_eq!(args.claude_wrapper.as_deref(), Some("claude-glm"));+ assert_eq!(args.native_args, ["--model", "opus"]);+ }+#[test]fn non_claude_unknown_harness_is_still_rejected() {let error = Cli::try_parse_from(["ai-memory", "run", "banana"])diff --git a/crates/ai-memory-cli/src/commands/continue_session.rs b/crates/ai-memory-cli/src/commands/continue_session.rsindex 8b1aeff7..81061d81 100644--- a/crates/ai-memory-cli/src/commands/continue_session.rs+++ b/crates/ai-memory-cli/src/commands/continue_session.rs@@ -85,6 +85,7 @@ pub async fn run(config: &Config, args: ContinueArgs) -> Result<i32> {// Bare mode: `run` resolves the harness that owns the newest// usable session for this workstream.harness: None,+ claude_wrapper: None,native_args: Vec::new(),},&target,diff --git a/crates/ai-memory-cli/src/commands/resume.rs b/crates/ai-memory-cli/src/commands/resume.rsindex 32405df9..42491651 100644--- a/crates/ai-memory-cli/src/commands/resume.rs+++ b/crates/ai-memory-cli/src/commands/resume.rs@@ -99,6 +99,7 @@ pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {env: Vec::new(),env_file: None,harness,+ claude_wrapper: None,native_args: Vec::new(),},&target,diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex 57615a8f..0c6cd1b9 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -425,6 +425,10 @@ fn apply_after_run_action(AfterRunAction::Rerun => run_harness_choice(outcome.harness),};args.harness = Some(choice);+ // A switch leaves the account the typed wrapper named; a rerun stays on it.+ if action != AfterRunAction::Rerun {+ args.claude_wrapper = None;+ }args.native_args =if action == AfterRunAction::Rerun && outcome.harness == ManagedHarness::KiroV3 {vec![OsString::from("--v3")]@@ -508,6 +512,12 @@ async fn run_once_with_wiring("--executable requires an explicit harness; try `ai-memory run --executable <path> codex`"));}+ default_claude_wrapper(+ &mut executable,+ requested_harness,+ args.claude_wrapper.as_deref(),+ executable_search,+ );let resolved_opencode =resolve_opencode_for_launch(requested_harness, executable.as_deref(), &child_env)?;if matches!(requested_harness, Some(RunHarnessChoice::OpenCode))@@ -3381,6 +3391,42 @@ fn store_mismatch_error())}+/// Points an unset `--executable` at the typed `claude*` wrapper, warning on+/// stderr when none is installed. An explicit `--executable` is never touched.+fn default_claude_wrapper(+ executable: &mut Option<OsString>,+ requested: Option<RunHarnessChoice>,+ spelling: Option<&str>,+ search: ExecutableSearch<'_>,+) {+ if executable.is_some() || requested != Some(RunHarnessChoice::Claude) {+ return;+ }+ let Some(spelling) = spelling else { return };+ match claude_wrapper_executable(spelling, search) {+ Ok(wrapper) => *executable = Some(wrapper),+ Err(warning) => eprintln!("{warning}"),+ }+}++/// The executable a `claude*` harness spelling selects when `--executable` is+/// absent: the exact spelling when it resolves on the launch `PATH`, else a+/// warning that plain `claude` runs instead, so a mistyped or missing wrapper+/// cannot silently start the wrong account.+fn claude_wrapper_executable(+ spelling: &str,+ search: ExecutableSearch<'_>,+) -> std::result::Result<OsString, String> {+ let bare_name = !spelling.contains(['/', '\\']);+ if bare_name && executable_available(OsStr::new(spelling), search) {+ return Ok(OsString::from(spelling));+ }+ Err(format!(+ "ai-memory: no `{spelling}` executable found on PATH; running plain `claude`. \+ To use a wrapper, put it on PATH or pass `--executable <path>`"+ ))+}+fn ensure_executable_available(harness: ManagedHarness,executable: Option<&OsStr>,@@ -5114,6 +5160,7 @@ mod tests {env: vec![("MODEL_HOME".into(), "custom".into())],env_file: None,harness: Some(RunHarnessChoice::Claude),+ claude_wrapper: None,native_args: vec![OsString::from("--model"), OsString::from("opus")],}}@@ -5397,6 +5444,124 @@ mod tests {);}+ #[cfg(unix)]+ fn path_with_fake_executables(names: &[&str]) -> (tempfile::TempDir, EffectiveChildEnv) {+ use std::os::unix::fs::PermissionsExt as _;++ let temp = tempfile::tempdir().unwrap();+ let bin = temp.path().join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ for name in names {+ let path = bin.join(name);+ std::fs::write(&path, "#!/bin/sh\nexit 0\n").unwrap();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let env = EffectiveChildEnv::for_tests([("PATH", bin.as_os_str())]);+ (temp, env)+ }++ #[cfg(unix)]+ #[test]+ fn claude_spelling_defaults_the_executable_to_the_matching_wrapper() {+ let (_temp, env) = path_with_fake_executables(&["claude", "claude-glm"]);+ let mut executable = None;+ default_claude_wrapper(+ &mut executable,+ Some(RunHarnessChoice::Claude),+ Some("claude-glm"),+ env.executable_search(),+ );+ assert_eq!(executable, Some(OsString::from("claude-glm")));+ }++ #[cfg(unix)]+ #[test]+ fn claude_spelling_without_a_wrapper_warns_and_keeps_plain_claude() {+ let (_temp, env) = path_with_fake_executables(&["claude"]);+ let search = env.executable_search();+ let warning = claude_wrapper_executable("claude-glm", search).unwrap_err();+ assert!(warning.contains("`claude-glm`"), "{warning}");+ assert!(warning.contains("plain `claude`"), "{warning}");+ assert!(warning.contains("--executable"), "{warning}");++ let mut executable = None;+ default_claude_wrapper(+ &mut executable,+ Some(RunHarnessChoice::Claude),+ Some("claude-glm"),+ search,+ );+ assert_eq!(executable, None);+ }++ #[cfg(unix)]+ #[test]+ fn explicit_executable_beats_the_claude_spelling() {+ let (_temp, env) = path_with_fake_executables(&["claude-glm", "claude-other"]);+ let mut executable = Some(OsString::from("claude-other"));+ default_claude_wrapper(+ &mut executable,+ Some(RunHarnessChoice::Claude),+ Some("claude-glm"),+ env.executable_search(),+ );+ assert_eq!(executable, Some(OsString::from("claude-other")));+ }++ #[cfg(unix)]+ #[test]+ fn claude_wrapper_lookup_accepts_bare_names_only() {+ let (_temp, env) = path_with_fake_executables(&["claude-glm"]);+ let search = env.executable_search();+ assert!(claude_wrapper_executable("claude-glm", search).is_ok());+ assert!(claude_wrapper_executable("claude-glm2", search).is_err());+ // A path-like spelling is never resolved relative to anything.+ assert!(claude_wrapper_executable("./claude-glm", search).is_err());+ assert!(claude_wrapper_executable("../bin/claude-glm", search).is_err());+ }++ #[cfg(unix)]+ #[test]+ fn other_harnesses_and_bare_claude_never_get_a_wrapper() {+ let (_temp, env) = path_with_fake_executables(&["claude-glm", "codex"]);+ let search = env.executable_search();+ for (requested, spelling) in [+ (Some(RunHarnessChoice::Codex), Some("claude-glm")),+ (Some(RunHarnessChoice::Claude), None),+ (None, Some("claude-glm")),+ ] {+ let mut executable = None;+ default_claude_wrapper(&mut executable, requested, spelling, search);+ assert_eq!(executable, None, "{requested:?} {spelling:?}");+ }+ }++ #[test]+ fn switching_harness_drops_the_claude_wrapper_but_rerun_keeps_it() {+ let outcome = RunOutcome {+ exit_code: 0,+ harness: ManagedHarness::Claude,+ interactive_session: true,+ mode: LaunchMode::Session,+ workstream_name: "ws".into(),+ degraded: false,+ };+ let mut args = run_args_for_after_run_test();+ args.claude_wrapper = Some("claude-glm".into());+ assert!(apply_after_run_action(+ &mut args,+ &outcome,+ AfterRunAction::Rerun+ ));+ assert_eq!(args.claude_wrapper.as_deref(), Some("claude-glm"));+ assert!(apply_after_run_action(+ &mut args,+ &outcome,+ AfterRunAction::Switch(RunHarnessChoice::Codex)+ ));+ assert_eq!(args.claude_wrapper, None);+ }+#[test]fn resolved_run_env_overlays_windows_keys_case_insensitively() {let mut entries = vec![("Path".to_string(), "C:\\base".to_string())];@@ -6868,6 +7033,7 @@ mod tests {env: Vec::new(),env_file: None,harness: Some(RunHarnessChoice::Claude),+ claude_wrapper: None,native_args: Vec::new(),};@@ -7214,6 +7380,7 @@ mod tests {env: vec![("CLAUDE_CONFIG_DIR".to_string(), "/from/cli".to_string())],env_file: Some(env_file.clone()),harness: Some(RunHarnessChoice::Claude),+ claude_wrapper: None,native_args: vec![OsString::from("--version")],};@@ -7320,6 +7487,7 @@ mod tests {env: Vec::new(),env_file: None,harness: Some(RunHarnessChoice::Claude),+ claude_wrapper: None,native_args: Vec::new(),};(temp, config, args)@@ -7816,6 +7984,7 @@ mod tests {)],env_file: None,harness: Some(RunHarnessChoice::Claude),+ claude_wrapper: None,native_args: Vec::new(),};@@ -8573,6 +8742,7 @@ mod tests {],env_file: None,harness: Some(RunHarnessChoice::OpenCode),+ claude_wrapper: None,native_args: vec![OsString::from("--help")],};@@ -8699,6 +8869,7 @@ mod tests {env: Vec::new(),env_file: None,harness: Some(RunHarnessChoice::Claude),+ claude_wrapper: None,native_args: vec![OsString::from("--version")],};@@ -8983,6 +9154,7 @@ mod tests {env,env_file: None,harness: Some(harness),+ claude_wrapper: None,native_args: native_args.iter().map(OsString::from).collect(),}}diff --git a/crates/ai-memory-cli/src/commands/show.rs b/crates/ai-memory-cli/src/commands/show.rsindex ba960c75..0b2c6774 100644--- a/crates/ai-memory-cli/src/commands/show.rs+++ b/crates/ai-memory-cli/src/commands/show.rs@@ -246,6 +246,7 @@ pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {env: Vec::new(),env_file: None,harness: Some(harness),+ claude_wrapper: None,native_args: args.native_args,},&target,diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex ebd242e1..616aa7b7 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -66,21 +66,26 @@ ai-memory run --profile work omp --profile omp-workstarting with `claude` is accepted (`claude-corp`, `claude-personal`, ...)and always selects the Claude harness. The exact spelling never changesthe agent kind, session store, or transcript import.-Combine that wildcard with `--executable` to launch the right account's-binary while keeping each account's managed workstream distinguishable in-your shell history:+A `claude*` name other than plain `claude` and `claude-code` also picks the+binary: when no `--executable` is given and an executable with exactly that+name is on the launch `PATH` (including a `PATH` set with `--env`), `run`+launches it. Per-account wrapper scripts therefore work without repeating+yourself:```bash# ~/bin/claude-corp and ~/bin/claude-personal are wrapper scripts (earlier on# PATH than the bare `claude`) that each exec the real claude binary with# that account's config/credentials directory.-ai-memory run claude-corp --executable claude-corp --model opus-ai-memory run claude-personal --executable claude-personal+ai-memory run claude-corp --model opus+ai-memory run claude-personal```-Only the `--executable` value matters for which binary actually runs; the-positional name is free-form as long as it starts with `claude`, so pick-whatever reads clearly to you.+If no executable with that name exists, `run` prints a warning on stderr and+starts plain `claude`, so a mistyped or missing wrapper cannot silently put you+on the wrong account. An explicit `--executable` always wins, and `claude` and+`claude-code` always mean the plain `claude` binary. The name must be a bare+command name found through `PATH` (a shell alias or function is invisible+here); to use a binary elsewhere, pass `--executable <path>`.```bashcd /path/to/project