Skip to content

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

Rust

feat(handoffs): clear a stale open-handoff backlog (#513) (#543)

Fabio Akita48b5f86acb62
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d11366b6..c43bd266 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- `ai-memory handoffs --expire-all --confirm` and `POST /admin/handoffs/expire`
+ clear a stale open-handoff backlog for one scope. The listing added in
+ v1.35.0 made a backlog visible and gave `memory_handoff_cancel` the ids it
+ needs, but clearing one required a call per handoff (#513).
+
+ It deliberately does **not** honour the exemptions the automatic sweep
+ applies. `expire_superseded_auto_handoffs` spares manual handoffs
+ (`from_session_id IS NULL`) and ones whose `cwd` does not match the accepting
+ session — correct for a sweep triggered by an unrelated accept, and the
+ reason a backlog accumulates at all. The leftover backlog is therefore made,
+ by construction, of exactly the handoffs that sweep will never touch, so an
+ operator-driven expiry honouring the same exemptions would clear nothing. A
+ test pins that: applying the sweep's manual-handoff exemption leaves the
+ backlog behind.
+
+ A state change rather than a delete — the summary, provenance and timestamps
+ survive and the handoff simply stops being consumable, which is also why it
+ is recoverable in a way a delete would not be. Owner scoping lives inside the
+ `UPDATE` so expiring another user's baton is a zero-row no-op rather than a
+ read-then-write race, matching `cancel_handoff`. `--older-than-days N` keeps
+ recent batons; `--confirm` is required and the count is audited.
- `ai-memory purge-session --session-id <uuid> --confirm` and
`POST /admin/purge-session` delete one session by UUID: its row, its
observations, the handoffs it authored, its `sessions/<id>.md` page and
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 59ee9650..1562595e 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -332,6 +332,24 @@ pub struct HandoffsArgs {
/// Emit JSON instead of the human listing.
#[arg(long)]
pub json: bool,
+ /// Expire every open handoff in the scope instead of listing them.
+ ///
+ /// Unlike the automatic sweep this does NOT spare manual handoffs or ones
+ /// from another directory — those exemptions are exactly what a leftover
+ /// backlog is made of, so honouring them would clear nothing. Pair with
+ /// `--older-than-days` to keep recent batons.
+ ///
+ /// This is a state change, not a delete: the summary and provenance
+ /// survive and the handoff simply stops being consumable. Requires
+ /// `--confirm`.
+ #[arg(long)]
+ pub expire_all: bool,
+ /// With `--expire-all`, only expire handoffs at least this many days old.
+ #[arg(long)]
+ pub older_than_days: Option<u32>,
+ /// REQUIRED by `--expire-all`.
+ #[arg(long)]
+ pub confirm: bool,
}
#[derive(Debug, Args)]
diff --git a/crates/ai-memory-cli/src/commands/handoffs.rs b/crates/ai-memory-cli/src/commands/handoffs.rs
index 3b8374a0..33fa6d9b 100644
--- a/crates/ai-memory-cli/src/commands/handoffs.rs
+++ b/crates/ai-memory-cli/src/commands/handoffs.rs
@@ -39,6 +39,11 @@ 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;
+
+ if args.expire_all {
+ return expire(&endpoint, &workspace, &project, &args).await;
+ }
+
let response: OpenHandoffsResponse = get_json(
&endpoint,
"/admin/handoffs",
@@ -110,3 +115,61 @@ mod tests {
assert_eq!(humanize_age_secs(-5), "just now");
}
}
+
+/// Request body for `POST /admin/handoffs/expire`.
+#[derive(serde::Serialize)]
+struct ExpireRequest<'a> {
+ workspace: &'a str,
+ project: &'a str,
+ confirm: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ older_than_days: Option<u32>,
+}
+
+/// Clear the open handoff backlog for one scope.
+async fn expire(
+ endpoint: &ServerEndpoint,
+ workspace: &str,
+ project: &str,
+ args: &HandoffsArgs,
+) -> Result<()> {
+ if !args.confirm {
+ let age = args
+ .older_than_days
+ .map(|d| format!(" --older-than-days {d}"))
+ .unwrap_or_default();
+ anyhow::bail!(
+ "--expire-all marks every open handoff in {workspace}/{project} expired.\n\
+ The rows and their summaries are kept; they just stop being consumable.\n\
+ Unlike the automatic sweep this also clears manual handoffs and ones from \
+ another directory.\n\n \
+ ai-memory handoffs --workspace {workspace} --project {project}{age} \
+ --expire-all --confirm"
+ );
+ }
+
+ let report: serde_json::Value = crate::http_client::post_json(
+ endpoint,
+ "/admin/handoffs/expire",
+ &ExpireRequest {
+ workspace,
+ project,
+ confirm: true,
+ older_than_days: args.older_than_days,
+ },
+ )
+ .await?;
+
+ let expired = report["expired"].as_u64().unwrap_or(0);
+ if expired == 0 {
+ println!("No open handoffs to expire in {workspace}/{project}.");
+ } else {
+ println!(
+ "Expired {expired} open handoff{} in {workspace}/{project}. \
+ The rows are kept and remain visible in the audit log; they are \
+ no longer offered to an agent.",
+ if expired == 1 { "" } else { "s" }
+ );
+ }
+ Ok(())
+}
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 91142d0d..40f70c96 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -583,6 +583,7 @@ pub fn admin_router_with_sweep_tuning(
)
.route("/admin/curator", post(handle_curator))
.route("/admin/handoffs", get(handle_open_handoffs_list))
+ .route("/admin/handoffs/expire", post(handle_expire_handoffs))
.route("/admin/pending-writes", get(handle_pending_writes_list))
.route(
"/admin/pending-writes/{id}",
@@ -2349,6 +2350,75 @@ async fn handle_open_handoffs_list(
}
}
+/// `POST /admin/handoffs/expire` request body.
+#[derive(Deserialize)]
+struct ExpireHandoffsRequest {
+ workspace: String,
+ project: String,
+ /// Mandatory. Without `confirm: true` the server returns 400.
+ confirm: bool,
+ /// Only expire handoffs at least this many days old. Omitted clears the
+ /// whole open backlog for the scope.
+ #[serde(default)]
+ older_than_days: Option<u32>,
+}
+
+/// `POST /admin/handoffs/expire` — clear the open handoff backlog for one
+/// scope.
+///
+/// Unlike the automatic sweep this does not spare manual or
+/// different-directory handoffs. Those exemptions are what the leftover
+/// backlog is made of, so honouring them here would expire nothing. It is a
+/// state change rather than a delete: the summary and provenance survive and
+/// the handoff simply stops being consumable (#513).
+async fn handle_expire_handoffs(
+ State(state): State<Arc<AdminState>>,
+ actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
+ author_ext: Option<axum::Extension<ai_memory_core::UserId>>,
+ Json(req): Json<ExpireHandoffsRequest>,
+) -> impl IntoResponse {
+ if !req.confirm {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": "expiring the handoff backlog requires confirm=true"
+ })),
+ );
+ }
+ let (ws, proj) = match lookup_ws_proj_no_create(&state, &req.workspace, &req.project).await {
+ Ok(ids) => ids,
+ Err(e) => return e,
+ };
+
+ // Same owner scoping as cancel: a caller clears their own and shared
+ // batons, never somebody else's.
+ let actor = actor_ext
+ .map(|axum::Extension(a)| a)
+ .unwrap_or_else(ai_memory_core::ActorContext::anonymous);
+ let owner_filter = ai_memory_core::OwnerFilter::for_actor_context(&actor);
+ let author_id = author_ext.map(|axum::Extension(u)| u);
+
+ let older_than_us = req.older_than_days.map(|days| {
+ jiff::Timestamp::now().as_microsecond() - i64::from(days) * 24 * 60 * 60 * 1_000_000
+ });
+
+ match state
+ .writer
+ .expire_open_handoffs(ws, proj, owner_filter, older_than_us, author_id)
+ .await
+ {
+ Ok(expired) => (
+ StatusCode::OK,
+ Json(serde_json::json!({
+ "expired": expired,
+ "workspace": req.workspace,
+ "project": req.project,
+ })),
+ ),
+ Err(e) => internal_err(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/ops.rs b/crates/ai-memory-store/src/ops.rs
index 09e24ebe..d2a34de6 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -2540,6 +2540,93 @@ fn expire_superseded_auto_handoffs(
Ok(expired)
}
+/// Expire every open handoff in one scope, optionally only those older than
+/// `older_than_us`. Returns how many rows changed.
+///
+/// # Why this ignores the automatic expiry's exemptions
+///
+/// [`expire_superseded_auto_handoffs`] deliberately spares two kinds of open
+/// handoff: manual ones (`from_session_id IS NULL`, written by a person on
+/// purpose) and ones whose `cwd` does not match the accepting session's. Those
+/// exemptions are correct for an automatic sweep triggered by an unrelated
+/// accept.
+///
+/// They also mean the leftover backlog consists, by construction, of exactly
+/// the handoffs the sweep will never touch. An operator-driven bulk expiry
+/// that honoured the same exemptions would therefore expire nothing at all —
+/// it would be a no-op for the only situation it exists to resolve. So this
+/// applies to every open handoff in scope, which is what an operator asking to
+/// clear a backlog is asking for.
+///
+/// Owner scoping still applies, and lives inside the `UPDATE` rather than a
+/// preceding read, so expiring another user's baton is a zero-row no-op rather
+/// than a read-then-write race — the same shape [`cancel_handoff`] uses.
+///
+/// This is a state change, not a delete: the summary, provenance and
+/// timestamps survive. An expired handoff simply stops being consumable.
+///
+/// # Errors
+/// Propagates SQL errors.
+pub fn expire_open_handoffs(
+ conn: &mut Connection,
+ workspace_id: &WorkspaceId,
+ project_id: &ProjectId,
+ owner_filter: &OwnerFilter,
+ older_than_us: Option<i64>,
+ author_id: Option<ai_memory_core::UserId>,
+) -> StoreResult<u64> {
+ let tx = conn.transaction()?;
+ let owner_clause = match owner_filter {
+ OwnerFilter::Any => "",
+ OwnerFilter::User(_) => " AND (owner_user IS NULL OR owner_user = :owner)",
+ OwnerFilter::Unattributed => " AND owner_user IS NULL",
+ };
+ let age_clause = if older_than_us.is_some() {
+ " AND created_at <= :cutoff"
+ } else {
+ ""
+ };
+ let sql = format!(
+ "UPDATE handoffs SET state = 'expired' \
+ WHERE workspace_id = :ws AND project_id = :proj \
+ AND state = 'open'{owner_clause}{age_clause}"
+ );
+
+ let ws_bytes: Vec<u8> = workspace_id.as_bytes().to_vec();
+ let proj_bytes: Vec<u8> = project_id.as_bytes().to_vec();
+ let mut params: Vec<(&str, &dyn rusqlite::ToSql)> = vec![
+ (":ws", &ws_bytes as &dyn rusqlite::ToSql),
+ (":proj", &proj_bytes as &dyn rusqlite::ToSql),
+ ];
+ let owner_value;
+ if let OwnerFilter::User(user) = owner_filter {
+ owner_value = user.clone();
+ params.push((":owner", &owner_value as &dyn rusqlite::ToSql));
+ }
+ let cutoff_value;
+ if let Some(cutoff) = older_than_us {
+ cutoff_value = cutoff;
+ params.push((":cutoff", &cutoff_value as &dyn rusqlite::ToSql));
+ }
+
+ let changed = tx.execute(&sql, params.as_slice())? as u64;
+
+ if changed > 0 {
+ audit_with_detail(
+ &tx,
+ "expire_open_handoffs",
+ Some(workspace_id.as_bytes()),
+ Some(project_id.as_bytes()),
+ None,
+ author_id.as_ref().map(ai_memory_core::UserId::as_bytes),
+ Timestamp::now().as_microsecond(),
+ &format!("{{\"expired\":{changed}}}"),
+ )?;
+ }
+ tx.commit()?;
+ Ok(changed)
+}
+
/// Mark an open handoff expired so it will no longer be consumed.
pub fn cancel_handoff(
conn: &mut Connection,
@@ -4417,6 +4504,184 @@ pub(crate) mod tests {
);
}
+ /// Insert one open handoff. `manual` writes `from_session_id = NULL`,
+ /// which is what makes a handoff exempt from the automatic sweep.
+ fn seed_handoff(
+ conn: &Connection,
+ ws: WorkspaceId,
+ proj: ProjectId,
+ cwd: Option<&str>,
+ manual: bool,
+ owner: Option<&str>,
+ created_at: i64,
+ ) -> Vec<u8> {
+ let id = uuid::Uuid::now_v7().as_bytes().to_vec();
+ let from_session: Option<Vec<u8>> = if manual {
+ None
+ } else {
+ Some(SessionId::new().as_bytes().to_vec())
+ };
+ // An auto handoff needs a real session row for the FK.
+ if let Some(sid) = &from_session {
+ conn.execute(
+ "INSERT INTO sessions (id, workspace_id, project_id, agent_kind, started_at, \
+ actor_user) VALUES (?1, ?2, ?3, 'codex', 1, ?4)",
+ rusqlite::params![&sid[..], ws.as_bytes(), proj.as_bytes(), owner],
+ )
+ .unwrap();
+ }
+ conn.execute(
+ "INSERT INTO handoffs (id, workspace_id, project_id, from_session_id, from_agent, \
+ summary, state, created_at, cwd, owner_user) \
+ VALUES (?1, ?2, ?3, ?4, 'codex', 'baton', 'open', ?5, ?6, ?7)",
+ rusqlite::params![
+ &id[..],
+ ws.as_bytes(),
+ proj.as_bytes(),
+ from_session,
+ created_at,
+ cwd,
+ owner
+ ],
+ )
+ .unwrap();
+ id
+ }
+
+ fn open_handoffs(conn: &Connection) -> i64 {
+ conn.query_row(
+ "SELECT COUNT(*) FROM handoffs WHERE state = 'open'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap()
+ }
+
+ /// #513: the leftover backlog is made of exactly the handoffs the
+ /// automatic sweep exempts — manual ones and ones from a non-matching
+ /// cwd. An operator-driven bulk expiry has to clear those, or it clears
+ /// nothing at all.
+ #[test]
+ fn expire_open_handoffs_clears_the_handoffs_the_auto_sweep_exempts() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ seed_handoff(&conn, ws, proj, Some("/work/a"), true, None, 100);
+ seed_handoff(&conn, ws, proj, Some("/elsewhere"), false, None, 200);
+ seed_handoff(&conn, ws, proj, Some("/work/a"), false, None, 300);
+ assert_eq!(open_handoffs(&conn), 3, "precondition");
+
+ let expired =
+ expire_open_handoffs(&mut conn, &ws, &proj, &OwnerFilter::Any, None, None).unwrap();
+
+ assert_eq!(expired, 3, "every open handoff in scope is cleared");
+ assert_eq!(open_handoffs(&conn), 0);
+ }
+
+ /// It is a state change, not a delete: the summary and provenance survive
+ /// so an operator can still see what was cleared.
+ #[test]
+ fn expire_open_handoffs_preserves_the_rows_it_expires() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ seed_handoff(&conn, ws, proj, Some("/work/a"), true, None, 100);
+
+ expire_open_handoffs(&mut conn, &ws, &proj, &OwnerFilter::Any, None, None).unwrap();
+
+ let (state, summary): (String, String) = conn
+ .query_row("SELECT state, summary FROM handoffs", [], |r| {
+ Ok((r.get(0)?, r.get(1)?))
+ })
+ .unwrap();
+ assert_eq!(state, "expired");
+ assert_eq!(summary, "baton", "content is not destroyed");
+ }
+
+ /// `--older-than` lets an operator clear a backlog without touching a
+ /// handoff created moments ago.
+ #[test]
+ fn expire_open_handoffs_respects_the_age_cutoff() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ seed_handoff(&conn, ws, proj, None, true, None, 100);
+ seed_handoff(&conn, ws, proj, None, true, None, 5_000);
+
+ let expired =
+ expire_open_handoffs(&mut conn, &ws, &proj, &OwnerFilter::Any, Some(1_000), None)
+ .unwrap();
+
+ assert_eq!(expired, 1, "only the older one");
+ assert_eq!(open_handoffs(&conn), 1);
+ }
+
+ /// Scope containment: another project's backlog is untouched.
+ #[test]
+ fn expire_open_handoffs_does_not_cross_project_boundaries() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let other = get_or_create_project(&mut conn, &ws, "other", None).unwrap();
+ seed_handoff(&conn, ws, proj, None, true, None, 100);
+ seed_handoff(&conn, ws, other, None, true, None, 100);
+
+ let expired =
+ expire_open_handoffs(&mut conn, &ws, &proj, &OwnerFilter::Any, None, None).unwrap();
+
+ assert_eq!(expired, 1);
+ assert_eq!(
+ open_handoffs(&conn),
+ 1,
+ "the other project's handoff survives"
+ );
+ }
+
+ /// Owner scoping: expiring as one user must not clear another's baton.
+ #[test]
+ fn expire_open_handoffs_leaves_another_owners_baton_alone() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ seed_handoff(&conn, ws, proj, None, true, Some("user:alice"), 100);
+ seed_handoff(&conn, ws, proj, None, true, Some("user:bob"), 100);
+ seed_handoff(&conn, ws, proj, None, true, None, 100);
+
+ let expired = expire_open_handoffs(
+ &mut conn,
+ &ws,
+ &proj,
+ &OwnerFilter::User("user:alice".into()),
+ None,
+ None,
+ )
+ .unwrap();
+
+ assert_eq!(expired, 2, "alice's own plus the shared one");
+ let remaining: String = conn
+ .query_row(
+ "SELECT owner_user FROM handoffs WHERE state = 'open'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(remaining, "user:bob");
+ }
+
+ /// Already-accepted handoffs are history, not backlog.
+ #[test]
+ fn expire_open_handoffs_does_not_touch_accepted_ones() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ conn.execute(
+ "INSERT INTO handoffs (id, workspace_id, project_id, from_agent, summary, state, \
+ created_at) VALUES (?1, ?2, ?3, 'codex', 'done', 'accepted', 1)",
+ rusqlite::params![
+ &uuid::Uuid::now_v7().as_bytes()[..],
+ ws.as_bytes(),
+ proj.as_bytes()
+ ],
+ )
+ .unwrap();
+
+ let expired =
+ expire_open_handoffs(&mut conn, &ws, &proj, &OwnerFilter::Any, None, None).unwrap();
+ assert_eq!(expired, 0);
+ let state: String = conn
+ .query_row("SELECT state FROM handoffs", [], |r| r.get(0))
+ .unwrap();
+ assert_eq!(state, "accepted", "an accepted handoff is not backlog");
+ }
+
/// Accepting a handoff does not make its text yours. Purging the
/// accepting session must not destroy the authoring session's record.
#[test]
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index e2796f35..64f276b4 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -194,6 +194,17 @@ pub(crate) enum WriteCmd {
acceptance: HandoffAcceptance,
reply: oneshot::Sender<StoreResult<bool>>,
},
+ /// Expire every open handoff in one scope (#513). See
+ /// [`ops::expire_open_handoffs`] for why this ignores the automatic
+ /// sweep's exemptions.
+ ExpireOpenHandoffs {
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ owner_filter: OwnerFilter,
+ older_than_us: Option<i64>,
+ author_id: Option<ai_memory_core::UserId>,
+ reply: oneshot::Sender<StoreResult<u64>>,
+ },
CancelHandoff {
handoff_id: HandoffId,
workspace_id: WorkspaceId,
@@ -931,6 +942,37 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ /// Expire every open handoff in one scope, optionally only those older
+ /// than `older_than_us`. Returns how many changed.
+ ///
+ /// Unlike the automatic sweep this does not spare manual or
+ /// different-directory handoffs: those are precisely what a leftover
+ /// backlog is made of. It is a state change, not a delete — the summary
+ /// and provenance survive.
+ ///
+ /// # Errors
+ /// [`StoreError::WriterClosed`], or a propagated SQL error.
+ pub async fn expire_open_handoffs(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ owner_filter: OwnerFilter,
+ older_than_us: Option<i64>,
+ author_id: Option<ai_memory_core::UserId>,
+ ) -> StoreResult<u64> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::ExpireOpenHandoffs {
+ workspace_id,
+ project_id,
+ owner_filter,
+ older_than_us,
+ author_id,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
/// Mark an open handoff expired so it will no longer be consumed.
///
/// Returns `true` when an open handoff was changed, `false` when the id was
@@ -2082,6 +2124,24 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
let result = ops::accept_handoff(&mut conn, &acceptance);
send_or_warn(reply, result, "accept_handoff");
}
+ WriteCmd::ExpireOpenHandoffs {
+ workspace_id,
+ project_id,
+ owner_filter,
+ older_than_us,
+ author_id,
+ reply,
+ } => {
+ let result = ops::expire_open_handoffs(
+ &mut conn,
+ &workspace_id,
+ &project_id,
+ &owner_filter,
+ older_than_us,
+ author_id,
+ );
+ send_or_warn(reply, result, "expire_open_handoffs");
+ }
WriteCmd::CancelHandoff {
handoff_id,
workspace_id,
diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.md
index 0b1f7b7f..d3b0c73c 100644
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@ -10,6 +10,7 @@ on a homelab box where mistakes are harder to undo.
|---|---|---|---|---|
| `purge-project --confirm` | ✅ yes | the one project's data | no | Deletes the UUID-namespaced wiki root and raw workstream segments; sibling projects remain untouched. Refuses with `409` while a managed workstream under the project holds a live run lease — `--force` overrides. |
| `purge-session --session-id --confirm` | ✅ yes | the one session's data | no | Deletes one session by UUID: its row, its observations, the handoffs it **authored**, its `sessions/<id>.md` page and every superseded version, their embeddings, and its auto-improve runs. Strictly scoped — a session that does not belong to the named workspace/project is a `404` and nothing is deleted. Handoffs the session only *accepted* are kept: that text belongs to the session that wrote it. Logical delete by default; `--compact` additionally rebuilds the FTS indexes and `VACUUM`s (see below). |
+| `handoffs --expire-all --confirm` | ✅ yes | no (state change only) | no (but nothing is destroyed) | Marks every **open** handoff in the scope `expired` so it stops being offered to an agent. Rows, summaries and provenance are kept and stay visible in the audit log. Unlike the automatic sweep it does **not** spare manual handoffs or ones from another directory — those exemptions are exactly what a leftover backlog is made of, so honouring them would clear nothing. `--older-than-days N` keeps recent batons. Owner-scoped: never touches another user's baton. |
| `rename-project --from --to` | ✅ yes | no | yes (rename back) | Column-only update on `projects.name`. The on-disk dir is keyed by `project_id` (UUID), so the rename never moves a file. |
| `/admin/rename-workspace` | ✅ yes | no | yes (rename back) | Column-only update on `workspaces.name`; refreshes `_meta.md` scope manifests and checkpoints the wiki tree. |
| `/admin/delete-workspace` | ✅ yes | the workspace and every child project | no | Runs `purge_workspace` admission first, deletes SQLite rows in one cascade, removes the UUID-keyed workspace directory and managed-workstream raw segments, reports filesystem partial failures, and dispatches mirror notification after durable work. |