Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): start an Antigravity session once per conversation, not per turn
Gabriel Alencarec89e6a8dc7d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b43a8edc..51574268 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Fixed+- Fixed Antigravity CLI posting a session start and claiming a handoff on every+ user turn: `invocationNum` restarts at 0 each turn, so only the first turn of+ a conversation (keyed by `conversationId`) now maps to SessionStart, in the+ native, shell and PowerShell hooks. Payloads without a `conversationId` keep+ the previous per-turn behavior.- Fixed Cursor tool calls being stored with no title or content: Cursor's ownhooks, and the Claude Code hooks Cursor also runs, send Claude's`tool_name`/`tool_input` fields, but Cursor was missing from the tool-capturediff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex ed2228c2..51a47e94 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -452,6 +452,29 @@ fn should_process_hook_event(agent: AgentKind, event: HookEvent, raw: &serde_jsotrue}+/// `<data_dir>/briefed/agy-start-<conversationId>` for an Antigravity+/// SessionStart that names its conversation; `None` for every other event.+fn antigravity_conversation_start_marker(+ data_dir: &Path,+ agent: AgentKind,+ event: HookEvent,+ raw: &serde_json::Value,+) -> Option<PathBuf> {+ if agent != AgentKind::AntigravityCli || event != HookEvent::SessionStart {+ return None;+ }+ let conversation = raw+ .get("conversationId")+ .and_then(serde_json::Value::as_str)+ .map(str::trim)+ .filter(|id| !id.is_empty())?;+ Some(+ data_dir+ .join("briefed")+ .join(format!("agy-start-{}", sanitize_briefed_key(conversation))),+ )+}+/// A `--agent claude-code` hook invoked by Cursor (it runs Claude Code's/// settings too) is a duplicate when Cursor's own ai-memory hooks are also/// installed: the native `--agent cursor` hook already delivers the same@@ -654,6 +677,23 @@ wherewrite_success_response(stdout, agent_kind, hook_event)?;return Ok(());}+ // `invocationNum` restarts at 0 on every user turn, so invocation zero+ // marks a turn, not a conversation. Only the first turn of a conversation+ // may post session-start and claim a handoff.+ if !args.check_capture+ && let Some(marker) = antigravity_conversation_start_marker(+ &resolve_data_dir_with(data_dir.as_deref(), &runtime_env),+ agent_kind,+ hook_event,+ &json,+ )+ {+ if marker.exists() {+ write_success_response(stdout, agent_kind, hook_event)?;+ return Ok(());+ }+ mark_briefed(&marker);+ }// Assistant/Stop capture (#196). On an opted-in install// (`install-hooks --capture-assistant`), extract the assistant message,// sanitize + cap it, and splice the versioned `_ai_memory_assistant` marker@@ -3388,6 +3428,86 @@ mod tests {);}+ #[tokio::test]+ async fn antigravity_second_turn_of_a_conversation_does_not_restart_the_session() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let payload = serde_json::json!({+ "invocationNum": 0,+ "conversationId": "agy-conversation",+ "workspacePaths": [tmp.path()]+ })+ .to_string();+ let (base, _first) = serve_requests("200 OK", "AGY-HANDOFF").await;+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ antigravity_hook_args("session-start", &base),+ payload.clone(),+ &mut stdout,+ |_, _| Ok(()),+ )+ .await+ .unwrap();++ let (base, mut requests) = serve_requests("200 OK", "MUST-NOT-BE-CONSUMED").await;+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ antigravity_hook_args("session-start", &base),+ payload,+ &mut stdout,+ |_, _| Err(std::io::Error::other("must not spawn")),+ )+ .await+ .unwrap();++ assert_eq!(stdout, b"{}\n");+ assert!(first_request(&mut requests).await.is_none());+ }++ #[test]+ fn antigravity_conversation_marker_only_for_named_antigravity_starts() {+ let dir = Path::new("/d");+ let raw = serde_json::json!({"conversationId": "a/b"});+ assert_eq!(+ antigravity_conversation_start_marker(+ dir,+ AgentKind::AntigravityCli,+ HookEvent::SessionStart,+ &raw+ ),+ Some(dir.join("briefed").join("agy-start-a_b"))+ );+ assert!(+ antigravity_conversation_start_marker(+ dir,+ AgentKind::AntigravityCli,+ HookEvent::SessionStart,+ &serde_json::json!({})+ )+ .is_none()+ );+ assert!(+ antigravity_conversation_start_marker(+ dir,+ AgentKind::AntigravityCli,+ HookEvent::PostToolUse,+ &raw+ )+ .is_none()+ );+ assert!(+ antigravity_conversation_start_marker(+ dir,+ AgentKind::ClaudeCode,+ HookEvent::SessionStart,+ &raw+ )+ .is_none()+ );+ }+#[tokio::test]async fn antigravity_later_invocation_has_no_capture_or_handoff_side_effects() {let tmp = tempfile::tempdir().unwrap();diff --git a/docs/desktop/plan.md b/docs/desktop/plan.mdindex 7d11a61e..83d8abed 100644--- a/docs/desktop/plan.md+++ b/docs/desktop/plan.md@@ -115,8 +115,10 @@ The research's best new target — not the RFC's `.mcpb`:5. Tray stack choice + Flatpak feasibility (Phase 4).6. Does the Claude Desktop Chat tab ever gain a local store/export? (Nocurrent path; re-check quarterly.)-7. Antigravity's SessionStart mapping fires on every user turn- (`invocationNum` restarts per turn): keep, or gate per conversation?+7. Antigravity's SessionStart mapping fired on every user turn+ (`invocationNum` restarts per turn): resolved — gated per conversation by+ a `briefed/agy-start-<conversationId>` marker in the native, shell and+ PowerShell hooks.8. Cowork capture on Linux, where tasks run in a VM.9. Cursor runs the operator's Claude Code hooks by default, so a Cursorsession reaches ai-memory twice when Cursor's own hooks are installeddiff --git a/docs/support-matrix.md b/docs/support-matrix.mdindex 515354c5..1027b77e 100644--- a/docs/support-matrix.md+++ b/docs/support-matrix.md@@ -27,7 +27,7 @@| Claude Desktop (Chat) | MCP-only | Uses `mcp-remote`; the ordinary Chat surface does not run lifecycle hooks. macOS, Windows, and Linux (Anthropic's Debian/Ubuntu beta, `~/.config/Claude/claude_desktop_config.json`). Cowork capture is not claimed; see the explicit boundary in [`mcp-install.md`](mcp-install.md#claude-desktop). || Claude Desktop (Code tab) | Supported | Local Code-tab sessions run Claude Code with the user's `~/.claude/settings.json`, so the Claude Code hooks capture them as `claude-code`; a session without a project folder lands in its own scratch-directory project. || 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; 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`; its conversation store is not decoded, so the ledger takes user prompts from `agy`'s `history.jsonl` (only this conversation's lines typed in this checkout) and assistant and tool steps from hook capture. Tool outputs (`run_command`, `view_file`, `list_dir`, etc.) are resolved directly from `.system_generated/steps/<stepIdx>/output.txt` during `post-tool-use` while mutation tools preserve code from arguments (#966). |+| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). Only `PreInvocation` with `invocationNum = 0` on the first turn of a conversation maps to SessionStart (the counter restarts every turn, so later turns and 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`; its conversation store is not decoded, so the ledger takes user prompts from `agy`'s `history.jsonl` (only this conversation's lines typed in this checkout) and assistant and tool steps from hook capture. Tool outputs (`run_command`, `view_file`, `list_dir`, etc.) are resolved directly from `.system_generated/steps/<stepIdx>/output.txt` during `post-tool-use` while mutation tools preserve code from arguments (#966). || 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`. |diff --git a/hooks/antigravity-cli/session-start.sh b/hooks/antigravity-cli/session-start.shindex 7792c7e1..45771e1b 100755--- a/hooks/antigravity-cli/session-start.sh+++ b/hooks/antigravity-cli/session-start.sh@@ -17,6 +17,16 @@ QS=$(ai_memory_marker_qs "$CWD")# The `[briefing]` opt-in rides the handoff GET, as in the native hook.BRIEF_QS=$(ai_memory_briefing_qs "$CWD")SESSION_ID=$(ai_memory_extract_session_id "$PAYLOAD")+# invocationNum restarts at 0 on every user turn: only a conversation's first+# turn may post session-start and claim a handoff.+if [ -n "$SESSION_ID" ]; then+ START_MARKER=$(ai_memory_briefed_file "agy-start-$SESSION_ID")+ if [ -e "$START_MARKER" ]; then+ printf '{}\n'+ exit 0+ fi+ ai_memory_mark_briefed "$START_MARKER"+fiSESSION_QS=""if [ -n "$SESSION_ID" ]; thenSESSION_QS="&session_id=$(ai_memory_url_encode "$SESSION_ID")"diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index aa1af94f..2987251e 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -990,6 +990,20 @@ function Invoke-AiMemoryHook {[Console]::Out.Write("{}")return}+ # invocationNum restarts at 0 on every user turn: only a conversation's+ # first turn may post session-start and claim a handoff.+ if ($AntigravityPreInvocationOutput) {+ $Conversation = $null+ try { $Conversation = [string](($Payload | ConvertFrom-Json).conversationId) } catch { }+ if ($Conversation -and $Conversation.Trim()) {+ $StartMarker = Get-AiMemoryBriefedFile -Key ("agy-start-" + $Conversation.Trim())+ if (Test-Path -LiteralPath $StartMarker) {+ [Console]::Out.Write("{}")+ return+ }+ Set-AiMemoryBriefed -Path $StartMarker+ }+ }# Assistant/Stop capture (#196) is native-only. Scoped to claude-code + stop# so a PostToolUse whose tool output legitimately contains the literal string# is unaffected. If a Stop payload still carries the raw field, drop the wholediff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.shindex 75e26d40..60e18201 100755--- a/tests/hooks/test_lib.sh+++ b/tests/hooks/test_lib.sh@@ -1081,6 +1081,21 @@ assert_eq "powershell session-start handoff GET carries the briefing keys" "ok"assert_eq "no fixture event was spooled into the caller's data dir" "" \"$(grep -rlF -e "$TMP" -e '{"url":"http://memory.test' "$CALLER_SPOOL" 2>/dev/null | head -n 1)"+# Antigravity: invocationNum restarts per turn, so the first turn of a+# conversation records a start marker and the next turn exits before any+# request. A closed port proves no request is attempted on the second turn.+AGY_DATA="$TMP/agy-gate"+AGY_TURN='{"invocationNum":0,"conversationId":"agy/conv-1","workspacePaths":["/tmp"]}'+printf '%s' "$AGY_TURN" | AI_MEMORY_DATA_DIR="$AGY_DATA" AI_MEMORY_HOOK_URL="http://127.0.0.1:9" \+ sh hooks/antigravity-cli/session-start.sh >/dev/null 2>&1+assert_eq "antigravity first turn records the conversation start marker" "yes" \+ "$([ -e "$AGY_DATA/briefed/agy-start-agy_conv-1" ] && printf yes || printf no)"+assert_eq "antigravity later turn of the same conversation prints an empty reply" "{}" \+ "$(printf '%s' "$AGY_TURN" | AI_MEMORY_DATA_DIR="$AGY_DATA" AI_MEMORY_HOOK_URL="http://127.0.0.1:9" \+ sh -x hooks/antigravity-cli/session-start.sh 2>"$TMP/agy-trace")"+assert_eq "antigravity later turn sends no request" "" \+ "$(grep -E 'ai_memory_(post_hook|get_handoff)' "$TMP/agy-trace" | head -n 1)"+# --- summary ----------------------------------------------------------printf '\n%d passed, %d failed\n' "$PASS" "$FAIL"[ "$FAIL" -eq 0 ]