Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(cli): add `ai-memory workstreams` checkout-local discovery (#499)
Victor Cesconetto7e02f09f3b69
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f8a4e94b..9abc0fc6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0stable session/event idempotency keys, event/byte caps, and a durable partialfailure manifest make interrupted imports safely resumable. Product-specificChatGPT/Claude export adapters and watch folders remain out of tree. (#483)+- Added `ai-memory workstreams`, a read-only checkout-local list of recent+ managed workstreams with the current selection first, linked harnesses,+ timestamps, and stable ids. Human-readable and `--json` output share the same+ bounded POST query, which follows `run`'s exact workspace, project,+ repository, and worktree identity without returning checkout paths,+ fingerprints, or native session ids. The Docker shell wrapper routes the+ command through its native host client so repository identity remains+ correct. (#499)## [1.33.1] - 2026-08-28diff --git a/README.md b/README.mdindex d00f2176..e511c8a3 100644--- a/README.md+++ b/README.md@@ -222,6 +222,9 @@ priors are at the [bottom](#influences-and-prior-art).# Kiro defaults to v2; select its incompatible v3 engine explicitly once.ai-memory run kiro --v3++ # List the workstreams that can be selected from this checkout.+ ai-memory workstreams```- **"Pick the project instead of remembering where it lives."** Start from a@@ -611,11 +614,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`, `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+- **Managed-launch wrapper:** `ai-memory run`, `ai-memory show`,+ `ai-memory continue`, and `ai-memory workstreams` must be intercepted by the+ current host wrapper so local checkouts, native harnesses, and session stores+ remain accessible. An old wrapper may pass these commands into Docker and+ fail to find a checkout or host executable. Run`ai-memory 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 0a720389..c5849bee 100755--- a/bin/ai-memory+++ b/bin/ai-memory@@ -12,6 +12,7 @@# 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.+# ai-memory workstreams Use that client to inspect the host checkout identity.## Env overrides:# AI_MEMORY_IMAGE docker image (default: akitaonrails/ai-memory:latest)@@ -28,7 +29,7 @@# likewise# 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 binary used for `run`/`show`/`continue` (optional)+# AI_MEMORY_NATIVE_BIN native binary used for managed host commands (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)@@ -350,7 +351,7 @@ cmd_upgrade() {touch "${VERSION_CHECK_FILE}"}-# `ai-memory run`, `show`, and `continue` must execute on the host: checkouts, harnesses,+# Managed launch/discovery commands 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() {@@ -369,7 +370,7 @@ native_host_binary() {Darwin) os="macos" ;;*)echo "ai-memory: the Docker wrapper cannot provide managed host launches on this OS" >&2- echo "install the native release binary to use ai-memory run/show/continue" >&2+ echo "install the native release binary to use ai-memory run/show/continue/workstreams" >&2return 1;;esac@@ -444,7 +445,7 @@ case "${1:-}" incmd_upgradeexit 0;;- run | show | continue)+ run | show | continue | workstreams)NATIVE_HOST_COMMAND=$1shiftNATIVE_HOST_BIN=$(native_host_binary)diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 24c5b84a..2013e7d5 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -43,6 +43,8 @@ pub enum Command {/// Resume the most recently launched managed checkout from anywhere,/// without `cd` and without picking from a list.Continue(ContinueArgs),+ /// List recent managed workstreams selectable from the current checkout.+ Workstreams(WorkstreamsArgs),/// Search the complete visible event ledger for a managed workstream.WorkstreamSearch(WorkstreamSearchArgs),/// Audit the store for likely cross-project contamination (read-only,@@ -304,6 +306,24 @@ pub struct ContinueArgs {pub fresh: bool,}+/// Arguments for `workstreams`.+#[derive(Debug, Args)]+pub struct WorkstreamsArgs {+ /// Workspace containing the managed workstreams. Defaults to the nearest+ /// `.ai-memory.toml` marker's `workspace`, else `default`.+ #[arg(long)]+ pub workspace: Option<String>,+ /// Project override. Defaults to the current repository project.+ #[arg(long)]+ pub project: Option<String>,+ /// Maximum workstreams to return, current first then newest activity.+ #[arg(long, default_value_t = 20, value_parser = clap::value_parser!(u8).range(1..=100))]+ pub limit: u8,+ /// Emit JSON instead of readable rows.+ #[arg(long)]+ pub json: bool,+}+/// Arguments for `workstream-search`.#[derive(Debug, Args)]pub struct WorkstreamSearchArgs {diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 41e511c2..769832a7 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -58,6 +58,7 @@ pub mod status;pub mod uninstall;pub mod user;pub mod workstream_search;+pub mod workstreams;pub mod write_page;/// Resolve the effective `(workspace, project)` pair for a client command.diff --git a/crates/ai-memory-cli/src/commands/workstreams.rs b/crates/ai-memory-cli/src/commands/workstreams.rsnew file mode 100644index 00000000..c6211d9f--- /dev/null+++ b/crates/ai-memory-cli/src/commands/workstreams.rs@@ -0,0 +1,121 @@+//! Checkout-local discovery for managed workstreams.++use std::fmt::Write as _;++use ai_memory_core::{ListManagedWorkstreamsRequest, ManagedWorkstreamSummary};+use ai_memory_workstream::inspect_repository;+use anyhow::{Context as _, Result};++use crate::cli::WorkstreamsArgs;+use crate::config::Config;+use crate::http_client::{ServerEndpoint, post_json};++/// List workstreams that `run --workstream` can select in this checkout.+pub async fn run(config: &Config, args: WorkstreamsArgs) -> Result<()> {+ let cwd = std::env::current_dir().context("getting managed workstream checkout")?;+ let repository = inspect_repository(&cwd)?;+ let (workspace, project) =+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;+ let summaries: Vec<ManagedWorkstreamSummary> = post_json(+ &endpoint,+ "/workstream/recent",+ &ListManagedWorkstreamsRequest {+ workspace: workspace.clone(),+ project: project.clone(),+ repo_fingerprint: repository.repo_fingerprint,+ worktree_fingerprint: repository.worktree_fingerprint,+ limit: usize::from(args.limit),+ },+ )+ .await?;+ if args.json {+ println!("{}", serde_json::to_string_pretty(&summaries)?);+ return Ok(());+ }+ print!("{}", render_human(&summaries, &workspace, &project));+ Ok(())+}++fn render_human(summaries: &[ManagedWorkstreamSummary], workspace: &str, project: &str) -> String {+ let mut output = format!("Managed workstreams for {workspace}/{project}:\n");+ if summaries.is_empty() {+ output.push_str("No managed workstreams for this checkout.\n");+ return output;+ }+ for summary in summaries {+ let marker = if summary.current { '*' } else { ' ' };+ let harnesses = if summary.linked_harnesses.is_empty() {+ "no linked harnesses".to_owned()+ } else {+ summary+ .linked_harnesses+ .iter()+ .map(|agent| agent.as_str())+ .collect::<Vec<_>>()+ .join(", ")+ };+ let _ = writeln!(+ output,+ "{marker} {} {} [{}]",+ summary.name,+ humanize_age(&summary.last_active_at),+ harnesses,+ );+ let _ = writeln!(output, " id: {}", summary.workstream_id);+ }+ output+}++fn humanize_age(raw: &str) -> String {+ let Ok(then) = raw.parse::<jiff::Timestamp>() else {+ return "unknown activity".to_owned();+ };+ let seconds = (jiff::Timestamp::now() - then).get_seconds();+ if seconds < 60 {+ return "just now".to_owned();+ }+ let (value, unit) = match seconds {+ value if value < 3_600 => (value / 60, "minute"),+ value if value < 86_400 => (value / 3_600, "hour"),+ value if value < 2_592_000 => (value / 86_400, "day"),+ value => (value / 2_592_000, "month"),+ };+ format!("{value} {unit}{} ago", if value == 1 { "" } else { "s" })+}++#[cfg(test)]+mod tests {+ use ai_memory_core::{AgentKind, WorkstreamId};++ use super::*;++ #[test]+ fn human_output_marks_current_and_lists_harnesses() {+ let rows = vec![ManagedWorkstreamSummary {+ workstream_id: WorkstreamId::new(),+ name: "decide-after-death".into(),+ created_at: jiff::Timestamp::now().to_string(),+ last_active_at: jiff::Timestamp::now().to_string(),+ current: true,+ linked_harnesses: vec![AgentKind::OpenCode, AgentKind::Codex],+ }];++ let rendered = render_human(&rows, "default", "game");+ assert!(rendered.contains("Managed workstreams for default/game:"));+ assert!(rendered.contains("* decide-after-death"));+ // The id line is indented past the marker column so it cannot be+ // misread as a second, unmarked workstream.+ assert!(rendered.contains("\n id: "));+ assert!(rendered.contains("[open-code, codex]"));+ assert!(rendered.contains(&rows[0].workstream_id.to_string()));+ }++ #[test]+ fn human_output_explains_an_empty_checkout() {+ assert!(+ render_human(&[], "default", "game")+ .contains("No managed workstreams for this checkout.")+ );+ }+}diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rsindex 112a48e6..7f886c05 100644--- a/crates/ai-memory-cli/src/main.rs+++ b/crates/ai-memory-cli/src/main.rs@@ -95,6 +95,7 @@ async fn main() -> Result<()> {}Ok(())}+ Command::Workstreams(args) => commands::workstreams::run(&config, args).await,Command::WorkstreamSearch(args) => commands::workstream_search::run(&config, args).await,Command::AuditContamination(args) => {commands::audit_contamination::run(&config, args).awaitdiff --git a/crates/ai-memory-cli/tests/packaging.rs b/crates/ai-memory-cli/tests/packaging.rsindex 6805f0e8..6cb6481c 100644--- a/crates/ai-memory-cli/tests/packaging.rs+++ b/crates/ai-memory-cli/tests/packaging.rs@@ -835,6 +835,7 @@ fn managed_host_commands_use_native_path_and_remote_server_without_docker() {&["run", "codex", "--yolo", "resume"],&["show", "--json", "--no-scan"],&["continue", "--workspace", "work", "--yolo"],+ &["workstreams", "--limit", "5", "--json"],];for args in commands {let output = shell_script_command(&repo_root().join("bin/ai-memory"))diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex 7f8b6f38..98bdb7af 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -75,7 +75,8 @@ pub use slots::{pub use user::{MAX_EMAIL_LEN, MAX_USERNAME_LEN, NewUser, User, validate_email, validate_username};pub use workstream::{FinishManagedRunRequest, FinishManagedRunResponse, LinkManagedRunRequest,- MANAGED_WORKSTREAM_PACKET_MARKER, ManagedRunContextResponse, ManagedRunStatus,- NewWorkstreamEvent, PrepareManagedRunRequest, PrepareManagedRunResponse,- UNTRUSTED_MEMORY_NOTICE, WorkstreamCheckpoint, WorkstreamEvent, WorkstreamEventKind,+ ListManagedWorkstreamsRequest, MANAGED_WORKSTREAM_PACKET_MARKER, ManagedRunContextResponse,+ ManagedRunStatus, ManagedWorkstreamSummary, NewWorkstreamEvent, PrepareManagedRunRequest,+ PrepareManagedRunResponse, UNTRUSTED_MEMORY_NOTICE, WorkstreamCheckpoint, WorkstreamEvent,+ WorkstreamEventKind,};diff --git a/crates/ai-memory-core/src/workstream.rs b/crates/ai-memory-core/src/workstream.rsindex 9024bdd8..79858ff5 100644--- a/crates/ai-memory-core/src/workstream.rs+++ b/crates/ai-memory-core/src/workstream.rs@@ -251,6 +251,39 @@ pub struct ManagedRunStatus {pub state: String,}+/// Checkout identity used by read-only managed-workstream discovery.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ListManagedWorkstreamsRequest {+ /// Workspace name resolved by the host CLI.+ pub workspace: String,+ /// Project name resolved by the host CLI.+ pub project: String,+ /// Stable repository identity hash.+ pub repo_fingerprint: String,+ /// Stable worktree identity hash (distinct across linked worktrees).+ pub worktree_fingerprint: String,+ /// Maximum number of workstreams to return.+ pub limit: usize,+}++/// One checkout-local managed workstream returned by discovery reads.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ManagedWorkstreamSummary {+ /// Stable workstream identifier used by explicit ledger search.+ pub workstream_id: WorkstreamId,+ /// Human-readable name accepted by `ai-memory run --workstream`.+ pub name: String,+ /// Creation timestamp in RFC 3339 form.+ pub created_at: String,+ /// Most recent selection or transcript-import timestamp in RFC 3339 form.+ pub last_active_at: String,+ /// Whether bare `ai-memory run` currently selects this workstream.+ pub current: bool,+ /// Harnesses with a current native session linked to this workstream.+ #[serde(default)]+ pub linked_harnesses: Vec<AgentKind>,+}+/// Stored workstream event returned by history reads.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct WorkstreamEvent {diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rsindex 40558063..62047d01 100644--- a/crates/ai-memory-hooks/src/workstream.rs+++ b/crates/ai-memory-hooks/src/workstream.rs@@ -8,19 +8,20 @@ use std::str::FromStr as _;use ai_memory_core::{AgentKind, AuthLevel, Capability, FinishManagedRunRequest, FinishManagedRunResponse,- LinkManagedRunRequest, ManagedRunContextResponse, ManagedRunId, ManagedRunStatus,- NewWorkstreamEvent, PrepareManagedRunRequest, PrepareManagedRunResponse, Sanitizer,- WorkstreamEventKind, WorkstreamId,+ LinkManagedRunRequest, ListManagedWorkstreamsRequest, ManagedRunContextResponse, ManagedRunId,+ ManagedRunStatus, ManagedWorkstreamSummary, NewWorkstreamEvent, PrepareManagedRunRequest,+ PrepareManagedRunResponse, Sanitizer, WorkstreamEventKind, WorkstreamId,};use ai_memory_store::{- FinishWorkstreamRun, PrepareWorkstreamRun, ReaderPool, StoreError, WorkstreamSelection,- WriterHandle, create_explicit_scope,+ FinishWorkstreamRun, PrepareWorkstreamRun, ReaderPool, ScopeResolutionError, StoreError,+ WorkstreamSelection, WriterHandle, create_explicit_scope, lookup_existing_scope,};use axum::extract::{Path as AxumPath, Query, State};use axum::http::StatusCode;use axum::response::{IntoResponse, Response};use axum::routing::{get, post};use axum::{Extension, Json, Router};+use jiff::Timestamp;use serde::{Deserialize, Serialize};use sha2::{Digest as _, Sha256};use tracing::warn;@@ -61,6 +62,7 @@ pub fn workstream_router(state: WorkstreamState) -> Router {).route("/workstream/runs/{run_id}/link", post(link_run)).route("/workstream/runs/{run_id}/finish", post(finish_run))+ .route("/workstream/recent", post(list_recent_workstreams)).route("/workstream/{workstream_id}/events", get(search_events)).with_state(state)}@@ -379,6 +381,85 @@ const fn default_event_limit() -> usize {20}+async fn list_recent_workstreams(+ State(state): State<WorkstreamState>,+ level: Option<Extension<AuthLevel>>,+ Json(request): Json<ListManagedWorkstreamsRequest>,+) -> Response {+ if let Err(response) = authorize(level, Capability::NormalRead) {+ return response.into_response();+ }+ for (label, value) in [+ ("workspace", request.workspace.as_str()),+ ("project", request.project.as_str()),+ ("repo_fingerprint", request.repo_fingerprint.as_str()),+ (+ "worktree_fingerprint",+ request.worktree_fingerprint.as_str(),+ ),+ ] {+ if value.trim().is_empty() {+ return error(StatusCode::BAD_REQUEST, format!("{label} cannot be empty"));+ }+ if value.len() > MAX_NAME_BYTES {+ return error(StatusCode::BAD_REQUEST, format!("{label} is too long"));+ }+ }+ let scope = match lookup_existing_scope(+ &state.reader,+ request.workspace.trim(),+ request.project.trim(),+ )+ .await+ {+ Ok(scope) => scope,+ Err(failure) if failure.is_not_found() => {+ return error(StatusCode::NOT_FOUND, failure.to_string());+ }+ Err(failure) if failure.is_bad_request() => {+ return error(StatusCode::BAD_REQUEST, failure.to_string());+ }+ Err(ScopeResolutionError::Store(message)) => {+ return error(StatusCode::INTERNAL_SERVER_ERROR, message);+ }+ Err(failure) => return error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),+ };+ let summaries = match state+ .reader+ .recent_workstreams(+ scope.workspace_id,+ scope.project_id,+ request.repo_fingerprint,+ request.worktree_fingerprint,+ request.limit.clamp(1, 100),+ )+ .await+ {+ Ok(summaries) => summaries,+ Err(failure) => return error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),+ };+ let mut response = Vec::with_capacity(summaries.len());+ for summary in summaries {+ let created_at = match Timestamp::from_microsecond(summary.created_at) {+ Ok(timestamp) => timestamp.to_string(),+ Err(failure) => return error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),+ };+ let last_active_at = match Timestamp::from_microsecond(summary.last_active_at) {+ Ok(timestamp) => timestamp.to_string(),+ Err(failure) => return error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),+ };+ response.push(ManagedWorkstreamSummary {+ workstream_id: summary.workstream_id,+ name: summary.name,+ created_at,+ last_active_at,+ current: summary.current,+ linked_harnesses: summary.linked_harnesses,+ });+ }+ Json(response).into_response()+}+async fn search_events(State(state): State<WorkstreamState>,level: Option<Extension<AuthLevel>>,@@ -788,6 +869,94 @@ mod tests {(workspace_id, project_id)}+ #[tokio::test]+ async fn recent_workstream_endpoint_is_checkout_scoped_and_read_only() {+ 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;+ let prepared = store+ .writer+ .prepare_workstream_run(PrepareWorkstreamRun {+ selection: WorkstreamSelection::New("decide-after-death".into()),+ ..prepare_input(workspace_id, project_id, AgentKind::OpenCode, "launcher")+ })+ .await+ .unwrap();+ store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: prepared.run_id,+ native_session_id: Some("private-native-id".into()),+ source_cursor: None,+ events: Vec::new(),+ complete: true,+ segment_path: None,+ exit_code: Some(0),+ })+ .await+ .unwrap();++ let response = list_recent_workstreams(+ State(state.clone()),+ None,+ Json(ListManagedWorkstreamsRequest {+ workspace: "default".into(),+ project: "managed".into(),+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ limit: 20,+ }),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(json[0]["name"], "decide-after-death");+ assert_eq!(+ json[0]["linked_harnesses"],+ serde_json::json!(["open-code"])+ );+ assert_eq!(json[0]["current"], true);+ let encoded = String::from_utf8(body.to_vec()).unwrap();+ assert!(!encoded.contains("private-native-id"));+ assert!(!encoded.contains("/repo"));++ let other_checkout = list_recent_workstreams(+ State(state.clone()),+ None,+ Json(ListManagedWorkstreamsRequest {+ workspace: "default".into(),+ project: "managed".into(),+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "other-worktree".into(),+ limit: 20,+ }),+ )+ .await;+ let body = to_bytes(other_checkout.into_body(), 64 * 1024)+ .await+ .unwrap();+ assert_eq!(+ serde_json::from_slice::<serde_json::Value>(&body).unwrap(),+ serde_json::json!([])+ );++ let missing = list_recent_workstreams(+ State(state),+ None,+ Json(ListManagedWorkstreamsRequest {+ workspace: "missing".into(),+ project: "managed".into(),+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ limit: 20,+ }),+ )+ .await;+ assert_eq!(missing.status(), StatusCode::NOT_FOUND);+ }+#[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 83e147e6..b83c7c9b 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -69,7 +69,7 @@ pub use session_consolidation::{SESSION_CONSOLIDATION_MAX_ATTEMPTS, SessionConsopub use users::{TOKEN_HASH_LEN, TOKEN_RAW_LEN, TokenPepper, generate_token, hash_token};pub use workstream::{FinishWorkstreamRun, FinishedWorkstreamRun, ManagedRunContext, PrepareWorkstreamRun,- PreparedWorkstreamRun, StoredManagedRunStatus, WorkstreamSelection,+ PreparedWorkstreamRun, StoredManagedRunStatus, StoredWorkstreamSummary, WorkstreamSelection,};pub use writer::{StartupContextAcceptance, WriterHandle};@@ -5734,6 +5734,172 @@ mod tests {}}+ #[tokio::test]+ async fn recent_workstreams_are_checkout_local_and_include_linked_harnesses() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = open_managed_scope(&store, "managed-list").await;+ let prepare = |name: &str, agent| PrepareWorkstreamRun {+ agent,+ selection: WorkstreamSelection::New(name.into()),+ ..managed_prepare_input(ws, proj, name)+ };++ let older = store+ .writer+ .prepare_workstream_run(prepare("older", AgentKind::OpenCode))+ .await+ .unwrap();+ let current = store+ .writer+ .prepare_workstream_run(prepare("current", AgentKind::Codex))+ .await+ .unwrap();+ store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: current.run_id,+ native_session_id: Some("codex-native".into()),+ source_cursor: None,+ events: Vec::new(),+ complete: true,+ segment_path: None,+ exit_code: Some(0),+ })+ .await+ .unwrap();+ let claude = store+ .writer+ .prepare_workstream_run(PrepareWorkstreamRun {+ agent: AgentKind::ClaudeCode,+ selection: WorkstreamSelection::Named("current".into()),+ ..managed_prepare_input(ws, proj, "claude")+ })+ .await+ .unwrap();+ store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: claude.run_id,+ native_session_id: Some("claude-native".into()),+ source_cursor: None,+ events: Vec::new(),+ complete: true,+ segment_path: None,+ exit_code: Some(0),+ })+ .await+ .unwrap();+ // A non-current workstream may finish later and therefore be more+ // recently active; the selected workstream must still lead the list.+ store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: older.run_id,+ native_session_id: Some("open-code-native".into()),+ source_cursor: None,+ events: Vec::new(),+ complete: true,+ segment_path: None,+ exit_code: Some(0),+ })+ .await+ .unwrap();++ let hidden = store+ .writer+ .prepare_workstream_run(PrepareWorkstreamRun {+ repo_fingerprint: "other-repo".into(),+ worktree_fingerprint: "other-worktree".into(),+ selection: WorkstreamSelection::New("hidden".into()),+ ..managed_prepare_input(ws, proj, "hidden")+ })+ .await+ .unwrap();+ store+ .writer+ .cancel_managed_run(hidden.run_id)+ .await+ .unwrap();++ let rows = store+ .reader+ .recent_workstreams(ws, proj, "repo".into(), "worktree".into(), 20)+ .await+ .unwrap();+ assert_eq!(+ rows.iter().map(|row| row.name.as_str()).collect::<Vec<_>>(),+ ["current", "older"]+ );+ assert!(rows[0].current);+ assert!(!rows[1].current);+ assert_eq!(+ rows[0].linked_harnesses,+ [AgentKind::ClaudeCode, AgentKind::Codex]+ );+ assert_eq!(rows[1].linked_harnesses, [AgentKind::OpenCode]);+ assert!(rows[0].last_active_at >= rows[0].created_at);+ let limited = store+ .reader+ .recent_workstreams(ws, proj, "repo".into(), "worktree".into(), 1)+ .await+ .unwrap();+ assert_eq!(limited.len(), 1);+ assert_eq!(limited[0].workstream_id, current.workstream_id);+ assert!(limited[0].current);+ assert_eq!(+ limited[0].linked_harnesses,+ [AgentKind::ClaudeCode, AgentKind::Codex]+ );+ }++ #[tokio::test]+ async fn recent_workstreams_do_not_leak_across_workspaces() {+ // Two workspaces can hold a project of the same name over the very+ // same clone, so repo/worktree identity alone does not separate them:+ // only the scope columns do.+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (mine, mine_proj) = open_managed_scope(&store, "shared-name").await;+ let theirs = store+ .writer+ .get_or_create_workspace("other-workspace")+ .await+ .unwrap();+ let theirs_proj = store+ .writer+ .get_or_create_project(theirs, "shared-name", None)+ .await+ .unwrap();++ for (ws, proj, name) in [(mine, mine_proj, "mine"), (theirs, theirs_proj, "theirs")] {+ store+ .writer+ .prepare_workstream_run(PrepareWorkstreamRun {+ selection: WorkstreamSelection::New(name.into()),+ ..managed_prepare_input(ws, proj, name)+ })+ .await+ .unwrap();+ }++ async fn visible(store: &Store, ws: WorkspaceId, proj: ProjectId) -> Vec<String> {+ store+ .reader+ .recent_workstreams(ws, proj, "repo".into(), "worktree".into(), 20)+ .await+ .unwrap()+ .into_iter()+ .map(|row| row.name)+ .collect()+ }+ assert_eq!(visible(&store, mine, mine_proj).await, ["mine"]);+ assert_eq!(visible(&store, theirs, theirs_proj).await, ["theirs"]);+ // A real workspace paired with the other one's project must not fall+ // back to either list.+ assert!(visible(&store, mine, theirs_proj).await.is_empty());+ }+#[tokio::test]async fn prepare_expires_a_stale_lease_and_reopens_the_workstream() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex e2da2143..be102c32 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -36,7 +36,7 @@ use crate::error::{StoreError, StoreResult};use crate::fts_query::prepare_fts5_query;use crate::maintenance::MaintenanceJob;use crate::users::TOKEN_HASH_LEN;-use crate::workstream::{ManagedRunContext, StoredManagedRunStatus};+use crate::workstream::{ManagedRunContext, StoredManagedRunStatus, StoredWorkstreamSummary};/// TTL guard for retrieval surfaces (search / recent / embedding hits //// graph neighbours / briefing lists): appended to a WHERE clause that@@ -1328,6 +1328,28 @@ impl ReaderPool {.await}+ /// List recent managed workstreams for one exact repository/worktree.+ pub async fn recent_workstreams(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ repo_fingerprint: String,+ worktree_fingerprint: String,+ limit: usize,+ ) -> StoreResult<Vec<StoredWorkstreamSummary>> {+ self.with_conn(move |conn| {+ crate::workstream::list_recent(+ conn,+ workspace_id,+ project_id,+ &repo_fingerprint,+ &worktree_fingerprint,+ limit,+ )+ })+ .await+ }+/// Run a full-text search against the FTS5 index, apply the bounded page/// authority adjustment, and return the top `is_latest = 1` matches.///diff --git a/crates/ai-memory-store/src/workstream.rs b/crates/ai-memory-store/src/workstream.rsindex 6f70b481..f9ad9a63 100644--- a/crates/ai-memory-store/src/workstream.rs+++ b/crates/ai-memory-store/src/workstream.rs@@ -143,6 +143,23 @@ pub struct StoredManagedRunStatus {pub state: String,}+/// Checkout-local workstream metadata used by read-only discovery surfaces.+#[derive(Debug, Clone)]+pub struct StoredWorkstreamSummary {+ /// Stable workstream identifier.+ pub workstream_id: WorkstreamId,+ /// Human-readable workstream name.+ pub name: String,+ /// Creation timestamp in microseconds since the Unix epoch.+ pub created_at: i64,+ /// Most recent selection or import timestamp in microseconds.+ pub last_active_at: i64,+ /// Whether this is the checkout's most recently selected workstream.+ pub current: bool,+ /// Harnesses with a current native session, newest link first.+ pub linked_harnesses: Vec<AgentKind>,+}+struct FinishRunRow {workstream: Vec<u8>,agent_wire: String,@@ -323,7 +340,7 @@ fn select_workstream("SELECT id, name FROM workstreams \WHERE workspace_id = ?1 AND project_id = ?2 \AND repo_fingerprint = ?3 AND worktree_fingerprint = ?4 \- ORDER BY selected_at DESC LIMIT 1",+ ORDER BY selected_at DESC, id DESC LIMIT 1",params![input.workspace_id.as_bytes(),input.project_id.as_bytes(),@@ -783,6 +800,85 @@ pub(crate) fn run_status(.transpose()}+/// List recent workstreams selectable from one exact repository/worktree.+pub(crate) fn list_recent(+ conn: &Connection,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ repo_fingerprint: &str,+ worktree_fingerprint: &str,+ limit: usize,+) -> StoreResult<Vec<StoredWorkstreamSummary>> {+ let limit = i64::try_from(limit.clamp(1, 100)).unwrap_or(100);+ let mut statement = conn.prepare(+ "WITH scoped AS ( \+ SELECT id, name, created_at, selected_at, updated_at \+ FROM workstreams \+ WHERE workspace_id = ?1 AND project_id = ?2 \+ AND repo_fingerprint = ?3 AND worktree_fingerprint = ?4 \+ ), current_workstream AS ( \+ SELECT id FROM scoped ORDER BY selected_at DESC, id DESC LIMIT 1 \+ ), recent AS ( \+ SELECT scoped.id, scoped.name, scoped.created_at, scoped.updated_at, \+ 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 \+ ) \+ SELECT recent.id, recent.name, recent.created_at, recent.updated_at, \+ recent.is_current, native.agent_kind \+ FROM recent \+ LEFT JOIN workstream_native_sessions native \+ ON native.workstream_id = recent.id AND native.is_current = 1 \+ ORDER BY recent.is_current DESC, recent.updated_at DESC, recent.id DESC, \+ native.updated_at DESC, native.agent_kind ASC",+ )?;+ let rows = statement.query_map(+ params![+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ repo_fingerprint,+ worktree_fingerprint,+ limit,+ ],+ |row| {+ Ok((+ row.get::<_, Vec<u8>>(0)?,+ row.get::<_, String>(1)?,+ row.get::<_, i64>(2)?,+ row.get::<_, i64>(3)?,+ row.get::<_, bool>(4)?,+ row.get::<_, Option<String>>(5)?,+ ))+ },+ )?;++ let mut summaries: Vec<StoredWorkstreamSummary> = Vec::new();+ for row in rows {+ let (raw_id, name, created_at, last_active_at, current, agent) = row?;+ let workstream_id = WorkstreamId::from_slice(&raw_id)?;+ let is_new = summaries+ .last()+ .is_none_or(|summary| summary.workstream_id != workstream_id);+ if is_new {+ summaries.push(StoredWorkstreamSummary {+ workstream_id,+ name,+ created_at,+ last_active_at,+ current,+ linked_harnesses: Vec::new(),+ });+ }+ if let Some(agent) = agent+ && let Some(summary) = summaries.last_mut()+ {+ summary.linked_harnesses.push(AgentKind::from_wire(&agent));+ }+ }+ Ok(summaries)+}+/// Reader-side context range assigned to one managed run.pub(crate) fn run_context(conn: &Connection,diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 213c5743..ae78ea45 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -422,20 +422,21 @@ the explicit `install-mcp --client claude-code --session-aware` option.```init status run-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 move-session uninstall-auth user completions+show continue workstreams+workstream-search audit-contamination search+read-page write-page delete-page+serve reset backup+restore reindex install-hooks+hook install-mcp commit+checkpoints restore-page llm-test+forget-sweep lint curator+auto-improve-report auto-improve finalize-session+pending-writes embed generate-auth-token+setup-agent bootstrap install-instructions+install-skills reorg purge-project+rename-project move-project move-session+uninstall auth user+completions```Run `ai-memory --help` for the full tree.diff --git a/docs/install.md b/docs/install.mdindex 2288baa1..b22d0af4 100644--- a/docs/install.md+++ b/docs/install.md@@ -1709,6 +1709,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 |+| `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 || `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 |@@ -2001,11 +2002,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`, `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+`ai-memory run`, `ai-memory show`, `ai-memory continue`, and+`ai-memory workstreams` 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 46c0f717..dc0c8920 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -51,6 +51,19 @@ and worktree, creating one named `default` on first use. `--new NAME` starts anindependent line of work; `--workstream NAME` returns to one. These are optionalbranching controls, not harness-switch controls.+List the workstreams available to those selectors without launching a harness:++```bash+ai-memory workstreams [--workspace NAME] [--project NAME]+ai-memory workstreams --limit 50 --json+```++The list is scoped to the same `(workspace, project, repository, worktree)`+identity as `run`, puts the current selection first, then orders by recent+activity. Each row includes the linked harnesses and stable workstream id; the+response does not expose checkout paths, repository fingerprints, or native+session ids.+## Project-first launcher`ai-memory show` reverses the usual `cd` then `run` flow: choose a local@@ -414,14 +427,14 @@ original config is not modified. ai-memory opens the project database read-only;the launched Crush process continues its normal native session writes.The Linux/macOS Docker shell wrapper cannot inspect host projects or execute a-host agent from inside its helper container. For `run`, `show`, and `continue`,-it downloads the matching native release into+host agent from inside its helper container. For `run`, `show`, `continue`, and+`workstreams`, 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 all three commands before Docker and preserves the host+The wrapper intercepts all four 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.diff --git a/scripts/check-native-packaging.sh b/scripts/check-native-packaging.shindex 6b7fe2b7..7203618e 100755--- a/scripts/check-native-packaging.sh+++ b/scripts/check-native-packaging.sh@@ -97,9 +97,13 @@ main() {AI_MEMORY_DOCKER="${fake_docker}" AI_MEMORY_NATIVE_BIN="${fake_native}" \AI_MEMORY_WRAPPER_TEST_LOG="${wrapper_log}" \bin/ai-memory continue --workspace work --yolo+ AI_MEMORY_DOCKER="${fake_docker}" AI_MEMORY_NATIVE_BIN="${fake_native}" \+ AI_MEMORY_WRAPPER_TEST_LOG="${wrapper_log}" \+ bin/ai-memory workstreams --limit 5 --jsonassert_contains "${wrapper_log}" "run codex --yolo"assert_contains "${wrapper_log}" "show --json --no-scan"assert_contains "${wrapper_log}" "continue --workspace work --yolo"+ assert_contains "${wrapper_log}" "workstreams --limit 5 --json"log "Creating temporary alternate root"mkdir -p \diff --git a/scripts/managed-workstream-acceptance.sh b/scripts/managed-workstream-acceptance.shindex 701b8417..a9f9dcfb 100755--- a/scripts/managed-workstream-acceptance.sh+++ b/scripts/managed-workstream-acceptance.sh@@ -1177,6 +1177,73 @@ mapfile -t adoption_claude_argv <"$TMP/adoption-claude-argv.log"exit 1}+# `ai-memory workstreams` must answer from the same checkout identity `run`+# selects with, without turning that identity into readable output. The list is+# taken from the repository the previous legs launched in, so `edge-adopt` --+# the workstream the Claude adoption leg selected last -- has to lead it.+workstreams_json=$(cd "$REPO" && "$BIN" --data-dir "$DATA" workstreams --json)+jq -e '(type == "array") and (length > 1)' <<<"$workstreams_json" >/dev/null || {+ printf 'workstreams did not list this checkout\n' >&2+ printf '%s\n' "$workstreams_json" >&2+ exit 1+}+jq -e '[.[] | select(.current)] | length == 1' <<<"$workstreams_json" >/dev/null || {+ printf 'workstreams did not mark exactly one current selection\n' >&2+ printf '%s\n' "$workstreams_json" >&2+ exit 1+}+jq -e '.[0].current and .[0].name == "edge-adopt"' <<<"$workstreams_json" >/dev/null || {+ printf 'workstreams did not lead with the checkout current workstream\n' >&2+ printf '%s\n' "$workstreams_json" >&2+ exit 1+}+jq -e --arg name edge-kimi \+ '[.[] | select(.name == $name and (.linked_harnesses | index("kimi-code")))] | length == 1' \+ <<<"$workstreams_json" >/dev/null || {+ printf 'workstreams did not report the harnesses linked to edge-kimi\n' >&2+ printf '%s\n' "$workstreams_json" >&2+ exit 1+}+# Discovery is a read of workstream metadata only: the checkout path, its+# fingerprints, and native session ids must never travel back to the client.+for leaked in "$REPO" "$kimi_session_id" adoption-codex-id; do+ ! grep -qF -- "$leaked" <<<"$workstreams_json" || {+ printf 'workstreams leaked private checkout or native session data: %s\n' \+ "$leaked" >&2+ exit 1+ }+done+limited_json=$(cd "$REPO" && "$BIN" --data-dir "$DATA" workstreams --limit 1 --json)+jq -e 'length == 1 and .[0].current' <<<"$limited_json" >/dev/null || {+ printf 'workstreams --limit did not keep the current selection\n' >&2+ printf '%s\n' "$limited_json" >&2+ exit 1+}+workstreams_human=$(cd "$REPO" && "$BIN" --data-dir "$DATA" workstreams)+grep -q '^\* edge-adopt' <<<"$workstreams_human" || {+ printf 'human workstreams output did not mark the current selection\n' >&2+ printf '%s\n' "$workstreams_human" >&2+ exit 1+}++# A different worktree of the same project shares the workspace and project+# names but must not inherit the first checkout list.+OTHER_REPO="$TMP/repo-elsewhere"+mkdir -p "$OTHER_REPO"+git -C "$OTHER_REPO" init -q+git -C "$OTHER_REPO" config user.name "ai-memory acceptance"+git -C "$OTHER_REPO" config user.email "acceptance@localhost"+printf '# elsewhere\n' >"$OTHER_REPO/README.md"+git -C "$OTHER_REPO" add README.md+git -C "$OTHER_REPO" commit -qm "acceptance fixture"+other_json=$(cd "$OTHER_REPO" && "$BIN" --data-dir "$DATA" workstreams \+ --project "$(basename "$REPO")" --json)+jq -e 'length == 0' <<<"$other_json" >/dev/null || {+ printf 'workstreams returned another checkout workstreams\n' >&2+ printf '%s\n' "$other_json" >&2+ exit 1+}+if [ "$DETERMINISTIC_ONLY" = 1 ]; thenprintf 'deterministic managed-workstream acceptance passed\n'exit 0