Skip to content

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

Rust

feat(finalize-session): target one exact session by id

Wilson Luiz Prosdocimo13edbb920859
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e13f612b..cda223eb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- `ai-memory finalize-session --session-id <uuid>` targets exactly one open
+ session instead of "the latest open one for this agent+scope". Agents with
+ no true SessionEnd hook (Kiro CLI, Codex, Antigravity CLI) rely on
+ `finalize-session` to synthesize the summary+handoff, and the
+ newest-first default breaks down with several concurrent sessions for the
+ same agent in one project — e.g. multiple terminal tabs each running Kiro
+ CLI against the same repo — where it can close out a still-active session
+ instead of the one that actually finished. Backed by a new optional
+ `session_id` filter on `GET /admin/open-sessions`, composed with (not
+ bypassing) the existing owner filter: a session id belonging to another
+ operator is still unreachable without `--all-owners`, same as the default
+ query.
+
## [1.24.0] - 2026-08-04
### Added
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index ca2b9073..446a983c 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -1085,8 +1085,17 @@ pub struct FinalizeSessionArgs {
#[arg(long, default_value_t = false)]
pub all_owners: bool,
/// Finalize every matching open session instead of just the latest one.
+ /// Ignored when `--session-id` is set.
#[arg(long)]
pub all: bool,
+ /// Finalize exactly this session id instead of "the latest open one"
+ /// (still subject to `--all-owners`). Use this when other sessions for
+ /// the same agent may be open concurrently in the same project (e.g.
+ /// multiple terminal tabs each running Kiro CLI against one repo) —
+ /// picking "latest" in that case risks closing out the wrong
+ /// (still-active) session.
+ #[arg(long)]
+ pub session_id: Option<String>,
/// Emit a JSON summary.
#[arg(long)]
pub json: bool,
diff --git a/crates/ai-memory-cli/src/commands/finalize_session.rs b/crates/ai-memory-cli/src/commands/finalize_session.rs
index 93347679..6f463584 100644
--- a/crates/ai-memory-cli/src/commands/finalize_session.rs
+++ b/crates/ai-memory-cli/src/commands/finalize_session.rs
@@ -53,6 +53,9 @@ struct FinalizeSessionReport {
/// sessions or rejects a synthetic `session-end` hook.
pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {
let agent = args.agent.kind();
+ if let Some(raw) = args.session_id.as_deref() {
+ uuid::Uuid::parse_str(raw).with_context(|| format!("invalid --session-id: {raw}"))?;
+ }
let (workspace, project) =
super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
@@ -63,6 +66,7 @@ pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {
agent,
args.all,
args.all_owners,
+ args.session_id.as_deref(),
)
.await?;
if sessions.is_empty() {
@@ -100,21 +104,21 @@ async fn fetch_open_sessions(
agent: AgentKind,
all: bool,
all_owners: bool,
+ session_id: Option<&str>,
) -> Result<Vec<OpenSessionEntry>> {
let all = if all { "true" } else { "false" };
let all_owners = if all_owners { "true" } else { "false" };
- let result = get_json::<OpenSessionsResponse>(
- endpoint,
- "/admin/open-sessions",
- &[
- ("workspace", workspace),
- ("project", project),
- ("agent", agent.as_str()),
- ("all", all),
- ("all_owners", all_owners),
- ],
- )
- .await;
+ let mut query = vec![
+ ("workspace", workspace),
+ ("project", project),
+ ("agent", agent.as_str()),
+ ("all", all),
+ ("all_owners", all_owners),
+ ];
+ if let Some(sid) = session_id {
+ query.push(("session_id", sid));
+ }
+ let result = get_json::<OpenSessionsResponse>(endpoint, "/admin/open-sessions", &query).await;
match result {
Ok(response) => Ok(response.sessions),
Err(e) => {
@@ -294,6 +298,7 @@ mod tests {
AgentKind::AntigravityCli,
ai_memory_core::OwnerFilter::Any,
Some(1),
+ None,
)
.await
.unwrap();
@@ -302,6 +307,86 @@ mod tests {
assert_eq!(selected[0].session_id, latest);
}
+ /// Regression for the race a blind wrapper hits when several terminal
+ /// tabs each run Kiro CLI against the same repo: two sessions for the
+ /// same agent+scope are open at once (`older` started first, `latest`
+ /// started after — e.g. opened in a second tab while the first was
+ /// still running). Targeting `older` by its exact id must return only
+ /// `older`, never falling back to "the newest open one" and closing
+ /// out the still-active `latest` session instead.
+ #[tokio::test]
+ async fn exact_session_id_targets_that_session_even_with_a_newer_one_open() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default".to_string())
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "target".to_string(), None)
+ .await
+ .unwrap();
+ let older = SessionId::new();
+ let latest = SessionId::new();
+ for id in [older, latest] {
+ store
+ .writer
+ .begin_session(NewSession {
+ id,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: AgentKind::KiroCli,
+ cwd: Some(std::path::PathBuf::from("/tmp/target")),
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+ }
+
+ let selected = store
+ .reader
+ .open_sessions_for_scope_agent(
+ ws,
+ proj,
+ AgentKind::KiroCli,
+ ai_memory_core::OwnerFilter::Any,
+ None,
+ Some(older),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ selected.len(),
+ 1,
+ "exact session_id filter must return exactly one match"
+ );
+ assert_eq!(
+ selected[0].session_id, older,
+ "must target the requested session, not the newest open one"
+ );
+
+ // The other, still-open session must be untouched and independently
+ // discoverable — proving the exact-id filter didn't just narrow the
+ // default query, it left the sibling session alone.
+ let still_open = store
+ .reader
+ .open_sessions_for_scope_agent(
+ ws,
+ proj,
+ AgentKind::KiroCli,
+ ai_memory_core::OwnerFilter::Any,
+ None,
+ Some(latest),
+ )
+ .await
+ .unwrap();
+ assert_eq!(still_open.len(), 1);
+ assert_eq!(still_open[0].session_id, latest);
+ }
+
#[test]
fn synthetic_end_url_uses_requested_antigravity_agent() {
let endpoint =
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 56d383b3..e24d85a5 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -6005,6 +6005,7 @@ mod tests {
other,
AgentKind::Codex,
ai_memory_core::OwnerFilter::Any,
+ None,
None
)
.await
@@ -6021,6 +6022,7 @@ mod tests {
target,
AgentKind::ClaudeCode,
ai_memory_core::OwnerFilter::Any,
+ None,
None
)
.await
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 07c9b890..80aa4c87 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -902,6 +902,14 @@ struct OpenSessionsQuery {
/// is unaffected.
#[serde(default)]
all_owners: bool,
+ /// When set, narrow to exactly this session id (still subject to the
+ /// owner filter above) instead of `all`/newest-first selection — lets a
+ /// caller that captured its own session id at spawn time finalize
+ /// precisely that session, even when other sessions for the same agent
+ /// are open concurrently in the same project (e.g. multiple terminal
+ /// tabs each running Kiro CLI against one repo).
+ #[serde(default)]
+ session_id: Option<String>,
}
/// Wire shape for one open session in the `GET /admin/open-sessions`
@@ -1035,6 +1043,18 @@ async fn handle_open_sessions(
})),
);
};
+ let exact_session_id = match query.session_id.as_deref().map(str::parse::<SessionId>) {
+ Some(Ok(sid)) => Some(sid),
+ Some(Err(_)) => {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": format!("invalid session_id: {}", query.session_id.unwrap_or_default())
+ })),
+ );
+ }
+ None => None,
+ };
let (ws, proj) = match lookup_ws_proj_no_create(&state, &query.workspace, &query.project).await
{
Ok(ids) => ids,
@@ -1050,7 +1070,7 @@ async fn handle_open_sessions(
};
match state
.reader
- .open_sessions_for_scope_agent(ws, proj, agent, owner_filter, limit)
+ .open_sessions_for_scope_agent(ws, proj, agent, owner_filter, limit, exact_session_id)
.await
{
Ok(sessions) => {
@@ -5937,6 +5957,204 @@ mod tests {
);
}
+ /// Regression for the race a naive wrapper hits with several concurrent
+ /// Kiro CLI tabs against one repo: two open sessions for the same
+ /// agent+scope exist (`older`, `latest`), and `?session_id=` must return
+ /// exactly the one requested — never falling back to "newest open" —
+ /// while still composing with the owner filter (a session_id belonging
+ /// to another operator must not be reachable just by knowing its id,
+ /// same invariant `all_owners` already protects for the default query).
+ #[tokio::test]
+ async fn open_sessions_session_id_targets_exact_session() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone());
+ let ws = store
+ .writer
+ .get_or_create_workspace("default".to_string())
+ .await
+ .unwrap();
+ let target = store
+ .writer
+ .get_or_create_project(ws, "target".to_string(), None)
+ .await
+ .unwrap();
+ let other_project = store
+ .writer
+ .get_or_create_project(ws, "other".to_string(), None)
+ .await
+ .unwrap();
+ let older = SessionId::new();
+ let latest = SessionId::new();
+ let other_scope = SessionId::new();
+ let ended = SessionId::new();
+ let bobs_session = SessionId::new();
+ for (id, project_id, actor_user) in [
+ (older, target, None),
+ (latest, target, None),
+ (other_scope, other_project, None),
+ (ended, target, None),
+ (
+ bobs_session,
+ target,
+ Some(IdentityKey::User("bob".into()).storage_key()),
+ ),
+ ] {
+ store
+ .writer
+ .begin_session(NewSession {
+ id,
+ workspace_id: ws,
+ project_id,
+ agent_kind: AgentKind::KiroCli,
+ cwd: Some(std::path::PathBuf::from("/tmp/target")),
+ actor_user,
+ })
+ .await
+ .unwrap();
+ }
+ store.writer.end_session(ended, None).await.unwrap();
+
+ let router = admin_router(AdminState {
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki,
+ llm: None,
+ auto_improve_require_approval: false,
+ auto_improve_review_config: Default::default(),
+ embedder: None,
+ provider_health: ProviderHealth::default(),
+ decay_params: DecayParams::default(),
+ data_dir: tmp.path().to_path_buf(),
+ db_path: store.db_path().to_path_buf(),
+ bind: "127.0.0.1:49374".to_string(),
+ home_dir: None,
+ bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),
+ token_pepper: None,
+ active_project: ai_memory_core::ActiveProject::new(),
+ scope_invalidator: None,
+ trusted_proxy_identity: false,
+ });
+
+ // Targeting `older` by id must return only `older`, not `latest`.
+ let resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(format!(
+ "/admin/open-sessions?workspace=default&project=target&agent=kiro-cli&session_id={older}"
+ ))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ let sessions = json["sessions"].as_array().unwrap();
+ assert_eq!(sessions.len(), 1, "must not fall back to newest-open");
+ assert_eq!(sessions[0]["session_id"], older.to_string());
+
+ // A session id that belongs to a different project must not be
+ // reachable just by knowing the id — scope is still enforced.
+ let resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(format!(
+ "/admin/open-sessions?workspace=default&project=target&agent=kiro-cli&session_id={other_scope}"
+ ))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ json["sessions"].as_array().unwrap().len(),
+ 0,
+ "a session from another project must not be reachable by id"
+ );
+
+ // An already-ended session id is not "open" and must not match.
+ let resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(format!(
+ "/admin/open-sessions?workspace=default&project=target&agent=kiro-cli&session_id={ended}"
+ ))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["sessions"].as_array().unwrap().len(), 0);
+
+ // A colleague's session id is not reachable without all_owners, even
+ // when the exact id is known — session_id composes with the owner
+ // filter (AND), it doesn't bypass it.
+ let resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(format!(
+ "/admin/open-sessions?workspace=default&project=target&agent=kiro-cli&session_id={bobs_session}"
+ ))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ json["sessions"].as_array().unwrap().len(),
+ 0,
+ "session_id must not bypass the owner filter"
+ );
+
+ // ...but composes correctly WITH all_owners set.
+ let resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(format!(
+ "/admin/open-sessions?workspace=default&project=target&agent=kiro-cli&session_id={bobs_session}&all_owners=true"
+ ))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["sessions"].as_array().unwrap().len(), 1);
+
+ // A malformed session_id fails closed with a 400, not a silent
+ // empty/ignored filter.
+ let resp = router
+ .oneshot(
+ Request::builder()
+ .uri("/admin/open-sessions?workspace=default&project=target&agent=kiro-cli&session_id=not-a-uuid")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+ }
+
fn read_page_test_router() -> (TempDir, Router) {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path()).unwrap();
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index fa70b9aa..fc4c7189 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1843,6 +1843,14 @@ impl ReaderPool {
/// Results are newest-first so callers can default to finalizing only the
/// latest open session while offering an explicit all-sessions mode.
///
+ /// `exact_session_id`, when set, narrows to that one session id in
+ /// addition to (not instead of) the owner filter — this is what lets a
+ /// caller that already knows its own session id (e.g. a wrapper script
+ /// that captured it at spawn time) finalize precisely that session when
+ /// other sessions for the same agent are open concurrently in the same
+ /// project, without bypassing the "don't touch a colleague's session"
+ /// invariant `owner_filter` exists for.
+ ///
/// # Errors
/// Propagates any SQL or pool error.
pub async fn open_sessions_for_scope_agent(
@@ -1852,6 +1860,7 @@ impl ReaderPool {
agent_kind: AgentKind,
owner_filter: OwnerFilter,
limit: Option<usize>,
+ exact_session_id: Option<SessionId>,
) -> StoreResult<Vec<OpenSession>> {
let agent = agent_kind.as_str().to_string();
self.with_conn(move |conn| {
@@ -1864,10 +1873,20 @@ impl ReaderPool {
OwnerFilter::User(_) => " AND (actor_user IS NULL OR actor_user = ?4)",
OwnerFilter::Unattributed => " AND actor_user IS NULL",
};
+ let session_id_placeholder = if matches!(owner_filter, OwnerFilter::User(_)) {
+ "?5"
+ } else {
+ "?4"
+ };
+ let session_id_clause = if exact_session_id.is_some() {
+ format!(" AND id = {session_id_placeholder}")
+ } else {
+ String::new()
+ };
let sql = format!(
"SELECT id, cwd FROM sessions \
WHERE workspace_id = ?1 AND project_id = ?2 \
- AND agent_kind = ?3 AND ended_at IS NULL{owner_clause} \
+ AND agent_kind = ?3 AND ended_at IS NULL{owner_clause}{session_id_clause} \
ORDER BY started_at DESC, id DESC{limit_clause}"
);
let mut stmt = conn.prepare_cached(&sql)?;
@@ -1876,12 +1895,31 @@ impl ReaderPool {
let cwd: Option<String> = row.get(1)?;
Ok((id_bytes, cwd))
};
- let rows = match &owner_filter {
- OwnerFilter::User(user) => stmt.query_map(
+ let rows = match (&owner_filter, exact_session_id) {
+ (OwnerFilter::User(user), Some(sid)) => stmt.query_map(
+ params![
+ workspace_id.as_bytes(),
+ project_id.as_bytes(),
+ agent,
+ user,
+ sid.as_bytes()
+ ],
+ row_map,
+ )?,
+ (OwnerFilter::User(user), None) => stmt.query_map(
params![workspace_id.as_bytes(), project_id.as_bytes(), agent, user],
row_map,
)?,
- _ => stmt.query_map(
+ (_, Some(sid)) => stmt.query_map(
+ params![
+ workspace_id.as_bytes(),
+ project_id.as_bytes(),
+ agent,
+ sid.as_bytes()
+ ],
+ row_map,
+ )?,
+ (_, None) => stmt.query_map(
params![workspace_id.as_bytes(), project_id.as_bytes(), agent],
row_map,
)?,
diff --git a/crates/ai-memory-store/tests/handoff_ownership.rs b/crates/ai-memory-store/tests/handoff_ownership.rs
index 2345d8c5..373dca6d 100644
--- a/crates/ai-memory-store/tests/handoff_ownership.rs
+++ b/crates/ai-memory-store/tests/handoff_ownership.rs
@@ -891,7 +891,14 @@ async fn open_session_lookup_is_owner_scoped() {
// Bob sees only the shared session — never Alice's live one.
let bobs = ids(store
.reader
- .open_sessions_for_scope_agent(ws, proj, AgentKind::ClaudeCode, filter_for("bob"), None)
+ .open_sessions_for_scope_agent(
+ ws,
+ proj,
+ AgentKind::ClaudeCode,
+ filter_for("bob"),
+ None,
+ None,
+ )
.await
.unwrap());
assert_eq!(
@@ -903,7 +910,14 @@ async fn open_session_lookup_is_owner_scoped() {
// Alice sees her own plus the shared one.
let alices = ids(store
.reader
- .open_sessions_for_scope_agent(ws, proj, AgentKind::ClaudeCode, filter_for("alice"), None)
+ .open_sessions_for_scope_agent(
+ ws,
+ proj,
+ AgentKind::ClaudeCode,
+ filter_for("alice"),
+ None,
+ None,
+ )
.await
.unwrap());
assert!(alices.contains(&alice_session) && alices.contains(&shared_session));
@@ -911,7 +925,14 @@ async fn open_session_lookup_is_owner_scoped() {
// The recovery switch (`all_owners=true` on /admin/open-sessions) sees all.
let all = ids(store
.reader
- .open_sessions_for_scope_agent(ws, proj, AgentKind::ClaudeCode, OwnerFilter::Any, None)
+ .open_sessions_for_scope_agent(
+ ws,
+ proj,
+ AgentKind::ClaudeCode,
+ OwnerFilter::Any,
+ None,
+ None,
+ )
.await
.unwrap());
assert_eq!(all.len(), 2);