Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): harden Antigravity CLI support
AkitaOnRails4db48edacc56
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ffcc0246..aa0d3598 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -45,6 +45,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Google Gemini embeddings via `AI_MEMORY_EMBEDDING_PROVIDER=google` or`gemini`, with `gemini-embedding-001` as the default embedding model and`GEMINI_API_KEY` / `GOOGLE_API_KEY` support.+- Antigravity CLI (`agy`) support for MCP config (`serverUrl`) and lifecycle+ capture through its `PreInvocation`, `PreToolUse`, `PostToolUse`, and `Stop`+ hook events.- README support matrix for operating systems, agent integrations, LLMproviders, and embedding providers.diff --git a/README.md b/README.mdindex 97c3d6d9..96db6054 100644--- a/README.md+++ b/README.md@@ -30,7 +30,7 @@| Oh My Pi / OMP | Supported | `pi` / `omp` aliases for MCP config + TypeScript extension. || Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. || OpenClaw | Supported | MCP config + native plugin lifecycle hooks. |-| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks. |+| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). || LLM providers | Supported | Anthropic, OpenAI, Gemini, and OpenAI-compatible endpoints. || Embedding providers | Supported | OpenAI, Voyage, and Google Gemini. |@@ -73,7 +73,8 @@ priors are at the [bottom](#influences-and-prior-art).mode. Mounted on the same axum server as MCP.- **Multi-agent + multi-machine ready.** Supported clients: ClaudeCode, Codex, OpenCode, Cursor, Claude Desktop (via `mcp-remote`),- Gemini CLI, Antigravity CLI, OpenClaw, and Oh My Pi / OMP (`pi` / `omp` aliases).+ Gemini CLI, Antigravity CLI, OpenClaw, and Oh My Pi / OMP+ (`pi` / `omp` aliases).Server runs local (loopback) OR on a homelab box (LAN/VPN/cloud)with bearer-token auth.- **Thin-client CLI.** `ai-memory bootstrap`, `purge-project`,diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 7e9ba27b..e9c0a524 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -366,7 +366,8 @@ pub enum AgentChoice {/// session/tool/compaction hooks.Openclaw,/// Google Antigravity CLI (`agy`) — JSON-config hooks in- /// `~/.gemini/antigravity-cli/hooks.json`.+ /// `~/.gemini/config/hooks.json`.+ #[value(alias = "antigravity", alias = "agy")]AntigravityCli,}@@ -399,6 +400,7 @@ pub enum McpClient {#[value(alias = "omp", alias = "oh-my-pi")]Pi,/// Google Antigravity CLI (`agy`) — `~/.gemini/antigravity-cli/mcp_config.json`.+ #[value(alias = "antigravity", alias = "agy")]AntigravityCli,}@@ -688,4 +690,37 @@ mod tests {);}}++ #[test]+ fn antigravity_aliases_parse_to_same_variant() {+ for alias in ["antigravity-cli", "antigravity", "agy"] {+ let mcp_cli = Cli::try_parse_from([+ "ai-memory",+ "install-mcp",+ "--client",+ alias,+ "--server-url",+ "http://example.test:49374/mcp",+ ])+ .unwrap_or_else(|e| panic!("failed to parse install-mcp alias {alias}: {e}"));+ let Command::InstallMcp(mcp_args) = mcp_cli.command else {+ panic!("expected install-mcp command for alias {alias}");+ };+ assert!(matches!(mcp_args.client, McpClient::AntigravityCli));++ let hook_cli = Cli::try_parse_from([+ "ai-memory",+ "install-hooks",+ "--agent",+ alias,+ "--server-url",+ "http://example.test:49374",+ ])+ .unwrap_or_else(|e| panic!("failed to parse install-hooks alias {alias}: {e}"));+ let Command::InstallHooks(hook_args) = hook_cli.command else {+ panic!("expected install-hooks command for alias {alias}");+ };+ assert!(matches!(hook_args.agent, AgentChoice::AntigravityCli));+ }+ }}diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 93902ddf..7dabf8b8 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -403,7 +403,7 @@ fn merge_gemini_hooks(})}-/// Mutate `~/.gemini/antigravity-cli/hooks.json` so Antigravity CLI (`agy`)+/// Mutate `~/.gemini/config/hooks.json` so Antigravity CLI (`agy`)/// fires the ai-memory scripts on its lifecycle events.////// Antigravity CLI uses a named-groups format where hook groups are@@ -411,7 +411,7 @@ fn merge_gemini_hooks(/// events (`PreToolUse`, `PostToolUse`) use nested shape with matcher;/// lifecycle events (`PreInvocation`, `Stop`) use flat shape.///-/// Config file: `~/.gemini/antigravity-cli/hooks.json`+/// Config file: `~/.gemini/config/hooks.json`fn apply_to_antigravity_settings(hooks_dir: &Path,server_url: &str,@@ -421,9 +421,9 @@ fn apply_to_antigravity_settings(let path = match &args.config_file {Some(p) => p.clone(),None => dirs::home_dir()- .context("could not locate $HOME for ~/.gemini/antigravity-cli/hooks.json")?+ .context("could not locate $HOME for ~/.gemini/config/hooks.json")?.join(".gemini")- .join("antigravity-cli")+ .join("config").join("hooks.json"),};let staged = stage_hook_scripts(hooks_dir, "antigravity-cli")?;@@ -1907,9 +1907,9 @@ mod tests {hooks_tmp.path(),&["session-start.sh",- "session-end.sh","pre-tool-use.sh","post-tool-use.sh",+ "stop.sh",],);@@ -1963,9 +1963,9 @@ mod tests {hooks_tmp.path(),&["session-start.sh",- "session-end.sh","pre-tool-use.sh","post-tool-use.sh",+ "stop.sh",],);diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex f3add7c3..42dc3765 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -209,10 +209,8 @@ pub(crate) const ANTIGRAVITY_TOOL_EVENTS: [(&str, &str); 2] = [("PostToolUse", "post-tool-use.sh"),];-pub(crate) const ANTIGRAVITY_LIFECYCLE_EVENTS: [(&str, &str); 2] = [- ("PreInvocation", "session-start.sh"),- ("Stop", "session-end.sh"),-];+pub(crate) const ANTIGRAVITY_LIFECYCLE_EVENTS: [(&str, &str); 2] =+ [("PreInvocation", "session-start.sh"), ("Stop", "stop.sh")];/// Build the Antigravity CLI (`agy`) `hooks.json` payload.///@@ -769,6 +767,19 @@ mod tests {let cmd = handler.get("command").and_then(|c| c.as_str()).unwrap();assert!(cmd.contains("AI_MEMORY_AUTH_TOKEN=tok"));+ let stop = group+ .get("Stop")+ .and_then(|e| e.as_array())+ .expect("missing Stop");+ let stop_cmd = stop[0]+ .get("command")+ .and_then(|c| c.as_str())+ .expect("Stop command missing");+ assert!(+ stop_cmd.contains("stop.sh"),+ "Stop must record a stop observation, not synthesize session-end handoffs: {stop_cmd}"+ );+// All expected events presentfor expected in ["PreToolUse", "PostToolUse", "PreInvocation", "Stop"] {assert!(diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex d3801dcc..40e90deb 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -308,5 +308,8 @@ mod tests {serde_json::from_str::<AgentKind>("\"open-claw\"").unwrap(),AgentKind::OpenClaw);++ let antigravity = serde_json::to_string(&AgentKind::AntigravityCli).unwrap();+ assert_eq!(antigravity, "\"antigravity-cli\"");}}diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex 785f73bb..51d46ec1 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -149,26 +149,36 @@ impl HookEnvelope {let agent = query.agent.as_deref().map_or(AgentKind::Other, parse_agent);// OpenCode's plugin SDK sends `sessionID` (capital `ID`) on the// tool.execute.*/session.* events; Claude Code uses `session_id`,- // Codex `sessionId`. JSON keys are case-sensitive, so all three- // spellings must be listed or OpenCode tool events fail the- // "missing session_id" check in the router (issue #1).- let session_id = extract_string(&raw, &["session_id", "sessionId", "sessionID", "session"])- .or_else(|| {- extract_string_path(- &raw,- &[- &["info", "id"],- &["properties", "sessionID"],- &["properties", "info", "id"],- &["event", "properties", "sessionID"],- &["event", "properties", "info", "id"],- &["payload", "info", "id"],- &["payload", "properties", "sessionID"],- &["payload", "properties", "info", "id"],- ],- )- });+ // Codex `sessionId`, and Antigravity CLI uses `conversationId`.+ // JSON keys are case-sensitive, so all spellings must be listed+ // or tool events fail the router's "missing session_id" check.+ let session_id = extract_string(+ &raw,+ &[+ "session_id",+ "sessionId",+ "sessionID",+ "session",+ "conversationId",+ ],+ )+ .or_else(|| {+ extract_string_path(+ &raw,+ &[+ &["info", "id"],+ &["properties", "sessionID"],+ &["properties", "info", "id"],+ &["event", "properties", "sessionID"],+ &["event", "properties", "info", "id"],+ &["payload", "info", "id"],+ &["payload", "properties", "sessionID"],+ &["payload", "properties", "info", "id"],+ ],+ )+ });let body_cwd = extract_string(&raw, &["cwd", "current_dir", "working_dir", "directory"])+ .or_else(|| extract_first_string_array_item(&raw, &["workspacePaths"])).or_else(|| {extract_string_path(&raw,@@ -252,6 +262,44 @@ fn extract_string_path(value: &serde_json::Value, paths: &[&[&str]]) -> Option<SNone}+fn extract_scalar_string(value: &serde_json::Value, keys: &[&str]) -> Option<String> {+ for key in keys {+ for candidate in extraction_candidates(value) {+ if let Some(value) = candidate.get(*key) {+ if let Some(s) = value.as_str()+ && !s.is_empty()+ {+ return Some(s.to_string());+ }+ if let Some(n) = value.as_i64() {+ return Some(n.to_string());+ }+ if let Some(n) = value.as_u64() {+ return Some(n.to_string());+ }+ }+ }+ }+ None+}++fn extract_first_string_array_item(value: &serde_json::Value, keys: &[&str]) -> Option<String> {+ for key in keys {+ for candidate in extraction_candidates(value) {+ if let Some(items) = candidate.get(*key).and_then(serde_json::Value::as_array) {+ for item in items {+ if let Some(s) = item.as_str()+ && !s.is_empty()+ {+ return Some(s.to_string());+ }+ }+ }+ }+ }+ None+}+fn value_at_path<'a>(mut value: &'a serde_json::Value,path: &[&str],@@ -298,6 +346,10 @@ fn best_title_hint(event: HookEvent, raw: &serde_json::Value) -> Option<String>}HookEvent::PreToolUse | HookEvent::PostToolUse => {extract_string(raw, &["tool", "tool_name", "name"])+ .or_else(|| extract_string_path(raw, &[&["toolCall", "name"]]))+ .or_else(|| {+ extract_scalar_string(raw, &["stepIdx"]).map(|step| format!("step {step}"))+ })}HookEvent::Notification => extract_string(raw, &["message", "text"]),_ => None,@@ -329,8 +381,13 @@ fn best_body_excerpt(event: HookEvent, raw: &serde_json::Value) -> Option<Stringmatch event {HookEvent::UserPrompt => extract_string(raw, &["prompt", "message", "text"]),HookEvent::PostToolUse => {- let tool = extract_string(raw, &["tool", "tool_name", "name"])?;+ let tool = extract_string(raw, &["tool", "tool_name", "name"])+ .or_else(|| extract_string_path(raw, &[&["toolCall", "name"]]))+ .or_else(|| {+ extract_scalar_string(raw, &["stepIdx"]).map(|step| format!("step {step}"))+ })?;let result = extract_string(raw, &["tool_response", "tool_output", "output", "result"])+ .or_else(|| extract_string(raw, &["error"])).unwrap_or_else(|| "(no output captured)".into());Some(format!("tool: {tool}\n---\n{}", truncate_excerpt(&result)))}@@ -494,6 +551,59 @@ mod tests {assert_eq!(env.title_hint.as_deref(), Some("claude-sonnet-4-6"));}+ /// Antigravity CLI identifies the conversation as `conversationId`+ /// and reports cwd-like routing through `workspacePaths`.+ #[test]+ fn envelope_extracts_antigravity_conversation_and_workspace_path() {+ let q = HookQuery {+ event: "PreToolUse".into(),+ agent: Some("agy".into()),+ ..Default::default()+ };+ let raw = serde_json::json!({+ "conversationId": "ec33ebf9-0cba-4100-8142-c61503f6c587",+ "workspacePaths": ["/workspace/project", "/workspace/other"],+ "toolCall": {+ "name": "run_command",+ "args": {"CommandLine": "cargo test"}+ },+ "stepIdx": 3+ });+ let env = HookEnvelope::from_query_and_body(q, raw);++ assert_eq!(env.agent, AgentKind::AntigravityCli);+ assert_eq!(env.event, HookEvent::PreToolUse);+ assert_eq!(+ env.session_id.as_deref(),+ Some("ec33ebf9-0cba-4100-8142-c61503f6c587")+ );+ assert_eq!(env.cwd.as_deref(), Some("/workspace/project"));+ assert_eq!(env.title_hint.as_deref(), Some("run_command"));+ }++ #[test]+ fn envelope_uses_antigravity_step_idx_for_post_tool_title_fallback() {+ let q = HookQuery {+ event: "PostToolUse".into(),+ agent: Some("antigravity-cli".into()),+ ..Default::default()+ };+ let raw = serde_json::json!({+ "conversationId": "agy-conv",+ "workspacePaths": ["/workspace/project"],+ "stepIdx": 5,+ "error": "exit status 1"+ });+ let env = HookEnvelope::from_query_and_body(q, raw);++ assert_eq!(env.title_hint.as_deref(), Some("step 5"));+ assert!(+ env.body_excerpt+ .as_deref()+ .is_some_and(|body| body.contains("exit status 1"))+ );+ }+/// OpenCode's plugin SDK sends `sessionID` (capital `ID`) on the/// tool.execute.* / session.* events. Regression for issue #1: this/// spelling must be extracted, otherwise non-session-start events@@ -594,6 +704,9 @@ mod tests {assert_eq!(parse_agent("gemini"), AgentKind::GeminiCli);assert_eq!(parse_agent("claude-desktop"), AgentKind::ClaudeDesktop);assert_eq!(parse_agent("openclaw"), AgentKind::OpenClaw);+ assert_eq!(parse_agent("antigravity-cli"), AgentKind::AntigravityCli);+ assert_eq!(parse_agent("antigravity"), AgentKind::AntigravityCli);+ assert_eq!(parse_agent("agy"), AgentKind::AntigravityCli);assert_eq!(parse_agent("omp"), AgentKind::Omp);assert_eq!(parse_agent("pi"), AgentKind::Omp);assert_eq!(parse_agent("oh-my-pi"), AgentKind::Omp);diff --git a/crates/ai-memory-store/migrations/V11__sessions_antigravity_agent_kind.sql b/crates/ai-memory-store/migrations/V11__sessions_antigravity_agent_kind.sqlnew file mode 100644index 00000000..5c72cbd5--- /dev/null+++ b/crates/ai-memory-store/migrations/V11__sessions_antigravity_agent_kind.sql@@ -0,0 +1,30 @@+-- Expand sessions.agent_kind CHECK for Antigravity CLI (`agy`).+--+-- V09 intentionally enumerated every supported agent. Adding a concrete+-- AgentKind must update the persisted CHECK too, or Antigravity hook events+-- fail at begin_session on upgraded databases.++PRAGMA foreign_keys = OFF;++CREATE TABLE sessions_new (+ id BLOB PRIMARY KEY NOT NULL,+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,+ agent_kind TEXT NOT NULL CHECK (agent_kind IN ('claude-code','codex','open-code','cursor','gemini-cli','claude-desktop','openclaw','antigravity-cli','omp','other')),+ cwd TEXT,+ started_at INTEGER NOT NULL,+ ended_at INTEGER,+ summary_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL+);++INSERT INTO sessions_new SELECT * FROM sessions;++DROP TABLE sessions;++ALTER TABLE sessions_new RENAME TO sessions;++CREATE INDEX idx_sessions_recent ON sessions(workspace_id, project_id, started_at DESC);+CREATE INDEX idx_sessions_project ON sessions(project_id);+CREATE INDEX idx_sessions_started_at ON sessions(started_at DESC);++PRAGMA foreign_keys = ON;diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 7b21a80d..e2d0cf17 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -176,7 +176,7 @@ mod tests {}#[tokio::test]- async fn v09_session_agent_kind_migration_preserves_observations() {+ async fn session_agent_kind_migrations_preserve_observations() {let tmp = TempDir::new().unwrap();let db_dir = tmp.path().join("db");std::fs::create_dir_all(&db_dir).unwrap();@@ -225,7 +225,7 @@ mod tests {id: SessionId::new(),workspace_id: ws,project_id: proj,- agent_kind: AgentKind::Cursor,+ agent_kind: AgentKind::AntigravityCli,cwd: None,}).awaitdiff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 133b3d8b..02949c52 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -1053,6 +1053,7 @@ mod tests {AgentKind::GeminiCli,AgentKind::ClaudeDesktop,AgentKind::OpenClaw,+ AgentKind::AntigravityCli,AgentKind::Omp,AgentKind::Other,] {diff --git a/deny.toml b/deny.tomlindex b5a74f0f..32f3c6b0 100644--- a/deny.toml+++ b/deny.toml@@ -11,7 +11,13 @@ feature-depth = 1[advisories]version = 2-ignore = []+ignore = [+ # syntect transitively pulls these unmaintained crates. They are not+ # network-facing in ai-memory's usage and there is no safe upstream upgrade+ # path yet; keep cargo-deny useful for actionable advisories.+ "RUSTSEC-2025-0141", # bincode 1.3.3 unmaintained+ "RUSTSEC-2024-0320", # yaml-rust 0.4.5 unmaintained+][licenses]version = 2@@ -27,6 +33,7 @@ allow = ["Zlib","MPL-2.0","CC0-1.0",+ "CDLA-Permissive-2.0",]confidence-threshold = 0.9exceptions = []diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 8968b6b3..ffb9d79c 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -7,8 +7,8 @@## Purposeai-memory is a single Rust binary that gives AI coding agents (Claude-Code, OpenAI Codex, Cursor, Gemini CLI, OpenClaw, OpenCode, OMP, and-MCP-capable clients) long-term memory shared across CLIs.+Code, OpenAI Codex, Cursor, Gemini CLI, Antigravity CLI, OpenClaw,+OpenCode, OMP, and MCP-capable clients) long-term memory shared across CLIs.Quit one mid-task; open another in the same directory; continue. Nomanual `write_note` ceremony, no copy-pasting summaries betweensessions.@@ -26,6 +26,7 @@ markdown stays the source of truth.┌──────────────────────┐│ Claude Code / Codex ││ Cursor / Gemini CLI │+ │ Antigravity CLI ││ OpenClaw / OpenCode ││ OMP │└──────────┬───────────┘@@ -82,9 +83,12 @@ markdown stays the source of truth.untrusted text into the store), assigns an [`ObservationKind`], andenqueues a `WriteCmd` to the writer actor. `log.md` gets anappended `## [YYYY-MM-DDTHH:MM:SSZ] <event> | <title>` line.-3. On `SessionEnd`, the server synthesises a `sessions/<id>.md`- summary page (rule-based, no LLM) and opens a `Handoff` row for the- next agent. Auto-commits the wiki.+3. On true `SessionEnd` events, the server synthesises a+ `sessions/<id>.md` summary page (rule-based, no LLM) and opens a+ `Handoff` row for the next agent. Auto-commits the wiki. Clients+ without a true session-end hook (currently OpenCode and Antigravity+ CLI) should call `memory_handoff_begin` before quitting when a+ handoff is needed.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/`.diff --git a/docs/install.md b/docs/install.mdindex 17620842..567fdf17 100644--- a/docs/install.md+++ b/docs/install.md@@ -240,6 +240,14 @@ docker run --rm akitaonrails/ai-memory:latest \install-hooks --agent gemini-cli --auth-token "$TOKEN" \--server-url "http://homelab:49374"+docker run --rm akitaonrails/ai-memory:latest \+ install-mcp --client antigravity-cli --auth-token "$TOKEN" \+ --server-url "http://homelab:49374/mcp"++docker run --rm akitaonrails/ai-memory:latest \+ install-hooks --agent antigravity-cli --auth-token "$TOKEN" \+ --server-url "http://homelab:49374"+docker run --rm akitaonrails/ai-memory:latest \install-mcp --client openclaw --auth-token "$TOKEN" \--server-url "http://homelab:49374/mcp"@@ -253,7 +261,8 @@ Cursor, Gemini CLI, Antigravity CLI, and OpenClaw support both `install-mcp` and`install-hooks`. Claude Desktop is MCP-only here, so you'll need tonudge the model to call `memory_query` / `memory_handoff_accept` itself.For clients with `install-hooks` support, the capture path handles-handoff injection at session start.+handoff injection at session start or the client's closest equivalent+(Antigravity CLI uses `PreInvocation`).---diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex b4e8b10f..abbe3248 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -229,7 +229,7 @@ The rendered snippet writes to `mcp_config.json` under `mcpServers`:}```-**Config file (hooks):** `~/.gemini/antigravity-cli/hooks.json`+**Config file (hooks):** `~/.gemini/config/hooks.json`Antigravity CLI uses a named-groups hook format. Each top-level keyis a hook group name; inside, event arrays map to handlers. Tool@@ -277,7 +277,7 @@ The rendered hooks config looks like:"Stop": [{"type": "command",- "command": "AI_MEMORY_HOOK_URL=http://127.0.0.1:49374 /path/to/session-end.sh"+ "command": "AI_MEMORY_HOOK_URL=http://127.0.0.1:49374 /path/to/stop.sh"}]}@@ -289,8 +289,12 @@ The rendered hooks config looks like:or `httpUrl`. The `--apply` flag writes the correct key.- Hook scripts are staged under `~/.local/share/ai-memory/hooks/antigravity-cli/`.- The `PreInvocation` event fires before each model call (not just at- session start). This is the closest equivalent to Gemini CLI's- `SessionStart`.+ session start). ai-memory uses it as the closest equivalent to Gemini+ CLI's `SessionStart`; when a pending handoff exists, the hook injects+ it 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.- Source: <https://antigravity.google/docs/hooks>---@@ -429,7 +433,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 or by calling `memory_handoff_begin`. | Built-in for Claude Code, Codex, Cursor, Gemini CLI, Antigravity CLI, OpenClaw, and OMP. OpenCode has no true session-end event, so ask it to call `memory_handoff_begin` before quitting when you need a handoff. |+| **Ending side** | The agent must create a handoff, either through a true session-end hook or by calling `memory_handoff_begin`. | Built-in for Claude Code, Codex, Cursor, Gemini CLI, OpenClaw, and OMP. OpenCode and Antigravity CLI have no true session-end event, so ask them to call `memory_handoff_begin` before quitting when you need a handoff. || **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 / Cursor / Gemini CLI / Antigravity CLI / OpenClaw / OpenCode / OMP. (b) works for any MCP-capable client if you nudge the model - see [the routing snippet](usage.md#install-the-routing-snippet). |So a typical mixed workflow looks like:diff --git a/docs/usage.md b/docs/usage.mdindex 60a042d9..895cb9ff 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -61,7 +61,8 @@ Install ai-memory routing into this project.The agent calls `memory_install_self_routing`, receives the canonicalsnippet, and writes it to the right rules file (`CLAUDE.md` for Claude-Code, `AGENTS.md` for Codex / OpenCode / Cursor / Gemini CLI). The+Code, `AGENTS.md` for Codex / OpenCode / Cursor / Gemini CLI /+Antigravity CLI). Theblock is wrapped in `<!-- ai-memory:start -->` and`<!-- ai-memory:end -->`, so re-runs replace it in place.diff --git a/hooks/_lib.sh b/hooks/_lib.shindex d9654749..95612604 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -1,6 +1,6 @@# ai-memory hook helper — find marker file + parse minimal TOML.# Sourced by per-agent lifecycle hook scripts. POSIX shell only —-# no bash-isms, no external deps (no jq, no toml crate). Keep changes+# no bash-isms, no non-standard deps (no jq, no toml crate). Keep changes# byte-trivial because every supported agent (claude-code, codex,# cursor, gemini-cli, antigravity-cli, opencode, omp) sources this same file.@@ -36,16 +36,24 @@ ai_memory_parse_toml_key() {"$file" | head -n 1}-# Extract the first `cwd` from a JSON payload on stdin or in $1. Returns-# the value or nothing. This is intentionally a tiny shell fallback, not-# a JSON parser; taking the first match preserves the top-level cwd when-# tool payloads contain nested `cwd` fields later in the object.+# Extract the first cwd-like path from a JSON payload on stdin or in $1.+# Returns the value or nothing. This is intentionally a tiny shell fallback,+# not a JSON parser; taking the first match preserves the top-level cwd when+# tool payloads contain nested `cwd` fields later in the object. Antigravity+# CLI sends `workspacePaths: ["/repo", ...]` instead of `cwd`.ai_memory_extract_cwd() {payload="${1:-$(cat)}"rest=${payload#*\"cwd\"}+ if [ "$rest" != "$payload" ]; then+ printf '%s' "$rest" \+ | sed -n -E 's/^[[:space:]]*:[[:space:]]*"([^"]*)".*/\1/p' \+ | head -n 1+ return 0+ fi+ rest=${payload#*\"workspacePaths\"}[ "$rest" = "$payload" ] && return 0printf '%s' "$rest" \- | sed -n -E 's/^[[:space:]]*:[[:space:]]*"([^"]*)".*/\1/p' \+ | sed -n -E 's/^[[:space:]]*:[[:space:]]*\[[[:space:]]*"([^"]*)".*/\1/p' \| head -n 1}@@ -106,3 +114,19 @@ ai_memory_get_handoff() {curl -s --max-time 1.0 "$1"fi}++# Encode stdin as a JSON string. Used only by Antigravity's PreInvocation+# hook, whose stdout contract is JSON rather than raw context text.+ai_memory_json_string() {+ awk '+ BEGIN { printf "\"" }+ {+ gsub(/\\/, "\\\\")+ gsub(/"/, "\\\"")+ gsub(/\r/, "\\r")+ printf "%s%s", sep, $0+ sep = "\\n"+ }+ END { printf "\"" }+ '+}diff --git a/hooks/antigravity-cli/post-tool-use.ps1 b/hooks/antigravity-cli/post-tool-use.ps1index 1d615041..743f307b 100644--- a/hooks/antigravity-cli/post-tool-use.ps1+++ b/hooks/antigravity-cli/post-tool-use.ps1@@ -1,3 +1,4 @@. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"Invoke-AiMemoryHook -Event "post-tool-use" -Agent "antigravity-cli"+[Console]::Out.WriteLine("{}")exit 0diff --git a/hooks/antigravity-cli/post-tool-use.sh b/hooks/antigravity-cli/post-tool-use.shindex 1b9bdf98..115fba25 100755--- a/hooks/antigravity-cli/post-tool-use.sh+++ b/hooks/antigravity-cli/post-tool-use.sh@@ -12,4 +12,5 @@ QS=$(ai_memory_marker_qs "$CWD")printf '%s' "$PAYLOAD" \| ai_memory_post_hook "$SERVER/hook?event=post-tool-use&agent=antigravity-cli${QS}" >/dev/null 2>&1 || true+printf '{}\n'exit 0diff --git a/hooks/antigravity-cli/pre-compact.ps1 b/hooks/antigravity-cli/pre-compact.ps1deleted file mode 100644index 35a9f03f..00000000--- a/hooks/antigravity-cli/pre-compact.ps1+++ /dev/null@@ -1,3 +0,0 @@-. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"-Invoke-AiMemoryHook -Event "pre-compact" -Agent "antigravity-cli"-exit 0diff --git a/hooks/antigravity-cli/pre-compact.sh b/hooks/antigravity-cli/pre-compact.shdeleted file mode 100755index b874cb79..00000000--- a/hooks/antigravity-cli/pre-compact.sh+++ /dev/null@@ -1,15 +0,0 @@-#!/bin/sh-# antigravity-cli pre-compact hook.-# Forwards the event JSON to the ai-memory server, fire-and-forget.-_lib_dir="$(dirname "$0")"-[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."-. "$_lib_dir/_lib.sh"--SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-PAYLOAD=$(cat)-CWD=$(ai_memory_extract_cwd "$PAYLOAD")-QS=$(ai_memory_marker_qs "$CWD")--printf '%s' "$PAYLOAD" \- | ai_memory_post_hook "$SERVER/hook?event=pre-compact&agent=antigravity-cli${QS}" >/dev/null 2>&1 || true-exit 0diff --git a/hooks/antigravity-cli/pre-tool-use.ps1 b/hooks/antigravity-cli/pre-tool-use.ps1index 3b979396..8da2d7f1 100644--- a/hooks/antigravity-cli/pre-tool-use.ps1+++ b/hooks/antigravity-cli/pre-tool-use.ps1@@ -1,3 +1,4 @@. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"Invoke-AiMemoryHook -Event "pre-tool-use" -Agent "antigravity-cli"+[Console]::Out.WriteLine("{}")exit 0diff --git a/hooks/antigravity-cli/pre-tool-use.sh b/hooks/antigravity-cli/pre-tool-use.shindex e436ed80..f6a42335 100755--- a/hooks/antigravity-cli/pre-tool-use.sh+++ b/hooks/antigravity-cli/pre-tool-use.sh@@ -12,4 +12,5 @@ QS=$(ai_memory_marker_qs "$CWD")printf '%s' "$PAYLOAD" \| ai_memory_post_hook "$SERVER/hook?event=pre-tool-use&agent=antigravity-cli${QS}" >/dev/null 2>&1 || true+printf '{}\n'exit 0diff --git a/hooks/antigravity-cli/session-end.ps1 b/hooks/antigravity-cli/session-end.ps1deleted file mode 100644index d0fe1dc7..00000000--- a/hooks/antigravity-cli/session-end.ps1+++ /dev/null@@ -1,3 +0,0 @@-. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"-Invoke-AiMemoryHook -Event "session-end" -Agent "antigravity-cli"-exit 0diff --git a/hooks/antigravity-cli/session-end.sh b/hooks/antigravity-cli/session-end.shdeleted file mode 100755index 1331ecfc..00000000--- a/hooks/antigravity-cli/session-end.sh+++ /dev/null@@ -1,15 +0,0 @@-#!/bin/sh-# antigravity-cli session-end hook.-# Forwards the event JSON to the ai-memory server, fire-and-forget.-_lib_dir="$(dirname "$0")"-[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."-. "$_lib_dir/_lib.sh"--SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-PAYLOAD=$(cat)-CWD=$(ai_memory_extract_cwd "$PAYLOAD")-QS=$(ai_memory_marker_qs "$CWD")--printf '%s' "$PAYLOAD" \- | ai_memory_post_hook "$SERVER/hook?event=session-end&agent=antigravity-cli${QS}" >/dev/null 2>&1 || true-exit 0diff --git a/hooks/antigravity-cli/session-start.ps1 b/hooks/antigravity-cli/session-start.ps1index 9b8abe45..b659c880 100644--- a/hooks/antigravity-cli/session-start.ps1+++ b/hooks/antigravity-cli/session-start.ps1@@ -1,3 +1,3 @@. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"-Invoke-AiMemoryHook -Event "session-start" -Agent "antigravity-cli" -FetchHandoff+Invoke-AiMemoryHook -Event "session-start" -Agent "antigravity-cli" -FetchHandoff -AntigravityPreInvocationOutputexit 0diff --git a/hooks/antigravity-cli/session-start.sh b/hooks/antigravity-cli/session-start.shindex fd28a687..4e8c817a 100755--- a/hooks/antigravity-cli/session-start.sh+++ b/hooks/antigravity-cli/session-start.sh@@ -1,11 +1,7 @@#!/bin/sh-# antigravity-cli SessionStart hook.-# 1. Forwards the event JSON to the ai-memory server (fire-and-forget).-# 2. Synchronously fetches any pending cross-agent handoff and prints-# it to stdout — agent CLIs prepend session-start hook stdout to-# the next session, so the resuming agent sees prior context with-# no human in the loop.-#+# antigravity-cli PreInvocation hook. Forwards the event JSON to the+# ai-memory server, then injects any pending handoff as an ephemeral+# model-visible message using Antigravity's JSON stdout contract._lib_dir="$(dirname "$0")"[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/..". "$_lib_dir/_lib.sh"@@ -17,5 +13,12 @@ QS=$(ai_memory_marker_qs "$CWD")printf '%s' "$PAYLOAD" \| ai_memory_post_hook "$SERVER/hook?event=session-start&agent=antigravity-cli${QS}" >/dev/null 2>&1 || true-ai_memory_get_handoff "$SERVER/handoff?agent=antigravity-cli${QS}" 2>/dev/null || true+HANDOFF=$(ai_memory_get_handoff "$SERVER/handoff?agent=antigravity-cli${QS}" 2>/dev/null || true)+if [ -n "$HANDOFF" ]; then+ printf '{"injectSteps":[{"ephemeralMessage":'+ printf '%s' "$HANDOFF" | ai_memory_json_string+ printf '}]}\n'+else+ printf '{}\n'+fiexit 0diff --git a/hooks/antigravity-cli/stop.ps1 b/hooks/antigravity-cli/stop.ps1index 4a0d6563..cf44daea 100644--- a/hooks/antigravity-cli/stop.ps1+++ b/hooks/antigravity-cli/stop.ps1@@ -1,3 +1,4 @@. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"Invoke-AiMemoryHook -Event "stop" -Agent "antigravity-cli"+[Console]::Out.WriteLine('{"decision":""}')exit 0diff --git a/hooks/antigravity-cli/stop.sh b/hooks/antigravity-cli/stop.shindex 2a4be75c..540299fc 100755--- a/hooks/antigravity-cli/stop.sh+++ b/hooks/antigravity-cli/stop.sh@@ -12,4 +12,5 @@ QS=$(ai_memory_marker_qs "$CWD")printf '%s' "$PAYLOAD" \| ai_memory_post_hook "$SERVER/hook?event=stop&agent=antigravity-cli${QS}" >/dev/null 2>&1 || true+printf '{"decision":""}\n'exit 0diff --git a/hooks/antigravity-cli/user-prompt-submit.ps1 b/hooks/antigravity-cli/user-prompt-submit.ps1deleted file mode 100644index 59246ce7..00000000--- a/hooks/antigravity-cli/user-prompt-submit.ps1+++ /dev/null@@ -1,3 +0,0 @@-. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"-Invoke-AiMemoryHook -Event "user-prompt" -Agent "antigravity-cli"-exit 0diff --git a/hooks/antigravity-cli/user-prompt-submit.sh b/hooks/antigravity-cli/user-prompt-submit.shdeleted file mode 100755index 09385fd2..00000000--- a/hooks/antigravity-cli/user-prompt-submit.sh+++ /dev/null@@ -1,15 +0,0 @@-#!/bin/sh-# antigravity-cli user-prompt hook.-# Forwards the event JSON to the ai-memory server, fire-and-forget.-_lib_dir="$(dirname "$0")"-[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."-. "$_lib_dir/_lib.sh"--SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"-PAYLOAD=$(cat)-CWD=$(ai_memory_extract_cwd "$PAYLOAD")-QS=$(ai_memory_marker_qs "$CWD")--printf '%s' "$PAYLOAD" \- | ai_memory_post_hook "$SERVER/hook?event=user-prompt&agent=antigravity-cli${QS}" >/dev/null 2>&1 || true-exit 0diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index 81241f5d..67a3ada6 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -3,6 +3,8 @@ function Get-AiMemoryCwd {if (-not $Payload) { return $null }$match = [regex]::Match($Payload, '"cwd"\s*:\s*"([^"]*)"')if ($match.Success) { return $match.Groups[1].Value }+ $workspaceMatch = [regex]::Match($Payload, '"workspacePaths"\s*:\s*\[\s*"([^"]*)"')+ if ($workspaceMatch.Success) { return $workspaceMatch.Groups[1].Value }return $null}@@ -48,7 +50,8 @@ function Invoke-AiMemoryHook {param([Parameter(Mandatory = $true)] [string] $Event,[Parameter(Mandatory = $true)] [string] $Agent,- [switch] $FetchHandoff+ [switch] $FetchHandoff,+ [switch] $AntigravityPreInvocationOutput)$Server = if ($env:AI_MEMORY_HOOK_URL) { $env:AI_MEMORY_HOOK_URL } else { "http://127.0.0.1:49374" }@@ -80,10 +83,24 @@ function Invoke-AiMemoryHook {-TimeoutSec 1 `-Uri "$Server/handoff?agent=$Agent$QS" `-Headers $Headers- if ($null -ne $Response -and $null -ne $Response.Content) {- [Console]::Out.Write($Response.Content)+ if ($null -ne $Response -and $Response.Content) {+ if ($AntigravityPreInvocationOutput) {+ $Payload = @{+ injectSteps = @(@{ ephemeralMessage = $Response.Content })+ }+ [Console]::Out.Write(($Payload | ConvertTo-Json -Depth 5 -Compress))+ } else {+ [Console]::Out.Write($Response.Content)+ }+ } elseif ($AntigravityPreInvocationOutput) {+ [Console]::Out.Write("{}")}} catch {+ if ($AntigravityPreInvocationOutput) {+ [Console]::Out.Write("{}")+ }}+ } elseif ($AntigravityPreInvocationOutput) {+ [Console]::Out.Write("{}")}}diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.shindex 09da2891..bdf4ef4a 100755--- a/tests/hooks/test_lib.sh+++ b/tests/hooks/test_lib.sh@@ -3,7 +3,7 @@## sh tests/hooks/test_lib.sh#-# Exits non-zero on any failure. POSIX shell + sed only, so no extra+# Exits non-zero on any failure. POSIX shell + sed/awk only, so no extra# CI setup needed.set -eu@@ -58,6 +58,14 @@ assert_eq "extract cwd from payload" "/home/u/foo" "$(ai_memory_extract_cwdassert_eq "extract cwd from empty json" "" "$(ai_memory_extract_cwd '{}')"PAYLOAD_NESTED='{"session_id":"x","cwd":"/home/u/root","tool_input":{"cwd":"/tmp/nested"}}'assert_eq "extract cwd prefers first match" "/home/u/root" "$(ai_memory_extract_cwd "$PAYLOAD_NESTED")"+PAYLOAD_AGY='{"conversationId":"x","workspacePaths":["/home/u/agy","/tmp/other"]}'+assert_eq "extract cwd from antigravity workspacePaths" "/home/u/agy" "$(ai_memory_extract_cwd "$PAYLOAD_AGY")"++# --- json_string -------------------------------------------------------+JSON_INPUT='quoted "thing" \ path+next line'+assert_eq "json_string escapes text" '"quoted \"thing\" \\ path\nnext line"' \+ "$(printf '%s' "$JSON_INPUT" | ai_memory_json_string)"# --- marker_qs --------------------------------------------------------QS=$(ai_memory_marker_qs "$TMP/a/b/c")