Skip to content

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

Rust

feat(cli): add interactive workstream resume picker (#534)

Paulo Vitor Martins676e55f43b67
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2e5e74f9..98ca1bed 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Added `ai-memory resume`, an interactive picker for recent managed
+ workstreams from the current checkout and validated client-local links. It
+ launches the selected named workstream with the established automatic harness
+ selection while the server continues to receive only repository/worktree
+ fingerprints, extending the checkout-local discovery introduced by
+ `workstreams`. Left/Right cycles `auto` and the supported harnesses found in
+ `PATH`, so the selected workstream can be continued directly in another agent.
+ (#499)
+
- `ai-memory handoffs --expire-all --confirm` and `POST /admin/handoffs/expire`
clear a stale open-handoff backlog for one scope. The listing added in
v1.35.0 made a backlog visible and gave `memory_handoff_cancel` the ids it
diff --git a/README.md b/README.md
index 7c1b92c3..5404f2c6 100644
--- a/README.md
+++ b/README.md
@@ -232,6 +232,9 @@ priors are at the [bottom](#influences-and-prior-art).
# Fix a name you regret; the ledger and the current selection stay put.
ai-memory rename-workstream --from typo-nmae --to refactor-db
+ # Pick a managed workstream from any linked local checkout, then resume it.
+ ai-memory resume
+
# List open cross-agent handoffs, oldest first, with the id
# `memory_handoff_cancel` needs to clear a stale one.
ai-memory handoffs
@@ -296,6 +299,22 @@ priors are at the [bottom](#influences-and-prior-art).
reported on stderr and skipped, so a resume never quietly lands in the wrong
project. `--workspace` narrows the search; `--yolo` and `--fresh` are
forwarded.
+- **"Let me choose which workstream to resume."** From any directory, select
+ one of the recent workstreams from your valid client-local managed checkouts:
+
+ ```bash
+ ai-memory resume
+ ai-memory resume --workspace work
+ ```
+
+ The picker shows the workstream name, project scope, activity, and linked
+ harnesses. Use Up/Down (or `j`/`k`) to choose a workstream and Left/Right to
+ cycle its launch harness. Every row starts at `auto`, preserving normal
+ session discovery; the other choices are supported harnesses currently found
+ in `PATH`. Enter launches the displayed combination. The checkout is
+ revalidated first, while the server continues to receive fingerprints rather
+ than a local path. Use `ai-memory workstreams` when you are already in a
+ checkout and only want the read-only list.
- **"Quit at 4 PM, pick up at 9 AM in a different agent."** The
classic. SessionStart hook in the next supported hook client prepends a
typed handoff with open questions, next steps, and a session summary. Grok
@@ -629,10 +648,10 @@ one matching entry.
required when the env vars are set. Any non-loopback server should use
bearer auth.
- **Managed-launch wrapper:** `ai-memory run`, `ai-memory show`,
- `ai-memory continue`, and `ai-memory workstreams` must be intercepted by the
- current host wrapper so local checkouts, native harnesses, and session stores
- remain accessible. An old wrapper may pass these commands into Docker and
- fail to find a checkout or host executable. Run
+ `ai-memory continue`, `ai-memory resume`, and `ai-memory workstreams` must be
+ intercepted by the current host wrapper so local checkouts, native harnesses,
+ and session stores remain accessible. An old wrapper may pass these commands
+ into Docker and fail to find a checkout or host executable. Run
`ai-memory upgrade` on the agent machine to refresh it. The host-native runner
inherits `AI_MEMORY_SERVER_URL`, `AI_MEMORY_AUTH_TOKEN`, and the host `PATH`.
- **Upgrades:** for Docker-wrapper installs, run `ai-memory upgrade` on each
diff --git a/bin/ai-memory b/bin/ai-memory
index b6dc08a7..49897fce 100755
--- a/bin/ai-memory
+++ b/bin/ai-memory
@@ -372,7 +372,7 @@ native_host_binary() {
Darwin) os="macos" ;;
*)
echo "ai-memory: the Docker wrapper cannot provide managed host launches on this OS" >&2
- echo "install the native release binary to use ai-memory run/show/continue/workstreams/rename-workstream" >&2
+ echo "install the native release binary to use ai-memory run/show/continue/resume/workstreams/rename-workstream" >&2
return 1
;;
esac
@@ -447,7 +447,7 @@ case "${1:-}" in
cmd_upgrade
exit 0
;;
- run | show | continue | workstreams | rename-workstream)
+ run | show | continue | resume | workstreams | rename-workstream)
NATIVE_HOST_COMMAND=$1
shift
NATIVE_HOST_BIN=$(native_host_binary)
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 1106c60b..7873bb67 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -43,6 +43,8 @@ pub enum Command {
/// Resume the most recently launched managed checkout from anywhere,
/// without `cd` and without picking from a list.
Continue(ContinueArgs),
+ /// Interactively pick a recent managed workstream and launch harness.
+ Resume(ResumeArgs),
/// List open cross-agent handoffs so a stale one can be cancelled by id.
Handoffs(HandoffsArgs),
/// List recent managed workstreams selectable from the current checkout.
@@ -334,6 +336,29 @@ pub struct ContinueArgs {
pub fresh: bool,
}
+/// Arguments for `resume`.
+///
+/// The picker deliberately accepts only wrapper-owned flags. Harness selection
+/// happens interactively, then it delegates to `run --workstream NAME` in the
+/// selected checkout.
+#[derive(Debug, Args)]
+pub struct ResumeArgs {
+ /// Only consider checkouts resolving to this workspace.
+ #[arg(long)]
+ pub workspace: Option<String>,
+ /// Maximum workstreams to show in the picker.
+ #[arg(long, default_value_t = 20, value_parser = clap::value_parser!(u8).range(1..=100))]
+ pub limit: u8,
+ /// Disable native permission prompts using the resolved harness's
+ /// equivalent dangerous-mode option. Forwarded to `run`.
+ #[arg(long)]
+ pub yolo: bool,
+ /// Start a new native session instead of resuming the linked one.
+ /// Forwarded to `run`.
+ #[arg(long)]
+ pub fresh: bool,
+}
+
/// Arguments for `workstreams`.
/// Arguments for `handoffs`.
#[derive(Debug, Args)]
@@ -2164,6 +2189,42 @@ mod tests {
}
}
+ /// `resume` is an interactive selector, so it keeps the same narrow
+ /// wrapper-only command-line surface as `continue`; its picker selects the
+ /// native harness without accepting harness-native arguments.
+ #[test]
+ fn resume_takes_picker_and_wrapper_flags_only() {
+ let parsed = Cli::try_parse_from([
+ "ai-memory",
+ "resume",
+ "--workspace",
+ "work",
+ "--limit",
+ "50",
+ "--yolo",
+ ])
+ .expect("resume parses picker flags");
+ let Command::Resume(args) = parsed.command else {
+ panic!("expected resume command");
+ };
+ assert_eq!(args.workspace.as_deref(), Some("work"));
+ assert_eq!(args.limit, 50);
+ assert!(args.yolo);
+ assert!(!args.fresh);
+
+ for rejected in [
+ vec!["ai-memory", "resume", "claude"],
+ vec!["ai-memory", "resume", "--model", "opus"],
+ vec!["ai-memory", "resume", "--executable", "/bin/claude"],
+ vec!["ai-memory", "resume", "--limit", "0"],
+ ] {
+ assert!(
+ Cli::try_parse_from(&rejected).is_err(),
+ "{rejected:?} must not parse"
+ );
+ }
+ }
+
#[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/src/commands/continue_session.rs b/crates/ai-memory-cli/src/commands/continue_session.rs
index 7ee1cfd0..395d839f 100644
--- a/crates/ai-memory-cli/src/commands/continue_session.rs
+++ b/crates/ai-memory-cli/src/commands/continue_session.rs
@@ -130,7 +130,7 @@ fn linked_at(link: &ProjectLink) -> Option<jiff::Timestamp> {
/// replaced by a symlink; the scope check rejects a directory that still
/// exists but now resolves to a different project, which would otherwise
/// file this session's memory under the wrong scope.
-fn resolve_target(config: &Config, link: &ProjectLink) -> Result<PathBuf> {
+pub(super) fn resolve_target(config: &Config, link: &ProjectLink) -> Result<PathBuf> {
let path = validate_registered_path(&link.path)?;
let (workspace, project) = super::resolve_scope_for_path(config, &path)?;
if workspace != link.workspace || project != link.project {
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 1ba8948c..1ac37c4a 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -53,6 +53,7 @@ pub mod reorg;
pub mod reset;
pub mod restore;
pub mod restore_page;
+pub mod resume;
pub mod run;
pub mod search;
pub mod serve;
diff --git a/crates/ai-memory-cli/src/commands/resume.rs b/crates/ai-memory-cli/src/commands/resume.rs
new file mode 100644
index 00000000..6a65b672
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/resume.rs
@@ -0,0 +1,382 @@
+//! `ai-memory resume` — pick a managed workstream across local checkouts.
+//!
+//! The server deliberately cannot list client filesystem paths. This command
+//! joins its checkout-local registry to each checkout's privacy-preserving
+//! workstream listing, revalidates every path before use, and delegates the
+//! selected launch to `run --workstream`.
+
+use std::io::IsTerminal as _;
+use std::path::PathBuf;
+
+use ai_memory_core::ManagedWorkstreamSummary;
+use anyhow::{Context as _, Result, bail};
+
+use crate::cli::{ResumeArgs, RunArgs, RunHarnessChoice};
+use crate::commands::project_registry::{self, ProjectLink};
+use crate::commands::show::{
+ Choice, HorizontalDirection, available_harnesses, harness_name, select_with_horizontal,
+ terminal_text,
+};
+use crate::commands::{continue_session, workstreams};
+use crate::config::Config;
+use crate::http_client::ServerEndpoint;
+
+struct Candidate {
+ link: ProjectLink,
+ target: PathBuf,
+ summary: ManagedWorkstreamSummary,
+}
+
+/// Interactively select a workstream from every valid locally linked checkout.
+pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {
+ if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {
+ bail!(
+ "`ai-memory resume` needs a terminal; use `ai-memory workstreams` to list a checkout in scripts"
+ );
+ }
+
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
+ let mut links = project_registry::links_for_server(config, &endpoint)?;
+ match current_checkout_link(config, &endpoint) {
+ Ok(current) => {
+ if !links.iter().any(|link| {
+ link.workspace == current.workspace
+ && link.project == current.project
+ && link.path == current.path
+ }) {
+ links.insert(0, current);
+ }
+ }
+ Err(error) => eprintln!(
+ "skipping current checkout: {}",
+ terminal_text(&format!("{error:#}"))
+ ),
+ }
+ let mut candidates = Vec::new();
+ let mut skipped = 0usize;
+
+ for link in links.into_iter().filter(|link| {
+ args.workspace
+ .as_deref()
+ .is_none_or(|workspace| link.workspace == workspace)
+ }) {
+ let target = match continue_session::resolve_target(config, &link) {
+ Ok(target) => target,
+ Err(error) => {
+ eprintln!(
+ "skipping {}: {}",
+ scope_label(&link),
+ terminal_text(&error.to_string())
+ );
+ skipped += 1;
+ continue;
+ }
+ };
+ let summaries = match workstreams::list_for_checkout(
+ &endpoint,
+ &link.workspace,
+ &link.project,
+ &target,
+ usize::from(args.limit),
+ )
+ .await
+ {
+ Ok(summaries) => summaries,
+ Err(error) => {
+ eprintln!(
+ "skipping {}: could not list managed workstreams ({})",
+ scope_label(&link),
+ terminal_text(&format!("{error:#}"))
+ );
+ skipped += 1;
+ continue;
+ }
+ };
+ for summary in summaries {
+ if candidates.iter().any(|candidate: &Candidate| {
+ candidate.summary.workstream_id == summary.workstream_id
+ }) {
+ continue;
+ }
+ candidates.push(Candidate {
+ link: link.clone(),
+ target: target.clone(),
+ summary,
+ });
+ }
+ }
+
+ order_candidates(&mut candidates);
+ candidates.truncate(usize::from(args.limit));
+ if candidates.is_empty() {
+ let detail = if skipped == 0 {
+ "no local managed checkout has a saved workstream yet".to_owned()
+ } else {
+ format!(
+ "{skipped} local checkout{} could not be queried",
+ if skipped == 1 { "" } else { "s" }
+ )
+ };
+ bail!(
+ "no managed workstreams are available ({detail}); launch one with `ai-memory run <harness>` first"
+ );
+ }
+
+ let harnesses = available_harnesses();
+ let mut harness_indices = vec![0usize; candidates.len()];
+ let mut choices = candidates
+ .iter()
+ .map(|candidate| choice_for(candidate, None))
+ .collect::<Vec<_>>();
+ let Some(index) = select_with_horizontal(
+ "Resume workstream",
+ &mut choices,
+ "left/right harness",
+ &mut |index, direction, choice| {
+ let harness =
+ cycle_selected_harness(&mut harness_indices, index, &harnesses, direction);
+ *choice = choice_for(&candidates[index], harness);
+ },
+ )?
+ else {
+ return Ok(0);
+ };
+ let selected = &candidates[index];
+ let harness = selected_harness(harness_indices[index], &harnesses);
+ eprintln!(
+ "resuming workstream '{}' with harness '{}' in {} at {}",
+ terminal_text(&selected.summary.name),
+ harness
+ .map(harness_name)
+ .unwrap_or_else(|| "auto".to_owned()),
+ scope_label(&selected.link),
+ terminal_text(&selected.target.to_string_lossy())
+ );
+ crate::commands::run::run_from(
+ config,
+ RunArgs {
+ workspace: Some(selected.link.workspace.clone()),
+ project: Some(selected.link.project.clone()),
+ workstream: Some(selected.summary.name.clone()),
+ new_workstream: None,
+ executable: None,
+ yolo: args.yolo,
+ fresh: args.fresh,
+ harness,
+ native_args: Vec::new(),
+ },
+ &selected.target,
+ )
+ .await
+}
+
+fn current_checkout_link(config: &Config, endpoint: &ServerEndpoint) -> Result<ProjectLink> {
+ let path = std::env::current_dir()
+ .context("reading the current checkout")?
+ .canonicalize()
+ .context("canonicalizing the current checkout")?;
+ let (workspace, project) = super::resolve_scope_for_path(config, &path)?;
+ Ok(ProjectLink {
+ server: endpoint.identity(),
+ workspace,
+ project,
+ path,
+ linked_at: jiff::Timestamp::now().to_string(),
+ })
+}
+
+fn choice_for(candidate: &Candidate, harness: Option<RunHarnessChoice>) -> Choice {
+ let marker = if candidate.summary.current { "* " } else { "" };
+ let harnesses = if candidate.summary.linked_harnesses.is_empty() {
+ "no linked harnesses".to_owned()
+ } else {
+ candidate
+ .summary
+ .linked_harnesses
+ .iter()
+ .map(|agent| agent.as_str())
+ .collect::<Vec<_>>()
+ .join(", ")
+ };
+ Choice {
+ label: format!("{marker}{}", terminal_text(&candidate.summary.name)),
+ detail: format!(
+ "{} | {} | harness <{}> | linked [{}]",
+ scope_label(&candidate.link),
+ humanize_age(&candidate.summary.last_active_at),
+ harness
+ .map(harness_name)
+ .unwrap_or_else(|| "auto".to_owned()),
+ terminal_text(&harnesses)
+ ),
+ }
+}
+
+fn cycle_harness_index(
+ current: usize,
+ harness_count: usize,
+ direction: HorizontalDirection,
+) -> usize {
+ let choice_count = harness_count.saturating_add(1);
+ match direction {
+ HorizontalDirection::Left => current.checked_sub(1).unwrap_or(choice_count - 1),
+ HorizontalDirection::Right => (current + 1) % choice_count,
+ }
+}
+
+fn selected_harness(index: usize, harnesses: &[RunHarnessChoice]) -> Option<RunHarnessChoice> {
+ index
+ .checked_sub(1)
+ .and_then(|index| harnesses.get(index))
+ .copied()
+}
+
+fn cycle_selected_harness(
+ indices: &mut [usize],
+ row: usize,
+ harnesses: &[RunHarnessChoice],
+ direction: HorizontalDirection,
+) -> Option<RunHarnessChoice> {
+ indices[row] = cycle_harness_index(indices[row], harnesses.len(), direction);
+ selected_harness(indices[row], harnesses)
+}
+
+fn order_candidates(candidates: &mut [Candidate]) {
+ candidates.sort_by(|left, right| {
+ right
+ .summary
+ .current
+ .cmp(&left.summary.current)
+ .then_with(|| {
+ timestamp(&right.summary.last_active_at)
+ .cmp(&timestamp(&left.summary.last_active_at))
+ })
+ .then_with(|| left.link.workspace.cmp(&right.link.workspace))
+ .then_with(|| left.link.project.cmp(&right.link.project))
+ .then_with(|| left.summary.name.cmp(&right.summary.name))
+ });
+}
+
+fn timestamp(raw: &str) -> Option<jiff::Timestamp> {
+ raw.parse().ok()
+}
+
+fn humanize_age(raw: &str) -> String {
+ let Some(then) = timestamp(raw) else {
+ return "unknown activity".to_owned();
+ };
+ super::humanize_age_secs((jiff::Timestamp::now() - then).get_seconds())
+}
+
+fn scope_label(link: &ProjectLink) -> String {
+ terminal_text(&format!("{}/{}", link.workspace, link.project))
+}
+
+#[cfg(test)]
+mod tests {
+ use ai_memory_core::{AgentKind, WorkstreamId};
+
+ use super::*;
+
+ fn candidate(name: &str, current: bool, last_active_at: &str) -> Candidate {
+ Candidate {
+ link: ProjectLink {
+ server: "http://127.0.0.1:49374".to_owned(),
+ workspace: "default".to_owned(),
+ project: "app".to_owned(),
+ path: PathBuf::from("/checkout/app"),
+ linked_at: "2026-08-30T00:00:00Z".to_owned(),
+ },
+ target: PathBuf::from("/checkout/app"),
+ summary: ManagedWorkstreamSummary {
+ workstream_id: WorkstreamId::new(),
+ name: name.to_owned(),
+ created_at: "2026-08-01T00:00:00Z".to_owned(),
+ last_active_at: last_active_at.to_owned(),
+ current,
+ linked_harnesses: vec![AgentKind::Codex],
+ },
+ }
+ }
+
+ #[test]
+ fn current_workstream_leads_then_newest_activity_wins() {
+ let mut candidates = vec![
+ candidate("older", false, "2026-08-01T00:00:00Z"),
+ candidate("current", true, "2026-07-01T00:00:00Z"),
+ candidate("newer", false, "2026-08-02T00:00:00Z"),
+ ];
+
+ order_candidates(&mut candidates);
+
+ let names = candidates
+ .iter()
+ .map(|candidate| candidate.summary.name.as_str())
+ .collect::<Vec<_>>();
+ assert_eq!(names, ["current", "newer", "older"]);
+ }
+
+ #[test]
+ fn malformed_activity_sorts_after_valid_activity() {
+ let mut candidates = vec![
+ candidate("malformed", false, "not-a-timestamp"),
+ candidate("valid", false, "2026-08-01T00:00:00Z"),
+ ];
+
+ order_candidates(&mut candidates);
+
+ assert_eq!(candidates[0].summary.name, "valid");
+ }
+
+ #[test]
+ fn choice_sanitizes_server_control_characters() {
+ let choice = choice_for(&candidate("unsafe\u{1b}[31m", false, "invalid"), None);
+
+ assert!(!choice.label.contains('\u{1b}'));
+ assert!(choice.detail.contains("unknown activity"));
+ }
+
+ #[test]
+ fn harness_cycle_wraps_through_auto_and_available_harnesses() {
+ assert_eq!(cycle_harness_index(0, 2, HorizontalDirection::Right), 1);
+ assert_eq!(cycle_harness_index(1, 2, HorizontalDirection::Right), 2);
+ assert_eq!(cycle_harness_index(2, 2, HorizontalDirection::Right), 0);
+ assert_eq!(cycle_harness_index(0, 2, HorizontalDirection::Left), 2);
+ assert_eq!(cycle_harness_index(0, 0, HorizontalDirection::Right), 0);
+ }
+
+ #[test]
+ fn harness_index_zero_preserves_automatic_selection() {
+ let harnesses = [RunHarnessChoice::Claude, RunHarnessChoice::Codex];
+
+ assert!(selected_harness(0, &harnesses).is_none());
+ assert!(matches!(
+ selected_harness(2, &harnesses),
+ Some(RunHarnessChoice::Codex)
+ ));
+ }
+
+ #[test]
+ fn choice_displays_the_active_and_linked_harnesses() {
+ let choice = choice_for(
+ &candidate("feature", false, "invalid"),
+ Some(RunHarnessChoice::Claude),
+ );
+
+ assert!(choice.detail.contains("harness <claude>"));
+ assert!(choice.detail.contains("linked [codex]"));
+ }
+
+ #[test]
+ fn each_workstream_remembers_its_own_harness() {
+ let harnesses = [RunHarnessChoice::Claude, RunHarnessChoice::Codex];
+ let mut indices = [0, 0];
+
+ let first = cycle_selected_harness(&mut indices, 0, &harnesses, HorizontalDirection::Right);
+ let second = cycle_selected_harness(&mut indices, 1, &harnesses, HorizontalDirection::Left);
+
+ assert!(matches!(first, Some(RunHarnessChoice::Claude)));
+ assert!(matches!(second, Some(RunHarnessChoice::Codex)));
+ assert_eq!(indices, [1, 2]);
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/show.rs b/crates/ai-memory-cli/src/commands/show.rs
index f5d6da03..7058b733 100644
--- a/crates/ai-memory-cli/src/commands/show.rs
+++ b/crates/ai-memory-cli/src/commands/show.rs
@@ -102,9 +102,9 @@ impl Candidate {
}
}
-struct Choice {
- label: String,
- detail: String,
+pub(super) struct Choice {
+ pub(super) label: String,
+ pub(super) detail: String,
}
#[derive(Serialize)]
@@ -173,7 +173,7 @@ pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {
label: candidate.label(),
detail: candidate.detail(),
}));
- let Some(project_index) = select("Project", &project_choices)? else {
+ let Some(project_index) = select("Project", &mut project_choices)? else {
return Ok(0);
};
let new_project = if project_index == 0 {
@@ -185,7 +185,7 @@ pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {
None
};
- let harness_choices = harnesses
+ let mut harness_choices = harnesses
.iter()
.map(|choice| Choice {
label: harness_name(*choice),
@@ -196,7 +196,8 @@ pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {
.as_deref()
.map(terminal_text)
.unwrap_or_else(|| project_choices[project_index].label.clone());
- let Some(harness_index) = select(&format!("Agent | {project_label}"), &harness_choices)? else {
+ let Some(harness_index) = select(&format!("Agent | {project_label}"), &mut harness_choices)?
+ else {
return Ok(0);
};
let harness = harnesses[harness_index];
@@ -413,7 +414,7 @@ fn print_json(
Ok(())
}
-fn available_harnesses() -> Vec<RunHarnessChoice> {
+pub(super) fn available_harnesses() -> Vec<RunHarnessChoice> {
RunHarnessChoice::value_variants()
.iter()
.copied()
@@ -621,7 +622,7 @@ fn humanize_age(timestamp: Option<&str>) -> String {
super::humanize_age_secs((jiff::Timestamp::now() - then).get_seconds())
}
-fn harness_name(harness: RunHarnessChoice) -> String {
+pub(super) fn harness_name(harness: RunHarnessChoice) -> String {
harness
.to_possible_value()
.map_or_else(|| "unknown".to_owned(), |value| value.get_name().to_owned())
@@ -648,7 +649,33 @@ impl Drop for TerminalGuard {
}
}
-fn select(title: &str, choices: &[Choice]) -> Result<Option<usize>> {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(super) enum HorizontalDirection {
+ Left,
+ Right,
+}
+
+type HorizontalHandler<'a> = &'a mut dyn FnMut(usize, HorizontalDirection, &mut Choice);
+
+pub(super) fn select(title: &str, choices: &mut [Choice]) -> Result<Option<usize>> {
+ select_inner(title, choices, None, None)
+}
+
+pub(super) fn select_with_horizontal(
+ title: &str,
+ choices: &mut [Choice],
+ horizontal_hint: &str,
+ on_horizontal: &mut dyn FnMut(usize, HorizontalDirection, &mut Choice),
+) -> Result<Option<usize>> {
+ select_inner(title, choices, Some(horizontal_hint), Some(on_horizontal))
+}
+
+fn select_inner(
+ title: &str,
+ choices: &mut [Choice],
+ horizontal_hint: Option<&str>,
+ mut on_horizontal: Option<HorizontalHandler<'_>>,
+) -> Result<Option<usize>> {
if choices.is_empty() {
bail!("nothing to choose from");
}
@@ -663,7 +690,14 @@ fn select(title: &str, choices: &[Choice]) -> Result<Option<usize>> {
let mut offset = 0usize;
let mut drawn = 0u16;
loop {
- drawn = draw(title, choices, selected, &mut offset, drawn)?;
+ drawn = draw(
+ title,
+ choices,
+ selected,
+ &mut offset,
+ drawn,
+ horizontal_hint,
+ )?;
let Event::Key(KeyEvent {
code,
modifiers,
@@ -673,6 +707,12 @@ fn select(title: &str, choices: &[Choice]) -> Result<Option<usize>> {
else {
continue;
};
+ if let Some(direction) = horizontal_direction(&code) {
+ if let Some(callback) = on_horizontal.as_mut() {
+ callback(selected, direction, &mut choices[selected]);
+ }
+ continue;
+ }
match code {
KeyCode::Up | KeyCode::Char('k') => {
selected = selected.checked_sub(1).unwrap_or(choices.len() - 1);
@@ -701,6 +741,14 @@ fn select(title: &str, choices: &[Choice]) -> Result<Option<usize>> {
}
}
+fn horizontal_direction(code: &KeyCode) -> Option<HorizontalDirection> {
+ match code {
+ KeyCode::Left => Some(HorizontalDirection::Left),
+ KeyCode::Right => Some(HorizontalDirection::Right),
+ _ => None,
+ }
+}
+
fn prompt_project_name(parent: &Path) -> Result<Option<String>> {
terminal::enable_raw_mode().context("entering raw mode")?;
let _guard = TerminalGuard;
@@ -836,6 +884,7 @@ fn draw(
selected: usize,
offset: &mut usize,
previous: u16,
+ horizontal_hint: Option<&str>,
) -> Result<u16> {
let (columns, _) = terminal::size().unwrap_or((80, 24));
let width = usize::from(columns.max(20)).saturating_sub(1);
@@ -876,14 +925,17 @@ fn draw(
}
write!(out, "\r\n")?;
}
+ let horizontal_hint = horizontal_hint
+ .map(|hint| format!(" | {hint}"))
+ .unwrap_or_default();
let hint = if choices.len() > viewport {
format!(
- " up/down move | pgup/pgdn page | enter select | esc cancel [{}/{}]",
+ " up/down move{horizontal_hint} | pgup/pgdn page | enter select | esc cancel [{}/{}]",
selected + 1,
choices.len()
)
} else {
- " up/down move | enter select | esc cancel".to_owned()
+ format!(" up/down move{horizontal_hint} | enter select | esc cancel")
};
write!(out, "{}\r\n", truncate(&hint, width).dark_grey())?;
out.flush()?;
@@ -1077,4 +1129,17 @@ mod tests {
assert_ne!(harness_name(*harness), "unknown");
}
}
+
+ #[test]
+ fn horizontal_arrow_keys_map_to_picker_directions() {
+ assert_eq!(
+ horizontal_direction(&KeyCode::Left),
+ Some(HorizontalDirection::Left)
+ );
+ assert_eq!(
+ horizontal_direction(&KeyCode::Right),
+ Some(HorizontalDirection::Right)
+ );
+ assert_eq!(horizontal_direction(&KeyCode::Up), None);
+ }
}
diff --git a/crates/ai-memory-cli/src/commands/workstreams.rs b/crates/ai-memory-cli/src/commands/workstreams.rs
index ba259756..c0c3f01b 100644
--- a/crates/ai-memory-cli/src/commands/workstreams.rs
+++ b/crates/ai-memory-cli/src/commands/workstreams.rs
@@ -1,6 +1,7 @@
//! Checkout-local discovery for managed workstreams.
use std::fmt::Write as _;
+use std::path::Path;
use ai_memory_core::{ListManagedWorkstreamsRequest, ManagedWorkstreamSummary};
use ai_memory_workstream::inspect_repository;
@@ -13,20 +14,15 @@ use crate::http_client::{ServerEndpoint, post_json};
/// List workstreams that `run --workstream` can select in this checkout.
pub async fn run(config: &Config, args: WorkstreamsArgs) -> Result<()> {
let cwd = std::env::current_dir().context("getting managed workstream checkout")?;
- let repository = inspect_repository(&cwd)?;
let (workspace, project) =
super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
- let summaries: Vec<ManagedWorkstreamSummary> = post_json(
+ let summaries = list_for_checkout(
&endpoint,
- "/workstream/recent",
- &ListManagedWorkstreamsRequest {
- workspace: workspace.clone(),
- project: project.clone(),
- repo_fingerprint: repository.repo_fingerprint,
- worktree_fingerprint: repository.worktree_fingerprint,
- limit: usize::from(args.limit),
- },
+ &workspace,
+ &project,
+ &cwd,
+ usize::from(args.limit),
)
.await?;
if args.json {
@@ -37,6 +33,34 @@ pub async fn run(config: &Config, args: WorkstreamsArgs) -> Result<()> {
Ok(())
}
+/// List recent managed workstreams for one local checkout.
+///
+/// The server receives only its stable repository/worktree fingerprints; the
+/// checkout path stays client-local so a remote server can never choose or
+/// disclose a path on this host.
+pub(super) async fn list_for_checkout(
+ endpoint: &ServerEndpoint,
+ workspace: &str,
+ project: &str,
+ checkout: &Path,
+ limit: usize,
+) -> Result<Vec<ManagedWorkstreamSummary>> {
+ let repository =
+ inspect_repository(checkout).context("inspecting managed workstream checkout")?;
+ post_json(
+ endpoint,
+ "/workstream/recent",
+ &ListManagedWorkstreamsRequest {
+ workspace: workspace.to_owned(),
+ project: project.to_owned(),
+ repo_fingerprint: repository.repo_fingerprint,
+ worktree_fingerprint: repository.worktree_fingerprint,
+ limit,
+ },
+ )
+ .await
+}
+
fn render_human(summaries: &[ManagedWorkstreamSummary], workspace: &str, project: &str) -> String {
let mut output = format!("Managed workstreams for {workspace}/{project}:\n");
if summaries.is_empty() {
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 291d8653..34a0c2b6 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -95,6 +95,13 @@ async fn main() -> Result<()> {
}
Ok(())
}
+ Command::Resume(args) => {
+ let exit_code = commands::resume::run(&config, args).await?;
+ if exit_code != 0 {
+ std::process::exit(exit_code);
+ }
+ Ok(())
+ }
Command::Handoffs(args) => commands::handoffs::run(&config, args).await,
Command::Workstreams(args) => commands::workstreams::run(&config, args).await,
Command::RenameWorkstream(args) => commands::rename_workstream::run(&config, args).await,
diff --git a/crates/ai-memory-cli/tests/packaging.rs b/crates/ai-memory-cli/tests/packaging.rs
index 2072d443..5b1c6ff9 100644
--- a/crates/ai-memory-cli/tests/packaging.rs
+++ b/crates/ai-memory-cli/tests/packaging.rs
@@ -835,6 +835,7 @@ fn managed_host_commands_use_native_path_and_remote_server_without_docker() {
&["run", "codex", "--yolo", "resume"],
&["show", "--json", "--no-scan"],
&["continue", "--workspace", "work", "--yolo"],
+ &["resume", "--workspace", "work", "--limit", "5"],
&["workstreams", "--limit", "5", "--json"],
&["rename-workstream", "--from", "old", "--to", "new"],
];
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 0b01e61e..318648fe 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -442,23 +442,22 @@ the explicit `install-mcp --client claude-code --session-aware` option.
```
init status run
-show continue workstreams
-workstream-search audit-contamination search
-read-page write-page delete-page
-serve reset backup
-restore reindex install-hooks
-hook install-mcp commit
-checkpoints restore-page llm-test
-forget-sweep lint curator
-auto-improve-report auto-improve finalize-session
-pending-writes embed generate-auth-token
-setup-agent bootstrap install-instructions
-install-skills reorg purge-project
-rename-project move-project move-session
-uninstall auth user
-completions handoffs purge-session
-compact
-rename-workstream
+show continue resume
+workstreams rename-workstream workstream-search
+audit-contamination search read-page
+write-page delete-page serve
+reset backup restore
+reindex install-hooks hook
+install-mcp commit checkpoints
+restore-page llm-test forget-sweep
+lint curator auto-improve-report
+auto-improve finalize-session pending-writes
+embed generate-auth-token setup-agent
+bootstrap install-instructions install-skills
+reorg purge-project rename-project
+move-project move-session uninstall
+auth user completions
+handoffs purge-session compact
```
Run `ai-memory --help` for the full tree.
diff --git a/docs/install.md b/docs/install.md
index 2a545b51..b4e65df6 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -1795,6 +1795,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree
| `run [harness] [args...]` | host wrapper or native binary | Opt into one managed cross-harness workstream; omit the harness to resume the newest usable local session, or name Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Command Code, Kiro CLI v2/v3, OMP, Grok Build CLI, or Antigravity CLI explicitly; exact `--yolo` and `--fresh` flags are wrapper-owned and other native arguments pass through |
| `show [--json]` | host wrapper or native binary | Choose a client-local checkout and installed managed harness, or return structured discovery data without launching; remote servers never provide checkout paths |
| `continue [--workspace NAME]` | host wrapper or native binary | From any directory, revalidate and resume the newest client-local managed checkout; accepts `--yolo` and `--fresh` but no harness-native arguments |
+| `resume [--workspace NAME] [--limit N]` | host wrapper or native binary | Interactively choose a recent managed workstream from valid client-local checkouts; Up/Down selects the workstream and Left/Right cycles `auto` plus installed harnesses before launch; accepts `--yolo` and `--fresh` |
| `workstreams [--workspace NAME] [--project NAME] [--limit N] [--json]` | host wrapper or native binary | List recent workstreams selectable from the current checkout, including current selection and linked harnesses, without exposing paths or native session ids |
| `rename-workstream (--from NAME \| --workstream-id ID) --to NAME [--workspace NAME] [--project NAME] [--json]` | host wrapper or native binary | Retitle one workstream selectable from the current checkout; metadata only, so the stable id, the ledger, the listing order, and the current selection are unaffected |
| `workstream-search [query]` | managed child or thin HTTP client | Search the complete visible managed-workstream ledger; the managed child receives its workstream id automatically |
@@ -2089,7 +2090,7 @@ warns that relabeling system directories such as `/home` can make the host
inoperable. Docker documents `label=disable` in the
[`docker run` security options](https://docs.docker.com/reference/cli/docker/container/run/#security-opt).
-`ai-memory run`, `ai-memory show`, `ai-memory continue`,
+`ai-memory run`, `ai-memory show`, `ai-memory continue`, `ai-memory resume`,
`ai-memory workstreams`, and `ai-memory rename-workstream` are the exceptions:
the current wrapper intercepts them and starts a cached checksum-verified native
client on the host, where local checkouts, harness executables, and session
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index 9410d814..d1eb5437 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -150,6 +150,39 @@ directory, including automatic harness selection. `continue` therefore accepts
`--workspace`, `--yolo`, and `--fresh`, but not native harness arguments or
`--executable`, whose meaning depends on a harness the user did not name.
+## Picking a workstream
+
+`ai-memory resume` is the interactive counterpart to `continue`: it presents
+recent workstreams from every valid client-local managed checkout, then launches
+the selected named workstream without needing a `cd` first.
+
+```bash
+ai-memory resume
+ai-memory resume --workspace work --limit 50
+```
+
+Use Up/Down (or `j`/`k`) 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
+discovery of the newest usable session; the remaining choices are supported
+harness executables detected in the host `PATH`. Enter launches the displayed
+workstream/harness combination, while Escape or `q` cancels.
+
+The current selection for each checkout leads the picker, followed by recent
+activity. Each row identifies its workspace/project, activity age, selected
+launch harness, and already linked harnesses. Choosing a different harness is
+how an existing workstream can be continued in another agent. `--yolo` and
+`--fresh` are forwarded to the eventual managed launch.
+
+The picker seeds discovery with the current checkout and paths from this host's
+private `client-projects.json` registry. It revalidates both the canonical path
+and resolved scope before it asks the server for that checkout's workstreams,
+and deduplicates the same workstream reached through both sources. The server
+receives only the repository/worktree fingerprints required for the existing
+checkout-local listing, never a host path. It needs an interactive terminal;
+scripts can continue to use `ai-memory workstreams --json` after selecting a
+checkout themselves.
+
## Automatic harness selection
With no harness name, `ai-memory run` inspects checkout-local sessions for
@@ -444,14 +477,14 @@ original config is not modified. ai-memory opens the project database read-only;
the launched Crush process continues its normal native session writes.
The Linux/macOS Docker shell wrapper cannot inspect host projects or execute a
-host agent from inside its helper container. For `run`, `show`, `continue`, and
-`workstreams`, it downloads the matching native release into
+host agent from inside its helper container. For `run`, `show`, `continue`,
+`resume`, and `workstreams`, it downloads the matching native release into
`~/.cache/ai-memory/native-runner`, verifies the published SHA-256 checksum, and
executes that host client. Set `AI_MEMORY_NATIVE_BIN=/path/to/ai-memory` to use a
specific native build. Native package, release, and source installs need no
shim. On native Windows, use the published `ai-memory.exe` or a source build.
-The wrapper intercepts all four commands before Docker and preserves the host
+The wrapper intercepts all five commands before Docker and preserves the host
`PATH`, `AI_MEMORY_SERVER_URL`, and authentication environment. The native client's
startup log shows `server_url` as well as its local config paths; `data_dir` and
`bind` describe local defaults and do not override a configured remote server.