Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(cli): avoid working-tree scans before the resume picker
Paulo Vitor Martins7005f45b4d16
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d8e31270..5fdfb1df 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -136,6 +136,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0labelled `nix` / `full-ci`. (#989)### Fixed+- Removed unnecessary working-tree scans from checkout-local workstream listing+ and the resume picker, including `ai-jail ai-memory resume --yolo`; launching+ a selected workstream still captured its full checkpoint. (#1039)- Fixed completed retries and no-op session endings advancing`last_persisted_ms` without a durable write. Recovery still advances thetimestamp when it commits a new page or terminal effect. (#1015)diff --git a/README.md b/README.mdindex ddc6d700..80843af2 100644--- a/README.md+++ b/README.md@@ -372,6 +372,7 @@ ai-memory resume # pick from ALL workstreams in this checkout onlyai-memory resume --search auth # find a workstream by name (case-insensitive)ai-memory # same picker, when run in a terminalai-jail ai-memory # picker + selected harness inside ai-jail+ai-jail ai-memory resume --yolo # explicit picker + harness's dangerous modeai-jail --ssh ai-memory # also share SSH access```@@ -394,6 +395,22 @@ Running `ai-memory` without a subcommand in a terminal opens the same picker.ai-jail; add ai-jail options before `ai-memory`, such as `--ssh` above.This works with native installs and the Linux/macOS shell wrapper. Scriptsstill require an explicit CLI subcommand, and `ai-memory --help` shows help.+Workstream discovery reads Git identity only; it does not scan the working tree+with `git status` before showing the picker. Full checkpoints are still captured+when launching the selected workstream.++For an unreleased source build, install the native binary on your host `PATH`+before entering ai-jail. A temporary `/tmp` build is not a reliable executable+location inside the sandbox:++```bash+cargo build -p ai-memory-cli --bin ai-memory+mkdir -p "$HOME/.local/bin"+install -m755 target/debug/ai-memory "$HOME/.local/bin/ai-memory"+export PATH="$HOME/.local/bin:$PATH"+# Run from the checkout you want to resume:+ai-jail ai-memory resume --yolo+```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 withdiff --git a/crates/ai-memory-cli/src/commands/workstreams.rs b/crates/ai-memory-cli/src/commands/workstreams.rsindex e235e6fa..e6bee1f5 100644--- a/crates/ai-memory-cli/src/commands/workstreams.rs+++ b/crates/ai-memory-cli/src/commands/workstreams.rs@@ -5,7 +5,7 @@ use std::fmt::Write as _;use std::path::Path;use ai_memory_core::{ListManagedWorkstreamsRequest, ManagedWorkstreamSummary};-use ai_memory_workstream::inspect_repository;+use ai_memory_workstream::inspect_repository_fingerprints;use anyhow::{Context as _, Result};use crate::cli::WorkstreamsArgs;@@ -46,8 +46,8 @@ pub(super) async fn list_for_checkout(checkout: &Path,limit: usize,) -> Result<Vec<ManagedWorkstreamSummary>> {- let repository =- inspect_repository(checkout).context("inspecting managed workstream checkout")?;+ let repository = inspect_repository_fingerprints(checkout)+ .context("inspecting managed workstream checkout")?;post_json(endpoint,"/workstream/recent",@@ -70,8 +70,8 @@ pub(super) async fn list_all_for_checkout(project: &str,checkout: &Path,) -> Result<Vec<ManagedWorkstreamSummary>> {- let repository =- inspect_repository(checkout).context("inspecting managed workstream checkout")?;+ let repository = inspect_repository_fingerprints(checkout)+ .context("inspecting managed workstream checkout")?;let mut request = ListManagedWorkstreamsRequest {workspace: workspace.to_owned(),project: project.to_owned(),diff --git a/crates/ai-memory-cli/tests/suite/jail_toggles_e2e.rs b/crates/ai-memory-cli/tests/suite/jail_toggles_e2e.rsindex ae3967cf..aad2283f 100644--- a/crates/ai-memory-cli/tests/suite/jail_toggles_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/jail_toggles_e2e.rs@@ -794,6 +794,103 @@ async fn bare_nonterminal_command_help_version_and_typos_do_not_launch_a_picker(handle.abort();}+/// Run an installed ai-jail's actual PTY proxy without nesting a kernel sandbox.+/// The backend stub only executes the command after bwrap's separator.+#[cfg(target_os = "linux")]+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+#[ignore = "set AI_MEMORY_TEST_REAL_AI_JAIL to an ai-jail binary accepting a fixture BWRAP_BIN"]+async fn installed_ai_jail_proxy_displays_resume_yolo() {+ let jail = std::env::var_os("AI_MEMORY_TEST_REAL_AI_JAIL")+ .expect("AI_MEMORY_TEST_REAL_AI_JAIL points to the binary being tested");+ let fixture = Fixture::new(HELP_2_4_1, true, None);+ std::os::unix::fs::symlink(BIN, fixture.bin.join("ai-memory")).unwrap();+ write_script(+ &fixture.bin.join("bwrap"),+ "if [ \"$1\" = --version ]; then echo 'bubblewrap 0.11.0'; exit 0; fi\nwhile [ $# -gt 0 ]; do\nif [ \"$1\" = -- ]; then shift; exec \"$@\"; fi\nshift\ndone\nexit 1\n",+ );+ let (server, requests, handle) = mock_server().await;+ let launch = inside_ai_jail_here();+ let output = terminal_run_program(+ &fixture,+ &server,+ Path::new(&jail),+ "--no-landlock --no-seccomp --no-rlimits --no-mise --no-save-config --no-gpu --no-docker --no-display ai-memory resume --yolo",+ if launch { "\x1b[C\r" } else { "\x1b" },+ Some("Resume workstream"),+ )+ .await;+ assert!(output.contains("Resume workstream"), "{output}");+ if launch {+ let native_args = fs::read_to_string(&fixture.claude_ran).unwrap();+ assert!(+ native_args.contains("--dangerously-skip-permissions"),+ "{output}"+ );+ assert!(+ !output.contains("Re-run this session inside it?"),+ "{output}"+ );+ assert!(+ requests+ .lock()+ .unwrap()+ .iter()+ .any(|path| path.ends_with("/finish"))+ );+ } else {+ assert_eq!(requests.lock().unwrap().as_slice(), ["/workstream/recent"]);+ assert!(!fixture.claude_ran.exists());+ }+ handle.abort();+}++#[cfg(any(target_os = "linux", target_os = "macos"))]+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn resume_yolo_displays_picker_without_scanning_git_status() {+ let fixture = Fixture::new(HELP_2_4_1, true, None);+ std::os::unix::fs::symlink(BIN, fixture.bin.join("ai-memory")).unwrap();+ write_script(+ &fixture.bin.join("ai-jail"),+ &format!(+ "printf '%s\\n' \"$@\" > '{}'\nexec \"$@\"\n",+ fixture.jail_argv.display(),+ ),+ );+ let git_binary = host_tool("git");+ let status_called = fixture.home.join("git-status-called");+ fs::remove_file(fixture.bin.join("git")).unwrap();+ write_script(+ &fixture.bin.join("git"),+ &format!(+ "for arg in \"$@\"; do\nif [ \"$arg\" = status ]; then\nprintf scanned > '{}'\nfi\ndone\nexec '{}' \"$@\"\n",+ status_called.display(),+ git_binary.display(),+ ),+ );+ let (server, requests, handle) = mock_server().await;+ let output = terminal_run_program(+ &fixture,+ &server,+ &fixture.bin.join("ai-jail"),+ "ai-memory resume --yolo",+ "\x1b",+ Some("Resume workstream"),+ )+ .await;+ assert!(output.contains("Resume workstream"), "{output}");+ assert!(+ !status_called.exists(),+ "listing must not scan the working tree before drawing the picker"+ );+ assert_eq!(requests.lock().unwrap().as_slice(), ["/workstream/recent"]);+ assert_eq!(+ fixture.jail_argv().unwrap(),+ ["ai-memory", "resume", "--yolo"]+ );+ 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"))]@@ -839,6 +936,7 @@ async fn terminal_run_program(.env("JAIL_E2E_BINARY", program).env("AI_MEMORY_NATIVE_BIN", BIN).env("AI_MEMORY_RUN_AUTOWIRE", "false")+ .env("BWRAP_BIN", fixture.bin.join("bwrap")).current_dir(&fixture.repo).stdin(Stdio::piped()).stdout(Stdio::piped())diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rsindex 5b8c61d4..6841d099 100644--- a/crates/ai-memory-workstream/src/lib.rs+++ b/crates/ai-memory-workstream/src/lib.rs@@ -20,7 +20,9 @@ pub use jail::{inside_ai_jail_here, jail_checklist, jail_toggle, marked_choices, parse_jail_toggles,usable_ai_jail, usable_ai_jail_here,};-pub use repository::{RepositoryIdentity, inspect_repository};+pub use repository::{+ RepositoryFingerprints, RepositoryIdentity, inspect_repository, inspect_repository_fingerprints,+};pub use transcript::{AmbiguousNativeSession, ExportedTranscript, NativeSessionCandidate, discover_native_session,export_transcript, kiro_harness_from_source_cursor, kiro_v3_resume_uses_default_store,diff --git a/crates/ai-memory-workstream/src/repository.rs b/crates/ai-memory-workstream/src/repository.rsindex 73646994..cd4d55d3 100644--- a/crates/ai-memory-workstream/src/repository.rs+++ b/crates/ai-memory-workstream/src/repository.rs@@ -27,9 +27,49 @@ pub struct RepositoryIdentity {pub linked_worktree: bool,}+/// Stable checkout keys, without scanning files or collecting a checkpoint.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct RepositoryFingerprints {+ /// Repository identity hash shared by linked worktrees.+ pub repo_fingerprint: String,+ /// Worktree-specific identity hash.+ pub worktree_fingerprint: String,+}++struct RepositoryMetadata {+ cwd: PathBuf,+ fingerprints: RepositoryFingerprints,+ linked_worktree: bool,+}+/// Inspect the current checkout without committing, stashing, resetting, or/// otherwise changing it.pub fn inspect_repository(cwd: &Path) -> Result<RepositoryIdentity> {+ let metadata = inspect_metadata(cwd)?;+ Ok(RepositoryIdentity {+ checkpoint: checkpoint(&metadata.cwd),+ origin_push_url: git(&metadata.cwd, &["remote", "get-url", "--push", "origin"])+ .as_deref()+ .and_then(|urls| urls.lines().next())+ .map(str::trim)+ .filter(|url| !url.is_empty())+ .map(str::to_owned),+ cwd: metadata.cwd,+ repo_fingerprint: metadata.fingerprints.repo_fingerprint,+ worktree_fingerprint: metadata.fingerprints.worktree_fingerprint,+ linked_worktree: metadata.linked_worktree,+ })+}++/// Inspect only the stable keys needed to list checkout-local workstreams.+///+/// Listing must not run `git status`: a large working tree or an unavailable+/// filesystem-monitor hook can otherwise block the picker before its first frame.+pub fn inspect_repository_fingerprints(cwd: &Path) -> Result<RepositoryFingerprints> {+ Ok(inspect_metadata(cwd)?.fingerprints)+}++fn inspect_metadata(cwd: &Path) -> Result<RepositoryMetadata> {let canonical = cwd.canonicalize().with_context(|| format!("canonicalizing managed run cwd {}", cwd.display()))?;@@ -55,17 +95,12 @@ pub fn inspect_repository(cwd: &Path) -> Result<RepositoryIdentity> {(_, Some(root)) => format!("{}\nroot\n{root}", sha256(&repo_seed)),_ => format!("{}\ncwd\n{}", sha256(&repo_seed), canonical.display()),};- Ok(RepositoryIdentity {- cwd: canonical.clone(),- repo_fingerprint: sha256(&repo_seed),- worktree_fingerprint: sha256(&worktree_seed),- checkpoint: checkpoint(&canonical),- origin_push_url: git(&canonical, &["remote", "get-url", "--push", "origin"])- .as_deref()- .and_then(|urls| urls.lines().next())- .map(str::trim)- .filter(|url| !url.is_empty())- .map(str::to_owned),+ Ok(RepositoryMetadata {+ cwd: canonical,+ fingerprints: RepositoryFingerprints {+ repo_fingerprint: sha256(&repo_seed),+ worktree_fingerprint: sha256(&worktree_seed),+ },linked_worktree: matches!((&git_dir, &common_dir),(Some(git_dir), Some(common)) if git_dir != common@@ -163,6 +198,9 @@ mod tests {assert_eq!(first.repo_fingerprint.len(), 64);assert_eq!(first.origin_push_url, None);assert!(!first.linked_worktree);+ let lightweight = inspect_repository_fingerprints(temp.path()).unwrap();+ assert_eq!(lightweight.repo_fingerprint, first.repo_fingerprint);+ assert_eq!(lightweight.worktree_fingerprint, first.worktree_fingerprint);}fn git_fixture(cwd: &Path, args: &[&str]) {@@ -226,6 +264,13 @@ mod tests {let worktree = inspect_repository(&linked).unwrap();assert!(worktree.linked_worktree);assert_eq!(worktree.origin_push_url, primary.origin_push_url);+ for (path, full) in [(&main, &primary), (&linked, &worktree)] {+ let lightweight = inspect_repository_fingerprints(path).unwrap();+ assert_eq!(lightweight.repo_fingerprint, full.repo_fingerprint);+ assert_eq!(lightweight.worktree_fingerprint, full.worktree_fingerprint);+ }+ assert_eq!(primary.repo_fingerprint, worktree.repo_fingerprint);+ assert_ne!(primary.worktree_fingerprint, worktree.worktree_fingerprint);}/// The push URL counts, not the fetch URL. The `.invalid` host keeps adiff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 7b10256c..268dbfd4 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -274,6 +274,7 @@ ai-memory resume --search authai-memory resume --workspace work --limit 50ai-memory # no subcommand needed in a terminalai-jail ai-memory # picker and harness inside the jail+ai-jail ai-memory resume --yolo # explicit picker with dangerous-mode launchai-jail --ssh ai-memory # optional SSH access```@@ -282,6 +283,9 @@ 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 shellwrapper routes this interactive launch to its native host client. Non-terminalCLI calls still require a subcommand, and explicit help/version remain available.+Listing reads the stable repository/worktree fingerprints without running+`git status`, so a working-tree scan or filesystem-monitor hook cannot hold up+the picker. The selected launch still captures its normal Git checkpoint.Use Up/Down to move between workstreams and Left/Right to cycle thelaunch harness for the highlighted row. Each row remembers its choice while youdiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex ba417867..bbea961f 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -25,7 +25,7 @@ boundary not yet built.| 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)`; `reader.rs` `sessions_for_scope_filtered` joins only consolidation jobs in the requested workspace and project; `reader.rs` `incremental_pages` filters workspace and project before its keyset and limit; `reader.rs` `session_counts_by_agent` filters mixed-source observations by the requested workspace and project | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs`; `session_observations.rs` `consolidation_summary_latest_generation_is_scope_and_owner_bound` (a foreign-scope job is absent; the own latest generation and owner controls pass), `incremental_pages_equal_timestamps_cutoff_expiry_and_foreign_scope` (foreign scope absent with a same-scope control), `mixed_capture_count_scopes_observations_and_preserves_owner_and_window` (foreign-scope observations cannot turn an own session into a mixed one; same-scope control can) | STRONG || 1b | Reserved `_global` scope union never leaks a foreign project (#930) | `ai-memory-mcp/src/server.rs` `memory_query` — the union runs for single-project queries (`scopes` empty) and searches **only** `lookup_global_scope`'s reserved `(workspace_id, project_id)`, never an arbitrary project; the double-search guard resolves the *queried* project (named or active) so it can't be tricked into skipping | `server.rs` `global_union_never_leaks_a_foreign_projects_pages` (a third real project's page must not surface via the union; reserved page must), `single_project_query_unions_global_scope_and_multi_scope_skips_it` | STRONG || 2 | Workspace isolation | same as #1; same-named project → distinct ids per workspace | `scope.rs` cross-workspace resolution rows; `multi_scope` dedup/validate | STRONG |-| 2b | Managed-workstream discovery stays checkout-local, including pagination | `ai-memory-cli/src/commands/resume.rs` `candidates_for_checkout` queries only the cwd, never registry links; `ai-memory-hooks/src/workstream.rs` `list_recent_workstreams` resolves an authorized explicit scope on every page; `ai-memory-store/src/workstream.rs` `list_recent` applies workspace/project/repository/worktree predicates before `LIMIT`/`OFFSET` | `resume.rs` `resume_lists_all_current_checkout_rows_not_registered_foreign_checkouts` (same scope/remote foreign checkout refused, 125 local rows visible), `empty_current_checkout_does_not_fall_back_to_the_registry`; `workstream.rs` `recent_workstream_pages_reach_older_rows_without_crossing_checkout_or_scope` (foreign repo, worktree, project and workspace excluded on every page; 105 legitimate rows reach the client, huge offsets return nothing); store `recent_workstreams_are_checkout_local_and_include_linked_harnesses` (page two keeps native harness links) | STRONG |+| 2b | Managed-workstream discovery stays checkout-local, including pagination | `ai-memory-workstream/src/repository.rs` `inspect_repository_fingerprints` shares the launch identity derivation without checkpoint scans; `ai-memory-cli/src/commands/resume.rs` `candidates_for_checkout` queries only the cwd, never registry links; `ai-memory-hooks/src/workstream.rs` `list_recent_workstreams` resolves an authorized explicit scope on every page; `ai-memory-store/src/workstream.rs` `list_recent` applies workspace/project/repository/worktree predicates before `LIMIT`/`OFFSET` | `resume.rs` `resume_lists_all_current_checkout_rows_not_registered_foreign_checkouts` (same scope/remote foreign checkout refused, 125 local rows visible), `empty_current_checkout_does_not_fall_back_to_the_registry`; `workstream.rs` `recent_workstream_pages_reach_older_rows_without_crossing_checkout_or_scope` (foreign repo, worktree, project and workspace excluded on every page; 105 legitimate rows reach the client, huge offsets return nothing); store `recent_workstreams_are_checkout_local_and_include_linked_harnesses` (page two keeps native harness links); `repository.rs` `reports_origin_push_url_and_linked_worktree` verifies lightweight/full fingerprint parity and distinct worktree keys; CLI `resume_yolo_displays_picker_without_scanning_git_status` verifies listing skips status scans | STRONG || 3 | Multi-user auth ladder | `ai-memory-core/src/actor.rs` `AuthLevel::authorize`; `ai-memory-mcp/src/auth.rs` middleware; `admin.rs` `require_root_for_multiuser_admin` / `require_root`; `identity.rs` authorizes `NormalRead` behind the same machine bearer middleware as MCP; `serve.rs` mounts API-only and web+API protected routers behind `require_dual_auth` | `admin.rs` `multiuser_admin_routes_reject_db_user_tier` / `…reject_anonymous` / `create_user_as_user_tier_returns_403`; `auth.rs` unknown-bearer 401; `actor.rs` `skip_admission_chain_rejects_db_users`; `identity.rs` `identity_real_auth_isolates_users_root_and_revoked_keys`, `identity_anonymous_ignores_forged_headers_and_proxy_qualifies_oidc` (distinct users and root, invalid/revoked keys, forged headers, anonymous control); `serve.rs` `api_only_mode_keeps_data_authenticated_and_web_absent` (anonymous API read refused, authenticated control admitted, browser route absent; #986) | STRONG || 3b | Browser triage of pending writes (#855) | `ai-memory-web/src/routes/pending.rs` `require_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`, trusted-proxy flag from `WebMountSpec`) gates `GET {web_slug}/pending`; `html_auth.rs` `AdminRequired` keeps a non-root 403 off the change-password redirect; decisions post to the existing `/admin/pending-writes/{id}/approve\|reject` behind `require_dual_auth` (session + CSRF) and `require_root_for_multiuser_admin`. `ai-memory-web` has no write route | `ai-memory-web` `tests/suite/pending.rs` — anonymous refused (401, login redirect), DB user refused (403, no proposal text, no redirect), trusted-proxy flag reaches the gate, single-operator control admits, POSTs to `/pending*` refused, project filter keys do not collide on `/` in names, projects past the 500-row read cap stay counted and reachable; `ai-memory-mcp` `tests/suite/admin_pending_writes_session.rs` — anonymous and DB-user sessions refused, root session without a matching CSRF header refused (each leaves the proposal pending and no file), root approval keeps `auto_improve_proposal_id`/`auto_improve_run_id` and records the approver, root reject writes no file (each proven to fail with its guard removed) | STRONG || 4 | Handoff single-claim / no-steal | `ai-memory-store/src/ops.rs` `accept_handoff_in_transaction` (metadata `state='open'` guard + atomic CAS) | `multi_session.rs` `a_second_accept_cannot_steal_an_accepted_handoff`; `handoff_ownership.rs` `another_operator_cannot_claim_the_handoff` | STRONG |