Skip to content

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

Rust

feat(cli): open the checkout picker with ai-jail ai-memory

Paulo Vitor Martins20e7295e9f4d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c64619c3..d8e31270 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Added a default checkout-local workstream picker for commandless terminal
+ launches, including `ai-jail ai-memory`. The Linux/macOS shell wrapper now
+ routes a bare interactive launch to its native host client. Scripted CLI
+ calls still require a subcommand; help/version behavior is unchanged. (#1039)
- Added `install-hooks --agent claude-code --scope project`, which writes the
hook configuration to the checkout's gitignored `.claude/settings.local.json`
(where Claude Code reads it: the git root, or the launch directory on
@@ -122,7 +126,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
project, removed its default result cutoff with bounded server pagination,
and added `--search` plus immediate type-to-filter name search while preserving
Left/Right harness selection. Explicit limits now apply after the initial
- search; `continue` retained its cross-directory behavior. (#534)
+ search; `continue` retained its cross-directory behavior. (#1039)
- Documented FutureInfra as an endpoint for the existing `openai-compat`
provider. (#1026)
- `.github/workflows/nix.yml` builds the flake on `x86_64-linux` for path-
diff --git a/README.md b/README.md
index cf871518..ddc6d700 100644
--- a/README.md
+++ b/README.md
@@ -370,6 +370,9 @@ ai-memory continue # resume the newest managed checkout
ai-memory run --force-unlock codex
ai-memory resume # pick from ALL workstreams in this checkout only
ai-memory resume --search auth # find a workstream by name (case-insensitive)
+ai-memory # same picker, when run in a terminal
+ai-jail ai-memory # picker + selected harness inside ai-jail
+ai-jail --ssh ai-memory # also share SSH access
```
`--force-unlock` immediately expires the selected workstream's active lease;
@@ -386,6 +389,12 @@ there is no default workstream cutoff. Use `--limit N` only when you want to
cap the matching results. Workstreams from other repositories or worktrees
never appear; `continue` still resumes the newest linked checkout from anywhere.
+Running `ai-memory` without a subcommand in a terminal opens the same picker.
+`ai-jail ai-memory` keeps both the picker and the selected harness inside
+ai-jail; add ai-jail options before `ai-memory`, such as `--ssh` above.
+This works with native installs and the Linux/macOS shell wrapper. Scripts
+still require an explicit CLI subcommand, and `ai-memory --help` shows help.
+
Auto-wiring is on by default; opt out with `ai-memory run --no-autowire` or
`AI_MEMORY_RUN_AUTOWIRE=false`. You can still wire agents by hand with
`install-hooks` / `install-mcp` (e.g. for a harness you never launch through
diff --git a/bin/ai-memory b/bin/ai-memory
index df3f98eb..17504f7d 100755
--- a/bin/ai-memory
+++ b/bin/ai-memory
@@ -561,6 +561,11 @@ native_host_binary() {
# ---- intercept wrapper-only subcommands ----------------------------------
+if [ "$#" -eq 0 ] && [ -z "${AI_MEMORY_NO_TTY:-}" ] && [ -t 0 ] && [ -t 1 ]; then
+ # The picker must inspect the host checkout and launch host harnesses.
+ set -- resume
+fi
+
case "${1:-}" in
upgrade)
shift
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 606d9795..05af5cdf 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -1,6 +1,7 @@
//! Command-line interface definition (clap derive).
use std::ffi::OsString;
+use std::io::IsTerminal as _;
use std::path::PathBuf;
use clap::{Args, Parser, Subcommand};
@@ -16,7 +17,40 @@ use clap_complete::Shell;
/// wrapper-after-harness recovery (`--yolo`, `--fresh`, etc.) explicit in the
/// run command rather than dependent on clap's option-name knowledge.
pub(crate) fn parse_process() -> Cli {
- try_parse_from(std::env::args_os()).unwrap_or_else(|error| error.exit())
+ let mut args = std::env::args_os().collect::<Vec<_>>();
+ default_to_resume(
+ &mut args,
+ std::io::stdin().is_terminal() && std::io::stdout().is_terminal(),
+ );
+ try_parse_from(args).unwrap_or_else(|error| error.exit())
+}
+
+fn default_to_resume(args: &mut Vec<OsString>, interactive: bool) {
+ if !interactive || args.is_empty() {
+ return;
+ }
+ let mut index = 1;
+ while index < args.len() {
+ let Some(arg) = args[index].to_str() else {
+ return;
+ };
+ if matches!(arg, "--data-dir" | "--config") && index + 1 < args.len() {
+ if args[index + 1]
+ .to_str()
+ .is_some_and(|value| value.starts_with('-'))
+ {
+ return;
+ }
+ index += 2;
+ } else if arg.starts_with("--data-dir=") || arg.starts_with("--config=") {
+ index += 1;
+ } else {
+ // Explicit commands, help/version and invalid input keep clap's
+ // usual behavior. Only a commandless terminal launch gets a picker.
+ return;
+ }
+ }
+ args.push("resume".into());
}
pub(crate) fn try_parse_from<I, T>(args: I) -> Result<Cli, clap::Error>
@@ -90,7 +124,10 @@ fn delimit_run_native_args(args: &mut Vec<OsString>) {
/// Top-level CLI for the `ai-memory` binary.
#[derive(Debug, Parser)]
-#[command(name = "ai-memory", version, about, long_about = None)]
+#[command(
+ name = "ai-memory", version, about, long_about = None,
+ after_help = "Run without a command in a terminal to pick a workstream in this checkout.\nTo run inside ai-jail: ai-jail ai-memory"
+)]
pub struct Cli {
/// Override the data directory.
///
@@ -3448,6 +3485,51 @@ mod tests {
}
}
+ #[test]
+ fn commandless_terminal_launch_opens_the_checkout_picker() {
+ for input in [
+ vec!["ai-memory"],
+ vec![
+ "ai-memory",
+ "--data-dir",
+ "data with spaces",
+ "--config=resume",
+ ],
+ vec!["ai-memory", "--config", "resume", "--data-dir=data"],
+ ] {
+ let mut args = input.into_iter().map(OsString::from).collect();
+ default_to_resume(&mut args, true);
+ let parsed = try_parse_from(args).unwrap();
+ let Command::Resume(picker) = parsed.command else {
+ panic!("expected checkout picker");
+ };
+ assert!(picker.limit.is_none() && picker.search.is_none());
+ assert!(!picker.yolo && !picker.true_yolo && !picker.fresh);
+ }
+ }
+
+ #[test]
+ fn default_picker_preserves_explicit_commands_help_errors_and_scripts() {
+ for (input, interactive) in [
+ (vec!["ai-memory"], false),
+ (vec!["ai-memory", "--config", "config.toml"], false),
+ (vec!["ai-memory", "--help"], true),
+ (vec!["ai-memory", "--version"], true),
+ (vec!["ai-memory", "status"], true),
+ (vec!["ai-memory", "run", "codex"], true),
+ (vec!["ai-memory", "user"], true),
+ (vec!["ai-memory", "resumee"], true),
+ (vec!["ai-memory", "--config"], true),
+ (vec!["ai-memory", "--config", "--help"], true),
+ (vec!["ai-memory", "--unknown"], true),
+ ] {
+ let expected = input.into_iter().map(OsString::from).collect::<Vec<_>>();
+ let mut args = expected.clone();
+ default_to_resume(&mut args, interactive);
+ assert_eq!(args, expected);
+ }
+ }
+
#[test]
fn show_parses_listing_and_launch_flags_without_consuming_native_args() {
let listing = Cli::try_parse_from(["ai-memory", "show", "--json", "--no-scan"])
diff --git a/crates/ai-memory-cli/tests/suite/jail_toggles_e2e.rs b/crates/ai-memory-cli/tests/suite/jail_toggles_e2e.rs
index f60220fe..ae3967cf 100644
--- a/crates/ai-memory-cli/tests/suite/jail_toggles_e2e.rs
+++ b/crates/ai-memory-cli/tests/suite/jail_toggles_e2e.rs
@@ -183,7 +183,18 @@ async fn mock_server() -> (String, Arc<Mutex<Vec<String>>>, tokio::task::JoinHan
let observed = observed.clone();
async move {
observed.lock().unwrap().push(uri.path().to_owned());
- if uri.path() == "/workstream/runs" {
+ if uri.path() == "/workstream/recent" {
+ (
+ StatusCode::OK,
+ Json(json!([{
+ "workstream_id": "12345678-1234-4234-9234-123456789abd",
+ "name": "fixture", "current": true,
+ "created_at": "2026-09-01T00:00:00Z",
+ "last_active_at": "2026-09-01T00:00:00Z",
+ "linked_harnesses": ["claude-code"]
+ }])),
+ )
+ } else if uri.path() == "/workstream/runs" {
(
StatusCode::OK,
Json(json!({
@@ -697,11 +708,109 @@ async fn yolo_offer_skips_the_checklist_for_a_project_ai_jail() {
handle.abort();
}
+/// Exercise direct external wrapping, including the installed shell wrapper.
+/// The forwarding stub preserves the terminal just like ai-jail's PTY proxy;
+/// no nested real jail is needed, so this also runs inside ai-jail.
+#[cfg(any(target_os = "linux", target_os = "macos"))]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn bare_ai_memory_opens_the_picker_directly_and_through_ai_jail() {
+ for mode in ["native", "jail-native", "jail-wrapper"] {
+ for launch in [false, true] {
+ let fixture = Fixture::new(HELP_2_4_1, true, None);
+ let entry = if mode == "jail-wrapper" {
+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../bin/ai-memory")
+ } else {
+ PathBuf::from(BIN)
+ };
+ std::os::unix::fs::symlink(entry, fixture.bin.join("ai-memory")).unwrap();
+ std::os::unix::fs::symlink(host_tool("bash"), fixture.bin.join("bash")).unwrap();
+ write_script(
+ &fixture.bin.join("ai-jail"),
+ &format!(
+ "if [ \"$1\" = --dry-run ]; then exit 0; fi\n\
+ if [ \"$1\" = --help ]; then exit 0; fi\n\
+ printf '%s\\n' \"$@\" > '{}'\nexec \"$@\"\n",
+ fixture.jail_argv.display(),
+ ),
+ );
+ let (server, requests, handle) = mock_server().await;
+ let jailed = mode != "native";
+ let output = terminal_run_program(
+ &fixture,
+ &server,
+ &fixture
+ .bin
+ .join(if jailed { "ai-jail" } else { "ai-memory" }),
+ if jailed { "ai-memory" } else { "" },
+ if launch { "\x1b[C\r" } else { "\x1b" },
+ Some("Resume workstream"),
+ )
+ .await;
+ assert!(output.contains("Resume workstream"), "{mode}: {output}");
+ if jailed {
+ assert_eq!(fixture.jail_argv().unwrap(), ["ai-memory"]);
+ } else {
+ assert!(fixture.jail_argv().is_none());
+ }
+ let requests = requests.lock().unwrap();
+ assert_eq!(
+ requests.first().map(String::as_str),
+ Some("/workstream/recent")
+ );
+ if launch {
+ assert!(fixture.claude_ran.exists(), "{mode}: {output}");
+ assert!(output.contains("with harness 'claude'"), "{output}");
+ assert!(requests.iter().any(|path| path == "/workstream/runs"));
+ assert!(requests.iter().any(|path| path.ends_with("/finish")));
+ } else {
+ assert_eq!(requests.as_slice(), ["/workstream/recent"]);
+ assert!(!fixture.claude_ran.exists(), "Escape cancels before launch");
+ }
+ handle.abort();
+ }
+ }
+}
+
+#[tokio::test]
+async fn bare_nonterminal_command_help_version_and_typos_do_not_launch_a_picker() {
+ let fixture = Fixture::new(HELP_2_4_1, true, None);
+ let (server, requests, handle) = mock_server().await;
+ for (args, succeeds) in [
+ (vec![], false),
+ (vec!["--help"], true),
+ (vec!["--version"], true),
+ (vec!["resumee"], false),
+ ] {
+ let output = run(&fixture, &server, &args).await;
+ assert_eq!(output.status.success(), succeeds, "{}", stderr(&output));
+ assert!(
+ !fixture.home.join("data").exists(),
+ "parsing must not load config"
+ );
+ }
+ assert!(requests.lock().unwrap().is_empty());
+ assert!(fixture.jail_argv().is_none());
+ assert!(!fixture.claude_ran.exists());
+ handle.abort();
+}
+
/// Run `ai-memory <args>` under `script` so stdin and stderr are a real
/// terminal, feed `input`, and return everything the terminal showed.
#[cfg(any(target_os = "linux", target_os = "macos"))]
async fn terminal_run(fixture: &Fixture, server: &str, args: &str, input: &str) -> String {
- use tokio::io::AsyncWriteExt as _;
+ terminal_run_program(fixture, server, Path::new(BIN), args, input, None).await
+}
+
+#[cfg(any(target_os = "linux", target_os = "macos"))]
+async fn terminal_run_program(
+ fixture: &Fixture,
+ server: &str,
+ program: &Path,
+ args: &str,
+ input: &str,
+ ready: Option<&str>,
+) -> String {
+ use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
let runner = fixture.home.join("runner.sh");
fs::write(&runner, format!("exec \"$JAIL_E2E_BINARY\" {args}\n")).unwrap();
let mut command = command(fixture, server, &[]);
@@ -727,14 +836,35 @@ async fn terminal_run(fixture: &Fixture, server: &str, args: &str, input: &str)
}
terminal
.env("HOME", &fixture.home)
- .env("JAIL_E2E_BINARY", BIN)
+ .env("JAIL_E2E_BINARY", program)
+ .env("AI_MEMORY_NATIVE_BIN", BIN)
+ .env("AI_MEMORY_RUN_AUTOWIRE", "false")
.current_dir(&fixture.repo)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = tokio::process::Command::from(terminal)
+ .kill_on_drop(true)
.spawn()
.expect("script provides a pseudo-terminal");
+ let mut prefix = Vec::new();
+ if let Some(ready) = ready {
+ let stdout = child.stdout.as_mut().unwrap();
+ tokio::time::timeout(std::time::Duration::from_secs(10), async {
+ let mut chunk = [0u8; 4096];
+ while !String::from_utf8_lossy(&prefix).contains(ready) {
+ let count = stdout.read(&mut chunk).await.unwrap();
+ assert!(
+ count > 0,
+ "terminal exited before picker: {}",
+ String::from_utf8_lossy(&prefix)
+ );
+ prefix.extend_from_slice(&chunk[..count]);
+ }
+ })
+ .await
+ .expect("picker appeared");
+ }
let mut stdin = child.stdin.take().unwrap();
stdin.write_all(input.as_bytes()).await.unwrap();
stdin.flush().await.unwrap();
@@ -745,8 +875,18 @@ async fn terminal_run(fixture: &Fixture, server: &str, args: &str, input: &str)
.await
.expect("terminal run finished")
.expect("wait for script");
+ if ready.is_some() {
+ assert!(
+ output.status.success(),
+ "{}{}{}",
+ String::from_utf8_lossy(&prefix),
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
format!(
- "{}{}",
+ "{}{}{}",
+ String::from_utf8_lossy(&prefix),
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
)
diff --git a/crates/ai-memory-cli/tests/suite/packaging.rs b/crates/ai-memory-cli/tests/suite/packaging.rs
index 6a11686f..7e842195 100644
--- a/crates/ai-memory-cli/tests/suite/packaging.rs
+++ b/crates/ai-memory-cli/tests/suite/packaging.rs
@@ -442,6 +442,11 @@ fn run_wrapper_with_piped_stdin(args: &[&str], stdin_payload: &str) -> String {
let mut child = shell_script_command(&repo_root().join("bin/ai-memory"))
.args(args)
.env("AI_MEMORY_DOCKER", shell_path(&docker))
+ .env(
+ "AI_MEMORY_NATIVE_BIN",
+ tmp.path().join("must-not-launch-native"),
+ )
+ .env("AI_MEMORY_IMAGE", "docker.io/akitaonrails/ai-memory:latest")
.env("AI_MEMORY_NO_VERSION_CHECK", "1")
.env("AI_MEMORY_DATA_VOLUME", "test-ai-memory-data")
.env("HOME", shell_path(tmp.path()))
@@ -2387,6 +2392,20 @@ mod slow {
);
}
+ #[cfg(unix)]
+ #[test]
+ fn bare_wrapper_with_piped_stdin_does_not_open_the_host_picker() {
+ let args = run_wrapper_with_piped_stdin(&[], "");
+ let flags = args.lines().collect::<Vec<_>>();
+ assert!(flags.contains(&"-i"));
+ assert!(!flags.contains(&"-t"));
+ assert!(!flags.contains(&"resume"), "{args}");
+ assert_eq!(
+ flags.last().copied(),
+ Some("docker.io/akitaonrails/ai-memory:latest")
+ );
+ }
+
#[cfg(unix)]
#[test]
fn wrapper_self_upgrade_rejects_a_checksum_mismatch() {
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index e1f322d9..7b10256c 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -272,8 +272,17 @@ linked checkout from any directory, use `ai-memory continue` instead.
ai-memory resume
ai-memory resume --search auth
ai-memory resume --workspace work --limit 50
+ai-memory # no subcommand needed in a terminal
+ai-jail ai-memory # picker and harness inside the jail
+ai-jail --ssh ai-memory # optional SSH access
```
+A commandless terminal launch opens the same checkout-local picker. Wrap it
+directly with `ai-jail ai-memory` to keep the selected harness in that jail.
+There is no extra ai-memory jail flag or nested sandbox. The Linux/macOS shell
+wrapper routes this interactive launch to its native host client. Non-terminal
+CLI calls still require a subcommand, and explicit help/version remain available.
+
Use Up/Down to move between workstreams and Left/Right to cycle the
launch harness for the highlighted row. Each row remembers its choice while you
navigate. `auto` is the initial choice and preserves bare `ai-memory run`'s