Skip to content

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

Rust

feat(finalize-session): allow re-finalizing an ended session with --reopen

Lucas Oliveira9524fef2dd3e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9c59817a..d39db253 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- `ai-memory finalize-session --reopen --session-id <uuid>` re-finalizes a
+ session that already ended, for agents without a true session-end event
+ (Antigravity CLI, Kiro, ZCode, Pool) whose conversation continued after a
+ first manual finalize: the discovery step now accepts `include_ended=true`
+ on `GET /admin/open-sessions` for an exact session id (rejected without
+ one, so reopening stays exact-id-only and never a bulk operation), and the
+ server's normal session-end path re-runs over the new observations
+ (updated summary page via supersession, new handoff, opt-in
+ consolidation). Re-running with nothing new since the first end remains a
+ harmless no-op. The default finalize behavior is unchanged: ended sessions
+ stay invisible unless `--reopen` is passed.
+
### Security
- Bumped `rmcp` to 2.x (2.2.0), resolving three MCP transport advisories:
GHSA-9pj6-vhgr-3mwh (unauthenticated Streamable-HTTP session-table leak /
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 22f3ac38..bdefdff8 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -1796,6 +1796,19 @@ pub struct FinalizeSessionArgs {
/// (still-active) session.
#[arg(long, conflicts_with = "all")]
pub session_id: Option<ai_memory_core::SessionId>,
+ /// Re-finalize a session that already ended (requires `--session-id`).
+ ///
+ /// Use this when the conversation continued after a first finalize and
+ /// landed new observations: agents without a true session-end event
+ /// (Antigravity CLI, Kiro, ZCode, Pool) keep capturing under the same
+ /// session id, but the plain discovery step only sees open sessions, so
+ /// a second finalize would silently find nothing. With `--reopen` the
+ /// lookup also matches the ended session and the normal session-end
+ /// path re-runs (updated summary page, handoff, opt-in consolidation).
+ /// When nothing new landed since the first end, the re-run is a
+ /// harmless no-op.
+ #[arg(long, requires = "session_id")]
+ pub reopen: bool,
/// 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 2246cd41..800d2724 100644
--- a/crates/ai-memory-cli/src/commands/finalize_session.rs
+++ b/crates/ai-memory-cli/src/commands/finalize_session.rs
@@ -64,6 +64,7 @@ pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {
args.all,
args.all_owners,
args.session_id,
+ args.reopen,
)
.await?;
if sessions.is_empty() {
@@ -101,6 +102,9 @@ pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {
/// workspace/project fails closed server-side with a 404; that maps to
/// "nothing to finalize" here, matching the previous direct-DB behavior
/// for a missing scope.
+// Eight arguments is the full request shape (scope + agent + the four
+// selection flags + exact id); cf. `post_session_end_batch` below.
+#[allow(clippy::too_many_arguments)]
async fn fetch_open_sessions(
endpoint: &ServerEndpoint,
workspace: &str,
@@ -109,15 +113,18 @@ async fn fetch_open_sessions(
all: bool,
all_owners: bool,
session_id: Option<SessionId>,
+ include_ended: bool,
) -> Result<Vec<OpenSessionEntry>> {
let all = if all { "true" } else { "false" };
let all_owners = if all_owners { "true" } else { "false" };
+ let include_ended = if include_ended { "true" } else { "false" };
let mut query = vec![
("workspace", workspace),
("project", project),
("agent", agent.as_str()),
("all", all),
("all_owners", all_owners),
+ ("include_ended", include_ended),
];
let session_id = session_id.map(|sid| sid.to_string());
if let Some(sid) = session_id.as_deref() {
@@ -363,6 +370,7 @@ mod tests {
AgentKind::KiroCli,
ai_memory_core::OwnerFilter::Any,
older,
+ false,
)
.await
.unwrap();
@@ -384,12 +392,86 @@ mod tests {
AgentKind::KiroCli,
ai_memory_core::OwnerFilter::Any,
latest,
+ false,
)
.await
.unwrap();
assert_eq!(still_open.map(|session| session.session_id), Some(latest));
}
+ /// Regression for the Antigravity manual-finalize gap: after a first
+ /// `finalize-session` closes the session, the conversation may continue
+ /// and land new observations under the same id. The default discovery
+ /// must keep excluding the ended session (closing something already
+ /// closed stays a silent no-op), while the `--reopen` lookup
+ /// (`include_ended = true`) must find it so a second finalize re-runs
+ /// the session-end path.
+ #[tokio::test]
+ async fn ended_session_matches_only_with_include_ended() {
+ 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 ended = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: ended,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: AgentKind::AntigravityCli,
+ cwd: Some(std::path::PathBuf::from("/tmp/target")),
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+ store.writer.end_session(ended, None).await.unwrap();
+
+ let default_lookup = store
+ .reader
+ .open_session_for_scope_agent_by_id(
+ ws,
+ proj,
+ AgentKind::AntigravityCli,
+ ai_memory_core::OwnerFilter::Any,
+ ended,
+ false,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ default_lookup.map(|session| session.session_id),
+ None,
+ "an ended session must stay invisible to the default finalize discovery"
+ );
+
+ let reopen_lookup = store
+ .reader
+ .open_session_for_scope_agent_by_id(
+ ws,
+ proj,
+ AgentKind::AntigravityCli,
+ ai_memory_core::OwnerFilter::Any,
+ ended,
+ true,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ reopen_lookup.map(|session| session.session_id),
+ Some(ended),
+ "--reopen must reach the ended session for a second finalize"
+ );
+ }
+
#[test]
fn synthetic_end_url_propagates_all_owners_once_when_requested() {
let endpoint =
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index e7de040c..9db28f4a 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -11992,7 +11992,8 @@ mod tests {
proj,
AgentKind::Codex,
ai_memory_core::OwnerFilter::Any,
- sid
+ sid,
+ false
)
.await
.unwrap()
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 77b513a0..eb25a827 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -9,7 +9,8 @@
//! - `POST /admin/curator` — dry-run or stage a rule-based curator report.
//! - `GET /admin/status` — lifetime counts + server data-dir info.
//! - `GET /admin/projects` — authoritative `(workspace, project)` list.
-//! - `GET /admin/open-sessions` — open (not yet ended) sessions for one scope + agent.
+//! - `GET /admin/open-sessions` — open (not yet ended) sessions for one scope + agent
+//! (an exact `session_id` plus `include_ended=true` also matches an ended one).
//! - `GET /admin/sessions/by-agent` — session counts per agent CLI for one scope.
//! - `GET /admin/activity/by-client` — MCP tool-call counts per client (server-wide).
//! - `GET /admin/audit-log` — paginated read of the append-only `audit_log`.
@@ -1231,7 +1232,9 @@ async fn handle_status(State(state): State<Arc<AdminState>>) -> impl IntoRespons
/// Query string for `GET /admin/open-sessions` — open (not yet ended)
/// sessions for one scope + agent, newest first. Backs the thin
/// `ai-memory finalize-session` command, which posts synthetic
-/// session-end hooks for whatever this returns.
+/// session-end hooks for whatever this returns. An exact `session_id` plus
+/// `include_ended=true` also matches an already-ended session, for the
+/// manual re-finalize path (`finalize-session --reopen`).
#[derive(Debug, Deserialize)]
struct OpenSessionsQuery {
/// Workspace name (required).
@@ -1262,6 +1265,15 @@ struct OpenSessionsQuery {
/// tabs each running Kiro CLI against one repo).
#[serde(default)]
session_id: Option<SessionId>,
+ /// Also match the exact `session_id` when it already ended, instead of
+ /// reporting "no open sessions". `finalize-session --reopen` passes
+ /// this when re-closing a session that received new observations after
+ /// its first end (e.g. an Antigravity conversation continued after a
+ /// manual finalize); the server's normal session-end path then re-runs
+ /// (page supersession, handoff, consolidation). Requires `session_id`:
+ /// reopening is exact-id-only, never a bulk operation.
+ #[serde(default)]
+ include_ended: bool,
}
/// Wire shape for one open session in the `GET /admin/open-sessions`
@@ -1395,6 +1407,14 @@ async fn handle_open_sessions(
})),
);
}
+ if query.include_ended && query.session_id.is_none() {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": "include_ended requires session_id"
+ })),
+ );
+ }
let Some(agent) = parse_agent_kind(&query.agent) else {
return (
StatusCode::BAD_REQUEST,
@@ -1418,7 +1438,14 @@ async fn handle_open_sessions(
let sessions = if let Some(session_id) = query.session_id {
state
.reader
- .open_session_for_scope_agent_by_id(ws, proj, agent, owner_filter, session_id)
+ .open_session_for_scope_agent_by_id(
+ ws,
+ proj,
+ agent,
+ owner_filter,
+ session_id,
+ query.include_ended,
+ )
.await
.map(|session| session.into_iter().collect())
} else {
@@ -8341,6 +8368,47 @@ mod tests {
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(json["sessions"].as_array().unwrap().len(), 0);
+ // The same ended session id IS reachable with `include_ended=true`
+ // (the `finalize-session --reopen` path): the id still narrows the
+ // response to exactly that session.
+ let resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(format!(
+ "/admin/open-sessions?workspace=default&project=target&agent=kiro-cli&session_id={ended}&include_ended=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();
+ let sessions = json["sessions"].as_array().unwrap();
+ assert_eq!(sessions.len(), 1);
+ assert_eq!(sessions[0]["session_id"], ended.to_string());
+
+ // `include_ended=true` without an exact id is rejected: reopening
+ // must never become a bulk operation over every ended session.
+ let resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(
+ "/admin/open-sessions?workspace=default&project=target&agent=kiro-cli&include_ended=true",
+ )
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+ 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["error"], "include_ended requires session_id");
+
// An exact id from another agent remains outside the requested
// agent boundary even when its scope matches.
let resp = router
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index bbb00efa..b72fdcc3 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -2773,6 +2773,7 @@ impl ReaderPool {
owner_filter,
limit,
None,
+ false,
)
.await
}
@@ -2784,6 +2785,12 @@ impl ReaderPool {
/// colleague's session unless the caller explicitly uses
/// [`OwnerFilter::Any`].
///
+ /// Pass `include_ended = true` to also match a session whose `ended_at`
+ /// is already set — the re-finalize path (`finalize-session --reopen`)
+ /// for agents without a native session-end, where new observations may
+ /// have landed after the first end. Reopening stays exact-id-only: the
+ /// bulk listing above always excludes ended sessions.
+ ///
/// # Errors
/// Propagates any SQL or pool error.
pub async fn open_session_for_scope_agent_by_id(
@@ -2793,6 +2800,7 @@ impl ReaderPool {
agent_kind: AgentKind,
owner_filter: OwnerFilter,
session_id: SessionId,
+ include_ended: bool,
) -> StoreResult<Option<OpenSession>> {
let mut sessions = self
.open_sessions_for_scope_agent_filtered(
@@ -2802,11 +2810,16 @@ impl ReaderPool {
owner_filter,
Some(1),
Some(session_id),
+ include_ended,
)
.await?;
Ok(sessions.pop())
}
+ // Eight arguments is the full lookup key (scope + agent + owner +
+ // limit + exact id + ended-state); splitting it would just move the
+ // same parameters into a struct at both call sites.
+ #[allow(clippy::too_many_arguments)]
async fn open_sessions_for_scope_agent_filtered(
&self,
workspace_id: WorkspaceId,
@@ -2815,6 +2828,7 @@ impl ReaderPool {
owner_filter: OwnerFilter,
limit: Option<usize>,
exact_session_id: Option<SessionId>,
+ include_ended: bool,
) -> StoreResult<Vec<OpenSession>> {
let agent = agent_kind.as_str().to_string();
self.with_conn(move |conn| {
@@ -2827,6 +2841,15 @@ impl ReaderPool {
OwnerFilter::User(_) => " AND (actor_user IS NULL OR actor_user = ?4)",
OwnerFilter::Unattributed => " AND actor_user IS NULL",
};
+ // An exact-id lookup with `include_ended` reaches sessions that
+ // already closed (a manual finalizer's re-run after more work
+ // landed); the default and every bulk listing only see sessions
+ // whose `ended_at` is still NULL.
+ let ended_clause = if include_ended {
+ ""
+ } else {
+ " AND ended_at IS NULL"
+ };
let session_id_placeholder = if matches!(owner_filter, OwnerFilter::User(_)) {
"?5"
} else {
@@ -2840,7 +2863,7 @@ impl ReaderPool {
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}{session_id_clause} \
+ AND agent_kind = ?3{ended_clause}{owner_clause}{session_id_clause} \
ORDER BY started_at DESC, id DESC{limit_clause}"
);
let mut stmt = conn.prepare_cached(&sql)?;
diff --git a/docs/install.md b/docs/install.md
index 1e86f884..6ababa9e 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -808,6 +808,9 @@ explicitly:
ai-memory finalize-session --agent antigravity-cli
# add --all only to close every matching open Antigravity session in this scope
# or add --session-id <uuid> to close one exact concurrent session
+# if the conversation continued after a first finalize, re-close it to cover
+# the new observations (a re-run with nothing new is a harmless no-op)
+ai-memory finalize-session --agent antigravity-cli --reopen --session-id <uuid>
```
### Devin CLI
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index a1fc114a..d3018356 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -618,7 +618,11 @@ The rendered hooks config looks like:
the conversation. After the final turn, run
`ai-memory finalize-session --agent antigravity-cli` to close the session and,
when it contains substantive events, create the final summary and automatic
- handoff and queue opt-in SessionEnd consolidation.
+ handoff and queue opt-in SessionEnd consolidation. If the conversation
+ continues after that first finalize, re-close it with
+ `ai-memory finalize-session --agent antigravity-cli --reopen --session-id <uuid>`
+ so the session-end path re-runs over the new observations (re-running with
+ nothing new is a harmless no-op).
- `memory_handoff_begin` always creates an explicit manual handoff with no
`from_session_id` and `from_agent = other`; it is project-wide for cwd
matching but belongs to the creating operator by default. Pass `shared=true`