Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(cli): scope resume to current checkout
Paulo Vitor Martinsb38c8905f6b6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 762d7fbb..c64619c3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -118,6 +118,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0older servers leave unsupported fields unknown. (#1016)### Changed+- Scoped `ai-memory resume` to the current checkout instead of every linked+ project, removed its default result cutoff with bounded server pagination,+ and added `--search` plus immediate type-to-filter name search while preserving+ Left/Right harness selection. Explicit limits now apply after the initial+ search; `continue` retained its cross-directory behavior. (#534)- Documented FutureInfra as an endpoint for the existing `openai-compat`provider. (#1026)- `.github/workflows/nix.yml` builds the flake on `x86_64-linux` for path-diff --git a/README.md b/README.mdindex a6b262f0..cf871518 100644--- a/README.md+++ b/README.md@@ -368,6 +368,8 @@ ai-memory run --profile work claude # reusable config.toml env/account presetai-memory continue # resume the newest managed checkout# after a dead launcher left its lease behind (same operator only)ai-memory run --force-unlock codex+ai-memory resume # pick from ALL workstreams in this checkout only+ai-memory resume --search auth # find a workstream by name (case-insensitive)````--force-unlock` immediately expires the selected workstream's active lease;@@ -376,6 +378,14 @@ native process, and it cannot evict another authenticated operator's run. Seethe [managed-workstream recovery notes](docs/managed-workstreams.md#lease-recovery)for the full safety contract.+In `resume`, just type to search, use Up/Down to select a workstream, and Left/Right+to choose its harness. Enter launches the selection; Escape clears a search,+then cancels when the search is empty (Ctrl-C always cancels).+The list scrolls and loads every checkout-local page;+there is no default workstream cutoff. Use `--limit N` only when you want to+cap the matching results. Workstreams from other repositories or worktrees+never appear; `continue` still resumes the newest linked checkout from anywhere.+Auto-wiring is on by default; opt out with `ai-memory run --no-autowire` or`AI_MEMORY_RUN_AUTOWIRE=false`. You can still wire agents by hand with`install-hooks` / `install-mcp` (e.g. for a harness you never launch throughdiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 076677aa..606d9795 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -144,7 +144,7 @@ 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.+ /// Interactively pick a managed workstream in the current checkout and launch harness.Resume(ResumeArgs),/// List open cross-agent handoffs so a stale one can be cancelled by id.Handoffs(HandoffsArgs),@@ -613,15 +613,18 @@ pub struct ContinueArgs {////// The picker deliberately accepts only wrapper-owned flags. Harness selection/// happens interactively, then it delegates to `run --workstream NAME` in the-/// selected checkout.+/// current checkout.#[derive(Debug, Args)]pub struct ResumeArgs {- /// Only consider checkouts resolving to this workspace.+ /// Require the current checkout to resolve 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,+ /// Maximum matching workstreams to show (defaults to all).+ #[arg(long, value_parser = clap::value_parser!(u32).range(1..))]+ pub limit: Option<u32>,+ /// Initial case-insensitive workstream-name search; type to edit it.+ #[arg(long)]+ pub search: Option<String>,/// Disable native permission prompts using the resolved harness's/// equivalent dangerous-mode option. Forwarded to `run`.#[arg(long)]@@ -3396,6 +3399,21 @@ mod tests {/// native harness without accepting harness-native arguments.#[test]fn resume_takes_picker_and_wrapper_flags_only() {+ let Command::Resume(defaults) = Cli::try_parse_from(["ai-memory", "resume"])+ .unwrap()+ .command+ else {+ panic!("expected resume");+ };+ assert!(defaults.limit.is_none());+ assert!(defaults.search.is_none());+ let Command::Resume(wide) = Cli::try_parse_from(["ai-memory", "resume", "--limit", "500"])+ .unwrap()+ .command+ else {+ panic!("expected resume");+ };+ assert_eq!(wide.limit, Some(500));let parsed = Cli::try_parse_from(["ai-memory","resume",@@ -3403,6 +3421,8 @@ mod tests {"work","--limit","50",+ "--search",+ "refactor","--yolo",]).expect("resume parses picker flags");@@ -3410,7 +3430,8 @@ mod tests {panic!("expected resume command");};assert_eq!(args.workspace.as_deref(), Some("work"));- assert_eq!(args.limit, 50);+ assert_eq!(args.limit, Some(50));+ assert_eq!(args.search.as_deref(), Some("refactor"));assert!(args.yolo);assert!(!args.fresh);diff --git a/crates/ai-memory-cli/src/commands/resume.rs b/crates/ai-memory-cli/src/commands/resume.rsindex e4835ef6..d160bae0 100644--- a/crates/ai-memory-cli/src/commands/resume.rs+++ b/crates/ai-memory-cli/src/commands/resume.rs@@ -1,18 +1,18 @@-//! `ai-memory resume` — pick a managed workstream across local checkouts.+//! `ai-memory resume` — pick a managed workstream in the current checkout.//!//! 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+//! uses only the current checkout's privacy-preserving workstream listing,+//! revalidates the path before use, and delegates the//! selected launch to `run --workstream`.use std::io::IsTerminal as _;-use std::path::PathBuf;+use std::path::{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::project_registry::ProjectLink;use crate::commands::show::{Choice, HorizontalDirection, available_harnesses, harness_name, select_with_horizontal,terminal_text,@@ -21,13 +21,14 @@ use crate::commands::{continue_session, workstreams};use crate::config::Config;use crate::http_client::ServerEndpoint;+#[derive(Debug)]struct Candidate {link: ProjectLink,target: PathBuf,summary: ManagedWorkstreamSummary,}-/// Interactively select a workstream from every valid locally linked checkout.+/// Interactively select a workstream in the current checkout only.pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {bail!(@@ -36,91 +37,8 @@ pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {}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 cwd = std::env::current_dir().context("reading the current checkout")?;+ let candidates = candidates_for_checkout(config, &endpoint, &args, &cwd).await?;let harnesses = available_harnesses();let mut harness_indices = vec![0usize; candidates.len()];@@ -132,6 +50,7 @@ pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {"Resume workstream",&mut choices,"left/right harness",+ args.search.as_deref(),&mut |index, direction, choice| {let harness =cycle_selected_harness(&mut harness_indices, index, &harnesses, direction);@@ -142,6 +61,7 @@ pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {return Ok(0);};let selected = &candidates[index];+ let target = continue_session::resolve_target(config, &selected.link)?;let harness = selected_harness(harness_indices[index], &harnesses);eprintln!("resuming workstream '{}' with harness '{}' in {} at {}",@@ -173,14 +93,69 @@ pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {harness,native_args: Vec::new(),},- &selected.target,+ &target,).await}-fn current_checkout_link(config: &Config, endpoint: &ServerEndpoint) -> Result<ProjectLink> {- let path = std::env::current_dir()- .context("reading the current checkout")?+async fn candidates_for_checkout(+ config: &Config,+ endpoint: &ServerEndpoint,+ args: &ResumeArgs,+ cwd: &Path,+) -> Result<Vec<Candidate>> {+ let link = current_checkout_link(config, endpoint, cwd)?;+ if args+ .workspace+ .as_deref()+ .is_some_and(|workspace| workspace != link.workspace)+ {+ bail!(+ "current checkout belongs to {}, not workspace '{}'",+ scope_label(&link),+ terminal_text(args.workspace.as_deref().unwrap_or_default())+ );+ }+ let summaries =+ workstreams::list_all_for_checkout(endpoint, &link.workspace, &link.project, &link.path)+ .await?;+ if summaries.is_empty() {+ bail!(+ "no managed workstreams for the current checkout ({}); launch one here with `ai-memory run <harness>` first",+ scope_label(&link)+ );+ }+ let mut candidates = summaries+ .into_iter()+ .map(|summary| Candidate {+ target: link.path.clone(),+ link: link.clone(),+ summary,+ })+ .collect::<Vec<_>>();+ order_candidates(&mut candidates);+ // A requested limit applies after search, so an older matching row is+ // never hidden behind newer non-matching workstreams.+ if let Some(limit) = args.limit {+ let search = args.search.as_deref().unwrap_or_default().to_lowercase();+ candidates.retain(|candidate| candidate.summary.name.to_lowercase().contains(&search));+ candidates.truncate(limit as usize);+ if candidates.is_empty() {+ bail!(+ "no workstreams match '{}' in the current checkout",+ terminal_text(&search)+ );+ }+ }+ Ok(candidates)+}++fn current_checkout_link(+ config: &Config,+ endpoint: &ServerEndpoint,+ cwd: &Path,+) -> Result<ProjectLink> {+ let path = cwd.canonicalize().context("canonicalizing the current checkout")?;let (workspace, project) = super::resolve_scope_for_path(config, &path)?;@@ -282,10 +257,238 @@ fn scope_label(link: &ProjectLink) -> String {#[cfg(test)]mod tests {- use ai_memory_core::{AgentKind, WorkstreamId};+ use crate::commands::project_registry;+ use ai_memory_core::{AgentKind, ListManagedWorkstreamsRequest, WorkstreamId};+ use axum::{Json, Router, routing::post};+ use std::sync::{Arc, Mutex};use super::*;+ fn args() -> ResumeArgs {+ ResumeArgs {+ workspace: None,+ limit: None,+ search: None,+ yolo: false,+ true_yolo: false,+ fresh: false,+ }+ }++ fn checkout(path: &Path) -> PathBuf {+ std::fs::create_dir_all(path).unwrap();+ assert!(+ std::process::Command::new("git")+ .args(["init", "--quiet"])+ .arg(path)+ .status()+ .unwrap()+ .success()+ );+ assert!(+ std::process::Command::new("git")+ .arg("-C")+ .arg(path)+ .args([+ "remote",+ "add",+ "origin",+ "https://example.invalid/shared.git"+ ])+ .status()+ .unwrap()+ .success()+ );+ std::fs::write(+ path.join(".ai-memory.toml"),+ "workspace = \"work\"\nproject = \"app\"\n",+ )+ .unwrap();+ path.canonicalize().unwrap()+ }++ async fn listing_server(+ local: &Path,+ rows: Vec<ManagedWorkstreamSummary>,+ paginate: bool,+ ) -> (+ ServerEndpoint,+ Arc<Mutex<Vec<ListManagedWorkstreamsRequest>>>,+ tokio::task::JoinHandle<()>,+ ) {+ let repository = ai_memory_workstream::inspect_repository(local).unwrap();+ let requests = Arc::new(Mutex::new(Vec::new()));+ let recorded = requests.clone();+ let foreign = candidate("foreign-workstream", false, "2026-09-01T00:00:00Z").summary;+ let app = Router::new().route(+ "/workstream/recent",+ post(move |Json(request): Json<ListManagedWorkstreamsRequest>| {+ let recorded = recorded.clone();+ let rows = rows.clone();+ let repository = repository.clone();+ let foreign = foreign.clone();+ async move {+ recorded.lock().unwrap().push(request.clone());+ let rows = if request.workspace == "work"+ && request.project == "app"+ && request.repo_fingerprint == repository.repo_fingerprint+ && request.worktree_fingerprint == repository.worktree_fingerprint+ {+ rows+ } else {+ vec![foreign]+ };+ Json(+ rows.into_iter()+ .skip(if paginate { request.offset } else { 0 })+ .take(request.limit)+ .collect::<Vec<_>>(),+ )+ }+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let endpoint = ServerEndpoint::from_pair(+ Some(format!("http://{}", listener.local_addr().unwrap())),+ None,+ );+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ (endpoint, requests, server)+ }++ #[tokio::test]+ async fn resume_lists_all_current_checkout_rows_not_registered_foreign_checkouts() {+ let tmp = tempfile::TempDir::new().unwrap();+ let local = checkout(&tmp.path().join("local"));+ let foreign = checkout(&tmp.path().join("foreign"));+ let config = Config {+ data_dir: tmp.path().join("data"),+ ..Config::default()+ };+ let rows = (0..125)+ .map(|index| {+ candidate(+ &format!("local-{index:03}"),+ index == 0,+ "2026-09-01T00:00:00Z",+ )+ .summary+ })+ .collect();+ let (endpoint, requests, server) = listing_server(&local, rows, true).await;+ project_registry::record_prepared_checkout(&config, &endpoint, "work", "app", &foreign)+ .unwrap();+ let candidates = candidates_for_checkout(&config, &endpoint, &args(), &local)+ .await+ .unwrap();+ assert_eq!(candidates.len(), 125);+ assert!(+ candidates+ .iter()+ .all(|row| row.summary.name.starts_with("local-") && row.target == local)+ );+ assert_eq!(+ requests+ .lock()+ .unwrap()+ .iter()+ .map(|r| r.offset)+ .collect::<Vec<_>>(),+ [0, 100]+ );+ assert!(candidates[0].summary.current);+ // Resume must not depend on even a readable project registry.+ std::fs::write(config.data_dir.join("client-projects.json"), "not json").unwrap();+ let mut searched = args();+ searched.search = Some("LOCAL-124".into());+ searched.limit = Some(1);+ let matching = candidates_for_checkout(&config, &endpoint, &searched, &local)+ .await+ .unwrap();+ assert_eq!(matching.len(), 1);+ assert_eq!(matching[0].summary.name, "local-124");+ searched.workspace = Some("elsewhere".into());+ let before = requests.lock().unwrap().len();+ assert!(+ candidates_for_checkout(&config, &endpoint, &searched, &local)+ .await+ .unwrap_err()+ .to_string()+ .contains("current checkout belongs to work/app")+ );+ assert_eq!(requests.lock().unwrap().len(), before);+ server.abort();+ }++ #[tokio::test]+ async fn empty_current_checkout_does_not_fall_back_to_the_registry() {+ let tmp = tempfile::TempDir::new().unwrap();+ let local = checkout(&tmp.path().join("local"));+ let foreign = checkout(&tmp.path().join("foreign"));+ let config = Config {+ data_dir: tmp.path().join("data"),+ ..Config::default()+ };+ let (endpoint, requests, server) = listing_server(&local, Vec::new(), true).await;+ project_registry::record_prepared_checkout(&config, &endpoint, "work", "app", &foreign)+ .unwrap();+ let error = candidates_for_checkout(&config, &endpoint, &args(), &local)+ .await+ .unwrap_err();+ assert!(+ error+ .to_string()+ .contains("no managed workstreams for the current checkout")+ );+ assert_eq!(requests.lock().unwrap().len(), 1);+ server.abort();+ }++ #[tokio::test]+ async fn a_server_ignoring_pagination_fails_instead_of_silently_truncating() {+ let tmp = tempfile::TempDir::new().unwrap();+ let local = checkout(&tmp.path().join("local"));+ let rows = (0..100)+ .map(|index| candidate(&format!("local-{index}"), false, "invalid").summary)+ .collect();+ let (endpoint, requests, server) = listing_server(&local, rows, false).await;+ let error = candidates_for_checkout(&Config::default(), &endpoint, &args(), &local)+ .await+ .unwrap_err();+ assert!(error.to_string().contains("upgrade the ai-memory server"));+ assert_eq!(requests.lock().unwrap().len(), 2);+ server.abort();+ }++ #[test]+ fn current_checkout_resolves_subdirectories_and_symlinks_without_registry_links() {+ let tmp = tempfile::TempDir::new().unwrap();+ let root = checkout(&tmp.path().join("local"));+ let nested = root.join("src");+ std::fs::create_dir(&nested).unwrap();+ let endpoint = ServerEndpoint::from_pair(None, None);+ let config = Config::default();+ for cwd in [&root, &nested] {+ let link = current_checkout_link(&config, &endpoint, cwd).unwrap();+ assert_eq!((&*link.workspace, &*link.project), ("work", "app"));+ let identity = ai_memory_workstream::inspect_repository(&link.path).unwrap();+ let expected = ai_memory_workstream::inspect_repository(&root).unwrap();+ assert_eq!(identity.repo_fingerprint, expected.repo_fingerprint);+ assert_eq!(identity.worktree_fingerprint, expected.worktree_fingerprint);+ }+ #[cfg(unix)]+ {+ let alias = tmp.path().join("alias");+ std::os::unix::fs::symlink(&root, &alias).unwrap();+ assert_eq!(+ current_checkout_link(&config, &endpoint, &alias)+ .unwrap()+ .path,+ root+ );+ }+ }+fn candidate(name: &str, current: bool, last_active_at: &str) -> Candidate {Candidate {link: ProjectLink {diff --git a/crates/ai-memory-cli/src/commands/show.rs b/crates/ai-memory-cli/src/commands/show.rsindex 6632a8c0..b1830307 100644--- a/crates/ai-memory-cli/src/commands/show.rs+++ b/crates/ai-memory-cli/src/commands/show.rs@@ -102,6 +102,7 @@ impl Candidate {}}+#[derive(Clone)]pub(super) struct Choice {pub(super) label: String,pub(super) detail: String,@@ -667,16 +668,63 @@ pub(super) enum HorizontalDirection {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)+ select_inner(title, choices, None, None, None)}pub(super) fn select_with_horizontal(title: &str,choices: &mut [Choice],horizontal_hint: &str,+ initial_search: Option<&str>,on_horizontal: &mut dyn FnMut(usize, HorizontalDirection, &mut Choice),) -> Result<Option<usize>> {- select_inner(title, choices, Some(horizontal_hint), Some(on_horizontal))+ select_inner(+ title,+ choices,+ Some(horizontal_hint),+ Some(on_horizontal),+ Some(initial_search.unwrap_or_default()),+ )+}++#[derive(Default)]+struct PickerSearch {+ query: String,+}++impl PickerSearch {+ fn indices(&self, choices: &[Choice]) -> Vec<usize> {+ let query = self.query.to_lowercase();+ choices+ .iter()+ .enumerate()+ .filter_map(|(index, choice)| {+ choice+ .label+ .to_lowercase()+ .contains(&query)+ .then_some(index)+ })+ .collect()+ }++ fn handle_key(&mut self, code: KeyCode, modifiers: KeyModifiers) -> bool {+ match code {+ KeyCode::Esc if !self.query.is_empty() => self.query.clear(),+ KeyCode::Backspace => {+ self.query.pop();+ }+ KeyCode::Char('u') if modifiers.contains(KeyModifiers::CONTROL) => self.query.clear(),+ KeyCode::Char(character)+ if !character.is_control()+ && !modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>+ {+ self.query.push(character)+ }+ _ => return false,+ }+ true+ }}fn select_inner(@@ -684,6 +732,7 @@ fn select_inner(choices: &mut [Choice],horizontal_hint: Option<&str>,mut on_horizontal: Option<HorizontalHandler<'_>>,+ initial_search: Option<&str>,) -> Result<Option<usize>> {if choices.is_empty() {bail!("nothing to choose from");@@ -698,14 +747,41 @@ fn select_inner(let mut selected = 0usize;let mut offset = 0usize;let mut drawn = 0u16;+ let mut search = PickerSearch {+ query: initial_search.unwrap_or_default().to_owned(),+ };loop {+ let indices = search.indices(choices);+ let visible = if indices.is_empty() {+ vec![Choice {+ label: "No matching workstreams — edit the search or press Esc to clear".into(),+ detail: String::new(),+ }]+ } else {+ indices+ .iter()+ .map(|index| choices[*index].clone())+ .collect::<Vec<_>>()+ };+ selected = selected.min(visible.len() - 1);+ let title = if initial_search.is_some() {+ format!(+ "{title} [{}/{}] | search: {}",+ indices.len(),+ choices.len(),+ search.query+ )+ } else {+ title.to_owned()+ };drawn = draw(- title,- choices,+ &title,+ &visible,selected,&mut offset,drawn,horizontal_hint,+ initial_search.is_some(),)?;let Event::Key(KeyEvent {code,@@ -716,26 +792,48 @@ fn select_inner(else {continue;};+ if initial_search.is_some() {+ let previous_query = search.query.clone();+ if search.handle_key(code, modifiers) {+ if search.query != previous_query {+ selected = 0;+ offset = 0;+ }+ continue;+ }+ }+ // The resume picker reserves every printable character for search,+ // including the other pickers' j/k/q shortcuts. Ctrl-C still cancels.+ if initial_search.is_some()+ && matches!(code, KeyCode::Char(_))+ && !(code == KeyCode::Char('c') && modifiers.contains(KeyModifiers::CONTROL))+ {+ continue;+ }if let Some(direction) = horizontal_direction(&code) {- if let Some(callback) = on_horizontal.as_mut() {- callback(selected, direction, &mut choices[selected]);+ if let Some(callback) = on_horizontal.as_mut()+ && let Some(&index) = indices.get(selected)+ {+ callback(index, direction, &mut choices[index]);}continue;}match code {KeyCode::Up | KeyCode::Char('k') => {- selected = selected.checked_sub(1).unwrap_or(choices.len() - 1);+ selected = selected.checked_sub(1).unwrap_or(visible.len() - 1);}- KeyCode::Down | KeyCode::Char('j') => selected = (selected + 1) % choices.len(),+ KeyCode::Down | KeyCode::Char('j') => selected = (selected + 1) % visible.len(),KeyCode::Home => selected = 0,- KeyCode::End => selected = choices.len() - 1,+ KeyCode::End => selected = visible.len() - 1,KeyCode::PageUp => selected = selected.saturating_sub(viewport_rows()),KeyCode::PageDown => {- selected = (selected + viewport_rows()).min(choices.len() - 1);+ selected = (selected + viewport_rows()).min(visible.len() - 1);}KeyCode::Enter => {- clear(drawn)?;- return Ok(Some(selected));+ if let Some(&index) = indices.get(selected) {+ clear(drawn)?;+ return Ok(Some(index));+ }}KeyCode::Esc | KeyCode::Char('q') => {clear(drawn)?;@@ -894,6 +992,7 @@ fn draw(offset: &mut usize,previous: u16,horizontal_hint: Option<&str>,+ searchable: bool,) -> Result<u16> {let (columns, _) = terminal::size().unwrap_or((80, 24));let width = usize::from(columns.max(20)).saturating_sub(1);@@ -937,7 +1036,9 @@ fn draw(let horizontal_hint = horizontal_hint.map(|hint| format!(" | {hint}")).unwrap_or_default();- let hint = if choices.len() > viewport {+ let hint = if searchable {+ " type to search | ↑↓ move | ←→ harness | enter select | esc clear/cancel".to_owned()+ } else if choices.len() > viewport {format!(" up/down move{horizontal_hint} | pgup/pgdn page | enter select | esc cancel [{}/{}]",selected + 1,@@ -967,6 +1068,66 @@ fn clear(drawn: u16) -> Result<()> {mod tests {use super::*;+ #[test]+ fn search_matches_names_case_insensitively_and_keeps_original_indices() {+ let choices = ["one", "Fix CHECKOUT", "three", "checkout search"].map(|label| Choice {+ label: label.into(),+ detail: "unrelated detail".into(),+ });+ let mut search = PickerSearch {+ query: "checkout".into(),+ };+ assert_eq!(search.indices(&choices), [1, 3]);+ search.query = "missing".into();+ assert!(search.indices(&choices).is_empty());+ search.query.clear();+ assert_eq!(search.indices(&choices), [0, 1, 2, 3]);+ }++ #[test]+ fn typing_searches_immediately_including_navigation_letters() {+ let mut search = PickerSearch::default();+ for character in "qjké".chars() {+ assert!(search.handle_key(KeyCode::Char(character), KeyModifiers::NONE));+ }+ assert_eq!(search.query, "qjké");+ assert!(search.handle_key(KeyCode::Backspace, KeyModifiers::NONE));+ assert_eq!(search.query, "qjk");+ assert!(search.handle_key(KeyCode::Char('u'), KeyModifiers::CONTROL));+ assert!(search.query.is_empty());+ assert!(search.handle_key(KeyCode::Char('q'), KeyModifiers::NONE));+ assert!(!search.handle_key(KeyCode::Enter, KeyModifiers::NONE));+ assert_eq!(search.query, "q");+ assert!(search.handle_key(KeyCode::Esc, KeyModifiers::NONE));+ assert!(search.query.is_empty());+ assert!(!search.handle_key(KeyCode::Esc, KeyModifiers::NONE));+ }++ #[test]+ fn search_does_not_consume_selection_arrows_or_cancel_shortcuts() {+ let mut search = PickerSearch {+ query: "auth".into(),+ };+ for code in [+ KeyCode::Up,+ KeyCode::Down,+ KeyCode::Left,+ KeyCode::Right,+ KeyCode::Home,+ KeyCode::End,+ KeyCode::PageUp,+ KeyCode::PageDown,+ KeyCode::Enter,+ ] {+ assert!(!search.handle_key(code, KeyModifiers::NONE));+ }+ assert!(!search.handle_key(KeyCode::Char('c'), KeyModifiers::CONTROL));+ assert!(!search.handle_key(KeyCode::Char('q'), KeyModifiers::ALT));+ assert_eq!(search.query, "auth");+ assert!(search.handle_key(KeyCode::Char('/'), KeyModifiers::NONE));+ assert_eq!(search.query, "auth/");+ }+fn config_at(path: &Path) -> Config {Config {data_dir: path.to_path_buf(),diff --git a/crates/ai-memory-cli/src/commands/workstreams.rs b/crates/ai-memory-cli/src/commands/workstreams.rsindex c0c3f01b..e235e6fa 100644--- a/crates/ai-memory-cli/src/commands/workstreams.rs+++ b/crates/ai-memory-cli/src/commands/workstreams.rs@@ -1,5 +1,6 @@//! Checkout-local discovery for managed workstreams.+use std::collections::HashSet;use std::fmt::Write as _;use std::path::Path;@@ -56,11 +57,57 @@ pub(super) async fn list_for_checkout(repo_fingerprint: repository.repo_fingerprint,worktree_fingerprint: repository.worktree_fingerprint,limit,+ offset: 0,},).await}+/// Fetch every checkout-local page without changing the server's per-page cap.+pub(super) async fn list_all_for_checkout(+ endpoint: &ServerEndpoint,+ workspace: &str,+ project: &str,+ checkout: &Path,+) -> Result<Vec<ManagedWorkstreamSummary>> {+ let repository =+ inspect_repository(checkout).context("inspecting managed workstream checkout")?;+ let mut request = ListManagedWorkstreamsRequest {+ workspace: workspace.to_owned(),+ project: project.to_owned(),+ repo_fingerprint: repository.repo_fingerprint,+ worktree_fingerprint: repository.worktree_fingerprint,+ limit: 100,+ offset: 0,+ };+ let mut summaries = Vec::new();+ let mut seen = HashSet::new();+ loop {+ let page: Vec<ManagedWorkstreamSummary> =+ post_json(endpoint, "/workstream/recent", &request).await?;+ let count = page.len();+ let before = summaries.len();+ summaries.extend(+ page.into_iter()+ .filter(|row| seen.insert(row.workstream_id)),+ );+ if count < request.limit {+ break;+ }+ // Older servers ignore offset. Do not loop forever or silently show+ // only their first page when the user requested all workstreams.+ anyhow::ensure!(+ summaries.len() > before,+ "server did not advance workstream pagination; upgrade the ai-memory server and retry"+ );+ request.offset = request+ .offset+ .checked_add(count)+ .context("workstream pagination offset overflow")?;+ }+ Ok(summaries)+}+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-core/src/workstream.rs b/crates/ai-memory-core/src/workstream.rsindex 035de2a4..259622b3 100644--- a/crates/ai-memory-core/src/workstream.rs+++ b/crates/ai-memory-core/src/workstream.rs@@ -276,6 +276,10 @@ pub struct ListManagedWorkstreamsRequest {pub worktree_fingerprint: String,/// Maximum number of workstreams to return.pub limit: usize,+ /// Number of workstreams to skip in the same stable checkout-local order.+ /// Omitted by older clients for the first page.+ #[serde(default)]+ pub offset: usize,}/// One checkout-local managed workstream returned by discovery reads.@@ -359,6 +363,19 @@ pub struct WorkstreamEvent {mod tests {use super::*;+ #[test]+ fn workstream_listing_without_offset_defaults_to_the_first_page() {+ let request: ListManagedWorkstreamsRequest = serde_json::from_value(serde_json::json!({+ "workspace": "default",+ "project": "app",+ "repo_fingerprint": "repo",+ "worktree_fingerprint": "tree",+ "limit": 20,+ }))+ .unwrap();+ assert_eq!(request.offset, 0);+ }+#[test]fn older_run_status_reads_as_nothing_linked() {let status: ManagedRunStatus = serde_json::from_value(serde_json::json!({diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rsindex f3a2292c..e36da884 100644--- a/crates/ai-memory-hooks/src/workstream.rs+++ b/crates/ai-memory-hooks/src/workstream.rs@@ -573,12 +573,13 @@ async fn list_recent_workstreams(};let summaries = match state.reader- .recent_workstreams(+ .recent_workstreams_page(scope.workspace_id,scope.project_id,request.repo_fingerprint,request.worktree_fingerprint,request.limit.clamp(1, 100),+ request.offset,).await{@@ -1342,6 +1343,7 @@ mod tests {repo_fingerprint: "repo".into(),worktree_fingerprint: "worktree".into(),limit: 20,+ offset: 0,}),).await;@@ -1368,6 +1370,7 @@ mod tests {repo_fingerprint: "repo".into(),worktree_fingerprint: "other-worktree".into(),limit: 20,+ offset: 0,}),).await;@@ -1389,12 +1392,115 @@ mod tests {repo_fingerprint: "repo".into(),worktree_fingerprint: "worktree".into(),limit: 20,+ offset: 0,}),).await;assert_eq!(missing.status(), StatusCode::NOT_FOUND);}+ #[tokio::test]+ async fn recent_workstream_pages_reach_older_rows_without_crossing_checkout_or_scope() {+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());+ let (workspace_id, project_id) = seed_scope(&store).await;+ for index in 0..105 {+ store+ .writer+ .prepare_workstream_run(PrepareWorkstreamRun {+ selection: WorkstreamSelection::New(format!("local-{index:03}")),+ ..prepare_input(workspace_id, project_id, AgentKind::Codex, "launcher")+ })+ .await+ .unwrap();+ }+ let other_workspace = store.writer.get_or_create_workspace("other").await.unwrap();+ let sibling_project = store+ .writer+ .get_or_create_project(workspace_id, "sibling", None)+ .await+ .unwrap();+ let other_project = store+ .writer+ .get_or_create_project(other_workspace, "managed", None)+ .await+ .unwrap();+ for (workspace, project, repo, worktree, name) in [+ (+ workspace_id,+ sibling_project,+ "repo",+ "worktree",+ "foreign-project",+ ),+ (+ workspace_id,+ project_id,+ "other-repo",+ "worktree",+ "foreign-repo",+ ),+ (+ workspace_id,+ project_id,+ "repo",+ "other-worktree",+ "foreign-worktree",+ ),+ (+ other_workspace,+ other_project,+ "repo",+ "worktree",+ "foreign-workspace",+ ),+ ] {+ store+ .writer+ .prepare_workstream_run(PrepareWorkstreamRun {+ selection: WorkstreamSelection::New(name.into()),+ repo_fingerprint: repo.into(),+ worktree_fingerprint: worktree.into(),+ ..prepare_input(workspace, project, AgentKind::Codex, "foreign")+ })+ .await+ .unwrap();+ }+ let mut rows = Vec::<ManagedWorkstreamSummary>::new();+ for (offset, expected) in [(0, 100), (100, 5), (105, 0), (usize::MAX, 0)] {+ let response = list_recent_workstreams(+ State(state.clone()),+ None,+ None,+ Json(ListManagedWorkstreamsRequest {+ workspace: "default".into(),+ project: "managed".into(),+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ limit: 100,+ offset,+ }),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ let body = to_bytes(response.into_body(), 256 * 1024).await.unwrap();+ let page: Vec<ManagedWorkstreamSummary> = serde_json::from_slice(&body).unwrap();+ assert_eq!(page.len(), expected);+ assert!(page.iter().all(|row| row.name.starts_with("local-")));+ rows.extend(page);+ }+ let ids = rows+ .iter()+ .map(|row| row.workstream_id)+ .collect::<std::collections::HashSet<_>>();+ assert_eq!(ids.len(), 105);+ assert_eq!(rows[0].name, "local-104");+ assert!(rows[0].current);+ assert_eq!(rows.iter().filter(|row| row.current).count(), 1);+ assert!(rows.iter().any(|row| row.name == "local-000"));+ }+#[tokio::test]async fn automatic_prepare_returns_the_established_available_harness() {let temp = TempDir::new().unwrap();diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex c4f07d39..8d7f1aee 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -6645,6 +6645,23 @@ mod tests {limited[0].linked_harnesses,[AgentKind::ClaudeCode, AgentKind::Codex]);+ let second_page = store+ .reader+ .recent_workstreams_page(ws, proj, "repo".into(), "worktree".into(), 1, 1)+ .await+ .unwrap();+ assert_eq!(second_page.len(), 1);+ assert_eq!(second_page[0].workstream_id, older.workstream_id);+ assert_eq!(second_page[0].linked_harnesses, [AgentKind::OpenCode]);+ assert!(!second_page[0].current);+ assert!(+ store+ .reader+ .recent_workstreams_page(ws, proj, "repo".into(), "worktree".into(), 1, 2)+ .await+ .unwrap()+ .is_empty()+ );}#[tokio::test]diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex a2ce885f..b1fc7c07 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -1938,6 +1938,28 @@ impl ReaderPool {repo_fingerprint: String,worktree_fingerprint: String,limit: usize,+ ) -> StoreResult<Vec<StoredWorkstreamSummary>> {+ self.recent_workstreams_page(+ workspace_id,+ project_id,+ repo_fingerprint,+ worktree_fingerprint,+ limit,+ 0,+ )+ .await+ }++ /// List one bounded page for an exact repository/worktree, preserving the+ /// current-first order and every linked harness on each returned row.+ pub async fn recent_workstreams_page(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ repo_fingerprint: String,+ worktree_fingerprint: String,+ limit: usize,+ offset: usize,) -> StoreResult<Vec<StoredWorkstreamSummary>> {self.with_conn(move |conn| {crate::workstream::list_recent(@@ -1947,6 +1969,7 @@ impl ReaderPool {&repo_fingerprint,&worktree_fingerprint,limit,+ offset,)}).awaitdiff --git a/crates/ai-memory-store/src/workstream.rs b/crates/ai-memory-store/src/workstream.rsindex f85a2c34..6e51bfa6 100644--- a/crates/ai-memory-store/src/workstream.rs+++ b/crates/ai-memory-store/src/workstream.rs@@ -1069,8 +1069,10 @@ pub(crate) fn list_recent(repo_fingerprint: &str,worktree_fingerprint: &str,limit: usize,+ offset: usize,) -> StoreResult<Vec<StoredWorkstreamSummary>> {let limit = i64::try_from(limit.clamp(1, 100)).unwrap_or(100);+ let offset = i64::try_from(offset).unwrap_or(i64::MAX);let mut statement = conn.prepare("WITH scoped AS ( \SELECT id, name, created_at, selected_at, updated_at \@@ -1084,7 +1086,7 @@ pub(crate) fn list_recent(EXISTS(SELECT 1 FROM current_workstream \WHERE current_workstream.id = scoped.id) AS is_current \FROM scoped \- ORDER BY is_current DESC, scoped.updated_at DESC, scoped.id DESC LIMIT ?5 \+ ORDER BY is_current DESC, scoped.updated_at DESC, scoped.id DESC LIMIT ?5 OFFSET ?6 \) \SELECT recent.id, recent.name, recent.created_at, recent.updated_at, \recent.is_current, native.agent_kind \@@ -1101,6 +1103,7 @@ pub(crate) fn list_recent(repo_fingerprint,worktree_fingerprint,limit,+ offset,],|row| {Ok((diff --git a/docs/cookbook.md b/docs/cookbook.mdindex 469e5e12..36e719f3 100644--- a/docs/cookbook.md+++ b/docs/cookbook.md@@ -327,6 +327,7 @@ Your agent runs most of these for you; `run` and `continue` are how you start it```bashai-memory run <harness> # launch a harness, hooks + MCP auto-wiredai-memory continue # resume the newest managed checkout+ai-memory resume --search auth # pick a matching workstream in this checkout onlyai-memory workstreams # list this checkout's managed workstreamsai-memory status # counts, paths, healthai-memory list-projects # every workspace/project the server knows aboutdiff --git a/docs/install.md b/docs/install.mdindex 782ce273..9d138f6d 100644--- a/docs/install.md+++ b/docs/install.md@@ -2267,7 +2267,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` |+| `resume [--workspace NAME] [--search TERM] [--limit N]` | host wrapper or native binary | Interactively choose from all workstreams in the current checkout only (no default cutoff); type to search names, Up/Down selects, Left/Right cycles `auto` plus installed harnesses, Enter launches, and Escape clears the search or cancels; an explicit limit caps initial search results; 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 |diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 1d4164ca..e1f322d9 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -261,36 +261,57 @@ directory, including automatic harness selection. `continue` therefore accepts## 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.+`ai-memory resume` presents all managed workstreams belonging to the **current+checkout**, then launches the selected named workstream there. Other repositories+and sibling Git worktrees are not included, even when they share a workspace,+project name, or remote URL. Running from a subdirectory of a checkout uses that+checkout's Git fingerprints and the nearest scope marker. To resume the newest+linked checkout from any directory, use `ai-memory continue` instead.```bashai-memory resume+ai-memory resume --search authai-memory resume --workspace work --limit 50```-Use Up/Down (or `j`/`k`) to move between workstreams and Left/Right to cycle the+Use Up/Down to move between workstreams and Left/Right to cycle thelaunch harness for the highlighted row. Each row remembers its choice while younavigate. `auto` is the initial choice and preserves bare `ai-memory run`'sdiscovery of the newest usable session; the remaining choices are supportedharness 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+workstream/harness combination. Escape clears a non-empty search, then cancels+when the search is empty; Ctrl-C always cancels.++Just type to filter workstream names with a case-insensitive substring search;+there is no search mode or prefix key. Results update immediately, and every+printable character (including `j`, `k`, `q`, and `/`) is literal search text.+Backspace removes a character and Ctrl-U clears the query. Enter launches the+highlighted result directly. Arrow keys navigate and switch harnesses without+leaving the search.+An empty result is not selectable; edit or clear the search to recover.++There is no default cutoff: the CLI fetches successive bounded server pages,+and the picker scrolls with Up/Down, PageUp/PageDown, Home, and End. `--search`+sets the initial query. An explicit `--limit N` caps results **after** that+initial search; clear or change the search without the limit to browse all rows.+`--workspace` checks the current checkout's resolved workspace, rather than+switching to another checkout.++The current selection leads the picker, followed by recentactivity. Each row identifies its workspace/project, activity age, selectedlaunch harness, and already linked harnesses. Choosing a different harness ishow 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+The picker does not read the private `client-projects.json` registry or fall back+to another checkout when this one has no workstreams. It revalidates the canonical+path and resolved scope before launching the selection. The serverreceives only the repository/worktree fingerprints required for the existingcheckout-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.+checkout themselves. Pagination requires an updated server; if an older server+ignores the page offset, the CLI reports that an upgrade is needed instead of+looping forever or silently presenting a truncated list.## Automatic harness selectiondiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 53774ace..ba417867 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -25,6 +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 || 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 |