Skip to content

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

Rust

fix(hooks): gate Antigravity startup handoff (#298)

AkitaOnRailsc1c1e6818601
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 66a497ac..00fa8779 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Fixed
+- Antigravity CLI's `PreInvocation` hook now maps only its documented
+ `invocationNum = 0` call to ai-memory's synthetic `SessionStart`. Later model
+ invocations perform no capture or destructive handoff fetch, so a manual
+ handoff created while the conversation winds down remains open for the next
+ session. Native Windows hooks also emit Antigravity's required `injectSteps`
+ envelope instead of Claude Code's `hookSpecificOutput` shape. (#298)
- Automatic handoff selection now prefers the newest cwd-eligible session over
a stale, more-specific ancestor. A new automatic handoff expires prior open
automatic handoffs from the exact cwd, and accepting the winner atomically
diff --git a/README.md b/README.md
index 4c2dbc69..d34bbecb 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). 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. |
+| 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. |
| 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. |
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index ba235274..360de879 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -360,6 +360,30 @@ fn parse_minutes(raw: Option<String>, default: Duration) -> Duration {
}
}
+fn should_process_hook_event(agent: AgentKind, event: HookEvent, raw: &serde_json::Value) -> bool {
+ if agent == AgentKind::AntigravityCli && event == HookEvent::SessionStart {
+ return raw.get("invocationNum").and_then(serde_json::Value::as_u64) == Some(0);
+ }
+ true
+}
+
+fn session_start_handoff_envelope(agent: AgentKind, handoff: String) -> serde_json::Value {
+ if agent == AgentKind::AntigravityCli {
+ serde_json::json!({
+ "injectSteps": [{
+ "ephemeralMessage": handoff,
+ }]
+ })
+ } else {
+ serde_json::json!({
+ "hookSpecificOutput": {
+ "hookEventName": "SessionStart",
+ "additionalContext": handoff,
+ }
+ })
+ }
+}
+
/// Run a single hook end-to-end. Always returns Ok and always writes a JSON
/// object to stdout — a hook must never fail the agent.
///
@@ -400,6 +424,16 @@ where
return Ok(());
}
};
+ let agent_kind = AgentKind::from_wire(&args.agent);
+ let hook_event = HookEvent::parse(&args.event);
+ // Antigravity exposes PreInvocation rather than a true SessionStart. It
+ // fires before every model call; invocation zero is the only startup
+ // boundary. Fail closed when the documented counter is absent so a later
+ // invocation can never consume a handoff intended for the next session.
+ if !should_process_hook_event(agent_kind, hook_event, &json) {
+ writeln!(stdout, "{{}}")?;
+ return Ok(());
+ }
// 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
@@ -408,11 +442,7 @@ where
// Reserialize only when the JSON actually changed, so unrelated events keep
// byte-exact spool bodies (see `native_hook_accepts_plain_and_bom_prefixed_json`).
let capture_assistant = if args.capture_assistant {
- let transform = ai_memory_hooks::transform_for_client(
- &mut json,
- AgentKind::from_wire(&args.agent),
- ai_memory_hooks::HookEvent::parse(&args.event),
- );
+ let transform = ai_memory_hooks::transform_for_client(&mut json, agent_kind, hook_event);
if transform.changed {
payload = serde_json::to_string(&json)?;
}
@@ -423,10 +453,7 @@ where
}
false
};
- if ai_memory_hooks::cap_lifecycle_body_for_client(
- &mut json,
- ai_memory_hooks::HookEvent::parse(&args.event),
- ) {
+ if ai_memory_hooks::cap_lifecycle_body_for_client(&mut json, hook_event) {
payload = serde_json::to_string(&json)?;
}
let (policy_cwd, canonical_session_id) = hook_context(&args.agent, &json);
@@ -571,7 +598,7 @@ where
// consume the handoff server-side (the GET is destructive) and then
// discard the result — silently losing it. Those agents recover the
// handoff on demand via the MCP `memory_handoff_accept` tool.
- if AgentKind::from_wire(&args.agent).session_start_injects_handoff() {
+ if agent_kind.session_start_injects_handoff() {
let client = build_client();
let bearer = hook_spool::resolve_bearer(&client, &dd, args.auth_token.as_deref()).await;
let native_session_qs = canonical_session_id
@@ -586,12 +613,7 @@ where
if let Some(handoff) =
get_handoff(&client, &handoff_url, bearer.as_deref(), handoff_timeout()).await
{
- let envelope = serde_json::json!({
- "hookSpecificOutput": {
- "hookEventName": "SessionStart",
- "additionalContext": handoff,
- }
- });
+ let envelope = session_start_handoff_envelope(agent_kind, handoff);
writeln!(stdout, "{envelope}")?;
return Ok(());
}
@@ -830,6 +852,33 @@ mod tests {
assert!(!should_spawn_background_drainer("user-prompt"));
}
+ #[test]
+ fn antigravity_preinvocation_only_maps_invocation_zero_to_session_start() {
+ for (raw, expected) in [
+ (serde_json::json!({"invocationNum": 0}), true),
+ (serde_json::json!({"invocationNum": 1}), false),
+ (serde_json::json!({"invocationNum": 0.5}), false),
+ (serde_json::json!({"invocationNum": "0"}), false),
+ (serde_json::json!({}), false),
+ ] {
+ assert_eq!(
+ should_process_hook_event(AgentKind::AntigravityCli, HookEvent::SessionStart, &raw,),
+ expected,
+ "{raw}"
+ );
+ }
+ assert!(should_process_hook_event(
+ AgentKind::ClaudeCode,
+ HookEvent::SessionStart,
+ &serde_json::json!({})
+ ));
+ assert!(should_process_hook_event(
+ AgentKind::AntigravityCli,
+ HookEvent::PostToolUse,
+ &serde_json::json!({})
+ ));
+ }
+
#[test]
fn incremental_threshold_parses_and_falls_back() {
assert_eq!(incremental_drain_threshold_from(|_| Some("64".into())), 64);
@@ -1641,6 +1690,18 @@ mod tests {
}
}
+ fn antigravity_hook_args(server_url: &str) -> HookArgs {
+ HookArgs {
+ event: "session-start".into(),
+ agent: "antigravity-cli".into(),
+ server_url: server_url.into(),
+ auth_token: None,
+ project_strategy: None,
+ check_capture: false,
+ capture_assistant: false,
+ }
+ }
+
/// Recording HTTP stub: replies to every request with `status`/`body` and
/// streams each request head back so tests can assert which endpoints the
/// hook touched (session-start also drains the spool, so POSTs to `/hook`
@@ -1681,6 +1742,80 @@ mod tests {
.flatten()
}
+ #[tokio::test]
+ async fn antigravity_initial_invocation_fetches_with_native_output_contract() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (base, mut requests) = serve_requests("200 OK", "AGY-HANDOFF").await;
+ let mut stdout = Vec::new();
+ run_with_payload(
+ Some(tmp.path().join("data")),
+ antigravity_hook_args(&base),
+ serde_json::json!({
+ "invocationNum": 0,
+ "initialNumSteps": 0,
+ "conversationId": "agy-conversation",
+ "workspacePaths": [tmp.path()]
+ })
+ .to_string(),
+ &mut stdout,
+ |_| Ok(()),
+ )
+ .await
+ .unwrap();
+
+ let output: serde_json::Value = serde_json::from_slice(&stdout).unwrap();
+ assert_eq!(
+ output,
+ serde_json::json!({
+ "injectSteps": [{"ephemeralMessage": "AGY-HANDOFF"}]
+ })
+ );
+ let mut recorded = Vec::new();
+ while let Some(request) = first_request(&mut requests).await {
+ recorded.push(request);
+ }
+ assert!(
+ recorded
+ .iter()
+ .any(|request| request.starts_with("POST /hook")),
+ "{recorded:?}"
+ );
+ assert!(
+ recorded.iter().any(|request| {
+ request.starts_with("GET /handoff?")
+ && request.contains("session_id=agy-conversation")
+ }),
+ "{recorded:?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn antigravity_later_invocation_has_no_capture_or_handoff_side_effects() {
+ let tmp = tempfile::tempdir().unwrap();
+ let data_dir = tmp.path().join("data");
+ 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(&base),
+ serde_json::json!({
+ "invocationNum": 4,
+ "initialNumSteps": 12,
+ "conversationId": "agy-conversation",
+ "workspacePaths": [tmp.path()]
+ })
+ .to_string(),
+ &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());
+ assert_eq!(hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)), 0);
+ }
+
#[tokio::test]
async fn kimi_user_prompt_prints_the_handoff_body_verbatim() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 7f379324..7508718f 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -184,6 +184,11 @@ normalises them to exactly one of these `ObservationKind` values:
| `session-end` | Agent session ended; summary/handoff path may run. |
| `other` | Unknown or unsupported hook event. |
+Antigravity CLI has no native SessionStart event. Its `PreInvocation` hook
+fires before every model call, so the bridge maps only the documented
+`invocationNum = 0` payload to `session-start`; later invocations are ignored
+before spool or network side effects.
+
Unknown events do **not** expand the enum and, by default, leave no
source-event metadata in storage; they collapse to `other`. Third-party
integrations that need their own vocabulary can opt in by sending
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index 987e2f7c..d0002255 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -193,6 +193,12 @@ struct Handoff {
MCP tools `memory_handoff_begin` (writes a handoff row tagged `state=open`), `memory_handoff_accept` (acknowledges, returns the handoff content, marks `accepted_by`), and `memory_handoff_cancel` (marks an exact open handoff id expired when it was created by mistake). The user can stop Claude Code, start Codex, and Codex's session-start hook fetches the open handoff for the cwd. The cwd is matched by path-boundary (the prior art's check), not exact equality: a handoff left in `/repo` is delivered to a session in `/repo/api`, but never to `/repo-other`. A manual `memory_handoff_begin` handoff is stored with no cwd and so is project-wide, and is preferred over the auto SessionEnd handoff so an explicit "where we left off" baton is never shadowed by the heuristic one. Among cwd-eligible automatic handoffs the newest wins, with cwd specificity only breaking timestamp ties, so stale subdirectory context cannot shadow a newer parent-session handoff. Creating an automatic handoff expires prior open automatic handoffs from the exact cwd. Accepting one atomically expires older automatic candidates eligible for that receiving cwd; manual and sibling-directory handoffs remain open.
+Handoffs are a next-session transfer rather than live inter-agent messaging.
+Antigravity CLI exposes `PreInvocation` instead of SessionStart, and it fires
+before every model call; only `invocationNum = 0` may perform the destructive
+handoff fetch. This keeps a manual handoff created during wind-down open for
+the next session instead of feeding it back to the same execution loop.
+
agentmemory has this informally (`/handoff` skill); we make it explicit from day one because every research report flagged cross-agent as the v0.1 weak spot.
## 10. MCP tool surface - narrow on purpose
diff --git a/docs/install.md b/docs/install.md
index 03061b4d..0ea61923 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -645,8 +645,13 @@ ai-memory finalize-session
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:
+closing the conversation. Its `PreInvocation` hook likewise runs before every
+model call; ai-memory treats only the documented `invocationNum = 0` call as
+SessionStart. Later invocations return an empty hook result without capturing
+another start or fetching the single-use handoff, so a handoff created while
+the current conversation winds down remains available to the next session.
+After the final turn, finalize the latest matching Antigravity session
+explicitly:
```bash
ai-memory finalize-session --agent antigravity-cli
diff --git a/docs/usage.md b/docs/usage.md
index e53128d4..96d83851 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -40,6 +40,13 @@ If an agent has MCP but no lifecycle hook surface, ask it to call
`memory_handoff_begin` before quitting. The next hooked agent can still
consume that handoff automatically.
+Handoffs are next-session transfer, not a live message bus between agents that
+are still running. In particular, Antigravity CLI exposes `PreInvocation`
+before every model call; ai-memory fetches a handoff only on invocation zero,
+which is the hook contract's startup boundary. A handoff created later in that
+conversation stays open instead of being consumed by its creator's next model
+call.
+
If an agent creates a handoff by mistake, cancel it immediately with
`memory_handoff_cancel` and the `handoff_id` returned by
`memory_handoff_begin`. Cancelling marks the handoff expired, so the next
diff --git a/hooks/_lib.sh b/hooks/_lib.sh
index 6f2d1962..b265160b 100644
--- a/hooks/_lib.sh
+++ b/hooks/_lib.sh
@@ -116,6 +116,20 @@ ai_memory_extract_session_id() {
done
}
+# Antigravity's PreInvocation hook fires before every model call. Only the
+# documented invocationNum=0 boundary represents the startup event that
+# ai-memory maps to SessionStart. Missing or malformed counters fail closed so
+# a repeated invocation cannot consume a next-session handoff.
+ai_memory_antigravity_is_initial_invocation() {
+ payload="${1:-$(cat)}"
+ rest=${payload#*\"invocationNum\"}
+ [ "$rest" != "$payload" ] || return 1
+ value=$(printf '%s' "$rest" \
+ | sed -n -E 's/^[[:space:]]*:[[:space:]]*([0-9]+)[[:space:]]*([,}]).*/\1/p' \
+ | head -n 1)
+ [ "$value" = "0" ]
+}
+
ai_memory_managed_qs() {
[ -n "${AI_MEMORY_RUN_ID:-}" ] || return 0
printf '&managed_run=%s' "$(ai_memory_url_encode "$AI_MEMORY_RUN_ID")"
diff --git a/hooks/antigravity-cli/session-start.sh b/hooks/antigravity-cli/session-start.sh
index 4e8c817a..9dbe861f 100755
--- a/hooks/antigravity-cli/session-start.sh
+++ b/hooks/antigravity-cli/session-start.sh
@@ -8,12 +8,21 @@ _lib_dir="$(dirname "$0")"
SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
PAYLOAD=$(cat)
+if ! ai_memory_antigravity_is_initial_invocation "$PAYLOAD"; then
+ printf '{}\n'
+ exit 0
+fi
CWD=$(ai_memory_extract_cwd "$PAYLOAD")
QS=$(ai_memory_marker_qs "$CWD")
+SESSION_ID=$(ai_memory_extract_session_id "$PAYLOAD")
+SESSION_QS=""
+if [ -n "$SESSION_ID" ]; then
+ SESSION_QS="&session_id=$(ai_memory_url_encode "$SESSION_ID")"
+fi
printf '%s' "$PAYLOAD" \
| ai_memory_post_hook "$SERVER/hook?event=session-start&agent=antigravity-cli${QS}" >/dev/null 2>&1 || true
-HANDOFF=$(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}${SESSION_QS}" 2>/dev/null || true)
if [ -n "$HANDOFF" ]; then
printf '{"injectSteps":[{"ephemeralMessage":'
printf '%s' "$HANDOFF" | ai_memory_json_string
diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1
index b50a0ace..4f81b4b1 100644
--- a/hooks/lib/ai-memory-hook.ps1
+++ b/hooks/lib/ai-memory-hook.ps1
@@ -261,6 +261,19 @@ function Read-AiMemoryStdin {
return ""
}
+function Test-AiMemoryAntigravityInitialInvocation {
+ param([string] $Payload)
+ try {
+ $Parsed = $Payload | ConvertFrom-Json
+ $Property = $Parsed.PSObject.Properties["invocationNum"]
+ if ($null -eq $Property) { return $false }
+ $Value = $Property.Value
+ return (($Value -is [int] -or $Value -is [long]) -and [long]$Value -eq 0)
+ } catch {
+ return $false
+ }
+}
+
function Invoke-AiMemoryHook {
param(
[Parameter(Mandatory = $true)] [string] $Event,
@@ -278,6 +291,10 @@ function Invoke-AiMemoryHook {
$Server = if ($env:AI_MEMORY_HOOK_URL) { $env:AI_MEMORY_HOOK_URL } else { "http://127.0.0.1:49374" }
$Payload = Read-AiMemoryStdin
+ if ($AntigravityPreInvocationOutput -and -not (Test-AiMemoryAntigravityInitialInvocation -Payload $Payload)) {
+ [Console]::Out.Write("{}")
+ return
+ }
# 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 whole
diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.sh
index 8c655a99..f1c6afda 100755
--- a/tests/hooks/test_lib.sh
+++ b/tests/hooks/test_lib.sh
@@ -88,6 +88,62 @@ PAYLOAD_WINDOWS='{"session_id":"x","cwd":"C:\\dev\\myproject"}'
assert_eq "extract cwd unescapes Windows JSON path" 'C:\dev\myproject' \
"$(ai_memory_extract_cwd "$PAYLOAD_WINDOWS")"
+antigravity_initial() {
+ if ai_memory_antigravity_is_initial_invocation "$1"; then
+ printf 'yes'
+ else
+ printf 'no'
+ fi
+}
+assert_eq "antigravity invocation zero is initial" "yes" \
+ "$(antigravity_initial '{"invocationNum":0,"conversationId":"agy"}')"
+assert_eq "antigravity later invocation is not initial" "no" \
+ "$(antigravity_initial '{"invocationNum":3,"conversationId":"agy"}')"
+assert_eq "antigravity missing invocation fails closed" "no" \
+ "$(antigravity_initial '{"conversationId":"agy"}')"
+assert_eq "antigravity quoted invocation fails closed" "no" \
+ "$(antigravity_initial '{"invocationNum":"0","conversationId":"agy"}')"
+assert_eq "antigravity fractional invocation fails closed" "no" \
+ "$(antigravity_initial '{"invocationNum":0.5,"conversationId":"agy"}')"
+assert_eq "extract antigravity conversation id" "agy" \
+ "$(ai_memory_extract_session_id '{"conversationId":"agy"}')"
+
+FAKE_CURL_BIN="$TMP/fake-curl-bin"
+FAKE_CURL_LOG="$TMP/fake-curl.log"
+mkdir -p "$FAKE_CURL_BIN"
+cat >"$FAKE_CURL_BIN/curl" <<'EOF'
+#!/bin/sh
+printf '%s\n' "$*" >>"$AI_MEMORY_CURL_LOG"
+case "$*" in
+ *'/handoff?'*) printf 'next-session-context' ;;
+esac
+EOF
+chmod +x "$FAKE_CURL_BIN/curl"
+
+rm -f "$FAKE_CURL_LOG"
+AGY_LATER_OUTPUT=$(printf '%s' '{"invocationNum":2,"conversationId":"agy","workspacePaths":["/work"]}' \
+ | PATH="$FAKE_CURL_BIN:$PATH" AI_MEMORY_CURL_LOG="$FAKE_CURL_LOG" \
+ AI_MEMORY_HOOK_URL='http://memory.test' sh hooks/antigravity-cli/session-start.sh)
+assert_eq "antigravity later invocation returns empty hook output" "{}" "$AGY_LATER_OUTPUT"
+assert_eq "antigravity later invocation makes no HTTP request" "0" \
+ "$([ -f "$FAKE_CURL_LOG" ] && wc -l <"$FAKE_CURL_LOG" | tr -d ' ' || printf '0')"
+
+rm -f "$FAKE_CURL_LOG"
+AGY_INITIAL_OUTPUT=$(printf '%s' '{"invocationNum":0,"conversationId":"agy","workspacePaths":["/work"]}' \
+ | PATH="$FAKE_CURL_BIN:$PATH" AI_MEMORY_CURL_LOG="$FAKE_CURL_LOG" \
+ AI_MEMORY_HOOK_URL='http://memory.test' sh hooks/antigravity-cli/session-start.sh)
+assert_eq "antigravity initial invocation injects handoff" \
+ '{"injectSteps":[{"ephemeralMessage":"next-session-context"}]}' "$AGY_INITIAL_OUTPUT"
+assert_eq "antigravity initial invocation posts then fetches" "2" \
+ "$(wc -l <"$FAKE_CURL_LOG" | tr -d ' ')"
+assert_eq "antigravity handoff fetch carries conversation id" "yes" \
+ "$(grep -q '/handoff?.*session_id=agy' "$FAKE_CURL_LOG" && printf 'yes' || printf 'no')"
+
+PS_ANTIGRAVITY_STATIC=$(grep -q 'function Test-AiMemoryAntigravityInitialInvocation' hooks/lib/ai-memory-hook.ps1 \
+ && grep -q '\$AntigravityPreInvocationOutput -and -not' hooks/lib/ai-memory-hook.ps1 \
+ && printf 'ok' || printf 'missing')
+assert_eq "powershell antigravity hook has invocation guard" "ok" "$PS_ANTIGRAVITY_STATIC"
+
# --- json_string -------------------------------------------------------
JSON_INPUT='quoted "thing" \ path
next line'