Skip to content

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

Rust

Add --env/--env-file pass-through to `ai-memory run` (#820)

AkitaOnRails5bdc20654366
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2cb16039..a5bf2bb7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- `ai-memory run` accepts a repeatable `--env KEY=VALUE` and an `--env-file
+ <path>` (blank lines and `#` comments skipped) to pass extra environment
+ into the spawned harness — e.g. a per-account `CLAUDE_CONFIG_DIR` for
+ callers who previously had to wrap the launch in `env KEY=VAL harness`.
+ Both flags are wrapper-owned like `--yolo`/`--executable` and must precede
+ the harness name; a `--env` entry overrides a same-key `--env-file` line.
+ The resolved environment reaches both the spawned process and ai-memory's
+ own native-session resolution, so the two agree on where a
+ `CLAUDE_CONFIG_DIR`-style override points the session store. See
+ `docs/managed-workstreams.md`. (#820)
- Fedora users can install prebuilt x86_64 and aarch64 RPMs from GitHub
Releases, with the existing native systemd service assets. (#858)
- `embedding_query_prefix` / `embedding_document_prefix` config keys (env:
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index bdefdff8..94eb1d9f 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -261,6 +261,19 @@ pub struct RunArgs {
/// `AI_MEMORY_RUN_AUTOWIRE=false`) to launch without touching harness config.
#[arg(long)]
pub no_autowire: bool,
+ /// Extra environment variable for the spawned harness, `KEY=VALUE`.
+ /// Repeatable; wrapper-owned like `--yolo`/`--executable`, so it must
+ /// precede `harness`. Reaches both the spawned process and ai-memory's own
+ /// native-session resolution (e.g. `CLAUDE_CONFIG_DIR`), so the two agree
+ /// on where the harness's session lives. A later `--env` wins over an
+ /// earlier one and over a same-key `--env-file` entry.
+ #[arg(long = "env", value_parser = parse_env_kv, value_name = "KEY=VALUE")]
+ pub env: Vec<(String, String)>,
+ /// Read `KEY=VALUE` lines from this file (blank lines and `#` comments
+ /// skipped) and merge them into the spawned harness's environment before
+ /// `--env` entries, which override a same-key line here.
+ #[arg(long = "env-file", value_name = "PATH")]
+ pub env_file: Option<PathBuf>,
/// 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
@@ -351,6 +364,23 @@ fn parse_run_harness_choice(value: &str) -> Result<RunHarnessChoice, String> {
))
}
+/// 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.
+pub(crate) fn parse_env_kv(value: &str) -> Result<(String, String), String> {
+ let Some((key, value)) = value.split_once('=') else {
+ return Err(format!(
+ "invalid value '{value}' for --env; expected KEY=VALUE"
+ ));
+ };
+ if key.is_empty() {
+ return Err(format!(
+ "invalid value '{key}={value}' for --env; KEY must not be empty"
+ ));
+ }
+ Ok((key.to_string(), value.to_string()))
+}
+
/// Arguments for `show`.
#[derive(Debug, Args)]
pub struct ShowArgs {
@@ -3212,6 +3242,88 @@ mod tests {
);
}
+ #[test]
+ fn run_env_flag_parses_repeatable_key_value_pairs() {
+ let cli = Cli::try_parse_from([
+ "ai-memory",
+ "run",
+ "--env",
+ "CLAUDE_CONFIG_DIR=/accounts/work",
+ "--env",
+ "FOO=bar=baz",
+ "claude",
+ ])
+ .expect("valid --env pairs parse");
+ let Command::Run(args) = cli.command else {
+ panic!("expected run command");
+ };
+ assert_eq!(
+ args.env,
+ vec![
+ (
+ "CLAUDE_CONFIG_DIR".to_string(),
+ "/accounts/work".to_string()
+ ),
+ ("FOO".to_string(), "bar=baz".to_string()),
+ ]
+ );
+ }
+
+ #[test]
+ fn run_env_flag_rejects_a_pair_without_equals() {
+ let error = Cli::try_parse_from(["ai-memory", "run", "--env", "NOEQUALS", "claude"])
+ .expect_err("a value without '=' must be rejected");
+ assert!(
+ error.to_string().contains("expected KEY=VALUE"),
+ "unexpected error: {error}"
+ );
+ }
+
+ #[test]
+ fn run_env_flag_rejects_an_empty_key() {
+ let error = Cli::try_parse_from(["ai-memory", "run", "--env", "=value", "claude"])
+ .expect_err("an empty key must be rejected");
+ assert!(
+ error.to_string().contains("KEY must not be empty"),
+ "unexpected error: {error}"
+ );
+ }
+
+ #[test]
+ fn run_env_file_flag_parses_as_a_path() {
+ let cli = Cli::try_parse_from([
+ "ai-memory",
+ "run",
+ "--env-file",
+ "/tmp/ai-memory-env-example.env",
+ "claude",
+ ])
+ .expect("--env-file parses");
+ let Command::Run(args) = cli.command else {
+ panic!("expected run command");
+ };
+ assert_eq!(
+ args.env_file,
+ Some(PathBuf::from("/tmp/ai-memory-env-example.env"))
+ );
+ }
+
+ #[test]
+ fn parse_env_kv_accepts_pairs_and_rejects_malformed_entries() {
+ assert_eq!(
+ parse_env_kv("KEY=VALUE"),
+ Ok(("KEY".to_string(), "VALUE".to_string()))
+ );
+ // The value is taken literally, including any further '=' signs.
+ assert_eq!(
+ parse_env_kv("KEY=a=b=c"),
+ Ok(("KEY".to_string(), "a=b=c".to_string()))
+ );
+ assert_eq!(parse_env_kv("KEY="), Ok(("KEY".to_string(), String::new())));
+ assert!(parse_env_kv("NOEQUALS").is_err());
+ assert!(parse_env_kv("=value").is_err());
+ }
+
#[test]
fn devin_hook_agent_parses() {
let hook_cli = Cli::try_parse_from([
diff --git a/crates/ai-memory-cli/src/commands/continue_session.rs b/crates/ai-memory-cli/src/commands/continue_session.rs
index 61475d27..5c31da92 100644
--- a/crates/ai-memory-cli/src/commands/continue_session.rs
+++ b/crates/ai-memory-cli/src/commands/continue_session.rs
@@ -74,6 +74,8 @@ pub async fn run(config: &Config, args: ContinueArgs) -> Result<i32> {
yolo: args.yolo,
fresh: args.fresh,
no_autowire: false,
+ env: Vec::new(),
+ env_file: None,
// Bare mode: `run` resolves the harness that owns the newest
// usable session for this workstream.
harness: None,
diff --git a/crates/ai-memory-cli/src/commands/resume.rs b/crates/ai-memory-cli/src/commands/resume.rs
index c75bcaf8..ba9b1c25 100644
--- a/crates/ai-memory-cli/src/commands/resume.rs
+++ b/crates/ai-memory-cli/src/commands/resume.rs
@@ -163,6 +163,8 @@ pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {
yolo: args.yolo,
fresh: args.fresh,
no_autowire: false,
+ env: Vec::new(),
+ env_file: None,
harness,
native_args: Vec::new(),
},
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index 1e1edbc2..34cd1b9c 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -13,11 +13,11 @@ use ai_memory_core::{
};
use ai_memory_workstream::{
ExportedTranscript, LaunchMode, LaunchPlan, ManagedHarness, NativeSessionCandidate,
- allows_native_session_adoption, apply_yolo, build_launch_plan, discover_native_session,
- export_transcript, has_native_session_selector, inspect_repository, kiro_explicit_session_id,
- kiro_harness_from_source_cursor, kiro_selects_non_default_engine, kiro_selects_v2_engine,
- kiro_selects_v3_engine, kiro_v3_resume_uses_default_store, list_native_sessions,
- native_session_exists, wait_for_transcript_flush,
+ allows_native_session_adoption, apply_yolo, build_launch_plan, build_launch_plan_with_env,
+ discover_native_session, export_transcript, has_native_session_selector, inspect_repository,
+ kiro_explicit_session_id, kiro_harness_from_source_cursor, kiro_selects_non_default_engine,
+ kiro_selects_v2_engine, kiro_selects_v3_engine, kiro_v3_resume_uses_default_store,
+ list_native_sessions, native_session_exists, wait_for_transcript_flush,
};
use anyhow::{Context as _, Result, anyhow};
use tokio::process::Command;
@@ -116,6 +116,8 @@ pub(super) async fn run_from_with_wiring(
let trailing_no_autowire = remove_wrapper_no_autowire(&mut native_args);
let force_fresh = args.fresh || trailing_fresh;
let no_autowire = args.no_autowire || trailing_no_autowire;
+ let run_env = resolve_run_env(args.env_file.as_deref(), &args.env)
+ .context("resolving --env/--env-file for the managed run")?;
if automatic_harness && !native_args.is_empty() {
return Err(anyhow!(
"native harness arguments require an explicit harness; try `ai-memory run codex ...`"
@@ -256,6 +258,7 @@ pub(super) async fn run_from_with_wiring(
force_fresh,
&home,
&repository.cwd,
+ &run_env,
));
if let Some(orphaned_session) = orphaned_session {
eprintln!(
@@ -282,11 +285,12 @@ pub(super) async fn run_from_with_wiring(
.find(|candidate| candidate.harness == harness)
.context("the selected automatic harness no longer has a checkout-local session")
);
- plan = acquired_try!(build_launch_plan(
+ plan = acquired_try!(build_launch_plan_with_env(
harness,
executable.clone(),
native_args.clone(),
Some(&candidate.session.native_session_id),
+ &run_env,
));
eprintln!(
"ai-memory: continuing newest checkout-local {} session {}",
@@ -324,11 +328,12 @@ pub(super) async fn run_from_with_wiring(
);
match selection {
Ok(Some(native_session_id)) => {
- plan = acquired_try!(build_launch_plan(
+ plan = acquired_try!(build_launch_plan_with_env(
harness,
executable,
native_args,
Some(&native_session_id),
+ &run_env,
));
}
Ok(None) => {}
@@ -430,9 +435,13 @@ pub(super) async fn run_from_with_wiring(
// unresolvable program reaching the spawn error below, which explains it.
let program = resolve_program(&plan.program).unwrap_or_else(|| plan.program.clone().into());
let mut command = Command::new(&program);
+ command.args(&plan.args).current_dir(&repository.cwd);
+ // Caller-supplied `--env`/`--env-file` entries go first so the fixed
+ // AI_MEMORY_* plumbing below always wins on a key collision.
+ for (key, value) in &run_env {
+ command.env(key, value);
+ }
command
- .args(&plan.args)
- .current_dir(&repository.cwd)
.env("AI_MEMORY_RUN_ID", prepared.run_id.to_string())
.env(
"AI_MEMORY_WORKSTREAM_ID",
@@ -817,6 +826,48 @@ fn remove_wrapper_no_autowire(args: &mut Vec<OsString>) -> bool {
args.len() != before
}
+/// Merge `--env-file` lines with `--env` entries into the final key/value
+/// list applied to the spawned harness, preserving file order but letting a
+/// `--env` entry override a same-key `--env-file` line. Values are taken
+/// literally; neither source is expanded or interpreted.
+fn resolve_run_env(
+ env_file: Option<&Path>,
+ env_args: &[(String, String)],
+) -> Result<Vec<(String, String)>> {
+ let mut merged: Vec<(String, String)> = Vec::new();
+ if let Some(path) = env_file {
+ let contents = std::fs::read_to_string(path)
+ .with_context(|| format!("reading --env-file {}", path.display()))?;
+ for (line_number, line) in contents.lines().enumerate() {
+ let trimmed = line.trim();
+ if trimmed.is_empty() || trimmed.starts_with('#') {
+ continue;
+ }
+ let (key, value) = crate::cli::parse_env_kv(trimmed)
+ .map_err(|error| anyhow!("{}:{}: {error}", path.display(), line_number + 1))?;
+ upsert_env(&mut merged, key, value);
+ }
+ }
+ for (key, value) in env_args {
+ upsert_env(&mut merged, key.clone(), value.clone());
+ }
+ Ok(merged)
+}
+
+/// Insert or replace one entry in an ordered env list, keeping the position
+/// of an existing key so `--env-file` order stays stable across overrides.
+fn upsert_env(entries: &mut Vec<(String, String)>, key: String, value: String) {
+ if let Some(existing) = entries
+ .iter_mut()
+ .find(|(existing_key, _)| *existing_key == key)
+ {
+ existing.1 = value;
+ } else {
+ entries.push((key, value));
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
fn build_preflighted_launch_plan(
harness: ManagedHarness,
executable: Option<OsString>,
@@ -825,6 +876,7 @@ fn build_preflighted_launch_plan(
force_fresh: bool,
home: &Path,
cwd: &Path,
+ env_overrides: &[(String, String)],
) -> Result<(LaunchPlan, Option<String>)> {
let explicit_selector = has_native_session_selector(harness, &native_args);
if force_fresh && explicit_selector {
@@ -833,11 +885,12 @@ fn build_preflighted_launch_plan(
));
}
let linked_session_id = if force_fresh { None } else { linked_session_id };
- let plan = build_launch_plan(
+ let plan = build_launch_plan_with_env(
harness,
executable.clone(),
native_args.clone(),
linked_session_id,
+ env_overrides,
)?;
let Some(linked_session_id) = linked_session_id else {
return Ok((plan, None));
@@ -854,7 +907,7 @@ fn build_preflighted_launch_plan(
) {
Ok(true) => Ok((plan, None)),
Ok(false) => Ok((
- build_launch_plan(harness, executable, native_args, None)?,
+ build_launch_plan_with_env(harness, executable, native_args, None, env_overrides)?,
Some(linked_session_id.to_string()),
)),
Err(error) => {
@@ -2130,6 +2183,7 @@ mod tests {
false,
temp.path(),
&cwd,
+ &[],
)
.unwrap();
assert_eq!(
@@ -2193,6 +2247,164 @@ mod tests {
assert_eq!(trailing, ["--model", "opus"].map(OsString::from));
}
+ #[test]
+ fn resolve_run_env_merges_file_then_overrides_with_cli_pairs() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("vars.env");
+ std::fs::write(&path, "# a comment\n\n \nFOO=from-file\nBAR=keep\n").unwrap();
+
+ let cli_pairs = vec![("FOO".to_string(), "from-cli".to_string())];
+ let merged = resolve_run_env(Some(&path), &cli_pairs).unwrap();
+
+ assert_eq!(
+ merged,
+ vec![
+ ("FOO".to_string(), "from-cli".to_string()),
+ ("BAR".to_string(), "keep".to_string()),
+ ]
+ );
+ }
+
+ #[test]
+ fn resolve_run_env_without_a_file_returns_only_cli_pairs() {
+ let cli_pairs = vec![("A".to_string(), "1".to_string())];
+ let merged = resolve_run_env(None, &cli_pairs).unwrap();
+ assert_eq!(merged, vec![("A".to_string(), "1".to_string())]);
+ }
+
+ #[test]
+ fn resolve_run_env_rejects_a_malformed_env_file_line() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("bad.env");
+ std::fs::write(&path, "NOVALUE\n").unwrap();
+ let error = resolve_run_env(Some(&path), &[]).unwrap_err();
+ assert!(
+ error.to_string().contains("expected KEY=VALUE"),
+ "unexpected error: {error}"
+ );
+ }
+
+ #[test]
+ fn build_launch_plan_with_env_overrides_reach_native_session_resolution() {
+ // The same override list is what `run.rs` also applies to the spawned
+ // child's `Command`; proving it steers `session_dir` here proves
+ // ai-memory's own native-session resolution and the harness process
+ // agree on a caller-supplied `CLAUDE_CONFIG_DIR`, per the docs note
+ // this closes (#820).
+ let overrides = vec![(
+ "CLAUDE_CONFIG_DIR".to_string(),
+ "/accounts/work".to_string(),
+ )];
+ let plan =
+ build_launch_plan_with_env(ManagedHarness::Claude, None, Vec::new(), None, &overrides)
+ .unwrap();
+ assert_eq!(
+ plan.session_dir.as_deref(),
+ Some(Path::new("/accounts/work/projects"))
+ );
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn run_env_reaches_the_spawned_child_and_overrides_env_file() {
+ use std::os::unix::fs::PermissionsExt as _;
+
+ use crate::commands::run_autowire::WireOverrides;
+ use crate::config::Config;
+
+ let app = Router::new()
+ .route(
+ "/workstream/runs",
+ post(|| async {
+ axum::Json(PrepareManagedRunResponse {
+ workstream_id: WorkstreamId::new(),
+ workstream_name: "default".into(),
+ run_id: ManagedRunId::new(),
+ resolved_agent: None,
+ native_session_id: None,
+ source_cursor: None,
+ sync_after: 0,
+ sync_through: 0,
+ may_adopt_existing_session: false,
+ })
+ }),
+ )
+ .route(
+ "/workstream/runs/{run_id}/finish",
+ post(|| async {
+ axum::Json(FinishManagedRunResponse {
+ imported_events: 0,
+ latest_sequence: 0,
+ })
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+
+ let home = tempfile::tempdir().unwrap();
+ let data = tempfile::tempdir().unwrap();
+ let repo = tempfile::tempdir().unwrap();
+
+ let captured = repo.path().join("captured-env");
+ let script = repo.path().join("capture-env-harness");
+ std::fs::write(
+ &script,
+ format!(
+ "#!/bin/sh\nprintf 'FOO=%s\\nCLAUDE_CONFIG_DIR=%s\\n' \"$FOO\" \"$CLAUDE_CONFIG_DIR\" > {}\nexit 0\n",
+ captured.display()
+ ),
+ )
+ .unwrap();
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ let env_file = repo.path().join("run.env");
+ std::fs::write(
+ &env_file,
+ "# comment\n\nFOO=from-file\nCLAUDE_CONFIG_DIR=/from/file\n",
+ )
+ .unwrap();
+
+ let mut config = Config::load(None, Some(home.path().to_path_buf())).unwrap();
+ config.data_dir = data.path().to_path_buf();
+ config.home_dir = Some(home.path().to_string_lossy().into_owned());
+ config.server_url = format!("http://{address}");
+ config.run_autowire = false;
+
+ let args = RunArgs {
+ workspace: Some("ws".into()),
+ project: Some("proj".into()),
+ workstream: None,
+ new_workstream: None,
+ executable: Some(script.clone()),
+ yolo: false,
+ fresh: false,
+ no_autowire: true,
+ env: vec![("CLAUDE_CONFIG_DIR".to_string(), "/from/cli".to_string())],
+ env_file: Some(env_file.clone()),
+ harness: Some(RunHarnessChoice::Claude),
+ native_args: vec![OsString::from("--version")],
+ };
+
+ let overrides = WireOverrides::default();
+ let exit = run_from_with_wiring(&config, args, repo.path(), &overrides)
+ .await
+ .expect("managed passthrough run completes");
+ assert_eq!(exit, 0, "the harmless child exits 0");
+
+ let captured_env = std::fs::read_to_string(&captured).unwrap();
+ assert!(
+ captured_env.contains("FOO=from-file"),
+ "an --env-file entry not overridden by --env must reach the spawned child: {captured_env}"
+ );
+ assert!(
+ captured_env.contains("CLAUDE_CONFIG_DIR=/from/cli"),
+ "--env must override a same-key --env-file entry for the spawned child: {captured_env}"
+ );
+
+ server.abort();
+ }
+
#[test]
fn missing_linked_session_starts_fresh_but_explicit_selectors_win() {
let temp = tempfile::tempdir().unwrap();
@@ -2223,6 +2435,7 @@ mod tests {
false,
temp.path(),
&cwd,
+ &[],
)
.unwrap();
assert!(orphaned.is_none());
@@ -2238,6 +2451,7 @@ mod tests {
false,
temp.path(),
&cwd,
+ &[],
)
.unwrap();
assert_eq!(orphaned.as_deref(), Some("linked"));
@@ -2256,6 +2470,7 @@ mod tests {
false,
temp.path(),
&cwd,
+ &[],
)
.unwrap();
assert!(orphaned.is_none());
@@ -2275,6 +2490,7 @@ mod tests {
true,
temp.path(),
&cwd,
+ &[],
)
.unwrap();
assert!(orphaned.is_none());
@@ -2289,6 +2505,7 @@ mod tests {
true,
temp.path(),
&cwd,
+ &[],
)
.unwrap_err();
assert!(error.to_string().contains("--fresh cannot be combined"));
@@ -2467,6 +2684,8 @@ mod tests {
yolo: false,
fresh: false,
no_autowire: false,
+ env: Vec::new(),
+ env_file: None,
harness: Some(RunHarnessChoice::Claude),
native_args: vec![OsString::from("--version")],
};
diff --git a/crates/ai-memory-cli/src/commands/show.rs b/crates/ai-memory-cli/src/commands/show.rs
index b3f921d8..a093c8c4 100644
--- a/crates/ai-memory-cli/src/commands/show.rs
+++ b/crates/ai-memory-cli/src/commands/show.rs
@@ -227,6 +227,8 @@ pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {
yolo: args.yolo,
fresh: args.fresh,
no_autowire: false,
+ env: Vec::new(),
+ env_file: None,
harness: Some(harness),
native_args: args.native_args,
},
diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rs
index 9af1ec17..4cff9451 100644
--- a/crates/ai-memory-workstream/src/harness.rs
+++ b/crates/ai-memory-workstream/src/harness.rs
@@ -202,6 +202,25 @@ pub fn build_launch_plan(
executable: Option<OsString>,
native_args: Vec<OsString>,
linked_session_id: Option<&str>,
+) -> Result<LaunchPlan> {
+ build_launch_plan_with_env(harness, executable, native_args, linked_session_id, &[])
+}
+
+/// [`build_launch_plan`] with `--env`/`--env-file` overrides layered in front
+/// of the real process environment for native session-store resolution
+/// (e.g. `CLAUDE_CONFIG_DIR`).
+///
+/// A launch's own environment overrides must be visible here, not only to the
+/// spawned child: `ai-memory run` resolves the native transcript root from
+/// this same variable, so a caller-scoped override that only reached the
+/// child process would make the two disagree about where the session lives
+/// (see the `CLAUDE_CONFIG_DIR` note in `docs/managed-workstreams.md`).
+pub fn build_launch_plan_with_env(
+ harness: ManagedHarness,
+ executable: Option<OsString>,
+ native_args: Vec<OsString>,
+ linked_session_id: Option<&str>,
+ env_overrides: &[(String, String)],
) -> Result<LaunchPlan> {
let program = executable.unwrap_or_else(|| OsString::from(harness.executable()));
let mut args = native_args;
@@ -210,7 +229,15 @@ pub fn build_launch_plan(
ManagedHarness::Crush => flag_path(&args, &["--data-dir", "-D"]),
_ => None,
}
- .or_else(|| environment_session_dir(harness));
+ .or_else(|| {
+ environment_session_dir_with(harness, |name| {
+ env_overrides
+ .iter()
+ .find(|(key, _)| key == name)
+ .map(|(_, value)| OsString::from(value))
+ .or_else(|| std::env::var_os(name))
+ })
+ });
let mut expected = explicit_session_id(harness, &args);
let mode = launch_mode(harness, &args);
if mode == LaunchMode::Session
@@ -890,10 +917,6 @@ fn flag_path(args: &[OsString], names: &[&str]) -> Option<PathBuf> {
None
}
-fn environment_session_dir(harness: ManagedHarness) -> Option<PathBuf> {
- environment_session_dir_with(harness, |name| std::env::var_os(name))
-}
-
fn environment_session_dir_with(
harness: ManagedHarness,
get: impl Fn(&str) -> Option<OsString>,
diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rs
index 8e3b3e23..90a6e154 100644
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@ -6,8 +6,9 @@ mod transcript;
pub use harness::{
LaunchMode, LaunchPlan, ManagedHarness, allows_native_session_adoption, apply_yolo,
- build_launch_plan, has_native_session_selector, kiro_explicit_session_id,
- kiro_selects_non_default_engine, kiro_selects_v2_engine, kiro_selects_v3_engine,
+ build_launch_plan, build_launch_plan_with_env, has_native_session_selector,
+ kiro_explicit_session_id, kiro_selects_non_default_engine, kiro_selects_v2_engine,
+ kiro_selects_v3_engine,
};
pub use repository::{RepositoryIdentity, inspect_repository};
pub use transcript::{
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index 0e90668e..d56cf600 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -84,7 +84,7 @@ file, and the current checkout remain authoritative.
```text
ai-memory run [--workspace NAME] [--project NAME]
[--workstream NAME | --new NAME] [--executable PATH]
- [--yolo] [--fresh]
+ [--yolo] [--fresh] [--env KEY=VALUE]... [--env-file PATH]
[claude|claude*|codex|opencode|opencode2|pi|crush|omp|kimi|command-code|kiro|grok|antigravity]
[native arguments...]
```
@@ -407,6 +407,17 @@ the two disagree and the native transcript import fails. When you use per-accoun
config directories, set the variable before invoking `ai-memory run` (or in the
same wrapper that also runs it), so hook installation and native-session
resolution agree.
+
+A repeatable `ai-memory run --env KEY=VALUE <harness>` (and `--env-file
+<path>`, one `KEY=VALUE` per line, blank lines and `#` comments skipped) is
+the first-class alternative to the `env KEY=VAL harness` wrapper-alias
+pattern above: it is a wrapper-owned flag, so it must precede the harness
+name, and the resolved environment reaches both the spawned harness process
+*and* `ai-memory run`'s own native-session resolution — the same
+`CLAUDE_CONFIG_DIR`-agreement requirement described above, satisfied without
+having to export the variable into the invoking shell first. A later `--env`
+overrides a same-key `--env-file` entry; neither expands nor interprets the
+value.
The Pi-family adapter
also recognizes a complete `.jsonl.<nonce>.tmp` atomic-write file when a native
process exits before renaming it; incomplete final JSONL records are never