Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(cli): harden global managed resume
AkitaOnRailsdc2a210cf4ff
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e8bd7686..79e23199 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,10 +14,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0fingerprints, so it requires a `cd` first. `continue` orders the client-localcheckout links by their `linked_at` stamp, revalidates the newest one's pathand 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`,+ retargeted, scope-mismatched, or corrupt-ordering 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+ unavailable because bare mode does not know which harness it will pick.+ Docker-wrapper installs route the command through the checksum-verified host+ client so it can inspect local checkouts, session stores, and harnesses(#350).- New `GET /admin/sessions/by-agent` endpoint reporting how many sessionseach agent CLI opened in one scope (`claude-code`, `cursor`, `codex`, …),diff --git a/README.md b/README.mdindex 305a7020..a841b562 100644--- a/README.md+++ b/README.md@@ -239,10 +239,11 @@ priors are at the [bottom](#influences-and-prior-art).It picks the checkout whose managed launch is most recent, revalidates thepath 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.+ `ai-memory run` would. A link whose directory moved, was replaced, now+ resolves to a different project, or has a corrupt ordering timestamp 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. Grok@@ -518,6 +519,8 @@ ai-memory run claudeai-memory run codex --yolo# omit the name to continue the newest usable local harness sessionai-memory run+# or resume the newest managed checkout without changing directories first+ai-memory continue```To remove ai-memory later, run `ai-memory uninstall --apply` from the@@ -553,10 +556,11 @@ one matching entry.MCP/hooks. Explicit `--server-url` flags still work, but are no longerrequired when the env vars are set. Any non-loopback server should usebearer auth.-- **Managed-launch wrapper:** `ai-memory run` and `ai-memory show` must be- intercepted by the current host wrapper so local checkouts, native harnesses,- and session stores remain accessible. An old wrapper may pass either command- into Docker and fail to find a checkout or host executable. Run+- **Managed-launch wrapper:** `ai-memory run`, `ai-memory show`, and+ `ai-memory continue` 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 runnerinherits `AI_MEMORY_SERVER_URL`, `AI_MEMORY_AUTH_TOKEN`, and the host `PATH`.- **Upgrades:** for Docker-wrapper installs, run `ai-memory upgrade` on eachdiff --git a/bin/ai-memory b/bin/ai-memoryindex 23328a09..1a2d85d7 100755--- a/bin/ai-memory+++ b/bin/ai-memory@@ -11,6 +11,7 @@# ai-memory upgrade Pull the latest image + remind to re-stage hooks.# ai-memory run ... Use a cached native client so it can exec host agents.# ai-memory show ... Use that client for host project/harness discovery.+# ai-memory continue ... Use that client to resume the newest linked checkout.## Env overrides:# AI_MEMORY_IMAGE docker image (default: akitaonrails/ai-memory:latest)@@ -23,7 +24,7 @@# COPILOT_GITHUB_TOKEN GitHub token for AI_MEMORY_LLM_PROVIDER=copilot# AI_MEMORY_NO_TTY=1 force non-interactive even on a real tty# AI_MEMORY_NO_VERSION_CHECK=1 skip the once-per-day update check-# AI_MEMORY_NATIVE_BIN native ai-memory binary used for `run`/`show` (optional)+# AI_MEMORY_NATIVE_BIN native binary used for `run`/`show`/`continue` (optional)# AI_MEMORY_WRAPPER_URL wrapper release asset override (optional; its# .sha256 companion is required)# AI_MEMORY_WRAPPER_SHA256_URL wrapper checksum URL override (optional)@@ -224,7 +225,7 @@ cmd_upgrade() {touch "${VERSION_CHECK_FILE}"}-# `ai-memory run` and `show` must execute on the host: checkouts, harnesses,+# `ai-memory run`, `show`, and `continue` must execute on the host: checkouts, harnesses,# and native transcript stores are host resources, not contents of the helper# container. Keep a checksum-verified release client beside the wrapper cache.native_host_binary() {@@ -243,7 +244,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" >&2+ echo "install the native release binary to use ai-memory run/show/continue" >&2return 1;;esac@@ -318,7 +319,7 @@ case "${1:-}" incmd_upgradeexit 0;;- run | show)+ run | show | continue)NATIVE_HOST_COMMAND=$1shiftNATIVE_HOST_BIN=$(native_host_binary)diff --git a/crates/ai-memory-cli/src/commands/continue_session.rs b/crates/ai-memory-cli/src/commands/continue_session.rsindex 7749da32..7ee1cfd0 100644--- a/crates/ai-memory-cli/src/commands/continue_session.rs+++ b/crates/ai-memory-cli/src/commands/continue_session.rs@@ -34,8 +34,15 @@ pub async fn run(config: &Config, args: ContinueArgs) -> Result<i32> {);}- let mut rejected = Vec::new();- for link in newest_first(candidates) {+ let (candidates, invalid_timestamps) = newest_first(candidates);+ let mut rejected = invalid_timestamps.len();+ for link in invalid_timestamps {+ eprintln!(+ "skipping {}: client registry has an invalid linked_at timestamp",+ scope_label(&link)+ );+ }+ for link in candidates {let target = match resolve_target(config, &link) {Ok(target) => target,Err(reason) => {@@ -47,7 +54,7 @@ pub async fn run(config: &Config, args: ContinueArgs) -> Result<i32> {// the terminal.let label = scope_label(&link);eprintln!("skipping {label}: {}", terminal_text(&reason.to_string()));- rejected.push(label);+ rejected += 1;continue;}};@@ -79,7 +86,7 @@ pub async fn run(config: &Config, args: ContinueArgs) -> Result<i32> {bail!("no linked checkout is still usable ({} skipped); \pick one explicitly with `ai-memory show`",- rejected.len()+ rejected)}@@ -92,17 +99,25 @@ fn filter_workspace(links: Vec<ProjectLink>, workspace: Option<&str>) -> Vec<Pro/// 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))+/// Corrupt timestamps are returned separately and are never launch candidates.+/// One bad row must not strand valid checkouts. Ties break on `(workspace,+/// project)` so the choice is deterministic.+fn newest_first(links: Vec<ProjectLink>) -> (Vec<ProjectLink>, Vec<ProjectLink>) {+ let mut valid = Vec::with_capacity(links.len());+ let mut invalid = Vec::new();+ for link in links {+ match linked_at(&link) {+ Some(timestamp) => valid.push((timestamp, link)),+ None => invalid.push(link),+ }+ }+ valid.sort_by(|(a_timestamp, a_link), (b_timestamp, b_link)| {+ b_timestamp+ .cmp(a_timestamp)+ .then_with(|| a_link.workspace.cmp(&b_link.workspace))+ .then_with(|| a_link.project.cmp(&b_link.project))});- links+ (valid.into_iter().map(|(_, link)| link).collect(), invalid)}fn linked_at(link: &ProjectLink) -> Option<jiff::Timestamp> {@@ -152,11 +167,12 @@ mod tests {#[test]fn newest_linked_checkout_wins() {- let ordered = newest_first(vec![+ let (ordered, invalid) = 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!(invalid.is_empty());assert_eq!(projects(&ordered), ["newest", "middle", "older"]);}@@ -164,41 +180,47 @@ mod tests {/// that sorts earlier lexically can still be the newer instant.#[test]fn ordering_compares_instants_not_raw_strings() {- let ordered = newest_first(vec![+ let (ordered, invalid) = newest_first(vec![link("default", "utc", "2026-08-01T09:00:00Z"),link("default", "offset", "2026-08-01T11:30:00+02:00"),]);+ assert!(invalid.is_empty());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![+ fn unparsable_timestamps_are_rejected_without_stranding_valid_links() {+ let (ordered, invalid) = newest_first(vec![link("default", "corrupt", "not-a-timestamp"),link("default", "valid", "2026-01-01T00:00:00Z"),]);- assert_eq!(projects(&ordered), ["valid", "corrupt"]);+ assert_eq!(projects(&ordered), ["valid"]);+ assert_eq!(projects(&invalid), ["corrupt"]);}#[test]fn equal_timestamps_break_ties_deterministically() {let same = "2026-08-01T09:00:00Z";- let first = newest_first(vec![+ let (first, first_invalid) = newest_first(vec![link("b-workspace", "zeta", same),link("a-workspace", "alpha", same),]);- let second = newest_first(vec![+ let (second, second_invalid) = newest_first(vec![link("a-workspace", "alpha", same),link("b-workspace", "zeta", same),]);+ assert!(first_invalid.is_empty());+ assert!(second_invalid.is_empty());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());+ let (ordered, invalid) = newest_first(Vec::new());+ assert!(ordered.is_empty());+ assert!(invalid.is_empty());}fn config_at(path: &std::path::Path) -> Config {diff --git a/crates/ai-memory-cli/src/commands/project_registry.rs b/crates/ai-memory-cli/src/commands/project_registry.rsindex e80ea7f1..084c10fe 100644--- a/crates/ai-memory-cli/src/commands/project_registry.rs+++ b/crates/ai-memory-cli/src/commands/project_registry.rs@@ -129,7 +129,6 @@ pub(super) fn rekey_scope(if !destination_exists {source.workspace = to_workspace.to_owned();source.project = to_project.to_owned();- source.linked_at = jiff::Timestamp::now().to_string();registry.links.push(source);}Ok(true)@@ -395,4 +394,28 @@ mod tests {assert_eq!(links.len(), 1);assert_eq!(links[0].path, destination.canonicalize().unwrap());}++ #[test]+ fn rekey_preserves_the_source_link_timestamp() {+ let tmp = tempfile::TempDir::new().unwrap();+ let source = tmp.path().join("source");+ fs::create_dir(&source).unwrap();+ let config = config_at(&tmp.path().join("data"));+ let endpoint = endpoint("http://memory:49374");+ record_prepared_checkout(&config, &endpoint, "from", "app", &source).unwrap();+ let original_linked_at = "2025-01-02T03:04:05Z";+ update_registry(&config, |registry| {+ registry.links[0].linked_at = original_linked_at.to_owned();+ Ok(true)+ })+ .unwrap();++ rekey_scope(&config, &endpoint, "from", "app", "to", "renamed").unwrap();++ let links = links_for_server(&config, &endpoint).unwrap();+ assert_eq!(links.len(), 1);+ assert_eq!(links[0].workspace, "to");+ assert_eq!(links[0].project, "renamed");+ assert_eq!(links[0].linked_at, original_linked_at);+ }}diff --git a/crates/ai-memory-cli/tests/packaging.rs b/crates/ai-memory-cli/tests/packaging.rsindex d8a5935f..30a5d130 100644--- a/crates/ai-memory-cli/tests/packaging.rs+++ b/crates/ai-memory-cli/tests/packaging.rs@@ -769,7 +769,7 @@ fn hook_installer_writes_only_expected_files_from_a_verified_archive() {#[cfg(unix)]#[test]-fn managed_run_wrapper_uses_host_binary_path_and_remote_server_without_docker() {+fn managed_host_commands_use_native_path_and_remote_server_without_docker() {let tmp = tempfile::tempdir().unwrap();let native = tmp.path().join("native-ai-memory");let docker = tmp.path().join("docker");@@ -804,34 +804,40 @@ fn managed_run_wrapper_uses_host_binary_path_and_remote_server_without_docker()shell_path(tmp.path()),std::env::var("PATH").unwrap_or_default());- let output = shell_script_command(&repo_root().join("bin/ai-memory"))- .args(["run", "codex", "--yolo", "resume"])- .env("AI_MEMORY_NATIVE_BIN", &native)- .env("AI_MEMORY_DOCKER", &docker)- .env("AI_MEMORY_SERVER_URL", "http://192.168.0.90:49374")- .env("AI_MEMORY_AUTH_TOKEN", "remote-test-token")- .env("PATH", &host_path)- .output()- .unwrap();- assert!(- output.status.success(),- "wrapper failed: {}",- String::from_utf8_lossy(&output.stderr)- );- let record = std::fs::read_to_string(record).unwrap();- assert_eq!(- record,- format!(+ let commands: &[&[&str]] = &[+ &["run", "codex", "--yolo", "resume"],+ &["show", "--json", "--no-scan"],+ &["continue", "--workspace", "work", "--yolo"],+ ];+ for args in commands {+ let output = shell_script_command(&repo_root().join("bin/ai-memory"))+ .args(args.iter().copied())+ .env("AI_MEMORY_NATIVE_BIN", &native)+ .env("AI_MEMORY_DOCKER", &docker)+ .env("AI_MEMORY_SERVER_URL", "http://192.168.0.90:49374")+ .env("AI_MEMORY_AUTH_TOKEN", "remote-test-token")+ .env("PATH", &host_path)+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "wrapper failed for {args:?}: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let mut expected = format!("server=http://192.168.0.90:49374\n\auth=remote-test-token\n\- path={host_path}\n\- arg=run\n\- arg=codex\n\- arg=--yolo\n\- arg=resume\n"- )+ path={host_path}\n"+ );+ for arg in *args {+ expected.push_str(&format!("arg={arg}\n"));+ }+ assert_eq!(std::fs::read_to_string(&record).unwrap(), expected);+ }+ assert!(+ !docker_record.exists(),+ "managed host command entered Docker");- assert!(!docker_record.exists(), "managed run entered Docker");}#[cfg(unix)]diff --git a/docs/install.md b/docs/install.mdindex b682248c..f53f2ae5 100644--- a/docs/install.md+++ b/docs/install.md@@ -1259,6 +1259,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree| `serve` | `docker compose up -d` (already done) | Run the HTTP MCP server || `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, 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 || `workstream-search [query]` | managed child or thin HTTP client | Search the complete visible managed-workstream ledger; the managed child receives its workstream id automatically || `status` | `docker exec` | Counts, paths, derived-index diagnostics, and passive LLM/embedding provider health || `search "<query>"` | `docker exec` | Wiki FTS5 search + bounded source authority; use MCP `memory_query` for entity/graph/vector RRF |@@ -1522,10 +1523,11 @@ warns that relabeling system directories such as `/home` can make the hostinoperable. Docker documents `label=disable` in the[`docker run` security options](https://docs.docker.com/reference/cli/docker/container/run/#security-opt).-`ai-memory run` and `ai-memory show` 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 stores exist. It-preserves an explicit remote `AI_MEMORY_SERVER_URL`. If either command logs+`ai-memory run`, `ai-memory show`, and `ai-memory continue` 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+stores exist. It preserves an explicit remote `AI_MEMORY_SERVER_URL`. If one of+these commands logs`data_dir=/data`, cannot find a checkout, or cannot find `codex`, `claude`, oranother host executable, refresh the stale wrapper with `ai-memory upgrade` onthat client machine.diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 49f54a89..5a824a36 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -106,7 +106,8 @@ still canonicalize to itself (rejecting a directory that moved or was replacedby a symlink), and it must still resolve to the same `(workspace, project)`(rejecting a checkout that would file this session's memory under a differentscope). 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+next-newest link is tried. A corrupt `linked_at` timestamp is also reported and+never considered launchable. Falling through is never silent: the selectedproject and path are always printed before the harness starts.Once a checkout is selected, the launch is exactly bare `ai-memory run` in that@@ -351,15 +352,15 @@ 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` and `show`, it downloads-the matching native release into+host agent from inside its helper container. For `run`, `show`, and `continue`,+it downloads the matching native release into`~/.cache/ai-memory/native-runner`, verifies the published SHA-256 checksum, andexecutes that host client. Set `AI_MEMORY_NATIVE_BIN=/path/to/ai-memory` to use aspecific native build. Native package, release, and source installs need noshim. On native Windows, use the published `ai-memory.exe` or a source build.-The wrapper intercepts both commands before Docker and preserves the host `PATH`,-`AI_MEMORY_SERVER_URL`, and authentication environment. The native client's+The wrapper intercepts all three commands before Docker and preserves the host+`PATH`, `AI_MEMORY_SERVER_URL`, and authentication environment. The native client'sstartup 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.If logs showdiff --git a/scripts/check-native-packaging.sh b/scripts/check-native-packaging.shindex 5992d9b9..6b7fe2b7 100755--- a/scripts/check-native-packaging.sh+++ b/scripts/check-native-packaging.sh@@ -94,8 +94,12 @@ main() {AI_MEMORY_DOCKER="${fake_docker}" AI_MEMORY_NATIVE_BIN="${fake_native}" \AI_MEMORY_WRAPPER_TEST_LOG="${wrapper_log}" \bin/ai-memory show --json --no-scan+ AI_MEMORY_DOCKER="${fake_docker}" AI_MEMORY_NATIVE_BIN="${fake_native}" \+ AI_MEMORY_WRAPPER_TEST_LOG="${wrapper_log}" \+ bin/ai-memory continue --workspace work --yoloassert_contains "${wrapper_log}" "run codex --yolo"assert_contains "${wrapper_log}" "show --json --no-scan"+ assert_contains "${wrapper_log}" "continue --workspace work --yolo"log "Creating temporary alternate root"mkdir -p \