Skip to content

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

Rust

feat(cli): offer post-run harness switching

dajiaohuangdd52c7554996
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 54083f34..2e02377b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- After an interactive managed `ai-memory run` session exits successfully, a
+ default-quit prompt can switch to another installed harness or re-run the
+ current one in the same workstream. The prompt is limited to terminal
+ session launches without `--executable`; utility, failed, interrupted, and
+ non-interactive runs keep their existing exit behavior. (#909)
- `[consolidation] input_token_safety_margin` (float, default `0.8`, validated
to `(0.0, 1.0]`) scales the approximate char-count input budget. The
`max_input_tokens` budget uses a flat chars-per-token heuristic that
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 20c3ada9..ea6123bf 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -256,7 +256,7 @@ pub enum Command {
/// Arguments for `run`. Wrapper-owned flags must precede `harness`; the
/// trailing native argv is deliberately opaque to clap.
-#[derive(Debug, Args)]
+#[derive(Debug, Clone, Args)]
#[command(trailing_var_arg = true)]
pub struct RunArgs {
/// Workspace containing the managed workstream. Defaults to the nearest
@@ -315,7 +315,7 @@ pub struct RunArgs {
}
/// Harnesses supported by managed workstreams.
-#[derive(Debug, Clone, Copy, clap::ValueEnum)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum RunHarnessChoice {
/// Anthropic Claude Code (`claude`). Any `claude*`-prefixed name (e.g.
/// `claude-corp`, `claude-personal`) also selects this harness — see
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index 2e4c3984..897c2f1d 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -16,10 +16,11 @@ use ai_memory_workstream::{
ManagedHarness, NativeSessionCandidate, allows_native_session_adoption, apply_yolo,
build_launch_plan, build_launch_plan_with_env, crush_global_config_path,
discover_native_session, export_transcript, has_native_session_selector, inspect_repository,
- kiro_explicit_session_id, kiro_harness_from_source_cursor, kiro_selects_non_default_engine,
- kiro_selects_v2_engine, kiro_selects_v3_engine, kiro_v3_resume_uses_default_store,
- list_native_sessions, native_session_exists, native_session_in_checkout, omp_profile_flag,
- omp_profile_flag_env, store_override_vars, wait_for_transcript_flush,
+ is_interactive_session_invocation, 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, omp_profile_flag, omp_profile_flag_env, store_override_vars,
+ wait_for_transcript_flush,
};
use anyhow::{Context as _, Result, anyhow};
use tokio::process::Command;
@@ -79,7 +80,7 @@ impl HeartbeatHealth {
/// Run one native harness and return its exact process exit code.
pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {
let cwd = std::env::current_dir().context("getting managed run working directory")?;
- run_from(config, args, &cwd).await
+ run_with_exit_prompt(config, args, &cwd).await
}
/// Run one native harness from an explicit checkout without changing the
@@ -108,6 +109,212 @@ pub(super) async fn run_from_with_wiring(
cwd: &Path,
wire_overrides: &super::run_autowire::WireOverrides,
) -> Result<i32> {
+ run_once_with_wiring(config, args, cwd, wire_overrides)
+ .await
+ .map(|outcome| outcome.exit_code)
+}
+
+#[derive(Debug)]
+struct RunOutcome {
+ exit_code: i32,
+ harness: ManagedHarness,
+ interactive_session: bool,
+ mode: LaunchMode,
+ workstream_name: String,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum AfterRunAction {
+ Switch(RunHarnessChoice),
+ Rerun,
+ Quit,
+}
+
+const RUN_HARNESS_CHOICES: [RunHarnessChoice; 12] = [
+ RunHarnessChoice::Claude,
+ RunHarnessChoice::Codex,
+ RunHarnessChoice::OpenCode,
+ RunHarnessChoice::OpenCode2,
+ RunHarnessChoice::Pi,
+ RunHarnessChoice::Crush,
+ RunHarnessChoice::Omp,
+ RunHarnessChoice::Kimi,
+ RunHarnessChoice::CommandCode,
+ RunHarnessChoice::Kiro,
+ RunHarnessChoice::Grok,
+ RunHarnessChoice::Antigravity,
+];
+
+async fn run_with_exit_prompt(config: &Config, args: RunArgs, cwd: &Path) -> Result<i32> {
+ let interactive_terminal =
+ io::stdin().is_terminal() && io::stdout().is_terminal() && io::stderr().is_terminal();
+ let custom_executable = args.executable.is_some();
+ let mut next_args = args;
+ preserve_trailing_run_options(&mut next_args);
+
+ loop {
+ let outcome = run_once_with_wiring(
+ config,
+ next_args.clone(),
+ cwd,
+ &super::run_autowire::WireOverrides::default(),
+ )
+ .await?;
+ if !should_offer_after_run(&outcome, interactive_terminal, custom_executable) {
+ return Ok(outcome.exit_code);
+ }
+
+ let available = available_switch_harnesses(outcome.harness);
+ let action = {
+ let stdin = io::stdin();
+ let stderr = io::stderr();
+ choose_after_run(
+ outcome.harness,
+ &outcome.workstream_name,
+ &available,
+ &mut stdin.lock(),
+ &mut stderr.lock(),
+ )
+ };
+ let action = match action {
+ Ok(action) => action,
+ Err(error) => {
+ eprintln!("ai-memory: could not read the post-run choice ({error}); exiting");
+ return Ok(outcome.exit_code);
+ }
+ };
+ if !apply_after_run_action(&mut next_args, &outcome, action) {
+ return Ok(outcome.exit_code);
+ }
+ }
+}
+
+fn should_offer_after_run(
+ outcome: &RunOutcome,
+ interactive_terminal: bool,
+ custom_executable: bool,
+) -> bool {
+ outcome.exit_code == 0
+ && outcome.mode == LaunchMode::Session
+ && outcome.interactive_session
+ && interactive_terminal
+ && !custom_executable
+}
+
+fn preserve_trailing_run_options(args: &mut RunArgs) {
+ args.yolo |= args
+ .native_args
+ .iter()
+ .any(|arg| arg == OsStr::new("--yolo"));
+ args.no_autowire |= args
+ .native_args
+ .iter()
+ .any(|arg| arg == OsStr::new("--no-autowire"));
+}
+
+fn available_switch_harnesses(current: ManagedHarness) -> Vec<RunHarnessChoice> {
+ RUN_HARNESS_CHOICES
+ .into_iter()
+ .filter(|choice| {
+ managed_harness(*choice).agent_kind() != current.agent_kind()
+ && harness_available(*choice)
+ })
+ .collect()
+}
+
+fn choose_after_run(
+ current: ManagedHarness,
+ workstream_name: &str,
+ available: &[RunHarnessChoice],
+ input: &mut impl io::BufRead,
+ output: &mut impl io::Write,
+) -> io::Result<AfterRunAction> {
+ writeln!(
+ output,
+ "ai-memory: {} exited successfully in workstream '{}'.",
+ current.as_str(),
+ workstream_name
+ )?;
+ for (index, choice) in available.iter().enumerate() {
+ writeln!(
+ output,
+ " {}) switch to {}",
+ index + 1,
+ managed_harness(*choice).as_str()
+ )?;
+ }
+ writeln!(output, " r) run {} again", current.as_str())?;
+ writeln!(output, " q) quit (default)")?;
+
+ loop {
+ write!(output, "Select [q]: ")?;
+ output.flush()?;
+ let mut line = String::new();
+ if input.read_line(&mut line)? == 0 {
+ return Ok(AfterRunAction::Quit);
+ }
+ let choice = line.trim();
+ if choice.is_empty() || choice.eq_ignore_ascii_case("q") || choice == "0" {
+ return Ok(AfterRunAction::Quit);
+ }
+ if choice.eq_ignore_ascii_case("r") {
+ return Ok(AfterRunAction::Rerun);
+ }
+ if let Ok(index) = choice.parse::<usize>()
+ && let Some(harness) = index.checked_sub(1).and_then(|i| available.get(i))
+ {
+ return Ok(AfterRunAction::Switch(*harness));
+ }
+ writeln!(output, "Choose a listed number, r, or q.")?;
+ }
+}
+
+fn apply_after_run_action(
+ args: &mut RunArgs,
+ outcome: &RunOutcome,
+ action: AfterRunAction,
+) -> bool {
+ let choice = match action {
+ AfterRunAction::Quit => return false,
+ AfterRunAction::Switch(choice) => choice,
+ AfterRunAction::Rerun => run_harness_choice(outcome.harness),
+ };
+ args.harness = Some(choice);
+ args.native_args =
+ if action == AfterRunAction::Rerun && outcome.harness == ManagedHarness::KiroV3 {
+ vec![OsString::from("--v3")]
+ } else {
+ Vec::new()
+ };
+ args.workstream = Some(outcome.workstream_name.clone());
+ args.new_workstream = None;
+ args.fresh = false;
+ true
+}
+
+const fn run_harness_choice(harness: ManagedHarness) -> RunHarnessChoice {
+ match harness {
+ ManagedHarness::Claude => RunHarnessChoice::Claude,
+ ManagedHarness::Codex => RunHarnessChoice::Codex,
+ ManagedHarness::OpenCode => RunHarnessChoice::OpenCode,
+ ManagedHarness::OpenCode2 => RunHarnessChoice::OpenCode2,
+ ManagedHarness::Pi => RunHarnessChoice::Pi,
+ ManagedHarness::Crush => RunHarnessChoice::Crush,
+ ManagedHarness::Omp => RunHarnessChoice::Omp,
+ ManagedHarness::Kimi => RunHarnessChoice::Kimi,
+ ManagedHarness::CommandCode => RunHarnessChoice::CommandCode,
+ ManagedHarness::Kiro | ManagedHarness::KiroV3 => RunHarnessChoice::Kiro,
+ ManagedHarness::Grok => RunHarnessChoice::Grok,
+ ManagedHarness::Antigravity => RunHarnessChoice::Antigravity,
+ }
+}
+
+async fn run_once_with_wiring(
+ config: &Config,
+ args: RunArgs,
+ cwd: &Path,
+ wire_overrides: &super::run_autowire::WireOverrides,
+) -> Result<RunOutcome> {
let repository = inspect_repository(cwd)?;
let home = native_home(config).context("locating native harness session storage")?;
let automatic_harness = args.harness.is_none();
@@ -253,6 +460,7 @@ pub(super) async fn run_from_with_wiring(
&repository.cwd,
&run_env,
));
+ let interactive_session = is_interactive_session_invocation(harness, &native_args);
if let Some(orphaned_session) = orphaned_session {
eprintln!(
"ai-memory: linked {} session {} is missing from its native store; starting fresh and repointing workstream '{}' after the new session is established",
@@ -621,7 +829,13 @@ pub(super) async fn run_from_with_wiring(
prepared.workstream_name
);
interrupt_task.abort();
- Ok(exit_code)
+ Ok(RunOutcome {
+ exit_code,
+ harness,
+ interactive_session,
+ mode: plan.mode,
+ workstream_name: prepared.workstream_name,
+ })
}
async fn capture_interrupts(interrupted: CancellationToken) {
@@ -1694,6 +1908,142 @@ mod tests {
use super::*;
use crate::cli::{Cli, Command as CliCommand};
+ fn run_args_for_after_run_test() -> RunArgs {
+ RunArgs {
+ workspace: Some("work".into()),
+ project: Some("repo".into()),
+ workstream: None,
+ new_workstream: Some("initial".into()),
+ executable: None,
+ yolo: true,
+ fresh: true,
+ no_autowire: true,
+ env: vec![("MODEL_HOME".into(), "custom".into())],
+ env_file: None,
+ harness: Some(RunHarnessChoice::Claude),
+ native_args: vec![OsString::from("--model"), OsString::from("opus")],
+ }
+ }
+
+ #[test]
+ fn post_run_choice_defaults_to_quit_and_lists_same_workstream_actions() {
+ let mut input = Cursor::new(b"\n");
+ let mut output = Vec::new();
+ let action = choose_after_run(
+ ManagedHarness::Claude,
+ "research",
+ &[RunHarnessChoice::Codex],
+ &mut input,
+ &mut output,
+ )
+ .unwrap();
+
+ assert_eq!(action, AfterRunAction::Quit);
+ let output = String::from_utf8(output).unwrap();
+ assert!(output.contains("workstream 'research'"));
+ assert!(output.contains("1) switch to codex"));
+ assert!(output.contains("r) run claude again"));
+ assert!(output.contains("q) quit (default)"));
+ }
+
+ #[test]
+ fn post_run_choice_selects_an_installed_harness_by_number() {
+ let mut input = Cursor::new(b"1\n");
+ let mut output = Vec::new();
+ assert_eq!(
+ choose_after_run(
+ ManagedHarness::Claude,
+ "research",
+ &[RunHarnessChoice::Codex],
+ &mut input,
+ &mut output,
+ )
+ .unwrap(),
+ AfterRunAction::Switch(RunHarnessChoice::Codex)
+ );
+ }
+
+ #[test]
+ fn trailing_wrapper_options_survive_the_post_run_menu() {
+ let mut args = run_args_for_after_run_test();
+ args.yolo = false;
+ args.no_autowire = false;
+ args.native_args
+ .extend([OsString::from("--yolo"), OsString::from("--no-autowire")]);
+
+ preserve_trailing_run_options(&mut args);
+ assert!(args.yolo);
+ assert!(args.no_autowire);
+ }
+
+ #[test]
+ fn post_run_actions_reuse_the_workstream_without_replaying_native_args() {
+ let mut args = run_args_for_after_run_test();
+ let outcome = RunOutcome {
+ exit_code: 0,
+ harness: ManagedHarness::Claude,
+ interactive_session: true,
+ mode: LaunchMode::Session,
+ workstream_name: "research".into(),
+ };
+
+ assert!(apply_after_run_action(
+ &mut args,
+ &outcome,
+ AfterRunAction::Switch(RunHarnessChoice::Codex)
+ ));
+ assert_eq!(args.harness, Some(RunHarnessChoice::Codex));
+ assert_eq!(args.workstream.as_deref(), Some("research"));
+ assert_eq!(args.new_workstream, None);
+ assert!(!args.fresh);
+ assert!(args.native_args.is_empty());
+ assert!(args.yolo);
+ assert!(args.no_autowire);
+ assert_eq!(args.env, [("MODEL_HOME".into(), "custom".into())]);
+ }
+
+ #[test]
+ fn rerunning_kiro_v3_keeps_its_engine_without_replaying_user_args() {
+ let mut args = run_args_for_after_run_test();
+ let outcome = RunOutcome {
+ exit_code: 0,
+ harness: ManagedHarness::KiroV3,
+ interactive_session: true,
+ mode: LaunchMode::Session,
+ workstream_name: "research".into(),
+ };
+
+ assert!(apply_after_run_action(
+ &mut args,
+ &outcome,
+ AfterRunAction::Rerun
+ ));
+ assert_eq!(args.harness, Some(RunHarnessChoice::Kiro));
+ assert_eq!(args.native_args, [OsString::from("--v3")]);
+ assert_eq!(args.workstream.as_deref(), Some("research"));
+ }
+
+ #[test]
+ fn post_run_prompt_requires_clean_interactive_managed_session_without_custom_binary() {
+ let outcome = RunOutcome {
+ exit_code: 0,
+ harness: ManagedHarness::Claude,
+ interactive_session: true,
+ mode: LaunchMode::Session,
+ workstream_name: "research".into(),
+ };
+ assert!(should_offer_after_run(&outcome, true, false));
+ assert!(!should_offer_after_run(&outcome, false, false));
+ assert!(!should_offer_after_run(&outcome, true, true));
+
+ let mut failed = outcome;
+ failed.exit_code = 1;
+ assert!(!should_offer_after_run(&failed, true, false));
+ failed.exit_code = 0;
+ failed.mode = LaunchMode::Passthrough;
+ assert!(!should_offer_after_run(&failed, true, false));
+ }
+
#[tokio::test(start_paused = true)]
async fn native_session_choice_interrupt_does_not_wait_for_input() {
let interrupted = CancellationToken::new();
diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rs
index b1c79845..5ba03b92 100644
--- a/crates/ai-memory-workstream/src/harness.rs
+++ b/crates/ai-memory-workstream/src/harness.rs
@@ -467,6 +467,21 @@ pub fn allows_native_session_adoption(harness: ManagedHarness, native_args: &[Os
&& !noninteractive_invocation(harness, native_args)
}
+/// Whether a successful managed run represents an interactive session where
+/// follow-up choices may be offered in the parent terminal.
+///
+/// Explicit native session selectors remain interactive; this differs from
+/// [`allows_native_session_adoption`], which also rejects them because that
+/// function controls a separate prompt for choosing an existing session.
+#[must_use]
+pub fn is_interactive_session_invocation(
+ harness: ManagedHarness,
+ native_args: &[OsString],
+) -> bool {
+ launch_mode(harness, native_args) == LaunchMode::Session
+ && !noninteractive_invocation(harness, native_args)
+}
+
fn noninteractive_invocation(harness: ManagedHarness, args: &[OsString]) -> bool {
match harness {
ManagedHarness::Claude => has_flag(args, &["--print", "-p"]),
@@ -1662,6 +1677,30 @@ mod tests {
));
}
+ #[test]
+ fn post_run_prompt_is_limited_to_interactive_session_invocations() {
+ assert!(is_interactive_session_invocation(
+ ManagedHarness::Codex,
+ &[OsString::from("resume"), OsString::from("chosen")]
+ ));
+ assert!(!is_interactive_session_invocation(
+ ManagedHarness::Codex,
+ &[OsString::from("exec"), OsString::from("continue here")]
+ ));
+ assert!(!is_interactive_session_invocation(
+ ManagedHarness::Claude,
+ &[OsString::from("--print"), OsString::from("continue here")]
+ ));
+ assert!(!is_interactive_session_invocation(
+ ManagedHarness::Pi,
+ &[OsString::from("--no-session")]
+ ));
+ assert!(is_interactive_session_invocation(
+ ManagedHarness::Claude,
+ &[OsString::from("--model"), OsString::from("opus")]
+ ));
+ }
+
#[test]
fn opencode2_shares_v1_session_contract_with_its_own_binary() {
for name in ["opencode2", "opencode-v2", "open-code2"] {
diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rs
index ae4895a1..c3fb13c6 100644
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@ -8,9 +8,9 @@ pub use harness::{
LaunchMode, LaunchPlan, LaunchRoots, ManagedHarness, allows_native_session_adoption,
apply_yolo, build_launch_plan, build_launch_plan_with_env, clean_path, crush_data_dir,
crush_global_config_path, env_dir_override, has_native_session_selector,
- kiro_explicit_session_id, kiro_selects_non_default_engine, kiro_selects_v2_engine,
- kiro_selects_v3_engine, omp_agent_dir, omp_profile_flag, omp_profile_flag_env,
- store_override_vars,
+ is_interactive_session_invocation, kiro_explicit_session_id, kiro_selects_non_default_engine,
+ kiro_selects_v2_engine, kiro_selects_v3_engine, omp_agent_dir, omp_profile_flag,
+ omp_profile_flag_env, store_override_vars,
};
pub use repository::{RepositoryIdentity, inspect_repository};
pub use transcript::{
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index 525d4905..6f284a83 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -73,6 +73,18 @@ ai-memory run kiro --v3
ai-memory run
```
+After an interactive managed session exits successfully, `ai-memory run` offers
+the installed harnesses, a way to run the current harness again, and quit.
+Choosing another harness keeps the same workstream selected, so its saved
+context remains available to the next run. The prompt defaults to quit. It
+appears only when stdin, stdout, and stderr are terminals, the managed launch
+was a session, and `--executable` was not used; utility commands, failed or
+interrupted exits, and non-interactive launches do not prompt. A switch or
+re-run does not replay the previous harness's native arguments, which may be
+specific to that CLI; wrapper settings such as `--workspace`, `--project`,
+`--yolo`, `--no-autowire`, `--env`, and `--env-file` remain in effect. The
+initial `--fresh` choice applies only to the first launch.
+
Everything after the harness name is native argv except the wrapper-owned exact
flags `--yolo` and `--fresh`. No `--` separator is needed, and ai-memory does
not maintain a second copy of each harness's option schema. Other wrapper