Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(cli): list open handoffs so a stale one can be cancelled (#522)

Fabio Akita4ddef24647e1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b614f03d..85edd546 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- `ai-memory handoffs` lists the open cross-agent handoffs for a project,
+ oldest first, with the id `memory_handoff_cancel` requires. A backlog was
+ previously visible only as a count in `status`: nothing exposed an id, so the
+ one available remedy could not be used. Read-only and content-free —
+ identity, provenance and age, never the handoff body. Automatic expiry
+ deliberately spares manual and sibling-directory handoffs, so a months-old
+ entry appearing here is that policy working as intended; the listing exists
+ so an operator can see it and decide (#513).
+
### Fixed
- `install-mcp --client antigravity-cli` wrote to `~/.gemini/antigravity-cli/mcp_config.json`,
but the Antigravity CLI documents its global MCP config at
@@ -23,6 +33,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
what Claude Code's runner uses, so applying it everywhere would break the
integration that works today. A rendering test pins both directions, and
`uninstall` still recognises the new form (#515).
+
## [1.34.0] - 2026-08-28
### Added
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index eb203c55..ab2dee6f 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 open cross-agent handoffs so a stale one can be cancelled by id.
+ Handoffs(HandoffsArgs),
/// List recent managed workstreams selectable from the current checkout.
Workstreams(WorkstreamsArgs),
/// Search the complete visible event ledger for a managed workstream.
@@ -307,6 +309,23 @@ pub struct ContinueArgs {
}
/// Arguments for `workstreams`.
+/// Arguments for `handoffs`.
+#[derive(Debug, Args)]
+pub struct HandoffsArgs {
+ /// Workspace to inspect (defaults to the resolved scope).
+ #[arg(long)]
+ pub workspace: Option<String>,
+ /// Project to inspect (defaults to the resolved scope).
+ #[arg(long)]
+ pub project: Option<String>,
+ /// Maximum handoffs to list.
+ #[arg(long, default_value_t = 50, value_parser = clap::value_parser!(u16).range(1..=500))]
+ pub limit: u16,
+ /// Emit JSON instead of the human listing.
+ #[arg(long)]
+ pub json: bool,
+}
+
#[derive(Debug, Args)]
pub struct WorkstreamsArgs {
/// Workspace containing the managed workstreams. Defaults to the nearest
diff --git a/crates/ai-memory-cli/src/commands/handoffs.rs b/crates/ai-memory-cli/src/commands/handoffs.rs
new file mode 100644
index 00000000..5a5c9a38
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/handoffs.rs
@@ -0,0 +1,124 @@
+//! Read-only listing of open cross-agent handoffs.
+//!
+//! `memory_handoff_cancel` takes an exact handoff id and nothing exposed one,
+//! so an accumulated backlog was visible as a count in `status` and could not
+//! be addressed (#513). Automatic expiry deliberately spares manual and
+//! sibling-directory handoffs, so a months-old entry surviving here is the
+//! policy working as designed rather than a bug — but the operator still needs
+//! to see it to decide.
+
+use std::fmt::Write as _;
+
+use anyhow::Result;
+use serde::{Deserialize, Serialize};
+
+use crate::cli::HandoffsArgs;
+use crate::config::Config;
+use crate::http_client::{ServerEndpoint, get_json};
+
+#[derive(Debug, Deserialize, Serialize)]
+struct OpenHandoff {
+ id: String,
+ from_agent: String,
+ to_agent: Option<String>,
+ cwd: Option<String>,
+ created_at_ms: i64,
+}
+
+#[derive(Debug, Deserialize)]
+struct OpenHandoffsResponse {
+ handoffs: Vec<OpenHandoff>,
+}
+
+/// List the open handoffs for a project, oldest first.
+///
+/// # Errors
+/// Returns [`anyhow::Error`] when the scope cannot be resolved, the server is
+/// unreachable, or it answers non-2xx.
+pub async fn run(config: &Config, args: HandoffsArgs) -> Result<()> {
+ 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 response: OpenHandoffsResponse = get_json(
+ &endpoint,
+ "/admin/handoffs",
+ &[
+ ("workspace", workspace.as_str()),
+ ("project", project.as_str()),
+ ("limit", &args.limit.to_string()),
+ ],
+ )
+ .await?;
+
+ if args.json {
+ println!("{}", serde_json::to_string_pretty(&response.handoffs)?);
+ return Ok(());
+ }
+
+ if response.handoffs.is_empty() {
+ println!("No open handoffs for {workspace}/{project}.");
+ return Ok(());
+ }
+
+ let now_ms = jiff::Timestamp::now().as_millisecond();
+ let mut out = String::new();
+ let _ = writeln!(
+ out,
+ "Open handoffs for {workspace}/{project} (oldest first):"
+ );
+ for h in &response.handoffs {
+ let target = h.to_agent.as_deref().unwrap_or("any agent");
+ let _ = writeln!(
+ out,
+ " {} from {} -> {}",
+ age(now_ms.saturating_sub(h.created_at_ms)),
+ h.from_agent,
+ target
+ );
+ let _ = writeln!(out, " id: {}", h.id);
+ if let Some(cwd) = h.cwd.as_deref() {
+ let _ = writeln!(out, " cwd: {cwd}");
+ }
+ }
+ let _ = writeln!(
+ out,
+ "\nCancel one with the MCP tool `memory_handoff_cancel`, passing its id."
+ );
+ print!("{out}");
+ Ok(())
+}
+
+/// Coarse age, because the operator's question is "is this stale", not "when
+/// exactly".
+fn age(ms: i64) -> String {
+ let secs = ms.max(0) / 1_000;
+ let days = secs / 86_400;
+ if days > 0 {
+ return format!("{days}d ago");
+ }
+ let hours = secs / 3_600;
+ if hours > 0 {
+ return format!("{hours}h ago");
+ }
+ format!("{}m ago", secs / 60)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn age_reports_the_coarsest_useful_unit() {
+ assert_eq!(age(0), "0m ago");
+ assert_eq!(age(5 * 60 * 1_000), "5m ago");
+ assert_eq!(age(3 * 3_600 * 1_000), "3h ago");
+ assert_eq!(age(9 * 86_400 * 1_000), "9d ago");
+ }
+
+ /// A clock skew between server and client must not render as a huge
+ /// positive age from a negative difference.
+ #[test]
+ fn a_future_timestamp_clamps_to_zero() {
+ assert_eq!(age(-5_000), "0m ago");
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 769832a7..68edd247 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -22,6 +22,7 @@ pub mod embed;
pub mod finalize_session;
pub mod forget_sweep;
pub mod generate_auth_token;
+pub mod handoffs;
pub mod hook;
pub mod hook_capture;
pub mod hook_drain_process;
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 7f886c05..9b551c21 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::Handoffs(args) => commands::handoffs::run(&config, args).await,
Command::Workstreams(args) => commands::workstreams::run(&config, args).await,
Command::WorkstreamSearch(args) => commands::workstream_search::run(&config, args).await,
Command::AuditContamination(args) => {
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 00f06895..1c348de9 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -388,6 +388,19 @@ struct CuratorStageResponse {
report: CuratorReport,
}
+/// Query for `GET /admin/handoffs` (#513).
+#[derive(Debug, Deserialize)]
+struct OpenHandoffsQuery {
+ workspace: String,
+ project: String,
+ #[serde(default = "default_open_handoffs_limit")]
+ limit: usize,
+}
+
+const fn default_open_handoffs_limit() -> usize {
+ 50
+}
+
#[derive(Debug, Deserialize)]
struct PendingWritesQuery {
workspace: String,
@@ -551,6 +564,7 @@ pub fn admin_router_with_decay_breadth(state: AdminState, breadth_weight: f64) -
post(handle_auto_improve_report),
)
.route("/admin/curator", post(handle_curator))
+ .route("/admin/handoffs", get(handle_open_handoffs_list))
.route("/admin/pending-writes", get(handle_pending_writes_list))
.route(
"/admin/pending-writes/{id}",
@@ -2224,6 +2238,38 @@ fn auto_improve_report_target_path() -> String {
format!("notes/auto-improve-report-{stamp}.md")
}
+/// List open handoffs so an operator can cancel one (#513).
+///
+/// `memory_handoff_cancel` requires an exact id and nothing exposed one, so a
+/// backlog showed up as a count in `status` and could not be addressed.
+/// Read-only, oldest first, and content-free: identity, provenance and age,
+/// never the handoff body.
+async fn handle_open_handoffs_list(
+ State(state): State<Arc<AdminState>>,
+ Query(query): Query<OpenHandoffsQuery>,
+) -> impl IntoResponse {
+ let (ws, proj) = match lookup_ws_proj_no_create(&state, &query.workspace, &query.project).await
+ {
+ Ok(ids) => ids,
+ Err(e) => return e,
+ };
+ let limit = query.limit.clamp(1, 500);
+ match state
+ .reader
+ .open_handoffs_for_project(ws, proj, limit)
+ .await
+ {
+ Ok(handoffs) => (
+ StatusCode::OK,
+ Json(serde_json::json!({ "handoffs": handoffs })),
+ ),
+ Err(e) => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({ "error": e.to_string() })),
+ ),
+ }
+}
+
async fn handle_pending_writes_list(
State(state): State<Arc<AdminState>>,
Query(query): Query<PendingWritesQuery>,
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index b83c7c9b..4792d07f 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -2545,6 +2545,90 @@ mod tests {
"2. Make the backpressure test deterministic\n",
);
+ /// #513: `memory_handoff_cancel` takes an exact id and nothing exposed
+ /// one, so an accumulated backlog was visible as a count and impossible
+ /// to address. Oldest-first because the operator's question is which are
+ /// stale.
+ #[tokio::test]
+ async fn open_handoffs_are_listed_oldest_first_and_exclude_accepted() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "ai-memory", None)
+ .await
+ .unwrap();
+ let new_handoff = |agent: AgentKind| NewHandoff {
+ workspace_id: ws,
+ project_id: proj,
+ from_session_id: None,
+ from_agent: agent,
+ to_agent: None,
+ cwd: None,
+ summary: "continue".into(),
+ open_questions: Vec::new(),
+ next_steps: Vec::new(),
+ files_touched: Vec::new(),
+ owner_user: None,
+ };
+ let first = store
+ .writer
+ .insert_handoff(new_handoff(AgentKind::ClaudeCode))
+ .await
+ .unwrap();
+ let second = store
+ .writer
+ .insert_handoff(new_handoff(AgentKind::Codex))
+ .await
+ .unwrap();
+
+ let open = store
+ .reader
+ .open_handoffs_for_project(ws, proj, 50)
+ .await
+ .unwrap();
+ assert_eq!(open.len(), 2, "both handoffs are open");
+ assert_eq!(
+ open[0].id,
+ first.to_string(),
+ "oldest first: {:?}",
+ open.iter().map(|h| &h.id).collect::<Vec<_>>()
+ );
+ assert_eq!(open[1].id, second.to_string());
+ assert_eq!(open[0].from_agent, "claude-code");
+ assert_eq!(open[1].from_agent, "codex");
+
+ // The listing must answer "what is still pending", so an accepted
+ // handoff has to drop out — otherwise it re-proposes work already
+ // taken, which is the failure the backlog already causes.
+ store
+ .writer
+ .accept_handoff(HandoffAcceptance {
+ handoff_id: first,
+ workspace_id: ws,
+ project_id: proj,
+ accepting_agent: AgentKind::Codex,
+ accepting_session: None,
+ accepting_user: None,
+ owner_filter: ai_memory_core::OwnerFilter::Any,
+ receiving_cwd: None,
+ })
+ .await
+ .unwrap();
+ let open = store
+ .reader
+ .open_handoffs_for_project(ws, proj, 50)
+ .await
+ .unwrap();
+ assert_eq!(open.len(), 1, "the accepted handoff must not be listed");
+ assert_eq!(open[0].id, second.to_string());
+ }
+
#[tokio::test]
async fn a_written_summary_changes_what_the_descriptor_tells_the_reader() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index be102c32..908e781b 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -3586,6 +3586,63 @@ impl ReaderPool {
/// descriptor column there would compute one for the whole corpus on
/// every search. Here the input is only the handful of ids that survived
/// fusion and still lack a title.
+ /// Open handoffs for a project, oldest first (#513).
+ ///
+ /// `memory_handoff_cancel` takes an exact id and nothing exposed one, so a
+ /// backlog could be observed in `status` counts but never addressed. Oldest
+ /// first because the operator's question is "what is stale", and the
+ /// automatic expiry deliberately spares manual and sibling-directory
+ /// handoffs — which is how a months-old entry survives to be listed here.
+ pub async fn open_handoffs_for_project(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ limit: usize,
+ ) -> StoreResult<Vec<OpenHandoff>> {
+ self.with_conn(move |conn| {
+ let mut stmt = conn.prepare(
+ "SELECT id, from_agent, to_agent, cwd, created_at \
+ FROM handoffs \
+ WHERE workspace_id = ?1 AND project_id = ?2 AND state = 'open' \
+ ORDER BY created_at ASC, id ASC \
+ LIMIT ?3",
+ )?;
+ let rows = stmt.query_map(
+ params![
+ workspace_id.as_bytes(),
+ project_id.as_bytes(),
+ u64::try_from(limit).unwrap_or(u64::MAX),
+ ],
+ |row| {
+ let id: Vec<u8> = row.get(0)?;
+ Ok((
+ id,
+ row.get::<_, String>(1)?,
+ row.get::<_, Option<String>>(2)?,
+ row.get::<_, Option<String>>(3)?,
+ row.get::<_, i64>(4)?,
+ ))
+ },
+ )?;
+ let mut out = Vec::new();
+ for row in rows {
+ let (id, from_agent, to_agent, cwd, created_at) = row?;
+ let Ok(id) = HandoffId::from_slice(&id) else {
+ continue;
+ };
+ out.push(OpenHandoff {
+ id: id.to_string(),
+ from_agent,
+ to_agent,
+ cwd,
+ created_at_ms: created_at / 1_000,
+ });
+ }
+ Ok(out)
+ })
+ .await
+ }
+
async fn page_descriptors_for_ids(
&self,
workspace_id: WorkspaceId,
@@ -7427,6 +7484,20 @@ fn slot_exclusion_sql(
/// a server behind a trusted proxy what follows the prefix is whatever
/// `X-Memory-Actor-Sub` carried — an OIDC subject the engine never parses — so
/// nothing upstream constrains its characters.
+/// One open handoff, as an operator needs to see it to decide what to cancel.
+///
+/// Content-free by construction: identity, provenance and age only. The
+/// summary body is deliberately absent — this exists so
+/// `memory_handoff_cancel` has an id to be given, not to render the handoff.
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct OpenHandoff {
+ pub id: String,
+ pub from_agent: String,
+ pub to_agent: Option<String>,
+ pub cwd: Option<String>,
+ pub created_at_ms: i64,
+}
+
fn handoff_owner_sql(filter: &OwnerFilter, param_index: usize) -> (String, Option<String>) {
match filter {
OwnerFilter::Any => (String::new(), None),
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 9a7a71a3..b2734c24 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -436,7 +436,7 @@ setup-agent bootstrap install-instructions
install-skills reorg purge-project
rename-project move-project move-session
uninstall auth user
-completions
+completions handoffs
```
Run `ai-memory --help` for the full tree.