Skip to content

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

Rust

feat(run): finalize the session on exit for harnesses without a session-end hook

John Costa2a14b5db3f8d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cd43917c..da6776a5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,6 +34,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
any non-blocking observer/mirror webhook on success. `restore-page` and
version history remain intact. See `docs/okf.md` for the full design.
(#964)
+- `ai-memory run` now finalizes the session when a harness without a native
+ session-end hook exits (Command Code, Kiro CLI v2 and v3, Antigravity CLI),
+ so the summary, handoff and opt-in SessionEnd consolidation no longer wait
+ for a manual `ai-memory finalize-session`. Only a session the run can tie to
+ itself (named, chosen before the spawn, or linked during the run) is closed,
+ including again after it was resumed; if finalizing fails, the run prints
+ the exact command to run and keeps the harness's exit code. (#941)
- `[consolidation] input_token_safety_margin` (float, default `0.8`, validated
to `(0.0, 1.0]`) scales the approximate char-count input budget. The
`max_input_tokens` budget uses a flat chars-per-token heuristic that
diff --git a/crates/ai-memory-cli/src/commands/finalize_session.rs b/crates/ai-memory-cli/src/commands/finalize_session.rs
index 9facc9c2..46fa84cf 100644
--- a/crates/ai-memory-cli/src/commands/finalize_session.rs
+++ b/crates/ai-memory-cli/src/commands/finalize_session.rs
@@ -52,6 +52,18 @@ struct FinalizeSessionReport {
/// Returns an error if the configured server cannot list the scope's open
/// sessions or rejects a synthetic `session-end` hook.
pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {
+ let (workspace, project, finalized) = finalize(config, &args).await?;
+ let agent = args.agent;
+ print_report(args, workspace, project, agent, finalized)
+}
+
+/// Finalizes the sessions `args` selects (open ones, plus the exact ended
+/// session with `reopen`) and returns the scope and the ids it sent a
+/// session-end for, without printing; `ai-memory run` reports on its own.
+pub(crate) async fn finalize(
+ config: &Config,
+ args: &FinalizeSessionArgs,
+) -> Result<(String, String, Vec<String>)> {
let agent = args.agent;
let (workspace, project) =
super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
@@ -68,7 +80,7 @@ pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {
)
.await?;
if sessions.is_empty() {
- return print_report(args, workspace, project, agent, Vec::new());
+ return Ok((workspace, project, Vec::new()));
}
let client = reqwest::Client::new();
@@ -95,7 +107,7 @@ pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {
// agent session would inherit the closed id.
super::hook::clear_session_id(&config.data_dir, agent);
- print_report(args, workspace, project, agent, finalized)
+ Ok((workspace, project, finalized))
}
/// List open sessions for the scope + agent via the server. An unknown
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 595a9d17..5bbc140f 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -1836,7 +1836,7 @@ fn to_git_bash_path(path: &str) -> String {
/// command path. Leaves only conservative shell-safe characters unquoted;
/// wraps everything else in single quotes and escapes embedded `'` via
/// `'\''`.
-fn shell_quote(s: &str) -> String {
+pub(crate) fn shell_quote(s: &str) -> String {
if s.chars().all(|c| {
c.is_ascii_alphanumeric()
|| matches!(c, '-' | '_' | '.' | '/' | ':' | '@' | '%' | '+' | '=' | ',')
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index 2e4c3984..91e7f340 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -9,7 +9,7 @@ use std::time::{Duration, SystemTime};
use ai_memory_core::{
AgentKind, FinishManagedRunRequest, FinishManagedRunResponse, LinkManagedRunRequest,
ManagedRunContextResponse, ManagedRunStatus, PrepareManagedRunRequest,
- PrepareManagedRunResponse,
+ PrepareManagedRunResponse, SessionId,
};
use ai_memory_workstream::{
AmbiguousNativeSession, ExportedTranscript, LaunchMode, LaunchPlan, LaunchRoots,
@@ -564,6 +564,33 @@ pub(super) async fn run_from_with_wiring(
} else {
None
};
+ let own_session_id = match own_native_session(
+ &plan,
+ harness,
+ &home,
+ &repository.cwd,
+ server_status.as_ref(),
+ ) {
+ Ok(own) => own,
+ Err(error) => {
+ // Only a linked session is checked, so the server reported its id.
+ if harness.lacks_session_end_hook()
+ && let Some(linked) = server_status
+ .as_ref()
+ .and_then(|status| status.native_session_id.as_deref())
+ {
+ eprintln!(
+ "ai-memory: not finalizing the {} session: could not tie it to this run ({error:#}); if it was this run's, run `ai-memory finalize-session --agent {} --reopen --session-id {} --workspace {} --project {}`",
+ harness.as_str(),
+ harness.agent_kind().as_str(),
+ SessionId::from_native(linked),
+ super::render_shared::shell_quote(&workspace),
+ super::render_shared::shell_quote(&project)
+ );
+ }
+ None
+ }
+ };
let native_session_id = acquired_try!(
resolve_native_session_after_run(
&plan,
@@ -621,9 +648,81 @@ pub(super) async fn run_from_with_wiring(
prepared.workstream_name
);
interrupt_task.abort();
+ if let Some((session, finalized)) = finalize_hookless_session(
+ config,
+ harness,
+ own_session_id.as_deref(),
+ &workspace,
+ &project,
+ )
+ .await
+ {
+ let agent = harness.agent_kind().as_str();
+ match finalized {
+ Ok(ids) if !ids.is_empty() => {
+ eprintln!("ai-memory: finalized the {agent} session {session}");
+ }
+ // No session under that id for this agent and owner in this
+ // scope: its hooks are not installed or never fired, or they
+ // filed it under another workspace/project.
+ Ok(_) => {}
+ Err(error) => eprintln!(
+ "ai-memory: could not finalize the {agent} session {session} ({error:#}); run `ai-memory finalize-session --agent {agent} --reopen --session-id {session} --workspace {} --project {}`",
+ super::render_shared::shell_quote(&workspace),
+ super::render_shared::shell_quote(&project)
+ ),
+ }
+ }
Ok(exit_code)
}
+/// How long finalizing may hold up the harness's exit code.
+const FINALIZE_TIMEOUT: Duration = Duration::from_secs(30);
+
+/// Finalizes the run's own session when the harness has no native session-end
+/// hook, which would otherwise leave it open until a manual
+/// `ai-memory finalize-session` (#941). The harness has exited, so the session
+/// is over for this run.
+/// Returns the stored session id and the ids finalized, or `None` when there
+/// is nothing to do.
+async fn finalize_hookless_session(
+ config: &Config,
+ harness: ManagedHarness,
+ own_session_id: Option<&str>,
+ workspace: &str,
+ project: &str,
+) -> Option<(SessionId, Result<Vec<String>>)> {
+ let native_session_id = own_session_id?;
+ if !harness.lacks_session_end_hook() {
+ return None;
+ }
+ let session = SessionId::from_native(native_session_id);
+ let args = crate::cli::FinalizeSessionArgs {
+ agent: harness.agent_kind(),
+ workspace: Some(workspace.to_string()),
+ project: Some(project.to_string()),
+ all_owners: false,
+ all: false,
+ session_id: Some(session),
+ // These harnesses keep capturing under the same id when a session is
+ // resumed, so a later run must be able to end it again. A re-end
+ // with nothing new since the last one changes nothing on the server.
+ reopen: true,
+ json: false,
+ };
+ // Tokio keeps SIGINT once it has been captured, so listen afresh: Ctrl-C
+ // skips a slow finalize instead of being dropped.
+ let finalized = tokio::select! {
+ finalized = tokio::time::timeout(
+ FINALIZE_TIMEOUT,
+ super::finalize_session::finalize(config, &args),
+ ) => finalized
+ .unwrap_or_else(|_| Err(anyhow!("timed out after {}s", FINALIZE_TIMEOUT.as_secs()))),
+ Ok(()) = tokio::signal::ctrl_c() => Err(anyhow!("interrupted")),
+ };
+ Some((session, finalized.map(|(_, _, ids)| ids)))
+}
+
async fn capture_interrupts(interrupted: CancellationToken) {
while tokio::signal::ctrl_c().await.is_ok() {
interrupted.cancel();
@@ -681,12 +780,16 @@ async fn cancel_managed_run_after_failure(endpoint: &ServerEndpoint, run_path: &
}
}
-async fn resolve_native_session_after_run(
+/// The session this run can prove is its own: the one it launched or resumed,
+/// or the one its child linked under the run's id. A concurrent launch in the
+/// same checkout cannot link under this run's id, while discovery can only
+/// guess from timing. A descendant process inherits the id too, so the linked
+/// session must also be this checkout's.
+fn own_native_session(
plan: &LaunchPlan,
harness: ManagedHarness,
home: &Path,
cwd: &Path,
- started_at: SystemTime,
server_status: Option<&ManagedRunStatus>,
) -> Result<Option<String>> {
if plan.mode == LaunchMode::Passthrough {
@@ -695,19 +798,35 @@ async fn resolve_native_session_after_run(
if let Some(native_session_id) = &plan.expected_session_id {
return Ok(Some(native_session_id.clone()));
}
- // A session linked under this run's id was reported by this run's child,
- // which a concurrent launch in the same checkout cannot do; discovery
- // only sees the newest session there. A descendant process inherits the
- // id too, so the session must also be this checkout's.
+ let Some(linked) = server_status
+ .filter(|status| status.native_session_linked)
+ .and_then(|status| status.native_session_id.as_deref())
+ else {
+ return Ok(None);
+ };
+ let in_checkout =
+ native_session_in_checkout(harness, home, cwd, plan.session_dir.as_deref(), linked)
+ .with_context(|| format!("reading native session {linked}"))?;
+ Ok(in_checkout.then(|| linked.to_string()))
+}
+
+async fn resolve_native_session_after_run(
+ plan: &LaunchPlan,
+ harness: ManagedHarness,
+ home: &Path,
+ cwd: &Path,
+ started_at: SystemTime,
+ server_status: Option<&ManagedRunStatus>,
+) -> Result<Option<String>> {
+ if plan.mode == LaunchMode::Passthrough {
+ return Ok(None);
+ }
+ if let Ok(Some(own)) = own_native_session(plan, harness, home, cwd, server_status) {
+ return Ok(Some(own));
+ }
let linked = server_status
.filter(|status| status.native_session_linked)
.and_then(|status| status.native_session_id.as_deref());
- if let Some(linked) = linked
- && native_session_in_checkout(harness, home, cwd, plan.session_dir.as_deref(), linked)
- .unwrap_or(false)
- {
- return Ok(Some(linked.to_string()));
- }
let fresh = !has_native_session_selector(harness, &plan.args);
let discovered = match discover_native_session(
harness,
@@ -730,8 +849,8 @@ async fn resolve_native_session_after_run(
}
Err(error) => return Err(error),
};
- // A linked session set aside above belongs to another checkout, so it is
- // no fallback either.
+ // A linked session `own_native_session` rejected (not in this checkout,
+ // or its native store could not be read) is no fallback either.
Ok(discovered.or_else(|| {
server_status
.and_then(|status| status.native_session_id.clone())
@@ -2742,12 +2861,27 @@ mod tests {
context_delivered: true,
state: "active".to_string(),
};
- for (linked, native, expected) in [
- (true, "prepared", Some("prepared")),
- (false, "prepared", Some("concurrent-newer")),
- (true, "nested", Some("concurrent-newer")),
+ for (linked, native, expected, own) in [
+ (true, "prepared", Some("prepared"), Some("prepared")),
+ (false, "prepared", Some("concurrent-newer"), None),
+ (true, "nested", Some("concurrent-newer"), None),
] {
let status = status(linked, native);
+ // Only a session the run can prove is its own: never a discovered
+ // one, which may be a concurrent launch's (#941 finalizes it).
+ assert_eq!(
+ own_native_session(
+ &plan,
+ ManagedHarness::Codex,
+ temp.path(),
+ &cwd,
+ Some(&status)
+ )
+ .unwrap()
+ .as_deref(),
+ own,
+ "own: linked={linked} native={native}"
+ );
assert_eq!(
resolve_native_session_after_run(
&plan,
@@ -3688,4 +3822,119 @@ mod tests {
home.join(".omp").join("agent")
);
}
+
+ /// Harnesses without a native session-end hook get their session closed
+ /// when the managed run ends (#941): the exact session is looked up by the
+ /// stored id its native id maps to, and a synthetic session-end is posted.
+ /// Harnesses with their own hook, and runs with no session, are left alone.
+ #[tokio::test]
+ async fn run_end_finalizes_the_session_of_a_hookless_harness() {
+ use std::sync::Mutex;
+
+ use axum::extract::{Query, State};
+ use axum::routing::get;
+
+ use crate::config::Config;
+
+ #[derive(Default)]
+ struct Seen {
+ lookups: Vec<std::collections::HashMap<String, String>>,
+ batches: Vec<serde_json::Value>,
+ }
+ let seen = Arc::new(Mutex::new(Seen::default()));
+ let app = Router::new()
+ .route(
+ "/admin/open-sessions",
+ get(
+ |State(seen): State<Arc<Mutex<Seen>>>,
+ Query(query): Query<std::collections::HashMap<String, String>>| async move {
+ let session_id = query.get("session_id").cloned().unwrap_or_default();
+ seen.lock().unwrap().lookups.push(query);
+ axum::Json(serde_json::json!({
+ "sessions": [{ "session_id": session_id, "cwd": "/tmp/repo" }]
+ }))
+ },
+ ),
+ )
+ .route(
+ "/hook/batch",
+ post(
+ |State(seen): State<Arc<Mutex<Seen>>>, axum::Json(body): axum::Json<serde_json::Value>| async move {
+ seen.lock().unwrap().batches.push(body);
+ axum::Json(serde_json::json!({ "accepted": 1 }))
+ },
+ ),
+ )
+ .with_state(seen.clone());
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+
+ let home = tempfile::tempdir().unwrap();
+ let data = tempfile::tempdir().unwrap();
+ let mut config = Config::load(None, Some(home.path().to_path_buf())).unwrap();
+ config.data_dir = data.path().to_path_buf();
+ config.server_url = format!("http://{address}");
+
+ assert!(
+ finalize_hookless_session(
+ &config,
+ ManagedHarness::Claude,
+ Some("claude-1"),
+ "ws",
+ "proj"
+ )
+ .await
+ .is_none()
+ );
+ assert!(
+ finalize_hookless_session(&config, ManagedHarness::Antigravity, None, "ws", "proj")
+ .await
+ .is_none()
+ );
+ assert!(
+ seen.lock().unwrap().lookups.is_empty(),
+ "nothing to finalize yet"
+ );
+
+ let (session, finalized) = finalize_hookless_session(
+ &config,
+ ManagedHarness::Antigravity,
+ Some("agy-session-1"),
+ "ws",
+ "proj",
+ )
+ .await
+ .expect("a hookless harness with its own session is finalized");
+ let stored = SessionId::from_native("agy-session-1").to_string();
+ assert_eq!(session.to_string(), stored);
+ assert_eq!(finalized.unwrap(), vec![stored.clone()]);
+ let seen = seen.lock().unwrap();
+ assert_eq!(seen.lookups.len(), 1, "one exact-session lookup");
+ let lookup = &seen.lookups[0];
+ assert_eq!(
+ lookup.get("session_id"),
+ Some(&stored),
+ "looked up by the stored id"
+ );
+ assert_eq!(
+ lookup.get("agent").map(String::as_str),
+ Some("antigravity-cli")
+ );
+ assert_eq!(lookup.get("workspace").map(String::as_str), Some("ws"));
+ assert_eq!(lookup.get("project").map(String::as_str), Some("proj"));
+ assert_eq!(
+ lookup.get("include_ended").map(String::as_str),
+ Some("true"),
+ "a resumed session that was already ended is ended again"
+ );
+ assert_eq!(seen.batches.len(), 1, "one synthetic session-end batch");
+ assert!(
+ seen.batches[0].to_string().contains(&stored),
+ "the session-end targets that session: {}",
+ seen.batches[0]
+ );
+ drop(seen);
+ server.abort();
+ }
}
diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rs
index e5f449b8..bbcadbd6 100644
--- a/crates/ai-memory-core/src/ids.rs
+++ b/crates/ai-memory-core/src/ids.rs
@@ -80,6 +80,17 @@ macro_rules! id_newtype {
id_newtype!(pub WorkspaceId, "Workspace identifier (top of the 3-tuple).");
id_newtype!(pub ProjectId, "Project identifier (middle of the 3-tuple).");
id_newtype!(pub SessionId, "Identifier for a single agent run.");
+
+impl SessionId {
+ /// The stored id for a harness's own session id: the id itself when it is
+ /// a UUID, otherwise a deterministic v5 UUID of it, so hook POSTs and later
+ /// lookups by native id share one key.
+ #[must_use]
+ pub fn from_native(raw: &str) -> Self {
+ Self::from_str(raw)
+ .unwrap_or_else(|_| Self(Uuid::new_v5(&Uuid::NAMESPACE_OID, raw.as_bytes())))
+ }
+}
id_newtype!(pub ObservationId, "Identifier for a single observation captured during a session.");
id_newtype!(pub PageId, "Identifier for a single wiki page version.");
id_newtype!(pub EntityId, "Identifier for one project-scoped entity.");
@@ -749,6 +760,23 @@ mod tests {
AgentKind::Devin
);
}
+
+ #[test]
+ fn session_id_from_native_keeps_uuids_and_hashes_other_ids() {
+ let uuid = SessionId::new();
+ assert_eq!(SessionId::from_native(&uuid.to_string()), uuid);
+ let hashed = SessionId::from_native("agy-session-1");
+ assert_eq!(
+ hashed,
+ SessionId::from_native("agy-session-1"),
+ "deterministic"
+ );
+ assert_eq!(
+ hashed.0,
+ Uuid::new_v5(&Uuid::NAMESPACE_OID, b"agy-session-1"),
+ "the key hook POSTs have always used"
+ );
+ }
}
/// Names Windows reserves regardless of extension: `CON.md` is still the
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 1ebd3491..c418a0cc 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -30,7 +30,6 @@ use axum::routing::{get, post};
use jiff::Timestamp;
use serde::{Deserialize, Serialize};
use tracing::{debug, info, warn};
-use uuid::Uuid;
use crate::capture_policy::{
CaptureConfig, CaptureDisposition, CapturePolicy, CaptureProtocol, CaptureSource, PolicyState,
@@ -1481,7 +1480,7 @@ async fn fetch_and_accept_handoff_at(
.session_id
.as_deref()
.filter(|value| !value.trim().is_empty())
- .map(resolve_native_session_id);
+ .map(SessionId::from_native);
let receiving_session = if handoff.is_some() {
match accepting_session {
Some(id) => Some(NewSession {
@@ -3398,7 +3397,7 @@ fn parse_session_owner(owner: Option<String>) -> anyhow::Result<Option<IdentityK
fn resolve_session_id(env: &HookEnvelope) -> anyhow::Result<SessionId> {
if let Some(raw) = &env.session_id {
- return Ok(resolve_native_session_id(raw));
+ return Ok(SessionId::from_native(raw));
}
if matches!(env.event, HookEvent::SessionStart) {
return Ok(SessionId::new());
@@ -3406,13 +3405,6 @@ fn resolve_session_id(env: &HookEnvelope) -> anyhow::Result<SessionId> {
anyhow::bail!("hook payload missing session_id and event is not session-start")
}
-fn resolve_native_session_id(raw: &str) -> SessionId {
- // Accept either a UUID (canonical) or any string, hashing the latter to a
- // deterministic UUID v5 so hook POSTs and startup GETs share one key.
- SessionId::from_str(raw)
- .unwrap_or_else(|_| SessionId(Uuid::new_v5(&Uuid::NAMESPACE_OID, raw.as_bytes())))
-}
-
/// A session is substantive iff it logged at least one `UserPrompt`,
/// `PreToolUse`, or `PostToolUse` observation. Everything else — including
/// `Stop` and `Notification`, which some harnesses (e.g. OpenCode) fire for
@@ -12169,7 +12161,7 @@ mod tests {
.unwrap();
assert_eq!(
accepted.lifecycle.accepted_by_session,
- Some(resolve_native_session_id(empty_sid))
+ Some(SessionId::from_native(empty_sid))
);
for event in ["session-start", "session-end"] {
@@ -15077,7 +15069,7 @@ mod tests {
.await
.unwrap();
- let session_id = resolve_native_session_id(session);
+ let session_id = SessionId::from_native(session);
let summary = state
.reader
.session_summary_scoped(
diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rs
index b1c79845..2fe960cc 100644
--- a/crates/ai-memory-workstream/src/harness.rs
+++ b/crates/ai-memory-workstream/src/harness.rs
@@ -61,6 +61,16 @@ impl ManagedHarness {
}
}
+ /// Whether the harness has no native session-end hook, so its sessions
+ /// stay open until `ai-memory finalize-session` runs (docs/support-matrix.md).
+ #[must_use]
+ pub const fn lacks_session_end_hook(self) -> bool {
+ matches!(
+ self,
+ Self::CommandCode | Self::Kiro | Self::KiroV3 | Self::Antigravity
+ )
+ }
+
/// Core agent kind used on the wire and in storage.
#[must_use]
pub const fn agent_kind(self) -> AgentKind {
@@ -3183,4 +3193,35 @@ mod tests {
&[OsString::from("-i"), OsString::from("start here")]
));
}
+
+ #[test]
+ fn only_harnesses_without_a_session_end_hook_need_finalizing() {
+ let hookless = [
+ ManagedHarness::CommandCode,
+ ManagedHarness::Kiro,
+ ManagedHarness::KiroV3,
+ ManagedHarness::Antigravity,
+ ];
+ for harness in [
+ ManagedHarness::Claude,
+ ManagedHarness::Codex,
+ ManagedHarness::OpenCode,
+ ManagedHarness::OpenCode2,
+ ManagedHarness::Pi,
+ ManagedHarness::Crush,
+ ManagedHarness::Omp,
+ ManagedHarness::Kimi,
+ ManagedHarness::Grok,
+ ]
+ .into_iter()
+ .chain(hookless)
+ {
+ assert_eq!(
+ harness.lacks_session_end_hook(),
+ hookless.contains(&harness),
+ "{}",
+ harness.as_str()
+ );
+ }
+ }
}
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index 525d4905..34623df5 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -352,6 +352,13 @@ resume, continue, session, or fork selector.
5. Imports use deterministic event ids, incremental source cursors, immutable
sanitized JSONL segments, and bounded batches. A retry cannot duplicate
history. The native process's exit code is preserved.
+6. Command Code, Kiro CLI and Antigravity CLI have no native session-end hook,
+ so for them the run then finalizes the session itself (again after a
+ resume), as `ai-memory finalize-session --reopen` would: summary, handoff
+ and opt-in SessionEnd consolidation. It does this only for a session named
+ on the command line, chosen before the spawn, or linked during the run,
+ never for one it had to look for. If finalizing fails, it prints the exact
+ `finalize-session` command to run instead.
The next harness receives a bounded recent delta because no agent context window
can safely absorb an unbounded transcript. The complete visible ledger remains
diff --git a/docs/support-matrix.md b/docs/support-matrix.md
index aa1cc0f9..a501ce5e 100644
--- a/docs/support-matrix.md
+++ b/docs/support-matrix.md
@@ -12,7 +12,7 @@
| Native Windows | Experimental | Tagged releases publish `ai-memory-windows-x86_64.zip` with `ai-memory.exe`; Docker Desktop wrapper and source builds are also available. Native `ai-memory upgrade` is supported for writable x86_64 zip installs (checksum-verified zip + rename-aside self-replace + sibling `hooks/` refresh). Local supported profiles default to host-native hook commands; Claude Code may use its Windows exec form, while other agents use native single command strings matching their hook schema. PowerShell/Git Bash scripts are compatibility fallbacks. See [`docs/windows.md`](windows.md). |
| Claude Code | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. `install-mcp --session-aware` optionally enables per-session auto-scope isolation through a local stdio bridge. Optionally captures the assistant's final turn on `Stop` when installed with `--capture-assistant` and the server enables `capture_assistant` (double opt-in, off by default). |
| Codex | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. `SessionEnd` is wired since Codex CLI 0.145.0 (openai/codex#33895), so finished sessions get an automatic end-of-session summary/handoff; on older Codex the event is inert and `ai-memory finalize-session --agent codex` is the fallback. Optionally captures the assistant's final turn on `Stop` when installed with `--capture-assistant` and the server enables `capture_assistant` (double opt-in, off by default) — Codex's `Stop` payload carries `last_assistant_message`, same as Claude Code. |
-| Command Code | Supported | MCP config (`~/.commandcode/mcp.json`) + its four stable lifecycle-hook events (`~/.commandcode/settings.json`); native commands enforce capture exclusions and `SessionStart` injects handoffs. `Stop` is only a turn boundary, so use `ai-memory finalize-session --agent command-code` after the final turn. `ai-memory run command-code` adds exact v3 native-session resume and visible-event import; experimental unsandboxed Mods remain excluded. |
+| Command Code | Supported | MCP config (`~/.commandcode/mcp.json`) + its four stable lifecycle-hook events (`~/.commandcode/settings.json`); native commands enforce capture exclusions and `SessionStart` injects handoffs. `Stop` is only a turn boundary, so use `ai-memory finalize-session --agent command-code` after the final turn; an interactive session launched with `ai-memory run command-code` is finalized automatically when it exits if the run can tie the session to itself (see [`docs/managed-workstreams.md`](managed-workstreams.md)). `ai-memory run command-code` adds exact v3 native-session resume and visible-event import; experimental unsandboxed Mods remain excluded. |
| Devin CLI | Supported | MCP config + lifecycle hooks. Hooks use Devin's `PostCompaction` event, inject handoffs via `hookSpecificOutput.additionalContext`, and omit subagent events because Devin does not expose them. |
| OpenCode | Supported | Remote MCP config + generated TypeScript plugin; generated plugin enforces capture exclusions. |
| OpenCode 2 (`opencode2` beta) | Supported | V2 `mcp.servers` remote MCP config + generated TypeScript plugin (`ai-memory-opencode2.ts`) for the OpenCode 2.0.10+ event API, checked against 2.0.14; shares v1's config dir, session store, and agent kind. Completed root turns checkpoint the session page and baton without ending the shared service's session; MCP calls route by the native `_meta` session id, so concurrent sessions in different projects stay isolated. `--capture-assistant` is supported (double opt-in). Managed runs launch, resume, and import; ledger-delta acknowledgement is limited by the shared background service (see managed-workstreams notes). |
@@ -24,13 +24,13 @@
| Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, OpenCode 2 beta, Pi, Crush, Kimi Code, Command Code, both incompatible Kiro CLI engines, OMP, Grok Build CLI, and Antigravity CLI. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](managed-workstreams.md). |
| Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. |
| OpenClaw | Supported | MCP config + native plugin lifecycle hooks; generated plugin enforces capture exclusions. |
-| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). Only `PreInvocation` with `invocationNum = 0` maps to SessionStart; later model calls cannot consume a next-session handoff. No automatic true session-end hook, so run `ai-memory finalize-session --agent antigravity-cli` after the final turn when you need a summary, handoff, and opt-in SessionEnd consolidation. `ai-memory run antigravity` (aliases `antigravity-cli`, `agy`) adds managed workstream resume via `--conversation`; conversation text is not decoded, so the ledger for this harness comes from hook capture. |
+| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). Only `PreInvocation` with `invocationNum = 0` maps to SessionStart; later model calls cannot consume a next-session handoff. No automatic true session-end hook, so run `ai-memory finalize-session --agent antigravity-cli` after the final turn when you need a summary, handoff, and opt-in SessionEnd consolidation; an interactive session launched with `ai-memory run antigravity` is finalized automatically when it exits if the run can tie the session to itself (see [`docs/managed-workstreams.md`](managed-workstreams.md)). `ai-memory run antigravity` (aliases `antigravity-cli`, `agy`) adds managed workstream resume via `--conversation`; conversation text is not decoded, so the ledger for this harness comes from hook capture. |
| 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. `SessionStart` and `UserPromptSubmit` do not accept the handoff (Grok discards that stdout). The first `PostToolUse` prints `hookSpecificOutput.additionalContext` with the pending handoff and an opted-in `[briefing]`; the model sees it after that tool result. If no tool runs, recover via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. `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`). |
| Swival CLI | MCP-only | `install-mcp --client swival --apply` merges a native HTTP entry into the project-root `.swival/mcp.json`, preserving sibling servers. Lifecycle and managed-workstream support are not claimed because Swival's callback contract does not expose a stable session identifier. |
| 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_list` then `memory_handoff_accept` with that `handoff_id`. |
| ZCode | Supported | `install-mcp --client zcode --apply` merges a native HTTP entry (strict schema: `type`/`url`/`headers` only) into the `mcp.servers` map of `~/.zcode/cli/config.json`, preserving sibling servers. ZCode (z.ai, `zcode`, alias `zai`). Lifecycle-hook capture via `install-hooks --agent zcode --apply`: exec-form native commands (`type: "process"`, no shell) merged into the root `hooks` block of `~/.zcode/cli/config.json` around any third-party hooks; native commands enforce capture exclusions. Six documented triggers (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`); `PostToolUseFailure` fires instead of `PostToolUse` when a tool throws and lands on the same capture channel with the error preserved. `PermissionRequest` is deliberately not installed — its hook chain races the interactive permission client, so passive capture of that event is unreliable by design. No true session-end — `Stop` is a per-turn boundary, so run `ai-memory finalize-session --agent zcode` after the final turn. Unlike Pool and Zero, `SessionStart` stdout injection works (`hookSpecificOutput.additionalContext`, verified live against the embedded engine v0.16.5), so the prior session's handoff is delivered automatically. No first-party `install-mcp` client and no managed workstream are claimed yet. |
| 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 | MCP config uses `install-mcp --client kiro-cli` (alias `kiro`) and Kiro's Bedrock-compatible schema flavor. `install-hooks --agent kiro-cli` merges v2 hooks into existing agent configs; the explicit `--agent kiro-cli-v3` target writes the incompatible standalone v3 registration. Both preserve unrelated entries, honor `$KIRO_HOME`, enforce capture exclusions, and inject pending handoffs at session start. Kiro has no true SessionEnd hook; use `ai-memory finalize-session --agent kiro-cli`, with `--session-id <uuid>` for concurrent sessions. `ai-memory run kiro` manages v2; add `--v3`, `--mode`, or `--agent-engine v3` for version-safe v3 resume. |
+| Kiro CLI | Supported | MCP config uses `install-mcp --client kiro-cli` (alias `kiro`) and Kiro's Bedrock-compatible schema flavor. `install-hooks --agent kiro-cli` merges v2 hooks into existing agent configs; the explicit `--agent kiro-cli-v3` target writes the incompatible standalone v3 registration. Both preserve unrelated entries, honor `$KIRO_HOME`, enforce capture exclusions, and inject pending handoffs at session start. Kiro has no true SessionEnd hook; use `ai-memory finalize-session --agent kiro-cli`, with `--session-id <uuid>` for concurrent sessions, unless it is an interactive session launched with `ai-memory run kiro`, which finalizes it automatically when it exits if the run can tie the session to itself (see [`docs/managed-workstreams.md`](managed-workstreams.md)). `ai-memory run kiro` manages v2; add `--v3`, `--mode`, or `--agent-engine v3` for version-safe v3 resume. |
| Pool | Hooks-only | Poolside Agent CLI (`pool`). Lifecycle-hook capture via `install-hooks --agent pool` (alias `poolside`): Pool reads project-scoped hooks from the repo-root `.poolside/settings.yaml`, so ai-memory stages the scripts and prints a ready-to-paste `hooks:` snippet rather than writing project-local files; native commands enforce capture exclusions. Five Claude-shaped events (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `Stop`) and no true session-end — `Stop` is a turn boundary, so run `ai-memory finalize-session --agent pool` after the final turn. `SessionStart` stdout injection is not demonstrated, so capture works but handoff injection does not — recover handoffs via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. No first-party `install-mcp` client and no managed workstream (`ai-memory run pool`) are claimed: Pool's native session-store contract is not demonstrated (see [`docs/managed-harness-contributions.md`](managed-harness-contributions.md)). Verified against Poolside CLI v1.0.16. |
| 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. |