Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(cli): expose Antigravity session finalization (#284)
AkitaOnRails4e6462c8becf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3877f221..a0e94d1f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed+- Antigravity CLI hook installation and documentation now expose the existing+ agent-aware manual finalizer:+ `ai-memory finalize-session --agent antigravity-cli`. Antigravity's `Stop`+ event ends one execution loop rather than the conversation, so it remains a+ normal observation; the explicit command closes the latest scoped session+ through the canonical SessionEnd path, producing its summary and automatic+ handoff and queueing opt-in consolidation. The docs also clarify why a+ manual MCP handoff over Antigravity's static HTTP connection has no dynamic+ session attribution. (#284)+## [1.19.1] - 2026-07-27### Changeddiff --git a/README.md b/README.mdindex 320f5cfe..f8585930 100644--- a/README.md+++ b/README.md@@ -34,7 +34,7 @@| Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, OMP, and Grok Build CLI. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](docs/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). |+| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). 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. || 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. |@@ -114,8 +114,9 @@ priors are at the [bottom](#influences-and-prior-art).contribute without becoming absolute filters, so targeted history searchesstill find session pages.- **Karpathy-style LLM wiki.** Pages are compiled from observations- at session-end (or PreCompact; Codex can use `ai-memory finalize-session`- for a manual final close), not retrieved over raw logs.+ at session-end (or PreCompact; clients without a true session-end event can+ use `ai-memory finalize-session --agent <agent>` for a manual final close),+ not retrieved over raw logs.Supersession chain + git-versioned markdown means you cantime-travel with `ai-memory checkpoints`, `restore-page`, or raw `git log`.- **Built-in `/web` browser.** Read-only HTML UI for the wiki -diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 99bc80b1..c976677c 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -103,7 +103,7 @@ pub enum Command {AutoImproveReport(AutoImproveReportArgs),/// Run auto-improvement for one completed session.AutoImprove(AutoImproveArgs),- /// Manually finalize the latest open Codex session for this project.+ /// Manually finalize the latest open session for one agent in this project.FinalizeSession(FinalizeSessionArgs),/// Review, approve, or reject staged auto-improvement proposals.PendingWrites(PendingWritesArgs),@@ -1001,8 +1001,8 @@ impl AgentChoice {/// Arguments for `finalize-session`.#[derive(Debug, Args)]pub struct FinalizeSessionArgs {- /// Agent kind to finalize. Defaults to Codex because Codex has no reliable- /// true SessionEnd hook.+ /// Agent kind to finalize. Defaults to Codex for backward compatibility;+ /// Codex and Antigravity CLI have no reliable true SessionEnd hook.#[arg(long, value_enum, default_value_t = AgentChoice::Codex)]pub agent: AgentChoice,/// Workspace name. Defaults to the nearest `.ai-memory.toml` marker'sdiff --git a/crates/ai-memory-cli/src/commands/finalize_session.rs b/crates/ai-memory-cli/src/commands/finalize_session.rsindex 2828de7a..c79e07ce 100644--- a/crates/ai-memory-cli/src/commands/finalize_session.rs+++ b/crates/ai-memory-cli/src/commands/finalize_session.rs@@ -1,4 +1,4 @@-//! `ai-memory finalize-session` — manually synthesize SessionEnd for Codex.+//! `ai-memory finalize-session` — manually synthesize SessionEnd for an agent.use ai_memory_core::AgentKind;use anyhow::{Context, Result, bail};@@ -233,7 +233,7 @@ mod tests {use tempfile::TempDir;#[tokio::test]- async fn selects_latest_scoped_codex_session_only_by_default() {+ async fn selects_latest_scoped_session_for_requested_agent_by_default() {let tmp = TempDir::new().unwrap();let store = Store::open(tmp.path()).unwrap();let ws = store@@ -256,10 +256,10 @@ mod tests {let other_agent = SessionId::new();let other_scope = SessionId::new();for (id, project_id, agent) in [- (older, target, AgentKind::Codex),- (other_agent, target, AgentKind::ClaudeCode),- (other_scope, other_project, AgentKind::Codex),- (latest, target, AgentKind::Codex),+ (older, target, AgentKind::AntigravityCli),+ (other_agent, target, AgentKind::Codex),+ (other_scope, other_project, AgentKind::AntigravityCli),+ (latest, target, AgentKind::AntigravityCli),] {store.writer@@ -276,11 +276,36 @@ mod tests {let selected = store.reader- .open_sessions_for_scope_agent(ws, target, AgentKind::Codex, Some(1))+ .open_sessions_for_scope_agent(ws, target, AgentKind::AntigravityCli, Some(1)).await.unwrap();assert_eq!(selected.len(), 1);assert_eq!(selected[0].session_id, latest);}++ #[test]+ fn synthetic_end_url_uses_requested_antigravity_agent() {+ let endpoint =+ ServerEndpoint::from_pair(Some("http://127.0.0.1:49374/base".to_string()), None);+ let url = session_end_hook_url(+ &endpoint,+ "/tmp/project",+ "default",+ "project",+ AgentKind::AntigravityCli,+ )+ .unwrap();+ let parsed = reqwest::Url::parse(&url).unwrap();+ let query: std::collections::HashMap<_, _> = parsed.query_pairs().into_owned().collect();++ assert_eq!(parsed.path(), "/base/hook");+ assert_eq!(query.get("event").map(String::as_str), Some("session-end"));+ assert_eq!(+ query.get("agent").map(String::as_str),+ Some("antigravity-cli")+ );+ assert_eq!(query.get("workspace").map(String::as_str), Some("default"));+ assert_eq!(query.get("project").map(String::as_str), Some("project"));+ }}diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 5e960b08..90f16005 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -1608,9 +1608,16 @@ fn apply_to_antigravity_settings(ApplyOutcome::NoOp => "already up to date",});+ println!();+ print!("{ANTIGRAVITY_FINALIZATION_GUIDANCE}");Ok(())}+const ANTIGRAVITY_FINALIZATION_GUIDANCE: &str = "\+Antigravity `Stop` ends one execution loop, not the conversation. After the\n\+final turn, run `ai-memory finalize-session --agent antigravity-cli` to create\n\+the final summary and handoff and to queue opt-in SessionEnd consolidation.\n";+fn merge_antigravity_hooks(staged: &Path,server_url: &str,@@ -2920,6 +2927,10 @@ fn render_agent_output(out.push_str(&instruction);out.push('\n');}+ if label == "antigravity-cli" {+ out.push('\n');+ out.push_str(ANTIGRAVITY_FINALIZATION_GUIDANCE);+ }out}@@ -3997,6 +4008,26 @@ command = "AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/aassert!(!output.contains("AI_MEMORY_PROJECT_STRATEGY"));}+ #[test]+ fn antigravity_manual_render_explains_explicit_finalization() {+ let temp = TempDir::new().unwrap();+ stub_scripts(temp.path(), &["session-start.sh", "stop.sh"]);+ let output = render_agent_output(+ "antigravity-cli",+ temp.path(),+ "http://127.0.0.1:49374",+ None,+ None,+ &[&ANTIGRAVITY_LIFECYCLE_EVENTS],+ );++ assert!(output.contains("`Stop` ends one execution loop, not the conversation"));+ assert!(+ output.contains("ai-memory finalize-session --agent antigravity-cli"),+ "Antigravity install output must expose the supported finalizer: {output}"+ );+ }+#[test]fn manual_agent_render_uses_agent_profile_not_physical_bundle_listing() {let temp = TempDir::new().unwrap();diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 252ec194..8e02111f 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -82,8 +82,10 @@ from hook paths.converge. Existing ended sessions are baselined at migration instead ofbecoming historical catch-up work. Auto-commits the wiki. Clientswithout a reliable true session-end hook need an explicit ending action:- Codex provides `ai-memory finalize-session`, while Antigravity CLI should- call `memory_handoff_begin` before quitting when a handoff is needed.+ use `ai-memory finalize-session` for Codex, or+ `ai-memory finalize-session --agent antigravity-cli` for Antigravity CLI.+ The command selects the latest matching open session and enters the same+ canonical SessionEnd path as a native hook.4. When `AI_MEMORY_LLM_PROVIDER` is set, `memory_consolidate` rewritesthat summary into a richer durable page or fans out into amulti-page batch under `concepts/`, `decisions/`, `gotchas/`. Consolidationdiff --git a/docs/install.md b/docs/install.mdindex 627bbad6..21571522 100644--- a/docs/install.md+++ b/docs/install.md@@ -643,6 +643,16 @@ ai-memory finalize-session# add --all to close every matching open Codex session in this workspace/project```+Antigravity CLI also lacks a true session-end event. Its `Stop` hook marks the+end of one execution loop, so ai-memory intentionally records it without+closing the conversation. After the final turn, finalize the latest matching+Antigravity session explicitly:++```bash+ai-memory finalize-session --agent antigravity-cli+# add --all only to close every matching open Antigravity session in this scope+```+### Devin CLIDevin uses `~/.devin/config.json` for MCP servers and `~/.devin/hooks.v1.json`diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex 9cc1eb72..f8425d81 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -485,9 +485,18 @@ The rendered hooks config looks like:session start). ai-memory uses it as the closest equivalent to GeminiCLI's `SessionStart`; when a pending handoff exists, the hook injectsit via Antigravity's `injectSteps[].ephemeralMessage` output.-- Antigravity CLI does not expose a true session-end hook. `Stop` records- a stop observation only; call `memory_handoff_begin` before quitting when- you need the next agent to receive a handoff.+- Antigravity CLI does not expose a true session-end hook. `Stop` records a+ stop observation only because it marks the end of one execution loop, not+ the conversation. After the final turn, run+ `ai-memory finalize-session --agent antigravity-cli` to create the final+ summary and automatic handoff and to queue opt-in SessionEnd consolidation.+- A manual `memory_handoff_begin` call over Antigravity's static HTTP MCP+ connection cannot carry the hook's dynamic `conversationId`. The resulting+ project-wide handoff therefore has no `from_session_id` and uses+ `from_agent = other`; this is expected. The explicit finalizer selects the+ latest scoped Antigravity session instead. ai-memory does not guess session+ attribution for arbitrary MCP calls because concurrent conversations could+ be assigned to one another.- The built-in `/web` route displays compiled wiki pages, not raw session orobservation rows. To verify hook capture, compare the `sessions` and`observations` counts from `ai-memory status` before and after a prompt.@@ -885,7 +894,7 @@ that *starts* the next one - to play nicely with ai-memory:| Side | What's needed | Covered by ||---|---|---|-| **Ending side** | The agent must create a handoff, either through a true session-end hook, the supported Codex manual finalizer, or by calling `memory_handoff_begin`. | Built-in automatically for Claude Code, Devin CLI, Cursor, Gemini CLI, Grok Build CLI, Zero, Kimi Code, OpenClaw, OpenCode, and OMP. Codex has no reliable true session-end event, so run `ai-memory finalize-session` when you need the final summary/handoff/auto-improve eligibility. Antigravity CLI has no true session-end event in the current integration, so ask it to call `memory_handoff_begin` before quitting when you need a handoff. |+| **Ending side** | The agent must create a handoff through a true session-end hook, the manual finalizer, or `memory_handoff_begin`. | Built-in automatically for Claude Code, Devin CLI, Cursor, Gemini CLI, Grok Build CLI, Zero, Kimi Code, OpenClaw, OpenCode, and OMP. Codex and Antigravity CLI have no reliable true session-end event: run `ai-memory finalize-session` for Codex or `ai-memory finalize-session --agent antigravity-cli` for Antigravity after the final turn. || **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / Kimi Code / OpenClaw / OpenCode / OMP. It requires a client that consumes startup-hook stdout or an equivalent context-injection result. Grok and Zero are explicitly excluded because they discard SessionStart stdout; use (b). (b) works for any MCP-capable client if you nudge the model - see [the managed routing package](usage.md#install-the-routing-snippet-and-agent-skills). |OpenCode uses its official `session.deleted` plugin event for true session-end@@ -894,11 +903,13 @@ still-active sessions from `dispose` during normal plugin teardown; abruptprocess exits can still lose that fallback, so `session.deleted` remains theprimary close path.-Codex `Stop` is not a session end. The Codex hook install intentionally omits-`SessionEnd`; `ai-memory finalize-session` finds the latest open Codex session-for the current workspace/project and posts a synthetic `session-end` event-through the same server path as real hook clients. Use `--all` only when you-want to close every matching open Codex session in that scope.+Codex and Antigravity `Stop` events are not session ends. Their hook installs+intentionally omit `SessionEnd`; `ai-memory finalize-session` defaults to+Codex, while `--agent antigravity-cli` selects Antigravity. The command finds+the latest matching open session for the current workspace/project and posts a+synthetic `session-end` event through the same server path as real hook clients.+Use `--all` only when you want to close every matching open session for the+selected agent in that scope.So a typical mixed workflow looks like:diff --git a/docs/research-karpathy-llm-wiki.md b/docs/research-karpathy-llm-wiki.mdindex f754ca72..f78d396b 100644--- a/docs/research-karpathy-llm-wiki.md+++ b/docs/research-karpathy-llm-wiki.md@@ -76,7 +76,7 @@ Translating Karpathy faithfully - a "Karpathy-style" backend looks very differen- **Ingest must be a *write fan-out*, an insert.** A new observation should *touch ~10–15 existing pages* - updating an entity page, a concept page, a decisions log, a gotchas page. This is the single biggest deviation from vector RAG, which only ever appends.- **`index.md` and `log.md` as first-class files.** The log is the audit trail and the consolidation trigger source. Use the prefix convention (`## [YYYY-MM-DD] action | title`) so it's grep-able.- **Retrieval is hierarchical, nearest-neighbor.** Read `index.md` → narrow to candidate pages → read them → optionally fall back to hybrid search (BM25 + vector, RRF-fused) for novel queries. The index *is* the synthesis; the embeddings are a backstop.-- **Consolidation is an explicit, scheduled MCP operation**, not a side-effect. `memory_consolidate` is invoked on true session-end hooks where the client exposes them, on Codex's manual `ai-memory finalize-session` flow, on compaction events, or on a timer. It is LLM-driven (needs a provider key); if absent, it runs no-op as agentmemory does.+- **Consolidation is an explicit, scheduled MCP operation**, not a side-effect. `memory_consolidate` is invoked on true session-end hooks where the client exposes them, on the manual `ai-memory finalize-session` flow for clients such as Codex and Antigravity CLI, on compaction events, or on a timer. It is LLM-driven (needs a provider key); if absent, it runs no-op as agentmemory does.- **Cross-agent shared state.** Because the wiki is plain text, Claude Code, Codex, and OpenCode all read/write the *same* artifact. The MCP server is the gatekeeper; the markdown is the contract. No vendor lock.- **Coding-specific page types**: library gotchas, architectural decisions (ADR-style), failed approaches, repo conventions, environment quirks. Karpathy's example domains were personal/research; for coding agents the high-value pages are *failure modes* and *decisions*, because those are exactly what gets dropped on context compaction.