Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(cli): add `ai-memory continue` for global session resume
Vivaldo Junior82882ba87d80
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8aefb7c6..7a20b0a2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Added `ai-memory continue`, which resumes the most recently launched managed+ checkout from any directory. `run`'s bare mode already continues the current+ checkout, but its workstream lookup is keyed by repository and worktree+ fingerprints, so it requires a `cd` first. `continue` orders the client-local+ checkout links by their `linked_at` stamp, revalidates the newest one's path+ and resolved scope, and then delegates to the same bare-mode launch. Stale,+ retargeted, or scope-mismatched links are announced on stderr and skipped+ rather than silently resuming a different project. It accepts `--workspace`,+ `--yolo`, and `--fresh`; native harness arguments and `--executable` remain+ unavailable because bare mode does not know which harness it will pick+ (#349).+## [1.22.0] - 2026-08-01### Addeddiff --git a/README.md b/README.mdindex 0e0d8d1d..305a7020 100644--- a/README.md+++ b/README.md@@ -230,6 +230,19 @@ priors are at the [bottom](#influences-and-prior-art).Codex, OpenCode, Pi, Crush, Kimi Code, OMP, Grok Build CLI, and AntigravityCLI; direct harness launches remain unchanged. See[Managed cross-harness workstreams](docs/managed-workstreams.md).+- **"Just put me back where I was."** From any directory, with no name to+ type and no list to read:++ ```bash+ ai-memory continue+ ```++ It picks the checkout whose managed launch is most recent, revalidates the+ path and its resolved scope, then continues there exactly as bare+ `ai-memory run` would. A link whose directory moved, was replaced, or now+ resolves to a different project is reported on stderr and skipped, so a+ resume never quietly lands in the wrong project. `--workspace` narrows the+ search; `--yolo` and `--fresh` are forwarded.- **"Quit at 4 PM, pick up at 9 AM in a different agent."** Theclassic. SessionStart hook in the next supported hook client prepends atyped handoff with open questions, next steps, and a session summary. Grokdiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex e8f1b753..e311eb93 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -40,6 +40,9 @@ pub enum Command {/// Pick a local project and installed harness, then launch from that/// checkout. Removes the `cd` step `run` requires.Show(ShowArgs),+ /// Resume the most recently launched managed checkout from anywhere,+ /// without `cd` and without picking from a list.+ Continue(ContinueArgs),/// Search the complete visible event ledger for a managed workstream.WorkstreamSearch(WorkstreamSearchArgs),/// Audit the store for likely cross-project contamination (read-only,@@ -265,6 +268,26 @@ pub struct ShowArgs {pub native_args: Vec<OsString>,}+/// Arguments for `continue`.+///+/// Deliberately smaller than [`ShowArgs`]: `continue` always delegates to+/// `run`'s bare mode, which rejects native argv and `--executable` because+/// their meaning depends on a harness the user did not name.+#[derive(Debug, Args)]+pub struct ContinueArgs {+ /// Only consider checkouts resolving to this workspace.+ #[arg(long)]+ pub workspace: Option<String>,+ /// 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 `workstream-search`.#[derive(Debug, Args)]pub struct WorkstreamSearchArgs {@@ -1706,6 +1729,34 @@ mod tests {);}+ /// `continue` always delegates to `run`'s bare mode, which refuses native+ /// argv and `--executable`. Rejecting them at parse time keeps that+ /// contract visible in `--help` instead of failing after the launch has+ /// already started resolving a workstream.+ #[test]+ fn continue_takes_wrapper_flags_only() {+ let parsed =+ Cli::try_parse_from(["ai-memory", "continue", "--workspace", "work", "--yolo"])+ .expect("continue parses wrapper flags");+ let Command::Continue(args) = parsed.command else {+ panic!("expected continue command");+ };+ assert_eq!(args.workspace.as_deref(), Some("work"));+ assert!(args.yolo);+ assert!(!args.fresh);++ for rejected in [+ vec!["ai-memory", "continue", "claude"],+ vec!["ai-memory", "continue", "--model", "opus"],+ vec!["ai-memory", "continue", "--executable", "/bin/claude"],+ ] {+ 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.rsnew file mode 100644index 00000000..7749da32--- /dev/null+++ b/crates/ai-memory-cli/src/commands/continue_session.rs@@ -0,0 +1,311 @@+//! `ai-memory continue` — resume the most recent managed checkout globally.+//!+//! `run`'s bare mode already continues the current checkout's newest usable+//! session, but its workstream lookup is keyed by `(workspace, project,+//! repo fingerprint, worktree fingerprint)`, so the caller must already be+//! inside the project. This command supplies the missing step: it picks the+//! checkout from the client-local registry, then hands the same bare-mode+//! launch the directory to run in.+//!+//! Ordering comes from `ProjectLink::linked_at`, which every successful+//! managed prepare refreshes. No server round-trip decides the checkout: the+//! server never exposes host filesystem paths, and a stale or retargeted+//! link must be rejected on this host anyway.++use std::path::PathBuf;++use anyhow::{Result, bail};++use crate::cli::{ContinueArgs, RunArgs};+use crate::commands::project_registry::{self, ProjectLink};+use crate::commands::show::{terminal_text, validate_registered_path};+use crate::config::Config;+use crate::http_client::ServerEndpoint;++/// Resolve the newest still-valid checkout and continue it.+pub async fn run(config: &Config, args: ContinueArgs) -> Result<i32> {+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;+ let links = project_registry::links_for_server(config, &endpoint)?;+ let candidates = filter_workspace(links, args.workspace.as_deref());+ if candidates.is_empty() {+ bail!(+ "no managed checkout is linked for this server yet; \+ launch one with `ai-memory show` or `ai-memory run <harness>` first"+ );+ }++ let mut rejected = Vec::new();+ for link in newest_first(candidates) {+ let target = match resolve_target(config, &link) {+ Ok(target) => target,+ Err(reason) => {+ // Never fall through to an older checkout silently: the user+ // asked for "where I was", and landing somewhere else without+ // saying so would attach this session to the wrong project.+ // The reason quotes the registry's own path, so it is+ // stripped like every other stored string before it reaches+ // the terminal.+ let label = scope_label(&link);+ eprintln!("skipping {label}: {}", terminal_text(&reason.to_string()));+ rejected.push(label);+ continue;+ }+ };+ eprintln!(+ "continuing {} in {}",+ scope_label(&link),+ terminal_text(&target.to_string_lossy())+ );+ return crate::commands::run::run_from(+ config,+ RunArgs {+ workspace: Some(link.workspace),+ project: Some(link.project),+ workstream: None,+ new_workstream: None,+ executable: None,+ yolo: args.yolo,+ fresh: args.fresh,+ // Bare mode: `run` resolves the harness that owns the newest+ // usable session for this workstream.+ harness: None,+ native_args: Vec::new(),+ },+ &target,+ )+ .await;+ }++ bail!(+ "no linked checkout is still usable ({} skipped); \+ pick one explicitly with `ai-memory show`",+ rejected.len()+ )+}++fn filter_workspace(links: Vec<ProjectLink>, workspace: Option<&str>) -> Vec<ProjectLink> {+ match workspace {+ Some(name) => links.into_iter().filter(|l| l.workspace == name).collect(),+ None => links,+ }+}++/// Order links newest-first.+///+/// An unparsable `linked_at` sorts last rather than aborting: one corrupt+/// row must not make every other checkout unreachable. Ties break on+/// `(workspace, project)` so the choice is deterministic.+fn newest_first(mut links: Vec<ProjectLink>) -> Vec<ProjectLink> {+ links.sort_by(|a, b| {+ linked_at(b)+ .cmp(&linked_at(a))+ .then_with(|| a.workspace.cmp(&b.workspace))+ .then_with(|| a.project.cmp(&b.project))+ });+ links+}++fn linked_at(link: &ProjectLink) -> Option<jiff::Timestamp> {+ link.linked_at.parse().ok()+}++/// Revalidate a stored checkout before launching anything inside it.+///+/// Both checks matter. The path check rejects a directory that moved or was+/// 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> {+ let path = validate_registered_path(&link.path)?;+ let (workspace, project) = super::resolve_scope_for_path(config, &path)?;+ if workspace != link.workspace || project != link.project {+ bail!(+ "checkout now resolves to {}/{}",+ terminal_text(&workspace),+ terminal_text(&project)+ );+ }+ Ok(path)+}++fn scope_label(link: &ProjectLink) -> String {+ terminal_text(&format!("{}/{}", link.workspace, link.project))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn link(workspace: &str, project: &str, linked_at: &str) -> ProjectLink {+ ProjectLink {+ server: "http://127.0.0.1:49374".to_owned(),+ workspace: workspace.to_owned(),+ project: project.to_owned(),+ path: PathBuf::from("/checkout").join(project),+ linked_at: linked_at.to_owned(),+ }+ }++ fn projects(links: &[ProjectLink]) -> Vec<&str> {+ links.iter().map(|l| l.project.as_str()).collect()+ }++ #[test]+ fn newest_linked_checkout_wins() {+ let ordered = newest_first(vec![+ link("default", "older", "2026-07-01T10:00:00Z"),+ link("default", "newest", "2026-08-01T09:00:00Z"),+ link("default", "middle", "2026-07-20T23:59:59Z"),+ ]);+ assert_eq!(projects(&ordered), ["newest", "middle", "older"]);+ }++ /// Timestamps are compared as instants, not strings: an offset spelling+ /// that sorts earlier lexically can still be the newer instant.+ #[test]+ fn ordering_compares_instants_not_raw_strings() {+ let ordered = newest_first(vec![+ link("default", "utc", "2026-08-01T09:00:00Z"),+ link("default", "offset", "2026-08-01T11:30:00+02:00"),+ ]);+ assert_eq!(projects(&ordered), ["offset", "utc"]);+ }++ /// One corrupt row must not strand every other checkout.+ #[test]+ fn unparsable_timestamps_sort_last_without_failing() {+ let ordered = newest_first(vec![+ link("default", "corrupt", "not-a-timestamp"),+ link("default", "valid", "2026-01-01T00:00:00Z"),+ ]);+ assert_eq!(projects(&ordered), ["valid", "corrupt"]);+ }++ #[test]+ fn equal_timestamps_break_ties_deterministically() {+ let same = "2026-08-01T09:00:00Z";+ let first = newest_first(vec![+ link("b-workspace", "zeta", same),+ link("a-workspace", "alpha", same),+ ]);+ let second = newest_first(vec![+ link("a-workspace", "alpha", same),+ link("b-workspace", "zeta", same),+ ]);+ assert_eq!(projects(&first), ["alpha", "zeta"]);+ assert_eq!(projects(&first), projects(&second));+ }++ #[test]+ fn empty_registry_orders_to_nothing() {+ assert!(newest_first(Vec::new()).is_empty());+ }++ fn config_at(path: &std::path::Path) -> Config {+ Config {+ data_dir: path.to_path_buf(),+ ..Config::default()+ }+ }++ fn make_project(root: &std::path::Path, name: &str) -> PathBuf {+ let path = root.join(name);+ std::fs::create_dir_all(&path).unwrap();+ std::fs::write(path.join("Cargo.toml"), b"").unwrap();+ path.canonicalize().unwrap()+ }++ fn link_to(path: PathBuf, workspace: &str, project: &str) -> ProjectLink {+ ProjectLink {+ server: "http://127.0.0.1:49374".to_owned(),+ workspace: workspace.to_owned(),+ project: project.to_owned(),+ path,+ linked_at: "2026-08-01T09:00:00Z".to_owned(),+ }+ }++ #[test]+ fn a_checkout_whose_scope_still_matches_resolves() {+ let tmp = tempfile::TempDir::new().unwrap();+ let project = make_project(tmp.path(), "app");+ let link = link_to(project.clone(), "default", "app");++ assert_eq!(+ resolve_target(&config_at(tmp.path()), &link).unwrap(),+ project+ );+ }++ /// A checkout that was deleted (or renamed) must not resume: the launch+ /// would otherwise start in whatever now occupies the path.+ #[test]+ fn a_missing_checkout_is_rejected() {+ let tmp = tempfile::TempDir::new().unwrap();+ let project = make_project(tmp.path(), "app");+ let link = link_to(project.clone(), "default", "app");+ std::fs::remove_dir_all(&project).unwrap();++ assert!(resolve_target(&config_at(tmp.path()), &link).is_err());+ }++ /// The link's recorded scope is authoritative. If the directory now+ /// resolves elsewhere, resuming would file this session's memory under+ /// the wrong project.+ #[test]+ fn a_checkout_that_changed_scope_is_rejected() {+ let tmp = tempfile::TempDir::new().unwrap();+ let project = make_project(tmp.path(), "app");+ let link = link_to(project, "default", "was-named-differently");++ let error = resolve_target(&config_at(tmp.path()), &link).unwrap_err();+ assert!(+ error.to_string().contains("now resolves to"),+ "unexpected error: {error}"+ );+ }++ /// Registry strings reach the terminal on the skip path, so an escape+ /// sequence stored in a checkout path must not be replayed.+ #[test]+ fn skip_reasons_are_stripped_before_reaching_the_terminal() {+ let tmp = tempfile::TempDir::new().unwrap();+ let link = link_to(+ PathBuf::from("/missing\u{1b}[31m/checkout"),+ "default",+ "app",+ );++ let reason = resolve_target(&config_at(tmp.path()), &link).unwrap_err();+ let rendered = terminal_text(&reason.to_string());+ assert!(!rendered.contains('\u{1b}'), "escape survived: {rendered}");+ }++ /// A recorded directory replaced by a symlink pointing somewhere else+ /// must not be followed.+ #[cfg(unix)]+ #[test]+ fn a_checkout_replaced_by_a_symlink_is_rejected() {+ let tmp = tempfile::TempDir::new().unwrap();+ let real = make_project(tmp.path(), "app");+ let elsewhere = make_project(tmp.path(), "elsewhere");+ let link = link_to(real.clone(), "default", "app");++ std::fs::remove_dir_all(&real).unwrap();+ std::os::unix::fs::symlink(&elsewhere, &real).unwrap();++ assert!(resolve_target(&config_at(tmp.path()), &link).is_err());+ }++ #[test]+ fn workspace_filter_keeps_only_the_requested_scope() {+ let links = vec![+ link("work", "api", "2026-08-01T09:00:00Z"),+ link("personal", "blog", "2026-08-02T09:00:00Z"),+ ];+ let filtered = filter_workspace(links.clone(), Some("work"));+ assert_eq!(projects(&filtered), ["api"]);+ assert_eq!(filter_workspace(links.clone(), Some("absent")).len(), 0);+ assert_eq!(filter_workspace(links, None).len(), 2);+ }+}diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex d52fdb35..81ba57ca 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -14,6 +14,7 @@ pub mod bootstrap;pub mod checkpoints;pub mod commit;pub mod completions;+pub mod continue_session;pub mod curator;pub mod data_purge;pub mod delete_page;diff --git a/crates/ai-memory-cli/src/commands/show.rs b/crates/ai-memory-cli/src/commands/show.rsindex 7709959d..2031a87e 100644--- a/crates/ai-memory-cli/src/commands/show.rs+++ b/crates/ai-memory-cli/src/commands/show.rs@@ -421,7 +421,12 @@ fn available_harnesses() -> Vec<RunHarnessChoice> {.collect()}-fn validate_registered_path(path: &Path) -> Result<PathBuf> {+/// Re-check a stored checkout path immediately before it is used.+///+/// The canonical-equality check is the load-bearing one: it rejects a+/// recorded directory that has since been replaced by a symlink pointing+/// somewhere else, before any harness is launched inside it.+pub(super) fn validate_registered_path(path: &Path) -> Result<PathBuf> {if !path.is_absolute() {bail!("stored checkout path is not absolute");}@@ -633,7 +638,7 @@ fn harness_name(harness: RunHarnessChoice) -> String {.map_or_else(|| "unknown".to_owned(), |value| value.get_name().to_owned())}-fn terminal_text(text: &str) -> String {+pub(super) fn terminal_text(text: &str) -> String {text.chars().map(|character| {if character.is_control() {diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rsindex 99462c97..2c8c60bd 100644--- a/crates/ai-memory-cli/src/main.rs+++ b/crates/ai-memory-cli/src/main.rs@@ -88,6 +88,13 @@ async fn main() -> Result<()> {}Ok(())}+ Command::Continue(args) => {+ let exit_code = commands::continue_session::run(&config, args).await?;+ if exit_code != 0 {+ std::process::exit(exit_code);+ }+ Ok(())+ }Command::WorkstreamSearch(args) => commands::workstream_search::run(&config, args).await,Command::AuditContamination(args) => {commands::audit_contamination::run(&config, args).awaitdiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex a60e2f5f..8731cdb0 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -411,20 +411,20 @@ the explicit `install-mcp --client claude-code --session-aware` option.```init status run-show 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-uninstall auth user-completions+show continue 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 uninstall auth+user completions```Run `ai-memory --help` for the full tree.diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 70bcb8da..49f54a89 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -84,6 +84,36 @@ all setup succeeds. `--yolo`, `--fresh`, and trailing native arguments apply tothe selected harness. Non-terminal callers must use `--json`; JSON cannot becombined with launch arguments.+## Continuing from anywhere++Bare `ai-memory run` continues the current checkout, but its workstream lookup+is keyed by `(workspace, project, repo fingerprint, worktree fingerprint)`, so+the caller must already be in the project. `ai-memory continue` supplies the+missing step and needs no `cd`:++```bash+ai-memory continue+ai-memory continue --workspace work+```++The checkout is chosen entirely on the client, from the `linked_at` stamp that+every successful managed prepare writes to `client-projects.json`. The server+is never asked which directory to use — it does not expose host paths, and a+link can only be trusted after this host revalidates it.++Before launching, the newest link is rechecked twice: the recorded path must+still canonicalize to itself (rejecting a directory that moved or was replaced+by a symlink), and it must still resolve to the same `(workspace, project)`+(rejecting a checkout that would file this session's memory under a different+scope). A link failing either check is named on stderr and skipped, and the+next-newest link is tried. Falling through is never silent: the selected+project and path are always printed before the harness starts.++Once a checkout is selected, the launch is exactly bare `ai-memory run` in that+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.+## Automatic harness selectionWith no harness name, `ai-memory run` inspects checkout-local sessions for