Skip to content

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

Rust

fix(finalize-session): preserve typed exact targeting

AkitaOnRails728d3fff021b
diff --git a/README.md b/README.md
index 970d3e50..997f1d23 100644
--- a/README.md
+++ b/README.md
@@ -38,7 +38,7 @@
| Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works; no hook handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. `ai-memory run grok` adds managed workstream resume with the context packet delivered natively through `--rules`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). |
| Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. |
| Kimi Code | Supported | MCP config (`url` entry in `~/.kimi-code/mcp.json`) + lifecycle hooks (`[[hooks]]` in `~/.kimi-code/config.toml`, 10 events including subagent start/stop and `PostToolUseFailure` for tool-failure capture); both paths honor `$KIMI_CODE_HOME`. Handoffs inject via `UserPromptSubmit` stdout (Kimi Code discards `SessionStart` hook stdout); `ai-memory run kimi` adds managed workstream resume. |
-| Kiro CLI | Supported (v2) | MCP config uses `install-mcp --client kiro-cli` (alias `kiro`) and Kiro's Bedrock-compatible schema flavor. `install-hooks --agent kiro-cli` merges verified v2 hooks into existing agent configs, honors `$KIRO_HOME`, preserves unrelated entries, and injects pending handoffs through `agentSpawn` stdout. Explicit `ai-memory run kiro` adds v2 managed resume; it is not in bare automatic selection pending a logged-in current-format acceptance run. Kiro v3 hooks and managed sessions remain unsupported. |
+| Kiro CLI | Supported (v2) | MCP config uses `install-mcp --client kiro-cli` (alias `kiro`) and Kiro's Bedrock-compatible schema flavor. `install-hooks --agent kiro-cli` merges verified v2 hooks into existing agent configs, honors `$KIRO_HOME`, preserves unrelated entries, and injects pending handoffs through `agentSpawn` stdout. Kiro v2 has no true SessionEnd hook; use `ai-memory finalize-session --agent kiro-cli`, with `--session-id <uuid>` when concurrent sessions share a scope. Explicit `ai-memory run kiro` adds v2 managed resume; it is not in bare automatic selection pending a logged-in current-format acceptance run. Kiro v3 hooks and managed sessions remain unsupported. |
| VS Code Copilot | MCP-only | `.vscode/mcp.json` for Copilot agent mode; no lifecycle hooks (Copilot does not expose them yet). |
| Zed | MCP-only | Native remote MCP under `context_servers` in Zed's user `settings.json`; no lifecycle hooks or managed-workstream support. |
| Hermes Agent | Community | Core hook ingestion recognizes `agent=hermes` and Hermes' documented shell-hook `tool_name` / `tool_input` payload for concrete session attribution, tool-family titles, and capture exclusions. A community-maintained [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) is available, but no first-party installer is shipped; review its compatibility matrix, install/uninstall scripts, and secret handling before using it. Hermes ignores session-start hook stdout, so recover handoffs through MCP. |
@@ -176,7 +176,9 @@ priors are at the [bottom](#influences-and-prior-art).
sessions through `GET /admin/open-sessions`, then posts synthetic
`session-end` hooks back to the server. On shared deployments it defaults to
the caller's own plus unattributed sessions; root can pass `--all-owners` for
- explicit cross-operator recovery.
+ explicit cross-operator recovery. When concurrent sessions share an agent and
+ scope, pass `--session-id <uuid>` to target one exact open session; it cannot
+ be combined with `--all`.
- **LLM is opt-in.** Zero-LLM mode still gives you FTS5, manually declared
entity, and graph-neighbor search plus rule-based summarisation. Add a
provider when you want consolidated pages, lint contradictions, or staged
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 446a983c..09f036a6 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -1085,8 +1085,7 @@ 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)]
+ #[arg(long, conflicts_with = "session_id")]
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
@@ -1094,8 +1093,8 @@ pub struct FinalizeSessionArgs {
/// 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>,
+ #[arg(long, conflicts_with = "all")]
+ pub session_id: Option<ai_memory_core::SessionId>,
/// Emit a JSON summary.
#[arg(long)]
pub json: bool,
@@ -1725,6 +1724,44 @@ mod tests {
use clap::{CommandFactory, Parser};
use std::collections::BTreeSet;
+ #[test]
+ fn finalize_session_parses_typed_id_and_rejects_ambiguous_selection() {
+ let session_id = ai_memory_core::SessionId::new();
+ let parsed = Cli::try_parse_from([
+ "ai-memory",
+ "finalize-session",
+ "--session-id",
+ &session_id.to_string(),
+ ])
+ .expect("valid session id parses");
+ let Command::FinalizeSession(args) = parsed.command else {
+ panic!("expected finalize-session command");
+ };
+ assert_eq!(args.session_id, Some(session_id));
+
+ assert!(
+ Cli::try_parse_from([
+ "ai-memory",
+ "finalize-session",
+ "--session-id",
+ "not-a-uuid",
+ ])
+ .is_err(),
+ "malformed session ids must fail at the CLI boundary"
+ );
+ assert!(
+ Cli::try_parse_from([
+ "ai-memory",
+ "finalize-session",
+ "--all",
+ "--session-id",
+ &session_id.to_string(),
+ ])
+ .is_err(),
+ "--all and --session-id must be mutually exclusive"
+ );
+ }
+
#[test]
fn architecture_lists_every_visible_cli_subcommand() {
let architecture = include_str!("../../../docs/ARCHITECTURE.md");
diff --git a/crates/ai-memory-cli/src/commands/finalize_session.rs b/crates/ai-memory-cli/src/commands/finalize_session.rs
index 6f463584..64d3057e 100644
--- a/crates/ai-memory-cli/src/commands/finalize_session.rs
+++ b/crates/ai-memory-cli/src/commands/finalize_session.rs
@@ -1,6 +1,6 @@
//! `ai-memory finalize-session` — manually synthesize SessionEnd for an agent.
-use ai_memory_core::AgentKind;
+use ai_memory_core::{AgentKind, SessionId};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
@@ -53,9 +53,6 @@ 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;
@@ -66,7 +63,7 @@ pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {
agent,
args.all,
args.all_owners,
- args.session_id.as_deref(),
+ args.session_id,
)
.await?;
if sessions.is_empty() {
@@ -104,7 +101,7 @@ async fn fetch_open_sessions(
agent: AgentKind,
all: bool,
all_owners: bool,
- session_id: Option<&str>,
+ session_id: Option<SessionId>,
) -> Result<Vec<OpenSessionEntry>> {
let all = if all { "true" } else { "false" };
let all_owners = if all_owners { "true" } else { "false" };
@@ -115,7 +112,8 @@ async fn fetch_open_sessions(
("all", all),
("all_owners", all_owners),
];
- if let Some(sid) = session_id {
+ let session_id = session_id.map(|sid| sid.to_string());
+ if let Some(sid) = session_id.as_deref() {
query.push(("session_id", sid));
}
let result = get_json::<OpenSessionsResponse>(endpoint, "/admin/open-sessions", &query).await;
@@ -298,7 +296,6 @@ mod tests {
AgentKind::AntigravityCli,
ai_memory_core::OwnerFilter::Any,
Some(1),
- None,
)
.await
.unwrap();
@@ -347,24 +344,19 @@ mod tests {
let selected = store
.reader
- .open_sessions_for_scope_agent(
+ .open_session_for_scope_agent_by_id(
ws,
proj,
AgentKind::KiroCli,
ai_memory_core::OwnerFilter::Any,
- None,
- Some(older),
+ older,
)
.await
.unwrap();
assert_eq!(
- selected.len(),
- 1,
- "exact session_id filter must return exactly one match"
- );
- assert_eq!(
- selected[0].session_id, older,
+ selected.map(|session| session.session_id),
+ Some(older),
"must target the requested session, not the newest open one"
);
@@ -373,18 +365,16 @@ mod tests {
// default query, it left the sibling session alone.
let still_open = store
.reader
- .open_sessions_for_scope_agent(
+ .open_session_for_scope_agent_by_id(
ws,
proj,
AgentKind::KiroCli,
ai_memory_core::OwnerFilter::Any,
- None,
- Some(latest),
+ latest,
)
.await
.unwrap();
- assert_eq!(still_open.len(), 1);
- assert_eq!(still_open[0].session_id, latest);
+ assert_eq!(still_open.map(|session| session.session_id), Some(latest));
}
#[test]
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index e24d85a5..56d383b3 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -6005,7 +6005,6 @@ mod tests {
other,
AgentKind::Codex,
ai_memory_core::OwnerFilter::Any,
- None,
None
)
.await
@@ -6022,7 +6021,6 @@ 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 80aa4c87..d688eebc 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -903,13 +903,13 @@ struct OpenSessionsQuery {
#[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
+ /// owner filter above) instead of 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>,
+ session_id: Option<SessionId>,
}
/// Wire shape for one open session in the `GET /admin/open-sessions`
@@ -1035,6 +1035,14 @@ async fn handle_open_sessions(
actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
Query(query): Query<OpenSessionsQuery>,
) -> impl IntoResponse {
+ if query.all && query.session_id.is_some() {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": "all and session_id cannot be combined"
+ })),
+ );
+ }
let Some(agent) = parse_agent_kind(&query.agent) else {
return (
StatusCode::BAD_REQUEST,
@@ -1043,24 +1051,11 @@ 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,
Err(e) => return e,
};
- let limit = if query.all { None } else { Some(1) };
let owner_filter = if query.all_owners {
ai_memory_core::OwnerFilter::Any
} else {
@@ -1068,11 +1063,20 @@ async fn handle_open_sessions(
&actor_ext.map_or_else(ai_memory_core::ActorContext::anonymous, |ext| ext.0),
)
};
- match state
- .reader
- .open_sessions_for_scope_agent(ws, proj, agent, owner_filter, limit, exact_session_id)
- .await
- {
+ 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)
+ .await
+ .map(|session| session.into_iter().collect())
+ } else {
+ let limit = if query.all { None } else { Some(1) };
+ state
+ .reader
+ .open_sessions_for_scope_agent(ws, proj, agent, owner_filter, limit)
+ .await
+ };
+ match sessions {
Ok(sessions) => {
let sessions: Vec<OpenSessionEntry> = sessions
.into_iter()
@@ -5991,14 +5995,17 @@ mod tests {
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),
+ let wrong_agent = SessionId::new();
+ for (id, project_id, agent_kind, actor_user) in [
+ (older, target, AgentKind::KiroCli, None),
+ (latest, target, AgentKind::KiroCli, None),
+ (other_scope, other_project, AgentKind::KiroCli, None),
+ (ended, target, AgentKind::KiroCli, None),
+ (wrong_agent, target, AgentKind::Codex, None),
(
bobs_session,
target,
+ AgentKind::KiroCli,
Some(IdentityKey::User("bob".into()).storage_key()),
),
] {
@@ -6008,7 +6015,7 @@ mod tests {
id,
workspace_id: ws,
project_id,
- agent_kind: AgentKind::KiroCli,
+ agent_kind,
cwd: Some(std::path::PathBuf::from("/tmp/target")),
actor_user,
})
@@ -6099,6 +6106,25 @@ mod tests {
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(json["sessions"].as_array().unwrap().len(), 0);
+ // An exact id from another agent remains outside the requested
+ // agent boundary even when its scope matches.
+ let resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(format!(
+ "/admin/open-sessions?workspace=default&project=target&agent=kiro-cli&session_id={wrong_agent}"
+ ))
+ .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.
@@ -6141,6 +6167,22 @@ mod tests {
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(json["sessions"].as_array().unwrap().len(), 1);
+ // Selection modes are mutually exclusive instead of silently giving
+ // one of them precedence.
+ let resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(format!(
+ "/admin/open-sessions?workspace=default&project=target&agent=kiro-cli&all=true&session_id={older}"
+ ))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+
// A malformed session_id fails closed with a 400, not a silent
// empty/ignored filter.
let resp = router
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index fc4c7189..41d0d664 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1843,14 +1843,6 @@ 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(
@@ -1860,6 +1852,55 @@ impl ReaderPool {
agent_kind: AgentKind,
owner_filter: OwnerFilter,
limit: Option<usize>,
+ ) -> StoreResult<Vec<OpenSession>> {
+ self.open_sessions_for_scope_agent_filtered(
+ workspace_id,
+ project_id,
+ agent_kind,
+ owner_filter,
+ limit,
+ None,
+ )
+ .await
+ }
+
+ /// Return one exact open session for a scoped project and agent.
+ ///
+ /// The id narrows the scope, agent, open-state, and owner predicates; it
+ /// never replaces them. A known id therefore cannot expose or finalize a
+ /// colleague's session unless the caller explicitly uses
+ /// [`OwnerFilter::Any`].
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn open_session_for_scope_agent_by_id(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ agent_kind: AgentKind,
+ owner_filter: OwnerFilter,
+ session_id: SessionId,
+ ) -> StoreResult<Option<OpenSession>> {
+ let mut sessions = self
+ .open_sessions_for_scope_agent_filtered(
+ workspace_id,
+ project_id,
+ agent_kind,
+ owner_filter,
+ Some(1),
+ Some(session_id),
+ )
+ .await?;
+ Ok(sessions.pop())
+ }
+
+ async fn open_sessions_for_scope_agent_filtered(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ 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();
diff --git a/crates/ai-memory-store/tests/handoff_ownership.rs b/crates/ai-memory-store/tests/handoff_ownership.rs
index 373dca6d..2345d8c5 100644
--- a/crates/ai-memory-store/tests/handoff_ownership.rs
+++ b/crates/ai-memory-store/tests/handoff_ownership.rs
@@ -891,14 +891,7 @@ 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,
- None,
- )
+ .open_sessions_for_scope_agent(ws, proj, AgentKind::ClaudeCode, filter_for("bob"), None)
.await
.unwrap());
assert_eq!(
@@ -910,14 +903,7 @@ 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,
- None,
- )
+ .open_sessions_for_scope_agent(ws, proj, AgentKind::ClaudeCode, filter_for("alice"), None)
.await
.unwrap());
assert!(alices.contains(&alice_session) && alices.contains(&shared_session));
@@ -925,14 +911,7 @@ 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,
- None,
- )
+ .open_sessions_for_scope_agent(ws, proj, AgentKind::ClaudeCode, OwnerFilter::Any, None)
.await
.unwrap());
assert_eq!(all.len(), 2);
diff --git a/docs/install.md b/docs/install.md
index 3ecb0681..fc91e27f 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -641,6 +641,8 @@ auto-improvement eligibility for the current project, run:
```bash
ai-memory finalize-session
# add --all to close every matching open Codex session in this workspace/project
+# or target one exact concurrent session (mutually exclusive with --all)
+ai-memory finalize-session --session-id <uuid>
```
Antigravity CLI also lacks a true session-end event. Its `Stop` hook marks the
@@ -656,6 +658,7 @@ explicitly:
```bash
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
```
### Devin CLI
@@ -787,6 +790,15 @@ through successful `agentSpawn` stdout. Verified v2 tool payloads enforce
`[capture] ignore_paths`; an unrecognized payload shape is stored as bounded
metadata rather than exposing file content.
+Kiro v2's `stop` event ends a turn, not the session. After the final turn, close
+the matching session explicitly; use the exact id when several Kiro sessions
+are open in the same project:
+
+```bash
+ai-memory finalize-session --agent kiro-cli
+ai-memory finalize-session --agent kiro-cli --session-id <uuid>
+```
+
Kiro v3 hook capture is intentionally not advertised or installed. Its
[migration guide](https://kiro.dev/docs/cli/v3/hooks-migration/) documents the
standalone registration schema, and the
diff --git a/docs/users.md b/docs/users.md
index 8ace2c77..2b2aa6ba 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -142,6 +142,9 @@ to — and consumed by — the next session to start, whoever it belongs to.
multi-user mode.
- `ai-memory finalize-session --all-owners` does the same for sessions, and
`GET /admin/open-sessions?all_owners=true` is the underlying switch.
+ `--session-id <uuid>` / `session_id=<uuid>` narrows the same owner-scoped
+ lookup to one exact open session; it cannot be combined with `--all` /
+ `all=true`.
- `GET /admin/sessions/by-agent` reports how many sessions each agent CLI
opened in a scope. It follows the same rule: the caller's own sessions
plus the unowned ones, with `all_owners=true` to see every operator's. Pass