Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(antigravity): native SessionStart, transcript prompts, turn checkpoints
4nrry4f90d5a17532
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5a0c4f33..29db78ca 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -103,6 +103,27 @@ version in [`docs/changelog/`](docs/changelog/):recently updated; the store applies that cap before loading nodes or theirselected edges into the process. Expired pages stay hidden. An edge stillrequires both ends to be readable.+- Added Antigravity hook parity with Claude Code and Codex for the `agy` CLI,+ the desktop App and the IDE. `install-hooks --agent antigravity-cli` now+ wires the native `SessionStart`, which injects the handoff as an+ `injectSteps` system message that stays in the conversation, where the+ ephemeral message it replaces was dropped after the first turn.+ `PreInvocation` gets its own `pre-invocation` handler: on builds without+ `SessionStart`, the first turn's call stands in for it, once per+ conversation. The native hook now reads each turn's prompts from the+ conversation's own transcript (`transcriptPath`, only under+ `~/.gemini/<app>/brain/<conversationId>/`, no symlinks out of it, 8 MiB per+ hook) and records them as user prompts, so summaries and handoffs carry+ them. A `Stop` that finished the turn (`NO_TOOL_CALL` or `model_stop`) with+ `fullyIdle: true` writes a turn checkpoint, the path OpenCode 2 uses: the+ summary page and one handoff are refreshed and the conversation stays open,+ so `finalize-session` is no longer needed for normal use. It remains the+ explicit close, hands the baton over without the 10-minute quiet period,+ queues opt-in consolidation, and skips its `history.jsonl` prompt replay+ for a conversation whose prompts were already captured. Rerun+ `install-hooks --agent antigravity-cli --apply` to add `SessionStart`;+ existing native-hook installs get the prompts and checkpoints without it.+ (#TBD)### Fixed- Fixed `memory_lint` reporting findings for TTL-expired pages. The lint passdiff --git a/crates/ai-memory-cli/src/commands/finalize_session.rs b/crates/ai-memory-cli/src/commands/finalize_session.rsindex 7a9b4293..faf14c3f 100644--- a/crates/ai-memory-cli/src/commands/finalize_session.rs+++ b/crates/ai-memory-cli/src/commands/finalize_session.rs@@ -125,8 +125,9 @@ pub(crate) async fn finalize(Ok((workspace, project, finalized))}-/// Antigravity CLI's live hooks carry no prompt event, so its sessions reach-/// the server without a single prompt; its `history.jsonl` has them. Other+/// Antigravity's hooks carry no prompt event. Current native hooks recover+/// prompts from the conversation's transcript; for a session they did not+/// (shell hooks, an older install), `agy`'s `history.jsonl` has them. Other/// agents capture prompts live. `--all-owners` finalizes sessions owned by/// other users, whose prompts this machine's history does not hold.fn replays_prompts(agent: AgentKind, all_owners: bool) -> bool {@@ -148,6 +149,11 @@ async fn replay_prompts(if !super::hook::admits_capture_at(&config.data_dir, Path::new(cwd)) {return;}+ // Current hooks capture each prompt live from the conversation's+ // transcript; replaying `history.jsonl` too would store them twice.+ if super::hook::antigravity_transcript_prompts_captured(&config.data_dir, session_id) {+ return;+ }let Some(home) = super::run::native_home(config) else {eprintln!("ai-memory: no home directory; session {} is finalized without its prompts",diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex 75cb449c..ef5eea83 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -504,24 +504,57 @@ 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);+/// The event token the Antigravity `PreInvocation` hook is rendered with.+/// Earlier installs render it as `session-start`; both are read the same way.+pub(crate) const ANTIGRAVITY_PRE_INVOCATION_EVENT: &str = "pre-invocation";++/// What an Antigravity `session-start` or `pre-invocation` event marks+/// (<https://antigravity.google/docs/hooks/>).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum AntigravityBoundary {+ /// Any other agent or event.+ None,+ /// A later model call inside a turn, or a malformed counter: nothing to do.+ LaterInvocation,+ /// The native `SessionStart`, the only start event without `invocationNum`.+ ConversationStart,+ /// `PreInvocation` with `invocationNum` 0. The counter restarts on every+ /// user turn, so this marks a turn; it doubles as the conversation start+ /// on builds that fire no `SessionStart`.+ TurnStart,+}++fn antigravity_boundary(+ agent: AgentKind,+ event: &str,+ raw: &serde_json::Value,+) -> AntigravityBoundary {+ if agent != AgentKind::AntigravityCli {+ return AntigravityBoundary::None;+ }+ let pre_invocation = event == ANTIGRAVITY_PRE_INVOCATION_EVENT;+ if !pre_invocation && HookEvent::parse(event) != HookEvent::SessionStart {+ return AntigravityBoundary::None;}- true+ match raw.get("invocationNum") {+ None if !pre_invocation => AntigravityBoundary::ConversationStart,+ Some(counter) if counter.as_u64() == Some(0) => AntigravityBoundary::TurnStart,+ // A PreInvocation without its documented counter fails closed so a+ // later invocation can never consume a handoff.+ _ => AntigravityBoundary::LaterInvocation,+ }+}++fn should_process_hook_event(agent: AgentKind, event: &str, raw: &serde_json::Value) -> bool {+ antigravity_boundary(agent, event, raw) != AntigravityBoundary::LaterInvocation}-/// `<data_dir>/briefed/agy-start-<conversationId>` for an Antigravity-/// SessionStart that names its conversation; `None` for every other event.+/// `<data_dir>/briefed/agy-start-<conversationId>`, which records that an+/// Antigravity conversation already started; `None` without a conversation id.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)@@ -534,6 +567,145 @@ fn antigravity_conversation_start_marker()}+/// Transcript read cursors kept at once. A cursor that falls out only makes+/// the next read of its conversation start over, and the server's ingest+/// keys drop the prompts it already has.+const MAX_ANTIGRAVITY_TRANSCRIPT_CURSORS: usize = 256;++/// `<data_dir>/hook-state/antigravity-transcripts/<conversationId>.json`.+fn antigravity_transcript_cursor_path(data_dir: &Path, conversation: &str) -> PathBuf {+ data_dir+ .join("hook-state")+ .join("antigravity-transcripts")+ .join(format!("{}.json", sanitize_briefed_key(conversation)))+}++fn load_antigravity_transcript_cursor(path: &Path) -> ai_memory_hooks::TranscriptCursor {+ fs::read(path)+ .ok()+ .and_then(|bytes| serde_json::from_slice(&bytes).ok())+ .unwrap_or_default()+}++/// Atomic (tmp + rename) and best effort, with bounded retention: a lost+/// write only makes the next read repeat prompts the server drops by key.+fn store_antigravity_transcript_cursor(path: &Path, cursor: &ai_memory_hooks::TranscriptCursor) {+ let (Some(dir), Ok(bytes)) = (path.parent(), serde_json::to_vec(cursor)) else {+ return;+ };+ if fs::create_dir_all(dir).is_err() {+ return;+ }+ let tmp = path.with_extension(format!("json.tmp-{}", std::process::id()));+ let written = fs::File::create(&tmp).and_then(|mut file| {+ std::io::Write::write_all(&mut file, &bytes)?;+ file.sync_all()+ });+ if written.is_err() || fs::rename(&tmp, path).is_err() {+ let _ = fs::remove_file(&tmp);+ return;+ }+ let Ok(entries) = fs::read_dir(dir) else {+ return;+ };+ let mut others = entries+ .filter_map(Result::ok)+ .filter(|entry| entry.path() != path)+ .filter_map(|entry| Some((entry.metadata().ok()?.modified().ok()?, entry.path())))+ .collect::<Vec<_>>();+ others.sort_by_key(|(modified, _)| std::cmp::Reverse(*modified));+ for (_, stale) in others+ .into_iter()+ .skip(MAX_ANTIGRAVITY_TRANSCRIPT_CURSORS.saturating_sub(1))+ {+ let _ = fs::remove_file(stale);+ }+}++/// Whether the live hooks already captured prompts of this conversation+/// from its transcript, so `finalize-session` must not replay them again+/// from `history.jsonl`.+pub(crate) fn antigravity_transcript_prompts_captured(data_dir: &Path, conversation: &str) -> bool {+ load_antigravity_transcript_cursor(&antigravity_transcript_cursor_path(data_dir, conversation))+ .prompts+ > 0+}++/// Ingest key of a recovered prompt: stable per conversation and step, so a+/// repeated read (a lost cursor, a crash before it was stored) is dropped by+/// the server instead of stored twice.+fn antigravity_prompt_ingest_key(+ conversation: &str,+ prompt: &ai_memory_hooks::TranscriptPrompt,+) -> String {+ let step = prompt.step_index.map_or_else(+ || format!("offset:{}", prompt.line_offset),+ |step| format!("step:{step}"),+ );+ let mut hasher = Sha256::new();+ for part in ["antigravity-transcript-prompt", conversation, step.as_str()] {+ hasher.update(part.len().to_be_bytes());+ hasher.update(part.as_bytes());+ }+ let digest = format!("{:x}", hasher.finalize());+ format!("agy_{}", &digest[..60])+}++/// Recovered Antigravity prompts ready to spool, and the cursor to store+/// once they are.+struct AntigravityPromptEvents {+ /// `(ingest key, body)` of each `user-prompt` event, in transcript order.+ events: Vec<(String, String)>,+ cursor_path: PathBuf,+ cursor: ai_memory_hooks::TranscriptCursor,+}++/// The `user-prompt` events for the prompts Antigravity wrote to this+/// conversation's transcript since the last read. Antigravity puts no+/// prompt in any hook payload; `transcriptPath` names the transcript and is+/// read only inside the conversation's own `brain/<conversationId>/`+/// directory under `home` ([`ai_memory_hooks::antigravity_transcript_path`]).+/// Each body keeps the event's conversation and workspace fields so the+/// server scopes it like the event itself, and is capped and scrubbed like+/// any client-side prompt; the server sanitizes it again on ingest.+fn antigravity_transcript_prompt_events(+ data_dir: &Path,+ home: Option<&Path>,+ raw: &serde_json::Value,+) -> Option<AntigravityPromptEvents> {+ let conversation = ai_memory_hooks::antigravity_conversation_id(raw)?;+ let transcript = ai_memory_hooks::antigravity_transcript_path(raw, home?)?;+ let cursor_path = antigravity_transcript_cursor_path(data_dir, conversation);+ let read = ai_memory_hooks::read_transcript_prompts(+ &transcript,+ &load_antigravity_transcript_cursor(&cursor_path),+ )?;+ let mut events = Vec::with_capacity(read.prompts.len());+ for prompt in &read.prompts {+ let mut body = serde_json::Map::new();+ for key in ["conversationId", "workspacePaths", "cwd", "modelName"] {+ if let Some(value) = raw.get(key) {+ body.insert(key.into(), value.clone());+ }+ }+ body.insert("prompt".into(), prompt.text.clone().into());+ if let Some(at) = &prompt.created_at {+ body.insert("occurred_at".into(), at.clone().into());+ }+ let mut body = serde_json::Value::Object(body);+ ai_memory_hooks::cap_lifecycle_body_for_client(&mut body, HookEvent::UserPrompt);+ events.push((+ antigravity_prompt_ingest_key(conversation, prompt),+ serde_json::to_string(&body).ok()?,+ ));+ }+ Some(AntigravityPromptEvents {+ events,+ cursor_path,+ cursor: read.cursor,+ })+}+/// 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@@ -730,9 +902,11 @@ fn user_prompt_recap_envelope(recap: &str) -> serde_json::Value {fn session_start_handoff_envelope(agent: AgentKind, handoff: String) -> serde_json::Value {if agent == AgentKind::AntigravityCli {+ // A system message stays in the conversation for later turns; an+ // `ephemeralMessage` would be dropped after the first one.serde_json::json!({"injectSteps": [{- "ephemeralMessage": handoff,+ "systemMessage": { "systemMessage": handoff },}]})} else if agent == AgentKind::CopilotCli {@@ -786,6 +960,31 @@ async fn run_with_payload<W, S>(stdout: &mut W,spawn_background_drainer: S,) -> anyhow::Result<()>+where+ W: std::io::Write,+ S: FnOnce(&Path, Option<&str>) -> std::io::Result<()>,+{+ run_with_payload_in_home(+ data_dir,+ args,+ payload,+ stdout,+ spawn_background_drainer,+ home_dir(),+ )+ .await+}++/// [`run_with_payload`] with the home directory given, the root that the+/// Antigravity step output and transcript reads are confined to.+async fn run_with_payload_in_home<W, S>(+ data_dir: Option<PathBuf>,+ args: HookArgs,+ payload: String,+ stdout: &mut W,+ spawn_background_drainer: S,+ home: Option<PathBuf>,+) -> anyhow::Result<()>whereW: std::io::Write,S: FnOnce(&Path, Option<&str>) -> std::io::Result<()>,@@ -803,7 +1002,7 @@ whereargs.server_url.clone_from(&spool_policy.server_url);}let agent_kind = AgentKind::from_wire(&args.agent);- let hook_event = HookEvent::parse(&args.event);+ let mut hook_event = HookEvent::parse(&args.event);// This is inherited execution context, like AI_MEMORY_RUN_ID, rather// than server configuration. Hooks deliberately bypass Config::load.let external_capture = env_lookup(CAPTURE_OWNER_ENV).is_some_and(|v| !v.trim().is_empty());@@ -813,7 +1012,11 @@ where// Grok delivers the handoff on the first PostToolUse (its SessionStart /// UserPromptSubmit stdout is discarded); that path is context delivery// too, so external capture must not suppress it.- || (hook_event == HookEvent::PostToolUse && agent_kind.post_tool_injects_handoff());+ || (hook_event == HookEvent::PostToolUse && agent_kind.post_tool_injects_handoff())+ // On an Antigravity build without SessionStart, the first turn's+ // PreInvocation delivers the handoff in its place.+ || (agent_kind == AgentKind::AntigravityCli+ && args.event == ANTIGRAVITY_PRE_INVOCATION_EVENT);if external_capture && !args.check_capture && !delivers_context {// Retiring the fallback session ID is lifecycle housekeeping, not// capture. Preserve it even when no event is enqueued.@@ -840,11 +1043,10 @@ wherelet reload_requested = hook_event == HookEvent::UserPrompt&& ai_memory_hooks::user_prompt_text(&json).is_some_and(|prompt| ai_memory_core::compaction_recap::is_reload_request(&prompt));- // 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.- let event_admits_capture = should_process_hook_event(agent_kind, hook_event, &json)+ // Antigravity's PreInvocation fires before every model call; only+ // invocation zero, the start of a user turn, is a boundary.+ let antigravity = antigravity_boundary(agent_kind, &args.event, &json);+ let event_admits_capture = should_process_hook_event(agent_kind, &args.event, &json)&& !is_redundant_cursor_copy(agent_kind,&json,@@ -855,22 +1057,43 @@ 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.+ // Only a conversation's first start boundary posts session-start and+ // claims a handoff: the native SessionStart, or on builds without it the+ // first turn's PreInvocation. Every later turn start only recovers the+ // turn's prompts from the transcript (below) and posts no event of its+ // own. A turn start without a conversation id cannot be told from a new+ // conversation, so it does nothing.+ let mut antigravity_turn_only = false;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,+ && matches!(+ antigravity,+ AntigravityBoundary::ConversationStart | AntigravityBoundary::TurnStart){- if marker.exists() {+ let marker = antigravity_conversation_start_marker(+ &resolve_data_dir_with(data_dir.as_deref(), &runtime_env),+ &json,+ );+ let started = match &marker {+ Some(marker) if marker.exists() => true,+ Some(marker) => {+ mark_briefed(marker);+ false+ }+ None => antigravity == AntigravityBoundary::TurnStart,+ };+ if started && antigravity == AntigravityBoundary::ConversationStart {write_success_response(stdout, agent_kind, hook_event)?;return Ok(());}- mark_briefed(&marker);+ antigravity_turn_only = started;+ args.event = if started {+ ANTIGRAVITY_PRE_INVOCATION_EVENT+ } else {+ "session-start"+ }+ .into();+ hook_event = HookEvent::parse(&args.event);}// Assistant/Stop capture (#196). On an opted-in install// (`install-hooks --capture-assistant`), extract the assistant message,@@ -895,11 +1118,7 @@ wherepayload = serde_json::to_string(&json)?;}if agent_kind == AgentKind::AntigravityCli- && ai_memory_hooks::enrich_antigravity_step_output(- &mut json,- hook_event,- home_dir().as_deref(),- )+ && ai_memory_hooks::enrich_antigravity_step_output(&mut json, hook_event, home.as_deref()){payload = serde_json::to_string(&json)?;}@@ -1123,18 +1342,58 @@ where// delivery succeeded but whose response was lost — closing the// conservative-retry duplication vector. Older servers ignore the param.if !external_capture {- let ingest_key = uuid::Uuid::new_v4().simple().to_string();- let event_url = format!(- "{base}/hook?event={}&agent={}{}{}&ingest_key={ingest_key}",- args.event, args.agent, hook_qs, capture_qs- );- let entry =- hook_spool::entry_for(event_url, payload.clone(), effective_token, oidc_present)- .routed_to(profile_name);- if hook_spool::enqueue_with_config(&spool, &entry, Some(&spool_policy)).is_err() {- eprintln!(- "ai-memory hook warning: failed to spool lifecycle event; capture for this event was skipped"+ // Antigravity's prompts exist only in its transcript. A Stop's go+ // ahead of it, so the turn checkpoint it publishes includes them; a+ // start's follow it. A later turn start spools only its prompts.+ let mut antigravity_prompts = (agent_kind == AgentKind::AntigravityCli+ && (antigravity_turn_only+ || matches!(hook_event, HookEvent::SessionStart | HookEvent::Stop)))+ .then(|| antigravity_transcript_prompt_events(&dd, home.as_deref(), &json))+ .flatten();+ let spool_prompts = |prompts: AntigravityPromptEvents| {+ let mut spooled = true;+ for (ingest_key, body) in prompts.events {+ let url = format!(+ "{base}/hook?event=user-prompt&agent={}{hook_qs}&ingest_key={ingest_key}",+ args.agent+ );+ let entry = hook_spool::entry_for(url, body, effective_token, oidc_present)+ .routed_to(profile_name);+ spooled &=+ hook_spool::enqueue_with_config(&spool, &entry, Some(&spool_policy)).is_ok();+ }+ // Advance only past prompts that were all spooled; a re-read+ // repeats the spooled ones under the same ingest keys.+ if spooled {+ store_antigravity_transcript_cursor(&prompts.cursor_path, &prompts.cursor);+ } else {+ eprintln!(+ "ai-memory hook warning: failed to spool an Antigravity prompt; it is retried on the next turn"+ );+ }+ };+ if hook_event == HookEvent::Stop+ && let Some(prompts) = antigravity_prompts.take()+ {+ spool_prompts(prompts);+ }+ if !antigravity_turn_only {+ let ingest_key = uuid::Uuid::new_v4().simple().to_string();+ let event_url = format!(+ "{base}/hook?event={}&agent={}{}{}&ingest_key={ingest_key}",+ args.event, args.agent, hook_qs, capture_qs);+ let entry =+ hook_spool::entry_for(event_url, payload.clone(), effective_token, oidc_present)+ .routed_to(profile_name);+ if hook_spool::enqueue_with_config(&spool, &entry, Some(&spool_policy)).is_err() {+ eprintln!(+ "ai-memory hook warning: failed to spool lifecycle event; capture for this event was skipped"+ );+ }+ }+ if let Some(prompts) = antigravity_prompts {+ spool_prompts(prompts);}// ZCode is intentionally absent here: it has no SessionEnd and fires Stop// per turn, so its stored id is cleared by `finalize-session` (or@@ -2317,31 +2576,64 @@ mod tests {}}+ /// Each documented Antigravity start event, under both the current+ /// rendering (SessionStart → `session-start`, PreInvocation →+ /// `pre-invocation`) and the one earlier installs carry (PreInvocation →+ /// `session-start`).#[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),+ fn antigravity_start_events_map_to_conversation_and_turn_boundaries() {+ use AntigravityBoundary::{ConversationStart, LaterInvocation, TurnStart};+ let agy = AgentKind::AntigravityCli;+ for event in ["session-start", ANTIGRAVITY_PRE_INVOCATION_EVENT] {+ for (raw, expected) in [+ (+ serde_json::json!({"invocationNum": 0, "initialNumSteps": 4}),+ TurnStart,+ ),+ (serde_json::json!({"invocationNum": 1}), LaterInvocation),+ (serde_json::json!({"invocationNum": 0.5}), LaterInvocation),+ (serde_json::json!({"invocationNum": "0"}), LaterInvocation),+ (serde_json::json!({"invocationNum": null}), LaterInvocation),+ (serde_json::json!({"invocationNum": -1}), LaterInvocation),+ ] {+ assert_eq!(+ antigravity_boundary(agy, event, &raw),+ expected,+ "{event} {raw}"+ );+ assert_eq!(+ should_process_hook_event(agy, event, &raw),+ expected != LaterInvocation,+ "{event} {raw}"+ );+ }+ }+ // Only SessionStart omits the counter; a PreInvocation without it+ // fails closed.+ let session_start = serde_json::json!({"conversationId": "c", "workspacePaths": ["/w"]});+ assert_eq!(+ antigravity_boundary(agy, "session-start", &session_start),+ ConversationStart+ );+ assert_eq!(+ antigravity_boundary(agy, ANTIGRAVITY_PRE_INVOCATION_EVENT, &session_start),+ LaterInvocation+ );+ for (agent, event) in [+ (agy, "post-tool-use"),+ (agy, "pre-tool-use"),+ (agy, "stop"),+ (AgentKind::ClaudeCode, "session-start"),+ (AgentKind::ClaudeCode, ANTIGRAVITY_PRE_INVOCATION_EVENT),] {+ let later = serde_json::json!({"invocationNum": 3});assert_eq!(- should_process_hook_event(AgentKind::AntigravityCli, HookEvent::SessionStart, &raw,),- expected,- "{raw}"+ antigravity_boundary(agent, event, &later),+ AntigravityBoundary::None,+ "{agent:?} {event}");+ assert!(should_process_hook_event(agent, event, &later));}- 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]@@ -5954,7 +6246,7 @@ mod tests {assert_eq!(output,serde_json::json!({- "injectSteps": [{"ephemeralMessage": "AGY-HANDOFF"}]+ "injectSteps": [{"systemMessage": {"systemMessage": "AGY-HANDOFF"}}]}));let mut recorded = Vec::new();@@ -6015,45 +6307,25 @@ mod tests {}#[test]- fn antigravity_conversation_marker_only_for_named_antigravity_starts() {+ fn antigravity_conversation_marker_is_keyed_by_a_sanitized_conversation_id() {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+ &serde_json::json!({"conversationId": "a/b"})),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()- );+ for raw in [+ serde_json::json!({}),+ serde_json::json!({"conversationId": " "}),+ serde_json::json!({"conversationId": 7}),+ ] {+ assert!(+ antigravity_conversation_start_marker(dir, &raw).is_none(),+ "{raw}"+ );+ }}#[tokio::test]@@ -6083,6 +6355,483 @@ mod tests {assert_eq!(hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)), 0);}+ #[tokio::test]+ async fn antigravity_native_session_start_delivers_a_persistent_handoff_once() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let (base, mut requests) = 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),+ serde_json::json!({+ "conversationId": "agy-native",+ "workspacePaths": [tmp.path()],+ "modelName": "gemini-3-pro"+ })+ .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": [{"systemMessage": {"systemMessage": "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("GET /handoff?") && request.contains("session_id=agy-native")+ }),+ "{recorded:?}"+ );++ // The first turn's PreInvocation follows at once, under the current+ // rendering and under the one earlier installs carry; neither starts+ // the conversation again nor claims a second handoff.+ let spooled = hook_spool::spool_len(&hook_spool::spool_dir(&data_dir));+ let (base, mut requests) = serve_requests("200 OK", "MUST-NOT-BE-CONSUMED").await;+ for event in [ANTIGRAVITY_PRE_INVOCATION_EVENT, "session-start"] {+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ antigravity_hook_args(event, &base),+ serde_json::json!({+ "invocationNum": 0,+ "initialNumSteps": 1,+ "conversationId": "agy-native",+ "workspacePaths": [tmp.path()]+ })+ .to_string(),+ &mut stdout,+ |_, _| Err(std::io::Error::other("must not spawn")),+ )+ .await+ .unwrap();+ assert_eq!(stdout, b"{}\n", "{event}");+ }+ assert!(first_request(&mut requests).await.is_none());+ assert_eq!(+ hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)),+ spooled,+ "a turn start posts no event of its own"+ );+ }++ #[tokio::test]+ async fn antigravity_first_pre_invocation_starts_the_conversation_without_session_start() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let (base, mut requests) = serve_requests("200 OK", "AGY-HANDOFF").await;+ let turn = serde_json::json!({+ "invocationNum": 0,+ "initialNumSteps": 1,+ "conversationId": "agy-old-build",+ "workspacePaths": [tmp.path()]+ })+ .to_string();+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ antigravity_hook_args(ANTIGRAVITY_PRE_INVOCATION_EVENT, &base),+ turn.clone(),+ &mut stdout,+ |_, _| Ok(()),+ )+ .await+ .unwrap();+ let output: serde_json::Value = serde_json::from_slice(&stdout).unwrap();+ assert_eq!(+ output,+ serde_json::json!({+ "injectSteps": [{"systemMessage": {"systemMessage": "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.contains("event=session-start")),+ "the fallback posts a session-start: {recorded:?}"+ );+ assert!(+ recorded.iter().any(|request| {+ request.starts_with("GET /handoff?") && request.contains("session_id=agy-old-build")+ }),+ "{recorded:?}"+ );++ let (base, mut requests) = serve_requests("200 OK", "MUST-NOT-BE-CONSUMED").await;+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir),+ antigravity_hook_args(ANTIGRAVITY_PRE_INVOCATION_EVENT, &base),+ turn,+ &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());+ }++ /// `<home>/.gemini/antigravity/brain/<conversation>/.system_generated/logs/transcript.jsonl`.+ fn agy_transcript(home: &Path, conversation: &str) -> PathBuf {+ let logs = home+ .join(".gemini/antigravity/brain")+ .join(conversation)+ .join(".system_generated/logs");+ std::fs::create_dir_all(&logs).unwrap();+ logs.join("transcript.jsonl")+ }++ fn append_user_input(transcript: &Path, step: u64, text: &str) {+ use std::io::Write as _;+ let line = serde_json::json!({+ "step_index": step,+ "source": "USER_EXPLICIT",+ "type": "USER_INPUT",+ "status": "DONE",+ "created_at": "2026-10-18T10:00:00Z",+ "content": text,+ });+ let mut file = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(transcript)+ .unwrap();+ writeln!(file, "{line}").unwrap();+ }++ fn agy_event_payload(+ conversation: &str,+ workspace: &Path,+ transcript: &Path,+ extra: serde_json::Value,+ ) -> String {+ let mut payload = serde_json::json!({+ "conversationId": conversation,+ "workspacePaths": [workspace],+ "transcriptPath": transcript,+ "artifactDirectoryPath": transcript.parent().unwrap().parent().unwrap().parent().unwrap(),+ "modelName": "gemini-3-pro",+ });+ for (key, value) in extra.as_object().unwrap() {+ payload[key] = value.clone();+ }+ payload.to_string()+ }++ async fn run_agy_hook(data_dir: &Path, home: &Path, event: &str, payload: String) {+ let mut stdout = Vec::new();+ run_with_payload_in_home(+ Some(data_dir.to_path_buf()),+ antigravity_hook_args(event, &dead_server_url()),+ payload,+ &mut stdout,+ |_, _| Ok(()),+ Some(home.to_path_buf()),+ )+ .await+ .unwrap();+ }++ /// The spooled entries, removed from the spool (whose test capacity is+ /// three) so a longer sequence can keep spooling.+ fn take_spooled_entries(data_dir: &Path) -> Vec<hook_spool::SpoolEntry> {+ let spool = hook_spool::spool_dir(data_dir);+ let entries = read_spooled_entries(&spool);+ for entry in std::fs::read_dir(&spool).unwrap() {+ let path = entry.unwrap().path();+ if path.extension().and_then(|ext| ext.to_str()) == Some("json") {+ std::fs::remove_file(path).unwrap();+ }+ }+ entries+ }++ fn event_names(entries: &[hook_spool::SpoolEntry]) -> Vec<(String, Option<String>)> {+ entries+ .iter()+ .map(|entry| {+ let body: serde_json::Value = serde_json::from_str(&entry.body).unwrap();+ (+ query_param(&entry.url, "event").unwrap().to_owned(),+ body.get("prompt")+ .and_then(serde_json::Value::as_str)+ .map(str::to_owned),+ )+ })+ .collect()+ }++ fn spooled_events(data_dir: &Path) -> Vec<(String, Option<String>)> {+ event_names(&read_spooled_entries(&hook_spool::spool_dir(data_dir)))+ }++ /// No Antigravity event carries the prompt; the transcript does. Each is+ /// spooled once as a `user-prompt`: after the start, at the start of its+ /// turn, and ahead of a Stop that found it unread, so the turn+ /// checkpoint the Stop publishes includes it.+ #[tokio::test]+ async fn antigravity_transcript_prompts_are_spooled_once_in_turn_order() {+ let tmp = tempfile::tempdir().unwrap();+ let (data_dir, home, workspace) = (+ tmp.path().join("data"),+ tmp.path().join("home"),+ tmp.path().join("repo"),+ );+ std::fs::create_dir_all(&workspace).unwrap();+ let conversation = "ec33ebf9-0cba-4100-8142-c61503f6c587";+ let transcript = agy_transcript(&home, conversation);+ let payload = |extra: serde_json::Value| {+ agy_event_payload(conversation, &workspace, &transcript, extra)+ };+ append_user_input(&transcript, 0, "Fix the login redirect");++ let mut entries = Vec::new();+ run_agy_hook(+ &data_dir,+ &home,+ "session-start",+ payload(serde_json::json!({})),+ )+ .await;+ entries.extend(take_spooled_entries(&data_dir));+ let pre_invocation = ANTIGRAVITY_PRE_INVOCATION_EVENT;+ for counter in [0, 1, 2] {+ run_agy_hook(+ &data_dir,+ &home,+ pre_invocation,+ payload(serde_json::json!({"invocationNum": counter})),+ )+ .await;+ entries.extend(take_spooled_entries(&data_dir));+ }+ append_user_input(&transcript, 4, "Add a regression test");+ run_agy_hook(+ &data_dir,+ &home,+ pre_invocation,+ payload(serde_json::json!({"invocationNum": 0})),+ )+ .await;+ entries.extend(take_spooled_entries(&data_dir));+ append_user_input(&transcript, 9, "Also update the docs");+ let stop = payload(serde_json::json!({+ "executionNum": 0,+ "terminationReason": "NO_TOOL_CALL",+ "fullyIdle": true,+ }));+ run_agy_hook(&data_dir, &home, "stop", stop.clone()).await;+ entries.extend(take_spooled_entries(&data_dir));+ // A repeated Stop finds nothing new.+ run_agy_hook(&data_dir, &home, "stop", stop).await;+ entries.extend(take_spooled_entries(&data_dir));++ let prompt = |text: &str| ("user-prompt".to_owned(), Some(text.to_owned()));+ assert_eq!(+ event_names(&entries),+ [+ ("session-start".to_owned(), None),+ prompt("Fix the login redirect"),+ prompt("Add a regression test"),+ prompt("Also update the docs"),+ ("stop".to_owned(), None),+ ("stop".to_owned(), None),+ ]+ );++ let first = &entries[1];+ let body: serde_json::Value = serde_json::from_str(&first.body).unwrap();+ assert_eq!(body["conversationId"], conversation);+ assert_eq!(body["workspacePaths"], serde_json::json!([workspace]));+ assert_eq!(body["occurred_at"], "2026-10-18T10:00:00Z");+ assert!(body.get("transcriptPath").is_none(), "{body}");+ let key = query_param(&first.url, "ingest_key").unwrap();+ assert!(key.starts_with("agy_") && key.len() == 64, "{key}");+ let expected_key = antigravity_prompt_ingest_key(+ conversation,+ &ai_memory_hooks::TranscriptPrompt {+ step_index: Some(0),+ line_offset: 0,+ text: String::new(),+ created_at: None,+ },+ );+ assert_eq!(key, expected_key, "stable per conversation and step");+ assert_eq!(query_param(&first.url, "agent"), Some("antigravity-cli"));+ // The prompt is scoped exactly like the event it rode with.+ let scope = |url: &str| {+ url.split('?')+ .nth(1)+ .unwrap()+ .split('&')+ .filter(|part| !part.starts_with("event=") && !part.starts_with("ingest_key="))+ .map(str::to_owned)+ .collect::<Vec<_>>()+ };+ assert_eq!(scope(&first.url), scope(&entries[4].url));+ assert!(antigravity_transcript_prompts_captured(+ &data_dir,+ conversation+ ));+ assert!(!antigravity_transcript_prompts_captured(+ &data_dir,+ "agy-other"+ ));+ }++ /// Adversarial: `transcriptPath` is payload input and the hook uploads+ /// what it reads. Only the named conversation's own transcript under the+ /// home's Antigravity data directories is read; a forged path outside+ /// it, or another conversation's transcript, yields no prompt.+ #[tokio::test]+ async fn antigravity_transcript_reads_are_confined_to_the_conversations_own_logs() {+ let tmp = tempfile::tempdir().unwrap();+ let (home, workspace) = (tmp.path().join("home"), tmp.path().join("repo"));+ std::fs::create_dir_all(&workspace).unwrap();+ let foreign = agy_transcript(&tmp.path().join("elsewhere"), "agy-a");+ append_user_input(&foreign, 0, "outside the home");+ let other = agy_transcript(&home, "agy-b");+ append_user_input(&other, 0, "another conversation");+ let secret = home.join("notes.jsonl");+ std::fs::write(+ &secret,+ "{\"type\":\"USER_INPUT\",\"source\":\"USER_EXPLICIT\",\"content\":\"secret\"}\n",+ )+ .unwrap();+ let stop = serde_json::json!({"terminationReason": "NO_TOOL_CALL", "fullyIdle": true});+ for (case, path) in [+ ("foreign", &foreign),+ ("other", &other),+ ("secret", &secret),+ ] {+ let data_dir = tmp.path().join(format!("data-{case}"));+ run_agy_hook(+ &data_dir,+ &home,+ "stop",+ agy_event_payload("agy-a", &workspace, path, stop.clone()),+ )+ .await;+ assert_eq!(+ spooled_events(&data_dir),+ [("stop".to_owned(), None)],+ "{case}"+ );+ assert!(!antigravity_transcript_prompts_captured(&data_dir, "agy-a"));+ }+ // Control: the conversation's own transcript is read.+ let own = agy_transcript(&home, "agy-a");+ append_user_input(&own, 0, "own prompt");+ let data_dir = tmp.path().join("data-own");+ run_agy_hook(+ &data_dir,+ &home,+ "stop",+ agy_event_payload("agy-a", &workspace, &own, stop),+ )+ .await;+ assert_eq!(+ spooled_events(&data_dir),+ [+ ("user-prompt".to_owned(), Some("own prompt".to_owned())),+ ("stop".to_owned(), None)+ ]+ );+ }++ /// A repository the allowlist leaves out emits nothing, prompts included,+ /// and its transcript is not even read.+ #[tokio::test]+ async fn antigravity_transcript_prompts_follow_the_capture_allowlist() {+ let tmp = tempfile::tempdir().unwrap();+ let (data_dir, home, workspace) = (+ tmp.path().join("data"),+ tmp.path().join("home"),+ tmp.path().join("repo"),+ );+ std::fs::create_dir_all(&workspace).unwrap();+ let transcript = agy_transcript(&home, "agy-a");+ append_user_input(&transcript, 0, "unmarked repository");+ let mut args = antigravity_hook_args("stop", &dead_server_url());+ args.capture_mode = Some(crate::cli::CaptureModeArg::Allowlist);+ let mut stdout = Vec::new();+ run_with_payload_in_home(+ Some(data_dir.clone()),+ args,+ agy_event_payload(+ "agy-a",+ &workspace,+ &transcript,+ serde_json::json!({"terminationReason": "NO_TOOL_CALL", "fullyIdle": true}),+ ),+ &mut stdout,+ |_, _| Ok(()),+ Some(home),+ )+ .await+ .unwrap();+ assert_eq!(hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)), 0);+ assert!(!antigravity_transcript_prompts_captured(&data_dir, "agy-a"));+ }++ #[test]+ fn antigravity_transcript_cursor_store_is_atomic_and_bounded() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path().join("hook-state/antigravity-transcripts");+ let cursor = ai_memory_hooks::TranscriptCursor {+ file: Some("transcript.jsonl".into()),+ offset: 42,+ last_step: Some(3),+ resync: false,+ prompts: 2,+ };+ let path = antigravity_transcript_cursor_path(tmp.path(), "a/b");+ assert_eq!(path, dir.join("a_b.json"));+ store_antigravity_transcript_cursor(&path, &cursor);+ assert_eq!(load_antigravity_transcript_cursor(&path), cursor);+ assert!(antigravity_transcript_prompts_captured(tmp.path(), "a/b"));+ // Corrupt state reads as a fresh cursor rather than failing the hook.+ std::fs::write(&path, b"not json").unwrap();+ assert_eq!(+ load_antigravity_transcript_cursor(&path),+ ai_memory_hooks::TranscriptCursor::default()+ );+ for n in 0..MAX_ANTIGRAVITY_TRANSCRIPT_CURSORS + 5 {+ store_antigravity_transcript_cursor(+ &antigravity_transcript_cursor_path(tmp.path(), &format!("c{n}")),+ &cursor,+ );+ }+ let names = std::fs::read_dir(&dir)+ .unwrap()+ .map(|entry| entry.unwrap().file_name().into_string().unwrap())+ .collect::<Vec<_>>();+ assert!(+ names.len() <= MAX_ANTIGRAVITY_TRANSCRIPT_CURSORS,+ "{}",+ names.len()+ );+ assert!(+ names.iter().all(|name| name.ends_with(".json")),+ "{names:?}"+ );+ }+#[tokio::test]async fn kiro_session_start_prints_handoff_verbatim() {let tmp = tempfile::tempdir().unwrap();diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 39363a61..1a9e9f4f 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -3122,7 +3122,7 @@ fn merge_gemini_hooks(/// Antigravity CLI uses a named-groups format where hook groups are/// top-level keys (e.g. `"ai-memory"`) containing event arrays. Tool/// events (`PreToolUse`, `PostToolUse`) use nested shape with matcher;-/// lifecycle events (`PreInvocation`, `Stop`) use flat shape.+/// lifecycle events (`SessionStart`, `PreInvocation`, `Stop`) use flat shape.////// Config file: `~/.gemini/config/hooks.json`fn apply_to_antigravity_settings(@@ -3163,9 +3163,11 @@ fn apply_to_antigravity_settings(}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";+Antigravity has no conversation-end event. Each finished turn refreshes the\n\+session summary and its handoff, which a new session in this project picks up\n\+once the conversation has been quiet for 10 minutes. To close a conversation\n\+now, hand its baton over at once and queue opt-in SessionEnd consolidation,\n\+run `ai-memory finalize-session --agent antigravity-cli`.\n";fn merge_antigravity_hooks(staged: &Path,@@ -9727,7 +9729,10 @@ command = "AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/a#[test]fn antigravity_manual_render_explains_explicit_finalization() {let temp = TempDir::new().unwrap();- stub_scripts(temp.path(), &["session-start.sh", "stop.sh"]);+ stub_scripts(+ temp.path(),+ &["session-start.sh", "pre-invocation.sh", "stop.sh"],+ );let output = render_agent_output("antigravity-cli",temp.path(),@@ -9737,7 +9742,8 @@ command = "AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/a&[&ANTIGRAVITY_LIFECYCLE_EVENTS],);- assert!(output.contains("`Stop` ends one execution loop, not the conversation"));+ assert!(output.contains("Antigravity has no conversation-end event"));+ assert!(output.contains("quiet for 10 minutes"));assert!(output.contains("ai-memory finalize-session --agent antigravity-cli"),"Antigravity install output must expose the supported finalizer: {output}"@@ -14490,6 +14496,66 @@ process.exit(0);parsed["ai-memory"]["Stop"].is_array(),"Stop hook should be present");+ assert!(+ parsed["ai-memory"]["SessionStart"].is_array(),+ "SessionStart hook should be present"+ );+ }++ /// An install from before SessionStart was wired ran `session-start` on+ /// PreInvocation. Re-installing moves PreInvocation to its own+ /// `pre-invocation` handler and adds SessionStart, one entry each.+ #[test]+ fn antigravity_reinstall_rewires_pre_invocation_and_adds_session_start() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(+ hooks_tmp.path(),+ &[+ "session-start.sh",+ "pre-invocation.sh",+ "pre-tool-use.sh",+ "post-tool-use.sh",+ "stop.sh",+ ],+ );+ let config_tmp = TempDir::new().unwrap();+ let config_path = config_tmp.path().join("hooks.json");+ fs::write(+ &config_path,+ serde_json::json!({+ "ai-memory": {+ "PreInvocation": [{+ "type": "command",+ "command": "'/old/bin/ai-memory' hook --event session-start --agent antigravity-cli --server-url 'http://127.0.0.1:49374'"+ }]+ }+ })+ .to_string(),+ )+ .unwrap();++ merge_antigravity_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ None,+ &config_path,+ )+ .unwrap();++ let parsed: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ for (event, token) in [+ ("SessionStart", "session-start"),+ ("PreInvocation", "pre-invocation"),+ ] {+ let entries = parsed["ai-memory"][event].as_array().unwrap();+ assert_eq!(entries.len(), 1, "{event}: {entries:?}");+ let command = entries[0]["command"].as_str().unwrap();+ assert!(command.contains(token), "{event}: {command}");+ assert!(!command.contains("/old/bin"), "{event}: {command}");+ }}#[test]diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 272b2f3b..3b0466e8 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -1514,8 +1514,16 @@ 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", "stop.sh")];+/// `SessionStart` starts a conversation and delivers the handoff.+/// `PreInvocation` fires before every model call; its invocation zero starts+/// a user turn, where the native hook recovers the turn's prompts from the+/// transcript, and stands in for `SessionStart` on builds that have none.+/// `Stop` ends one execution loop; a finished, idle one is a turn checkpoint.+pub(crate) const ANTIGRAVITY_LIFECYCLE_EVENTS: [(&str, &str); 3] = [+ ("SessionStart", "session-start.sh"),+ ("PreInvocation", "pre-invocation.sh"),+ ("Stop", "stop.sh"),+];/// Build the Antigravity CLI (`agy`) `hooks.json` payload.///@@ -1523,8 +1531,8 @@ pub(crate) const ANTIGRAVITY_LIFECYCLE_EVENTS: [(&str, &str); 2] =/// maps hook-group names to their event configurations. Each group/// can contain any subset of the supported events. Tool events/// (`PreToolUse`, `PostToolUse`) use the nested shape with matcher;-/// lifecycle events (`PreInvocation`, `Stop`) use a flat handler-/// list where matcher is ignored.+/// lifecycle events (`SessionStart`, `PreInvocation`, `Stop`) use a flat+/// handler list where matcher is ignored.////// The output is `{ "ai-memory": { <events> } }`.pub(crate) fn build_antigravity_payload_with_data_dir(@@ -4651,12 +4659,49 @@ $payload = [Console]::In.ReadToEnd()"Stop must record a stop observation, not synthesize session-end handoffs: {stop_cmd}");- // All expected events present- for expected in ["PreToolUse", "PostToolUse", "PreInvocation", "Stop"] {- assert!(- group.contains_key(expected),- "missing Antigravity event {expected}"- );+ // All expected events present, each lifecycle event on its own+ // script: SessionStart starts the conversation, PreInvocation marks+ // a turn (and stands in for SessionStart on builds without it).+ assert_eq!(+ group.keys().map(String::as_str).collect::<Vec<_>>(),+ [+ "PreToolUse",+ "PostToolUse",+ "SessionStart",+ "PreInvocation",+ "Stop"+ ]+ );+ for (event, script) in [+ ("SessionStart", "session-start.sh"),+ ("PreInvocation", "pre-invocation.sh"),+ ] {+ let cmd = group[event][0]["command"].as_str().unwrap();+ assert!(cmd.ends_with(&format!("/{script}")), "{event}: {cmd}");+ }+ }++ /// The native command's event token is the script stem, so the native+ /// hook tells SessionStart and PreInvocation apart by their tokens.+ #[test]+ fn antigravity_native_commands_carry_distinct_start_tokens() {+ let v = build_antigravity_payload_for_platform(+ Path::new("/host/hooks/antigravity-cli"),+ "http://localhost:49374",+ None,+ HookCommandPlatform::PosixNative,+ "antigravity-cli",+ None,+ None,+ );+ for (event, token) in [+ ("SessionStart", "--event session-start "),+ ("PreInvocation", "--event pre-invocation "),+ ("Stop", "--event stop "),+ ] {+ let cmd = v["ai-memory"][event][0]["command"].as_str().unwrap();+ assert!(cmd.contains(token), "{event}: {cmd}");+ assert!(cmd.contains("--agent antigravity-cli"), "{event}: {cmd}");}}diff --git a/crates/ai-memory-hooks/src/antigravity.rs b/crates/ai-memory-hooks/src/antigravity.rsindex 9e320ffd..83abe8a2 100644--- a/crates/ai-memory-hooks/src/antigravity.rs+++ b/crates/ai-memory-hooks/src/antigravity.rs@@ -1,4 +1,5 @@-//! Antigravity CLI lifecycle hook output extraction and enrichment.+//! Antigravity lifecycle hook output extraction, enrichment and prompt+//! recovery.//!//! Antigravity CLI's native `PostToolUse` event payload carries invocation//! metadata (`toolCall`, `conversationId`, `stepIdx`, `artifactDirectoryPath`)@@ -10,10 +11,22 @@//! (e.g. `run_command`, `view_file`, `list_dir`, etc.) while strictly//! preserving the code extraction behavior for file-editing tools (`write_to_file`,//! `replace_file_content`, etc.), which extract actual code changes from `args`.+//!+//! No Antigravity hook event carries the user's prompt, but every event names+//! the conversation's `transcriptPath`. [`antigravity_transcript_path`] and+//! [`read_transcript_prompts`] recover the `USER_INPUT` steps from it, with+//! the same file safety as `output.txt` plus containment under the+//! conversation's own `brain/<conversationId>/` directory. The transcript+//! format is undocumented, so parsing is defensive.+//! [`stop_is_turn_checkpoint`] reads the `Stop` payload the server uses to+//! publish a turn checkpoint. Hook reference:+//! <https://antigravity.google/docs/hooks/>.use std::fs::File;-use std::io::Read;-use std::path::{Path, PathBuf};+use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};+use std::path::{Component, Path, PathBuf};++use serde::{Deserialize, Serialize};use crate::payload::HookEvent;@@ -203,6 +216,427 @@ pub fn enrich_antigravity_step_output(}}+/// Whether an Antigravity `Stop` closes a finished turn: the model ended it+/// on its own and nothing is still running in the background+/// (`fullyIdle`). The bundled hook reference spells the normal reason+/// `NO_TOOL_CALL` and the web page `model_stop`; both are accepted, in any+/// case. A cancelled, failed or budget-limited loop is not a checkpoint: the+/// next turn or an explicit `finalize-session` covers it.+#[must_use]+pub fn stop_is_turn_checkpoint(raw: &serde_json::Value) -> bool {+ let idle = raw.get("fullyIdle").and_then(serde_json::Value::as_bool) == Some(true);+ let failed = raw+ .get("error")+ .and_then(serde_json::Value::as_str)+ .is_some_and(|error| !error.trim().is_empty());+ idle && !failed+ && raw+ .get("terminationReason")+ .and_then(serde_json::Value::as_str)+ .is_some_and(is_normal_termination)+}++fn is_normal_termination(reason: &str) -> bool {+ let reason = reason.trim();+ let reason = strip_prefix_ignore_ascii_case(reason, "TERMINATION_REASON_").unwrap_or(reason);+ reason.eq_ignore_ascii_case("NO_TOOL_CALL") || reason.eq_ignore_ascii_case("MODEL_STOP")+}++fn strip_prefix_ignore_ascii_case<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {+ let head = text.get(..prefix.len())?;+ head.eq_ignore_ascii_case(prefix)+ .then(|| &text[prefix.len()..])+}++/// Antigravity's app data directories under `~/.gemini`, one per surface:+/// the desktop App, the CLI (`agy`) and the IDE.+pub const ANTIGRAVITY_APP_DATA_DIRS: [&str; 3] =+ ["antigravity", "antigravity-cli", "antigravity-ide"];++/// Transcript file names a `transcriptPath` may name. The docs name+/// `transcript.jsonl`; the CLI's payload points at `transcript_full.jsonl`+/// beside it (`docs/desktop/verification-2026-10.md`).+pub const ANTIGRAVITY_TRANSCRIPT_FILES: [&str; 2] = ["transcript.jsonl", "transcript_full.jsonl"];++/// Bytes of transcript one hook reads at most. Tool output makes most of the+/// file, so a turn's new prompt sits near where the previous read stopped;+/// a backlog is picked up by the following hooks.+pub const MAX_TRANSCRIPT_SCAN_BYTES: u64 = 8 * 1024 * 1024;++/// Longest transcript line that is parsed. Longer lines (large tool output)+/// are skipped without being held in memory.+pub const MAX_TRANSCRIPT_LINE_BYTES: usize = 1024 * 1024;++/// Prompts one read returns at most; the cursor stops after the last one.+pub const MAX_TRANSCRIPT_PROMPTS: usize = 64;++/// Where the transcript reader resumes for one conversation. Persisted by+/// the caller between hook processes.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct TranscriptCursor {+ /// File name of the transcript the offset belongs to.+ #[serde(default)]+ pub file: Option<String>,+ /// Byte offset just past the last line consumed.+ #[serde(default)]+ pub offset: u64,+ /// Highest `step_index` of a prompt already returned. A rewritten or+ /// truncated transcript is re-read from the start, and this keeps its+ /// old prompts from being returned twice.+ #[serde(default)]+ pub last_step: Option<u64>,+ /// The previous read stopped inside a line longer than the scan budget;+ /// the next one discards the rest of it first.+ #[serde(default)]+ pub resync: bool,+ /// Prompts returned for this conversation so far.+ #[serde(default)]+ pub prompts: u64,+}++/// One user prompt recovered from a transcript.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct TranscriptPrompt {+ /// The step's `step_index`, when it has one.+ pub step_index: Option<u64>,+ /// Byte offset of the step's line, the identity of a step without an index.+ pub line_offset: u64,+ /// Prompt text, outside any `<USER_REQUEST>` wrapper.+ pub text: String,+ /// The step's `created_at`, when it is an RFC 3339 timestamp.+ pub created_at: Option<String>,+}++/// The prompts one read found and the cursor to persist after delivering them.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct TranscriptRead {+ /// New prompts, in transcript order.+ pub prompts: Vec<TranscriptPrompt>,+ /// The cursor to store once `prompts` are delivered.+ pub cursor: TranscriptCursor,+}++/// The payload's `conversationId` when it is a plain id (ASCII+/// alphanumerics, `-`, `_`; Antigravity uses UUIDs). Anything else could+/// name another directory and yields `None`.+#[must_use]+pub fn antigravity_conversation_id(raw: &serde_json::Value) -> Option<&str> {+ let id = raw+ .get("conversationId")+ .and_then(serde_json::Value::as_str)?+ .trim();+ (!id.is_empty()+ && id.len() <= 128+ && id+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'))+ .then_some(id)+}++/// The transcript a payload's `transcriptPath` names, when it is the+/// conversation's own:+/// `~/.gemini/<app>/brain/<conversationId>/.system_generated/logs/<file>`+/// with `<app>` one of [`ANTIGRAVITY_APP_DATA_DIRS`] and `<file>` one of+/// [`ANTIGRAVITY_TRANSCRIPT_FILES`]. The containment check runs on+/// canonical paths, so a symlinked `brain/<id>`, `.system_generated` or+/// `logs` directory that leads elsewhere is refused, while a symlinked+/// `~/.gemini` (dotfile managers) still works. The file itself is checked+/// when it is opened. Returns the path under the canonical directory.+#[must_use]+pub fn antigravity_transcript_path(raw: &serde_json::Value, home: &Path) -> Option<PathBuf> {+ let conversation = antigravity_conversation_id(raw)?;+ let declared = raw+ .get("transcriptPath")+ .and_then(serde_json::Value::as_str)?;+ let path = resolve_artifact_dir(declared, Some(home))?;+ if !path.is_absolute()+ || path+ .components()+ .any(|c| matches!(c, Component::ParentDir | Component::CurDir))+ {+ return None;+ }+ let name = path.file_name()?.to_str()?;+ if !ANTIGRAVITY_TRANSCRIPT_FILES.contains(&name) {+ return None;+ }+ let logs = std::fs::canonicalize(path.parent()?).ok()?;+ ANTIGRAVITY_APP_DATA_DIRS.iter().find_map(|app| {+ let brain = std::fs::canonicalize(home.join(".gemini").join(app).join("brain")).ok()?;+ let expected = brain+ .join(conversation)+ .join(".system_generated")+ .join("logs");+ (logs == expected).then(|| expected.join(name))+ })+}++/// Open `path` only if it is a regular file, not a symlink, FIFO or device,+/// and is still the same file once open.+fn open_regular_file(path: &Path) -> Option<File> {+ let before = std::fs::symlink_metadata(path).ok()?;+ if !before.is_file() {+ return None;+ }+ let file = File::open(path).ok()?;+ let after = file.metadata().ok()?;+ if !after.is_file() {+ return None;+ }+ #[cfg(unix)]+ {+ use std::os::unix::fs::MetadataExt as _;+ if before.dev() != after.dev() || before.ino() != after.ino() {+ return None;+ }+ }+ Some(file)+}++/// Read the user prompts written to `path` since `cursor`. At most+/// [`MAX_TRANSCRIPT_SCAN_BYTES`] are read and [`MAX_TRANSCRIPT_PROMPTS`]+/// returned; a line still being written is left for the next read. `None`+/// when the file is not a readable regular file.+#[must_use]+pub fn read_transcript_prompts(path: &Path, cursor: &TranscriptCursor) -> Option<TranscriptRead> {+ let name = path.file_name()?.to_str()?.to_owned();+ let file = open_regular_file(path)?;+ let len = file.metadata().ok()?.len();+ let mut next = cursor.clone();+ if next.file.as_deref() != Some(name.as_str()) || len < next.offset {+ next.file = Some(name);+ next.offset = 0;+ next.resync = false;+ }+ let mut reader = BufReader::with_capacity(64 * 1024, file);+ reader.seek(SeekFrom::Start(next.offset)).ok()?;+ let start = next.offset;+ let mut scanned = 0_u64;+ let mut prompts = Vec::new();+ if next.resync {+ let (consumed, found) =+ skip_through_newline(&mut reader, MAX_TRANSCRIPT_SCAN_BYTES).ok()?;+ scanned += consumed;+ next.offset += consumed;+ if !found {+ return Some(TranscriptRead {+ prompts,+ cursor: next,+ });+ }+ next.resync = false;+ }+ let mut line = Vec::new();+ while prompts.len() < MAX_TRANSCRIPT_PROMPTS {+ let line_offset = next.offset;+ let budget = MAX_TRANSCRIPT_SCAN_BYTES.saturating_sub(scanned);+ let consumed = match read_bounded_line(&mut reader, &mut line, budget).ok()? {+ LineRead::Eof => break,+ LineRead::Complete(consumed) => consumed,+ // A final line with no newline yet: take it only once it is a+ // whole JSON object, otherwise it is still being written.+ LineRead::Unterminated(consumed) => {+ if !serde_json::from_slice::<serde_json::Value>(&line)+ .is_ok_and(|value| value.is_object())+ {+ break;+ }+ consumed+ }+ LineRead::OutOfBudget(consumed) => {+ // A line longer than a whole read is skipped in pieces;+ // otherwise the next read starts on it with a full budget.+ if line_offset == start {+ next.offset += consumed;+ next.resync = true;+ }+ break;+ }+ };+ scanned += consumed;+ next.offset += consumed;+ let Some(prompt) = parse_transcript_prompt(&line, line_offset) else {+ continue;+ };+ if let (Some(step), Some(last)) = (prompt.step_index, next.last_step)+ && step <= last+ {+ continue;+ }+ if let Some(step) = prompt.step_index {+ next.last_step = Some(next.last_step.map_or(step, |last| last.max(step)));+ }+ next.prompts += 1;+ prompts.push(prompt);+ }+ Some(TranscriptRead {+ prompts,+ cursor: next,+ })+}++enum LineRead {+ Eof,+ /// A newline-terminated line; bytes consumed including the newline.+ Complete(u64),+ /// End of file inside a line.+ Unterminated(u64),+ /// The budget ran out inside a line.+ OutOfBudget(u64),+}++/// Read one line into `out` (without its newline). A line longer than+/// [`MAX_TRANSCRIPT_LINE_BYTES`] is consumed but leaves `out` empty.+fn read_bounded_line(+ reader: &mut impl BufRead,+ out: &mut Vec<u8>,+ budget: u64,+) -> std::io::Result<LineRead> {+ out.clear();+ let mut consumed = 0_u64;+ let mut oversized = false;+ loop {+ if consumed >= budget {+ return Ok(LineRead::OutOfBudget(consumed));+ }+ let buf = reader.fill_buf()?;+ if buf.is_empty() {+ if oversized {+ out.clear();+ }+ return Ok(if consumed == 0 {+ LineRead::Eof+ } else {+ LineRead::Unterminated(consumed)+ });+ }+ let room = usize::try_from(budget - consumed).unwrap_or(usize::MAX);+ let window = &buf[..buf.len().min(room)];+ let newline = window.iter().position(|&b| b == b'\n');+ let chunk = &window[..newline.unwrap_or(window.len())];+ if !oversized {+ if out.len() + chunk.len() <= MAX_TRANSCRIPT_LINE_BYTES {+ out.extend_from_slice(chunk);+ } else {+ oversized = true;+ out.clear();+ }+ }+ let used = newline.map_or(window.len(), |at| at + 1);+ reader.consume(used);+ consumed += used as u64;+ if newline.is_some() {+ return Ok(LineRead::Complete(consumed));+ }+ }+}++/// Discard up to and including the next newline; returns the bytes consumed+/// and whether the newline was reached within `budget`.+fn skip_through_newline(reader: &mut impl BufRead, budget: u64) -> std::io::Result<(u64, bool)> {+ let mut consumed = 0_u64;+ while consumed < budget {+ let buf = reader.fill_buf()?;+ if buf.is_empty() {+ return Ok((consumed, false));+ }+ let room = usize::try_from(budget - consumed).unwrap_or(usize::MAX);+ let window = &buf[..buf.len().min(room)];+ let newline = window.iter().position(|&b| b == b'\n');+ let used = newline.map_or(window.len(), |at| at + 1);+ reader.consume(used);+ consumed += used as u64;+ if newline.is_some() {+ return Ok((consumed, true));+ }+ }+ Ok((consumed, false))+}++/// A transcript line's prompt: a `USER_INPUT` step typed by the user+/// (`source` absent or `USER_EXPLICIT`, so steps a hook injected are left+/// out) with non-empty text.+fn parse_transcript_prompt(line: &[u8], line_offset: u64) -> Option<TranscriptPrompt> {+ // Most lines are tool steps; only parse the ones that can be a prompt.+ if !line+ .windows(b"USER_INPUT".len())+ .any(|window| window.eq_ignore_ascii_case(b"USER_INPUT"))+ {+ return None;+ }+ let value: serde_json::Value = serde_json::from_slice(line).ok()?;+ let step = value.as_object()?;+ let kind = step.get("type")?.as_str()?.trim();+ if !(kind.eq_ignore_ascii_case("USER_INPUT")+ || kind.to_ascii_uppercase().ends_with("_USER_INPUT"))+ {+ return None;+ }+ if let Some(source) = step.get("source") {+ let source = source.as_str()?.trim().to_ascii_uppercase();+ if source != "USER_EXPLICIT" && !source.ends_with("_USER_EXPLICIT") {+ return None;+ }+ }+ let content = content_text(step.get("content")?)?;+ let text = user_request_text(&content).trim();+ if text.is_empty() {+ return None;+ }+ let step_index = step.get("step_index").and_then(|index| {+ index+ .as_u64()+ .or_else(|| index.as_str().and_then(|s| s.trim().parse().ok()))+ });+ let created_at = step+ .get("created_at")+ .and_then(serde_json::Value::as_str)+ .map(str::trim)+ .filter(|at| at.parse::<jiff::Timestamp>().is_ok())+ .map(str::to_owned);+ Some(TranscriptPrompt {+ step_index,+ line_offset,+ text: text.to_owned(),+ created_at,+ })+}++/// `content` as text: a string, or the strings and `text` fields of an+/// array or object of parts.+fn content_text(content: &serde_json::Value) -> Option<String> {+ match content {+ serde_json::Value::String(text) => Some(text.clone()),+ serde_json::Value::Object(part) => part+ .get("text")+ .and_then(serde_json::Value::as_str)+ .map(str::to_owned),+ serde_json::Value::Array(parts) => {+ let texts: Vec<&str> = parts+ .iter()+ .filter_map(|part| {+ part.as_str()+ .or_else(|| part.get("text").and_then(serde_json::Value::as_str))+ })+ .collect();+ (!texts.is_empty()).then(|| texts.join("\n"))+ }+ _ => None,+ }+}++/// The text inside `<USER_REQUEST>…</USER_REQUEST>` when the CLI's full+/// transcript wraps the prompt that way; the whole content otherwise.+fn user_request_text(content: &str) -> &str {+ const OPEN: &str = "<USER_REQUEST>";+ const CLOSE: &str = "</USER_REQUEST>";+ let Some(start) = content.find(OPEN) else {+ return content;+ };+ let inner = &content[start + OPEN.len()..];+ inner.find(CLOSE).map_or(inner, |end| &inner[..end])+}+#[cfg(test)]mod tests {use super::*;@@ -473,4 +907,541 @@ mod tests {Some("already populated"));}++ #[test]+ fn stop_checkpoint_needs_a_normal_reason_and_a_fully_idle_agent() {+ let cases = [+ // Bundled hook reference spellings.+ (+ serde_json::json!({"terminationReason": "NO_TOOL_CALL", "fullyIdle": true}),+ true,+ ),+ (+ serde_json::json!({"terminationReason": "no_tool_call", "fullyIdle": true}),+ true,+ ),+ (+ serde_json::json!({"terminationReason": "TERMINATION_REASON_NO_TOOL_CALL", "fullyIdle": true}),+ true,+ ),+ // Web page spelling.+ (+ serde_json::json!({"terminationReason": "model_stop", "fullyIdle": true}),+ true,+ ),+ (+ serde_json::json!({"terminationReason": " MODEL_STOP ", "fullyIdle": true, "error": ""}),+ true,+ ),+ // Background work still running.+ (+ serde_json::json!({"terminationReason": "NO_TOOL_CALL", "fullyIdle": false}),+ false,+ ),+ (+ serde_json::json!({"terminationReason": "NO_TOOL_CALL"}),+ false,+ ),+ (+ serde_json::json!({"terminationReason": "NO_TOOL_CALL", "fullyIdle": "true"}),+ false,+ ),+ // Abnormal ends.+ (+ serde_json::json!({"terminationReason": "NO_TOOL_CALL", "fullyIdle": true, "error": "boom"}),+ false,+ ),+ (serde_json::json!({"fullyIdle": true}), false),+ (+ serde_json::json!({"terminationReason": 0, "fullyIdle": true}),+ false,+ ),+ ];+ for (raw, expected) in cases {+ assert_eq!(stop_is_turn_checkpoint(&raw), expected, "{raw}");+ }+ for reason in [+ "MAX_INVOCATIONS",+ "MAX_FORCED_INVOCATIONS",+ "MAX_TOKEN_BUDGET_EXCEEDED",+ "ERROR",+ "USER_CANCELED",+ "TERMINAL_STEP_TYPE",+ "TERMINAL_CUSTOM_HOOK",+ "INJECTED_RESPONSE",+ "max_steps_exceeded",+ "error",+ "NO_TOOL_CALLS",+ "",+ ] {+ let raw = serde_json::json!({"terminationReason": reason, "fullyIdle": true});+ assert!(!stop_is_turn_checkpoint(&raw), "{reason}");+ }+ }++ #[test]+ fn conversation_id_must_be_a_plain_path_segment() {+ let id = |value: serde_json::Value| {+ antigravity_conversation_id(&serde_json::json!({ "conversationId": value }))+ .map(str::to_owned)+ };+ assert_eq!(+ id("ec33ebf9-0cba-4100-8142-c61503f6c587".into()).as_deref(),+ Some("ec33ebf9-0cba-4100-8142-c61503f6c587")+ );+ assert_eq!(id(" conv_1 ".into()).as_deref(), Some("conv_1"));+ for bad in ["", " ", "..", ".", "a/b", "a\\b", "../x", "c:x", "a b"] {+ assert_eq!(id(bad.into()), None, "{bad:?}");+ }+ assert_eq!(id("a".repeat(129).into()), None);+ assert_eq!(id(serde_json::json!(7)), None);+ }++ /// `<home>/.gemini/<app>/brain/<conversation>/.system_generated/logs/<file>`+ /// with `lines` written to it.+ fn write_transcript(+ home: &Path,+ app: &str,+ conversation: &str,+ file: &str,+ lines: &[&str],+ ) -> PathBuf {+ let logs = home+ .join(".gemini")+ .join(app)+ .join("brain")+ .join(conversation)+ .join(".system_generated")+ .join("logs");+ fs::create_dir_all(&logs).unwrap();+ let path = logs.join(file);+ let mut text = lines.join("\n");+ if !lines.is_empty() {+ text.push('\n');+ }+ fs::write(&path, text).unwrap();+ path+ }++ fn payload_for(path: &Path, conversation: &str) -> serde_json::Value {+ serde_json::json!({+ "conversationId": conversation,+ "transcriptPath": path.to_str().unwrap(),+ })+ }++ fn canonical(path: &Path) -> PathBuf {+ fs::canonicalize(path.parent().unwrap())+ .unwrap()+ .join(path.file_name().unwrap())+ }++ #[test]+ fn transcript_path_accepts_each_surface_and_both_file_names() {+ let home = tempdir().unwrap();+ for app in ANTIGRAVITY_APP_DATA_DIRS {+ for file in ANTIGRAVITY_TRANSCRIPT_FILES {+ let path = write_transcript(home.path(), app, "conv-1", file, &[]);+ assert_eq!(+ antigravity_transcript_path(&payload_for(&path, "conv-1"), home.path()),+ Some(canonical(&path)),+ "{app}/{file}"+ );+ }+ }+ let path = write_transcript(+ home.path(),+ "antigravity",+ "conv-2",+ "transcript.jsonl",+ &[],+ );+ let tilde = serde_json::json!({+ "conversationId": "conv-2",+ "transcriptPath": "~/.gemini/antigravity/brain/conv-2/.system_generated/logs/transcript.jsonl",+ });+ assert_eq!(+ antigravity_transcript_path(&tilde, home.path()),+ Some(canonical(&path))+ );+ }++ /// Adversarial: `transcriptPath` is payload input. Anything but the+ /// named conversation's own transcript under the home's Antigravity+ /// data directories is refused, so a forged payload cannot make the hook+ /// read and upload another file.+ #[test]+ fn transcript_path_refuses_anything_outside_the_conversations_own_logs() {+ let home = tempdir().unwrap();+ let elsewhere = tempdir().unwrap();+ let own = write_transcript(+ home.path(),+ "antigravity",+ "conv-a",+ "transcript.jsonl",+ &[],+ );+ let other = write_transcript(+ home.path(),+ "antigravity",+ "conv-b",+ "transcript.jsonl",+ &[],+ );+ // Same layout, but not under this home.+ let foreign = write_transcript(+ elsewhere.path(),+ "antigravity",+ "conv-a",+ "transcript.jsonl",+ &[],+ );+ // Same directory, other files.+ let logs = own.parent().unwrap();+ fs::write(logs.join("secrets.jsonl"), "{}\n").unwrap();+ // Another app data directory name.+ let unknown_app = write_transcript(+ home.path(),+ "antigravity-evil",+ "conv-a",+ "transcript.jsonl",+ &[],+ );++ let refused = [+ payload_for(&other, "conv-a"),+ payload_for(&foreign, "conv-a"),+ payload_for(&logs.join("secrets.jsonl"), "conv-a"),+ payload_for(&unknown_app, "conv-a"),+ payload_for(&logs.join("../logs/transcript.jsonl"), "conv-a"),+ payload_for(&own, "../conv-a"),+ payload_for(&own, ""),+ serde_json::json!({+ "conversationId": "conv-a",+ "transcriptPath": ".gemini/antigravity/brain/conv-a/.system_generated/logs/transcript.jsonl",+ }),+ serde_json::json!({ "conversationId": "conv-a" }),+ serde_json::json!({ "conversationId": "conv-a", "transcriptPath": 5 }),+ ];+ for raw in refused {+ assert_eq!(+ antigravity_transcript_path(&raw, home.path()),+ None,+ "{raw}"+ );+ }+ // Control: the conversation's own transcript is accepted.+ assert_eq!(+ antigravity_transcript_path(&payload_for(&own, "conv-a"), home.path()),+ Some(canonical(&own))+ );+ }++ #[test]+ #[cfg(unix)]+ fn transcript_path_refuses_symlinked_directories_that_leave_the_conversation() {+ use std::os::unix::fs::symlink;+ let home = tempdir().unwrap();+ let outside = tempdir().unwrap();+ fs::create_dir_all(outside.path().join("logs")).unwrap();+ fs::write(outside.path().join("logs/transcript.jsonl"), "{}\n").unwrap();++ // `.system_generated` leads out of the conversation directory.+ let conv = home.path().join(".gemini/antigravity/brain/conv-a");+ fs::create_dir_all(&conv).unwrap();+ symlink(outside.path(), conv.join(".system_generated")).unwrap();+ let path = conv.join(".system_generated/logs/transcript.jsonl");+ assert_eq!(+ antigravity_transcript_path(&payload_for(&path, "conv-a"), home.path()),+ None+ );++ // `brain/<id>` itself leads elsewhere.+ let brain = home.path().join(".gemini/antigravity-cli/brain");+ fs::create_dir_all(&brain).unwrap();+ let target = outside.path().join("conv-b");+ fs::create_dir_all(target.join(".system_generated/logs")).unwrap();+ fs::write(+ target.join(".system_generated/logs/transcript.jsonl"),+ "{}\n",+ )+ .unwrap();+ symlink(&target, brain.join("conv-b")).unwrap();+ let path = brain.join("conv-b/.system_generated/logs/transcript.jsonl");+ assert_eq!(+ antigravity_transcript_path(&payload_for(&path, "conv-b"), home.path()),+ None+ );++ // Control: a symlinked `~/.gemini` (a dotfile manager) still works.+ let dotfiles = tempdir().unwrap();+ let real_home = tempdir().unwrap();+ let gemini = dotfiles.path().join("gemini");+ let logs = gemini.join("antigravity/brain/conv-c/.system_generated/logs");+ fs::create_dir_all(&logs).unwrap();+ fs::write(logs.join("transcript.jsonl"), "").unwrap();+ symlink(&gemini, real_home.path().join(".gemini")).unwrap();+ let declared = real_home+ .path()+ .join(".gemini/antigravity/brain/conv-c/.system_generated/logs/transcript.jsonl");+ assert_eq!(+ antigravity_transcript_path(&payload_for(&declared, "conv-c"), real_home.path()),+ Some(fs::canonicalize(&logs).unwrap().join("transcript.jsonl"))+ );+ }++ fn user_input(step: u64, content: &str) -> String {+ serde_json::json!({+ "step_index": step,+ "source": "USER_EXPLICIT",+ "type": "USER_INPUT",+ "status": "DONE",+ "created_at": "2026-10-18T10:00:00Z",+ "content": content,+ })+ .to_string()+ }++ fn texts(read: &TranscriptRead) -> Vec<&str> {+ read.prompts.iter().map(|p| p.text.as_str()).collect()+ }++ #[test]+ fn reads_prompts_from_the_app_transcript_and_the_cli_full_transcript() {+ let home = tempdir().unwrap();+ let tool = serde_json::json!({+ "step_index": 2,+ "source": "MODEL",+ "type": "RUN_COMMAND",+ "content": "the word USER_INPUT inside tool output",+ "tool_calls": [{"name": "run_command"}],+ })+ .to_string();+ let app = write_transcript(+ home.path(),+ "antigravity",+ "conv-1",+ "transcript.jsonl",+ &[+ &user_input(0, "Fix the login bug"),+ &tool,+ &user_input(3, "Now add a test"),+ ],+ );+ let read = read_transcript_prompts(&app, &TranscriptCursor::default()).unwrap();+ assert_eq!(texts(&read), ["Fix the login bug", "Now add a test"]);+ assert_eq!(read.prompts[0].step_index, Some(0));+ assert_eq!(+ read.prompts[0].created_at.as_deref(),+ Some("2026-10-18T10:00:00Z")+ );+ assert_eq!(read.cursor.last_step, Some(3));+ assert_eq!(read.cursor.prompts, 2);+ assert_eq!(read.cursor.offset, fs::metadata(&app).unwrap().len());++ let wrapped = "<ADDITIONAL_METADATA>\nlocal time 10:00\n</ADDITIONAL_METADATA>\n\+ <USER_REQUEST>\nRename the module\n</USER_REQUEST>";+ let cli = write_transcript(+ home.path(),+ "antigravity-cli",+ "conv-2",+ "transcript_full.jsonl",+ &[&user_input(0, wrapped)],+ );+ let read = read_transcript_prompts(&cli, &TranscriptCursor::default()).unwrap();+ assert_eq!(texts(&read), ["Rename the module"]);+ }++ #[test]+ fn skips_injected_malformed_empty_and_non_prompt_steps() {+ let home = tempdir().unwrap();+ let injected = serde_json::json!({+ "step_index": 1, "source": "HOOK", "type": "USER_INPUT", "content": "injected by a hook",+ })+ .to_string();+ let no_source = serde_json::json!({+ "step_index": 2, "type": "CORTEX_STEP_TYPE_USER_INPUT", "content": [{"text": "part one"}, "part two"],+ })+ .to_string();+ let string_index = serde_json::json!({+ "step_index": "7", "source": "USER_EXPLICIT", "type": "user_input",+ "created_at": "yesterday", "content": {"text": "object content"},+ })+ .to_string();+ let path = write_transcript(+ home.path(),+ "antigravity",+ "conv-1",+ "transcript.jsonl",+ &[+ "{not json USER_INPUT",+ "",+ &injected,+ &user_input(3, " "),+ &user_input(4, "<USER_REQUEST> </USER_REQUEST>"),+ r#"{"type":"USER_INPUT","source":"USER_EXPLICIT","content":5}"#,+ r#"["USER_INPUT"]"#,+ &no_source,+ &string_index,+ ],+ );+ let read = read_transcript_prompts(&path, &TranscriptCursor::default()).unwrap();+ assert_eq!(texts(&read), ["part one\npart two", "object content"]);+ assert_eq!(read.prompts[1].step_index, Some(7));+ assert_eq!(read.prompts[1].created_at, None);+ }++ #[test]+ fn cursor_resumes_waits_for_partial_lines_and_survives_rewrites() {+ let home = tempdir().unwrap();+ let path = write_transcript(+ home.path(),+ "antigravity",+ "conv-1",+ "transcript.jsonl",+ &[&user_input(0, "first")],+ );+ let first = read_transcript_prompts(&path, &TranscriptCursor::default()).unwrap();+ assert_eq!(texts(&first), ["first"]);+ let again = read_transcript_prompts(&path, &first.cursor).unwrap();+ assert!(again.prompts.is_empty(), "nothing new since the last read");++ // A line still being written is left for the next read.+ let second = user_input(1, "second");+ let (head, tail) = second.split_at(second.len() / 2);+ let mut file = fs::OpenOptions::new().append(true).open(&path).unwrap();+ std::io::Write::write_all(&mut file, head.as_bytes()).unwrap();+ let partial = read_transcript_prompts(&path, &first.cursor).unwrap();+ assert!(partial.prompts.is_empty());+ assert_eq!(partial.cursor.offset, first.cursor.offset);+ std::io::Write::write_all(&mut file, tail.as_bytes()).unwrap();+ // Whole but not yet newline-terminated: taken once.+ let whole = read_transcript_prompts(&path, &partial.cursor).unwrap();+ assert_eq!(texts(&whole), ["second"]);+ std::io::Write::write_all(&mut file, b"\n").unwrap();+ std::io::Write::write_all(&mut file, user_input(2, "third").as_bytes()).unwrap();+ std::io::Write::write_all(&mut file, b"\n").unwrap();+ let next = read_transcript_prompts(&path, &whole.cursor).unwrap();+ assert_eq!(texts(&next), ["third"]);+ assert_eq!(next.cursor.prompts, 3);++ // Rewritten shorter: re-read from the start, old steps not repeated.+ fs::write(+ &path,+ format!(+ "{}\n{}\n",+ user_input(2, "third"),+ user_input(5, "after rewrite")+ ),+ )+ .unwrap();+ let rewritten = read_transcript_prompts(&path, &next.cursor).unwrap();+ assert_eq!(texts(&rewritten), ["after rewrite"]);++ // A cursor for the other transcript file starts over too.+ let mut other = rewritten.cursor.clone();+ other.file = Some("transcript_full.jsonl".into());+ other.last_step = None;+ let restarted = read_transcript_prompts(&path, &other).unwrap();+ assert_eq!(texts(&restarted), ["third", "after rewrite"]);+ }++ #[test]+ fn oversized_lines_are_skipped_without_losing_later_prompts() {+ let home = tempdir().unwrap();+ let huge = format!(+ r#"{{"step_index":1,"type":"USER_INPUT","source":"USER_EXPLICIT","content":"{}"}}"#,+ "x".repeat(MAX_TRANSCRIPT_LINE_BYTES)+ );+ let path = write_transcript(+ home.path(),+ "antigravity",+ "conv-1",+ "transcript.jsonl",+ &[&user_input(0, "before"), &huge, &user_input(2, "after")],+ );+ let read = read_transcript_prompts(&path, &TranscriptCursor::default()).unwrap();+ assert_eq!(texts(&read), ["before", "after"]);+ }++ #[test]+ fn a_line_longer_than_the_scan_budget_is_skipped_across_reads() {+ let home = tempdir().unwrap();+ let budget = usize::try_from(MAX_TRANSCRIPT_SCAN_BYTES).unwrap();+ let giant = format!(+ r#"{{"type":"TOOL","content":"{}"}}"#,+ "y".repeat(budget + 1024)+ );+ let path = write_transcript(+ home.path(),+ "antigravity",+ "conv-1",+ "transcript.jsonl",+ &[&giant, &user_input(1, "after the giant line")],+ );+ let first = read_transcript_prompts(&path, &TranscriptCursor::default()).unwrap();+ assert!(first.prompts.is_empty());+ assert!(first.cursor.resync, "stopped inside the giant line");+ assert_eq!(first.cursor.offset, MAX_TRANSCRIPT_SCAN_BYTES);+ let second = read_transcript_prompts(&path, &first.cursor).unwrap();+ assert_eq!(texts(&second), ["after the giant line"]);+ assert!(!second.cursor.resync);+ }++ #[test]+ fn one_read_returns_a_bounded_number_of_prompts() {+ let home = tempdir().unwrap();+ let lines: Vec<String> = (0..MAX_TRANSCRIPT_PROMPTS as u64 + 6)+ .map(|step| user_input(step, &format!("prompt {step}")))+ .collect();+ let refs: Vec<&str> = lines.iter().map(String::as_str).collect();+ let path = write_transcript(+ home.path(),+ "antigravity",+ "conv-1",+ "transcript.jsonl",+ &refs,+ );+ let first = read_transcript_prompts(&path, &TranscriptCursor::default()).unwrap();+ assert_eq!(first.prompts.len(), MAX_TRANSCRIPT_PROMPTS);+ let second = read_transcript_prompts(&path, &first.cursor).unwrap();+ assert_eq!(second.prompts.len(), 6);+ assert_eq!(+ second.prompts[0].text,+ format!("prompt {MAX_TRANSCRIPT_PROMPTS}")+ );+ }++ #[test]+ #[cfg(unix)]+ fn transcript_reader_refuses_symlinks_and_special_files() {+ use std::os::unix::fs::symlink;+ let home = tempdir().unwrap();+ let secret = home.path().join("secret.jsonl");+ fs::write(&secret, format!("{}\n", user_input(0, "not a transcript"))).unwrap();+ let path = write_transcript(+ home.path(),+ "antigravity",+ "conv-1",+ "transcript.jsonl",+ &[],+ );+ fs::remove_file(&path).unwrap();+ symlink(&secret, &path).unwrap();+ assert_eq!(+ read_transcript_prompts(&path, &TranscriptCursor::default()),+ None+ );+ assert_eq!(+ read_transcript_prompts(path.parent().unwrap(), &TranscriptCursor::default()),+ None+ );+ // Control: the same content as a regular file is read.+ fs::remove_file(&path).unwrap();+ fs::copy(&secret, &path).unwrap();+ assert_eq!(+ texts(&read_transcript_prompts(&path, &TranscriptCursor::default()).unwrap()),+ ["not a transcript"]+ );+ }}diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rsindex 4bd385f8..5e3d594a 100644--- a/crates/ai-memory-hooks/src/lib.rs+++ b/crates/ai-memory-hooks/src/lib.rs@@ -36,7 +36,9 @@ pub mod synth;pub mod workstream;pub use antigravity::{- MAX_ANTIGRAVITY_OUTPUT_BYTES, enrich_antigravity_step_output, is_output_eligible,+ MAX_ANTIGRAVITY_OUTPUT_BYTES, TranscriptCursor, TranscriptPrompt, TranscriptRead,+ antigravity_conversation_id, antigravity_transcript_path, enrich_antigravity_step_output,+ is_output_eligible, read_transcript_prompts,};// Re-export the sanitizer types from core so callers that grew updiff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex e4b07208..521ad860 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -4158,13 +4158,19 @@ async fn process_authorized(// Substantive sessions synthesize the summary page and auto-handoff below.// OpenCode's service outlives its CLI: a completed root turn publishes a// continuation checkpoint without claiming the native session has ended.- let turn_checkpoint = env.agent == AgentKind::OpenCode- && env.event == HookEvent::Stop- && env- .raw- .get("turn_checkpoint")- .and_then(serde_json::Value::as_bool)- == Some(true)+ // Antigravity has no conversation-end event at all, so a turn its model+ // finished with nothing left running in the background does the same.+ let turn_checkpoint = env.event == HookEvent::Stop+ && match env.agent {+ AgentKind::OpenCode => {+ env.raw+ .get("turn_checkpoint")+ .and_then(serde_json::Value::as_bool)+ == Some(true)+ }+ AgentKind::AntigravityCli => crate::antigravity::stop_is_turn_checkpoint(&env.raw),+ _ => false,+ }&& !managed&& !body_is_subagent(&env.raw);if matches!(env.event, HookEvent::SessionEnd) || turn_checkpoint {@@ -4302,10 +4308,10 @@ async fn process_authorized(// Other harnesses are not gated: Claude Code also sets `agent_type` on// a top-level `--agent` session, which still owns its baton.let child_session = env.agent == AgentKind::OpenCode && body_is_subagent(&env.raw);- // The opt-out covers both automatic batons: a session's end and an- // OpenCode root-turn checkpoint, which is OpenCode's only baton since- // a plugin unload no longer ends its sessions. The checkpoint still- // refreshes the summary page.+ // The opt-out covers both automatic batons: a session's end and a+ // turn checkpoint, which is OpenCode's only baton since a plugin+ // unload no longer ends its sessions, and Antigravity's since it has+ // no end event. The checkpoint still refreshes the summary page.let should_create_handoff =!managed && !child_session && state.create_handoff_on_session_end;let handoff = should_create_handoff.then(|| {@@ -14033,6 +14039,326 @@ pub(crate) mod tests {);}+ /// An Antigravity event as its hooks deliver it: `prompt` is the+ /// native hook's transcript-recovered prompt, `stop` the documented+ /// `Stop` input of a finished turn.+ fn antigravity_event(conversation: &str, event: &str, text: &str) -> HookEnvelope {+ let mut body = serde_json::json!({+ "conversationId": conversation,+ "modelName": "gemini-3-pro",+ });+ match event {+ "user-prompt" => body["prompt"] = text.into(),+ "post-tool-use" => {+ body["toolCall"] = serde_json::json!({+ "name": "run_command",+ "args": {"CommandLine": text},+ });+ body["stepIdx"] = 3.into();+ }+ "stop" => {+ body["executionNum"] = 0.into();+ body["terminationReason"] = "NO_TOOL_CALL".into();+ body["fullyIdle"] = true.into();+ }+ _ => {}+ }+ HookEnvelope::from_query_and_body(+ HookQuery {+ event: event.into(),+ agent: Some("antigravity-cli".into()),+ ..Default::default()+ },+ body,+ )+ }++ async fn antigravity_turn(+ state: &HookState,+ conversation: &str,+ text: &str,+ actor: Option<IdentityKey>,+ ) {+ for event in ["user-prompt", "post-tool-use", "stop"] {+ process(+ state,+ antigravity_event(conversation, event, text),+ actor.clone(),+ Vec::new(),+ )+ .await+ .unwrap();+ }+ }++ /// Antigravity has no conversation-end event: a finished, fully idle+ /// turn refreshes the summary page and the conversation's one baton,+ /// and leaves the native session open, the OpenCode turn-checkpoint path.+ #[tokio::test]+ async fn antigravity_idle_stop_checkpoints_page_and_baton_without_ending_the_conversation() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let conversation = "ec33ebf9-0cba-4100-8142-c61503f6c587";+ process(+ &state,+ antigravity_event(conversation, "session-start", ""),+ None,+ Vec::new(),+ )+ .await+ .unwrap();+ let session = SessionId::from_native(conversation);+ let mut previous_handoff = None;+ for text in ["Fix the login redirect", "Add a regression test"] {+ antigravity_turn(&state, conversation, text, None).await;+ assert_eq!(session_pages(&state).await.len(), 1);+ let page = state+ .reader+ .recent_pages_for_project(state.workspace_id, state.project_id, 20)+ .await+ .unwrap()+ .into_iter()+ .find(|page| page.path.as_str().starts_with("sessions/"))+ .unwrap();+ let body = state+ .wiki+ .read_page(state.workspace_id, state.project_id, &page.path)+ .unwrap()+ .body;+ assert!(body.contains(text), "{body}");+ let handoff = state+ .reader+ .latest_open_handoff(+ state.workspace_id,+ state.project_id,+ None,+ ai_memory_core::OwnerFilter::Any,+ )+ .await+ .unwrap()+ .expect("a finished turn publishes a baton");+ assert_eq!(handoff.origin.from_agent, AgentKind::AntigravityCli);+ assert_eq!(handoff.origin.from_session_id, Some(session));+ assert!(+ handoff.content.summary.contains(text),+ "{:?}",+ handoff.content+ );+ if let Some(previous) = previous_handoff {+ assert_eq!(previous, handoff.scope.id, "one baton, refreshed in place");+ }+ previous_handoff = Some(handoff.scope.id);+ assert_eq!(+ state+ .reader+ .session_end_disposition(+ session,+ state.workspace_id,+ state.project_id,+ AgentKind::AntigravityCli+ )+ .await+ .unwrap(),+ ai_memory_store::SessionEndDisposition::Open+ );+ }+ let batons = state+ .reader+ .list_handoffs(+ state.workspace_id,+ state.project_id,+ None,+ ai_memory_core::OwnerFilter::Any,+ 10,+ )+ .await+ .unwrap();+ assert_eq!(batons.len(), 1, "one baton row per live conversation");++ // `finalize-session` still closes the same conversation explicitly.+ process(+ &state,+ antigravity_event(conversation, "session-end", ""),+ None,+ Vec::new(),+ )+ .await+ .unwrap();+ assert_eq!(+ state+ .reader+ .latest_completed_session_for_project(state.workspace_id, state.project_id)+ .await+ .unwrap(),+ Some(session)+ );+ }++ #[tokio::test]+ async fn antigravity_stop_checkpoint_requires_a_finished_idle_root_unmanaged_stop() {+ for case in [+ "control",+ "busy",+ "cancelled",+ "errored",+ "web-spelling",+ "no-reason",+ "subagent",+ "managed",+ "wrong-agent",+ ] {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let conversation = format!("agy-{case}");+ for event in ["user-prompt", "post-tool-use"] {+ process(+ &state,+ antigravity_event(&conversation, event, "Real work"),+ None,+ Vec::new(),+ )+ .await+ .unwrap();+ }+ let mut stop = antigravity_event(&conversation, "stop", "");+ match case {+ "busy" => stop.raw["fullyIdle"] = false.into(),+ "cancelled" => stop.raw["terminationReason"] = "USER_CANCELED".into(),+ "errored" => stop.raw["error"] = "model unavailable".into(),+ "web-spelling" => stop.raw["terminationReason"] = "model_stop".into(),+ "no-reason" => {+ stop.raw+ .as_object_mut()+ .unwrap()+ .remove("terminationReason");+ }+ "subagent" => stop.raw["subagentType"] = "research".into(),+ "managed" => stop.managed_run = Some(ManagedRunId::new().to_string()),+ "wrong-agent" => stop.agent = AgentKind::Codex,+ _ => {}+ }+ process(&state, stop, None, Vec::new()).await.unwrap();+ let checkpointed = matches!(case, "control" | "web-spelling");+ assert_eq!(+ !session_pages(&state).await.is_empty(),+ checkpointed,+ "{case}"+ );+ assert_eq!(open_handoff_exists(&state).await, checkpointed, "{case}");+ }+ }++ /// Invariant #16 for Antigravity's turn checkpoints. Conversations+ /// never end, so every operator's parallel conversations hold live+ /// batons at once: pages stay shared, each baton stays with its owner,+ /// one conversation's turn never retires another's baton, a conversation+ /// still in use keeps its baton, and each baton is claimed exactly once.+ #[tokio::test]+ async fn antigravity_parallel_conversations_keep_owned_batons_claimed_once() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.trusted_proxy_identity = true;+ let alice = IdentityKey::User("alice".into());+ let bob = IdentityKey::User("bob".into());+ let conversations = [+ ("agy-alice-1", "alice first conversation", &alice),+ ("agy-alice-2", "alice second conversation", &alice),+ ("agy-bob-1", "bob conversation", &bob),+ ];+ for (conversation, text, owner) in conversations {+ antigravity_turn(&state, conversation, text, Some(owner.clone())).await;+ }+ let open_batons = || async {+ state+ .reader+ .list_handoffs(+ state.workspace_id,+ state.project_id,+ None,+ ai_memory_core::OwnerFilter::Any,+ 10,+ )+ .await+ .unwrap()+ .into_iter()+ .filter(|h| h.lifecycle.state == ai_memory_core::HandoffState::Open)+ .collect::<Vec<_>>()+ };+ let batons = open_batons().await;+ assert_eq!(+ batons.len(),+ 3,+ "a turn must not retire another conversation's baton"+ );+ for (conversation, _, owner) in conversations {+ let baton = batons+ .iter()+ .find(|h| h.origin.from_session_id == Some(SessionId::from_native(conversation)))+ .unwrap();+ assert_eq!(+ baton.origin.owner_user,+ Some(owner.storage_key()),+ "{conversation}"+ );+ }+ // Pages are shared: author attribution is never a read filter.+ assert_eq!(session_pages(&state).await.len(), 3);++ let receiver = || HandoffQuery {+ profile_contribute: None,+ profile_consume: None,+ profile_digest: None,+ agent: Some("claude-code".into()),+ session_id: Some(SessionId::new().to_string()),+ ..Default::default()+ };+ // Every conversation captured just now, so none is handed over yet.+ let busy = fetch_and_accept_handoff_at(+ &state,+ receiver(),+ Some(alice.clone()),+ Vec::new(),+ None,+ jiff::Timestamp::now(),+ )+ .await+ .unwrap();+ assert!(+ busy.is_none(),+ "a conversation in use keeps its baton: {busy:?}"+ );++ let quiet =+ jiff::Timestamp::now() + LIVE_BATON_QUIET_PERIOD + jiff::SignedDuration::from_secs(1);+ let claim = |actor: &IdentityKey| {+ fetch_and_accept_handoff_at(+ &state,+ receiver(),+ Some(actor.clone()),+ Vec::new(),+ None,+ quiet,+ )+ };+ // Alice gets her newest baton; it supersedes her own older quiet one+ // and never touches Bob's.+ let alices = claim(&alice).await.unwrap().expect("alice's own baton");+ assert!(alices.contains("alice second conversation"), "{alices}");+ assert!(!alices.contains("bob"), "{alices}");+ assert_eq!(open_batons().await.len(), 1);+ assert!(+ claim(&alice).await.unwrap().is_none(),+ "alice cannot reach bob's baton or reclaim her own"+ );+ let bobs = claim(&bob)+ .await+ .unwrap()+ .expect("bob's baton survived alice's claim");+ assert!(bobs.contains("bob conversation"), "{bobs}");+ assert!(claim(&bob).await.unwrap().is_none(), "claimed exactly once");+ assert!(open_batons().await.is_empty());+ }+// Live incident: a `.ai-memory.toml` naming a workspace appeared under// running OpenCode sessions, so their later events (same cwd) resolved to// a new `(workspace, project)`. Scope is not identity: those events arediff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 44f0cd6f..4aa46b8e 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -111,7 +111,10 @@ from hook paths.without a reliable true session-end hook need an explicit ending action:`ai-memory finalize-session --agent antigravity-cli` for Antigravity CLI(Codex has a native `SessionEnd` since CLI 0.145.0; `finalize-session- --agent codex` is only the fallback on older Codex).+ --agent codex` is only the fallback on older Codex). OpenCode 2 and+ Antigravity also publish a turn checkpoint on a finished `Stop`: the+ session page and the session's one open handoff are refreshed in place+ while the session stays open.The command selects the latest matching open session and enters the samecanonical SessionEnd path as a native hook. Generated session-pagefrontmatter records `session_id` plus the immutable `sessions.agent_kind`@@ -332,8 +335,8 @@ metadata-only notice naming the exact handoff id and leaves the row open foran explicit `memory_handoff_accept`; the managed event range is still claimed.With server-wide `[handoff].create_on_session_end = false`, session end writesthe summary page and enqueues consolidation but skips creating an automatic-baton, and an OpenCode root-turn checkpoint refreshes the page without one-(#1043). Manual handoffs take precedence;+baton, and an OpenCode or Antigravity turn checkpoint refreshes the page+without one (#1043). Manual handoffs take precedence;otherwise the newest cwd-eligible automatic handoff is delivered, and thatsame transaction expires older eligible automatic handoffs while preservingmanual and sibling-directory work. Insertion also expires prior open automatic@@ -401,10 +404,14 @@ harness cwd. Session identity and compiled-session ownership do not move; onlythe raw observations are attributed to the touched project (#932; #1199:Hermes reports its process cwd and locates each tool by `workdir`/`path`).-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.+Antigravity's `SessionStart` maps to `session-start`. Its `PreInvocation` hook+fires before every model call, so the bridge acts only on the documented+`invocationNum = 0` payload, the start of a user turn: it records the turn's+prompts from the conversation's transcript (no Antigravity payload carries a+prompt), and on builds without `SessionStart` the first turn's call posts+`session-start` in its place, once per conversation. Later invocations are+ignored before spool or network side effects. A `Stop` that finished the turn+with nothing left running is a turn checkpoint, as for OpenCode 2.Unknown events do **not** expand the enum and, by default, leave nosource-event metadata in storage; they collapse to `other`. Third-party@@ -1140,7 +1147,7 @@ per_user = false # shared + own slots in agent context[handoff] # optional server-wide handoff policyclaim_on_session_start = true # false offers metadata; explicit accept claims-create_on_session_end = true # false stops automatic handoffs at session end and OpenCode turn checkpoints+create_on_session_end = true # false stops automatic handoffs at session end and OpenCode/Antigravity turn checkpoints[profile] # cross-project profile (docs/cross-project-profile.md)enabled = "auto" # auto: on for single-user, off for multi-user; true / false@@ -1331,7 +1338,7 @@ drop_events = [] # whole hook event kinds to drop (e.g. ["pre-t# call that never finished ends lifecycle-only; post-tool-use# loses results and the completed-call count; stop loses the# opt-in assistant reply,- # the normal-completion signal and OpenCode's turn checkpoint;+ # the normal-completion signal and OpenCode's and Antigravity's turn checkpoints;# pre-compact/post-compaction lose the compaction checkpoint# and its rewrite job (the session is not ended);# notification loses the observation;diff --git a/docs/desktop/antigravity.md b/docs/desktop/antigravity.mdindex 6ca19381..94882dd4 100644--- a/docs/desktop/antigravity.md+++ b/docs/desktop/antigravity.md@@ -46,10 +46,14 @@ Official: <https://antigravity.google/docs/hooks/>- Config: workspace **`.agents/hooks.json`** or global**`~/.gemini/config/hooks.json`** (both read by 2.0, CLI, and IDE);plugin-bundled hooks also supported.-- Events: `PreToolUse`, `PostToolUse` (matcher = tool name regex:- `run_command`, `view_file`, `write_to_file`, `replace_file_content`,- `grep_search`, `invoke_subagent`, …), `PreInvocation`, `PostInvocation`- (around each model call), `Stop`.+- Events: `SessionStart` (once per new conversation, before the first model+ call; documented in the hook reference bundled with `agy` 1.4.0 and App+ 2.24.0, absent from `agy` 1.3.0), `PreToolUse`, `PostToolUse` (matcher =+ tool name regex: `run_command`, `view_file`, `write_to_file`,+ `replace_file_content`, `grep_search`, `invoke_subagent`, …),+ `PreInvocation`, `PostInvocation` (around each model call), `Stop`+ (`terminationReason`, `fullyIdle`). No event marks a conversation's end, and+ none carries the user's prompt.- Payload (stdin JSON, camelCase): `conversationId`, `workspacePaths`,**`transcriptPath`**, `artifactDirectoryPath`, `modelName`, plus`toolCall`, `stepIdx`, etc. Handlers are shell commands with a `timeout`@@ -63,9 +67,12 @@ Official: <https://antigravity.google/docs/hooks/>`~/.gemini/config/hooks.json`, which the IDE also loads, so globalcapture likely already extends to IDE sessions, with the IDE distinguishableby its `transcriptPath` prefix (`antigravity-ide/brain/...`). Differences to-handle: no `SessionStart`/`SessionEnd` events (session boundaries must be-inferred from PreInvocation/Stop), and `cwd` comes as `workspacePaths[]`-rather than a single `cwd`. Needs a live verification pass on the IDE.+handle: no `SessionEnd` event (a finished `Stop` is a turn checkpoint+instead), no prompt in any payload (read from the transcript), older builds+without `SessionStart` (the first turn's `PreInvocation` stands in), and `cwd`+comes as `workspacePaths[]` rather than a single `cwd`. Needs a live+verification pass on the IDE. Implemented in 3.2 (#TBD); see+[`plan.md`](plan.md#phase-1--antigravity-ide-capture-parity-smallest-new-code-step).**Verified with the CLI (`agy` 1.3.0, 2026-10-08; see`verification-2026-10.md`):** a workspace `.agents/hooks.json` runs with nodiff --git a/docs/desktop/plan.md b/docs/desktop/plan.mdindex d16df3b2..d537dcd7 100644--- a/docs/desktop/plan.md+++ b/docs/desktop/plan.md@@ -64,6 +64,35 @@ The research's best new target, ahead of the RFC's `.mcpb`:- Tests: payload-mapping unit tests against the documented schema(camelCase fields; `<app_data_dir>` variants per surface).+Status (3.2, #TBD): the premise above that Antigravity has no SessionStart is+out of date. The hook reference bundled with `agy` 1.4.0 and App 2.24.0 (and+<https://antigravity.google/docs/hooks/>) documents `SessionStart`, fired once+per new conversation before the first model call; `agy` 1.3.0, verified here+on 2026-10-08, fired none. There is still no end event and no prompt in any+payload. What shipped, under the existing `antigravity-cli` agent kind:++- `SessionStart` posts session-start and injects the handoff as an+ `injectSteps` `systemMessage`, which persists across turns (the old+ `ephemeralMessage` was dropped after the first). `PreInvocation` gets its+ own `pre-invocation` handler; its invocation zero stands in for+ `SessionStart` on builds without it, gated once per conversation by the+ existing `briefed/agy-start-<conversationId>` marker, so the two never+ deliver twice.+- Prompts come from `transcriptPath`: at each turn start, at `SessionStart`+ and at `Stop`, the native hook reads the `USER_INPUT` steps written since+ its per-conversation cursor and spools them as `user-prompt` events.+ Containment, bounds and symlink refusal are recorded in+ [`../security-boundaries.md`](../security-boundaries.md).+- A `Stop` with a normal `terminationReason` (`NO_TOOL_CALL`, or `model_stop`+ as the web page spells it) and `fullyIdle: true` takes OpenCode 2's+ turn-checkpoint path: summary page and one refreshed baton, session left+ open. `finalize-session` remains the explicit close and the way to queue+ opt-in consolidation.+- `PostInvocation` stays unwired: the turn checkpoint covers what a flush+ there would have done.+- Not done: the `.agents/hooks.json` workspace install option, and the IDE+ verification pass.+## Phase 2 — scope & dedup polish for desktop-originated sessions- Decide scratch-workspace routing: single `desktop/claude-scratch` project@@ -125,7 +154,9 @@ The research's best new target, ahead of the RFC's `.mcpb`:7. Antigravity's SessionStart mapping fired on every user turn(`invocationNum` restarts per turn): resolved — gated per conversation bya `briefed/agy-start-<conversationId>` marker in the native, shell and- PowerShell hooks.+ PowerShell hooks. Current builds fire a native `SessionStart`, which is now+ wired; the same marker keeps the `PreInvocation` fallback from delivering+ a second handoff.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/install.md b/docs/install.mdindex f7636cf4..1685a90d 100644--- a/docs/install.md+++ b/docs/install.md@@ -1362,15 +1362,52 @@ ai-memory finalize-sessionai-memory finalize-session --session-id <uuid>```-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. 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:+### Antigravity lifecycle hooks++Antigravity (the `agy` CLI, the desktop App and the IDE, which read the same+global `~/.gemini/config/hooks.json`) has no conversation-end event, and none+of its hook payloads carries the user's prompt. `install-hooks --agent+antigravity-cli` wires five of its+[documented hooks](https://antigravity.google/docs/hooks/):++- `SessionStart` records the session start and injects a pending handoff as+ an `injectSteps` system message, which stays in the conversation for later+ turns.+- `PreInvocation` runs before every model call. Only `invocationNum = 0`, the+ start of a user turn, does anything: the native hook reads the turn's prompt+ from the conversation's transcript (`transcriptPath`) and records it as a+ user prompt. On a build that fires no `SessionStart`, the first turn's+ `PreInvocation` records the start and claims the handoff instead. A+ per-conversation marker keeps either start to once, so a handoff created+ while the conversation winds down stays open for the next session.+- `PreToolUse` and `PostToolUse` capture tool calls.+- `Stop` ends one execution loop. When the model finished the turn+ (`terminationReason` `NO_TOOL_CALL`, spelled `model_stop` on the web page)+ and nothing is left running (`fullyIdle: true`), the server writes a turn+ checkpoint: it refreshes the session's summary page and its one open+ handoff and leaves the conversation open, the path OpenCode 2 uses. Prompts+ the transcript gained since the turn started are recorded ahead of the+ `Stop`, so the checkpoint includes them. A cancelled, failed or+ budget-limited loop is not a checkpoint.++The transcript is read only when `transcriptPath` names the conversation's own+`~/.gemini/<app>/brain/<conversationId>/.system_generated/logs/transcript.jsonl`+(or the `transcript_full.jsonl` beside it, which the CLI reports), with+`<app>` one of `antigravity`, `antigravity-cli` or `antigravity-ide`. Another+file, another conversation's transcript and a symlinked directory that leads+out of the conversation are refused. One hook reads at most 8 MiB, and a+cursor under `<data_dir>/hook-state/antigravity-transcripts/` resumes where+the previous read stopped. Steps a hook injected are skipped, the text inside+the CLI's `<USER_REQUEST>` wrapper is kept, and each prompt is capped and+scrubbed like any other before the server sanitizes it again. Its ingest key+comes from the conversation and step, so a repeated read stores it once. The+shell and PowerShell fallback hooks do not parse the transcript, and a+checkout the capture allowlist does not admit is not read at all.++Nothing tells a closed Antigravity window from a conversation still in use,+so a checkpoint's handoff goes to a new session in the same project only once+the conversation has been quiet for 10 minutes. To hand it over at once, or+to queue opt-in SessionEnd consolidation, close the conversation explicitly:```bashai-memory finalize-session --agent antigravity-cli@@ -1381,16 +1418,23 @@ ai-memory finalize-session --agent antigravity-cliai-memory finalize-session --agent antigravity-cli --reopen --session-id <uuid>```-Antigravity's hooks carry no prompt, so before the session-end-`finalize-session` replays the session's typed prompts from `agy`'s-`~/.gemini/antigravity-cli/history.jsonl` (only lines whose conversation and-workspace match the session), and the summary page and handoff are built with-them. Each prompt is keyed as `backfill` keys it, so a re-close stores it once-and a prompt typed after the first finalize arrives with the next. A checkout-the capture allowlist does not admit sends none, `--all-owners` replays none-(other users' prompts are not in this machine's history), and a missing or-unreadable `history.jsonl` only prints a warning. `agy -p` runs write no-`history.jsonl` line, so they have no prompt to replay.+For a session whose prompts the live hooks did not capture (the shell+fallback hooks, or an install from before transcript capture),+`finalize-session` replays its typed prompts from `agy`'s+`~/.gemini/antigravity-cli/history.jsonl` before the session-end (only lines+whose conversation and workspace match the session), and the summary page and+handoff are built with them. Each prompt is keyed as `backfill` keys it, so a+re-close stores it once and a prompt typed after the first finalize arrives+with the next. A checkout the capture allowlist does not admit sends none,+`--all-owners` replays none (other users' prompts are not in this machine's+history), and a missing or unreadable `history.jsonl` only prints a warning.+`agy -p` runs write no `history.jsonl` line, so they have no prompt to replay.++Rerun `ai-memory install-hooks --agent antigravity-cli --apply` after+upgrading. An install from an earlier release runs its `session-start` handler+on `PreInvocation` and has no `SessionStart` entry; the native hook reads that+as the first-turn fallback, with transcript prompts and turn checkpoints, until+the reinstall adds `SessionStart`.### Devin CLI@@ -2335,7 +2379,8 @@ token, so export that variable where you launch `prime-agent`.For clients with `install-hooks` support, the capture path handleshandoff injection at session start or the client's closest equivalent, exceptfor Zero's no-stdout SessionStart behavior. Grok delivers on the first-`PostToolUse` instead (Antigravity CLI uses `PreInvocation`).+`PostToolUse` instead (Antigravity uses `SessionStart`, or the first turn's+`PreInvocation` on builds without it).#### Cline CLI and FreeBuffdiff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex 83b3b119..cbaf4d35 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -919,7 +919,7 @@ The rendered snippet writes to `mcp_config.json` under `mcpServers`:Antigravity CLI uses a named-groups hook format. Each top-level keyis a hook group name; inside, event arrays map to handlers. Toolevents (`PreToolUse`, `PostToolUse`) use nested shape with matcher;-lifecycle events (`PreInvocation`, `Stop`) use flat shape.+lifecycle events (`SessionStart`, `PreInvocation`, `Stop`) use flat shape.```bash# One-shot via CLI:@@ -931,12 +931,18 @@ The rendered hooks config looks like:```json{"ai-memory": {- "PreInvocation": [+ "SessionStart": [{"type": "command","command": "AI_MEMORY_HOOK_URL=http://127.0.0.1:49374 /path/to/session-start.sh"}],+ "PreInvocation": [+ {+ "type": "command",+ "command": "AI_MEMORY_HOOK_URL=http://127.0.0.1:49374 /path/to/pre-invocation.sh"+ }+ ],"PreToolUse": [{"matcher": "",@@ -983,20 +989,25 @@ The rendered hooks config looks like:as `CLIXML` hook stderr. Rerun`install-hooks --agent antigravity-cli --apply` after upgrading to refreshexisting entries.-- The `PreInvocation` event fires before each model call (not just at- 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 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 close the session and,- when it contains substantive events, create the final summary and automatic- handoff and queue opt-in SessionEnd consolidation. If the conversation+- `SessionStart` delivers a pending handoff through Antigravity's+ `injectSteps[].systemMessage` output, which stays in the conversation for+ later turns. `PreInvocation` fires before each model call; at+ `invocationNum = 0`, the start of a user turn, the native hook records the+ turn's prompt from the conversation's transcript, and on builds without+ `SessionStart` the first turn's `PreInvocation` delivers the handoff+ instead.+- Antigravity has no conversation-end hook. A `Stop` that finished the turn+ with nothing left running writes a turn checkpoint (summary page and one+ refreshed handoff, conversation left open), which a new session in the+ project receives once the conversation has been quiet for 10 minutes. Run+ `ai-memory finalize-session --agent antigravity-cli` to close the session at+ once and queue opt-in SessionEnd consolidation. If the conversationcontinues after that first finalize, re-close it with`ai-memory finalize-session --agent antigravity-cli --reopen --session-id <uuid>`so the session-end path re-runs over the new observations (re-running with- nothing new is a harmless no-op).+ nothing new is a harmless no-op). See+ [`docs/install.md`](install.md#antigravity-lifecycle-hooks) for the+ transcript read's limits.- `memory_handoff_begin` always creates an explicit manual handoff with no`from_session_id` and `from_agent = other`; it is project-wide for cwdmatching but belongs to the creating operator by default. Pass `shared=true`diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 389a57f9..12a48d53 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -47,9 +47,9 @@ means the boundary is not built yet.| 3i | Cross-project `GET /admin/recent` (no `workspace`/`project`, the `ai-memory recent --global` path) is root-only on a multi-user server | `ai-memory-mcp/src/admin.rs` `handle_recent` runs the no-scope branch through `ReaderPool::recent_pages_global` as `OPERATOR` (every project, each hit tagged with its workspace and project); the route sits in the operational router under `require_root_for_multiuser_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`), so a DB user or proxy-asserted user never reaches the unfiltered read. A partial scope is still a 400, never a silent global fallback; an unknown scoped project is a 404 and does not leak another project's pages. `ai-memory-cli/src/commands/recent.rs` sends no scope only when `--global` is passed, and clap rejects `--global` with `--workspace`/`--project` | MCP `admin_status_search.rs` `global_recent_never_reaches_a_non_root_caller` (a restricted project the user holds no grant on, for both a DB-user deployment and a trusted-proxy deployment with no `users` rows: user 403 and anonymous 401 with neither the sentinel path nor the restricted snippet in the body; root control 200 with both projects' hits), `global_recent_tags_each_hit_with_its_workspace_and_project`, `recent_rejects_partial_scope_instead_of_global_fallback`, `recent_unknown_scope_is_404_and_does_not_leak_other_projects`; the shared `admin.rs` all-admin 403/401 route matrix includes `/admin/recent`; CLI `cli.rs` `recent_global_parses_and_conflicts_with_an_explicit_scope` | STRONG. Bite check: with the gate's operator test forced off (`authorize(Capability::Admin, false)`) the refusal test fails on the DB-user case (200 instead of 403) || 4 | Handoff single-claim / no-steal | `ai-memory-store/src/ops.rs` `accept_handoff_in_transaction` (metadata `state='open'` guard + atomic CAS; the receiver-session check, which requires the receiving session to exist in the claim's own workspace, project and agent kind and refuses with `InvalidState` before the handoff row is touched; an ended receiver is final EXCEPT for the agents where `AgentKind::reuses_session_id_after_end()` holds — Grok and Kimi Code, whose harnesses reuse the native session id across SessionEnd→resume, so accepting reopens `ended_at` only after the claim-once guard) | `multi_session.rs` `a_second_accept_cannot_steal_an_accepted_handoff`; `handoff_ownership.rs` `another_operator_cannot_claim_the_handoff`; `multi_session.rs` `handoff_accept_rejects_foreign_or_missing_receiver_session` (receivers from a sibling project, another workspace, a different agent kind, and a nonexistent session are each refused as `InvalidState` with the handoff left open and every `accepted_*` column NULL; the matching receiver claims it; the same receiver retrying and a second matching session get `false` with the first claim intact; fails with the `project_id` or `agent_kind` predicate, or the missing-session refusal, removed. The `workspace_id` predicate is redundant defence in depth: project ids are globally unique, so the cross-workspace receiver is already caught by `project_id`); `multi_session.rs` `accept_reopens_an_ended_receiver_session_but_keeps_claim_once` (Grok reopen + no-steal) and `accept_reopens_an_ended_kimi_receiver_but_keeps_every_guard` (Kimi Code resume claims and reopens `ended_at`; adversarial controls: an ended claude-code receiver stays refused, a kimi-code receiver in another project stays refused, and the already-claimed guard still refuses the resumed kimi session a second baton) | STRONG || 4b | Handoff owner-scoped recovery (`any_owner` admin gate) | `ai-memory-mcp/src/server.rs` `require_admin_capability` on `memory_handoff_accept`/`_cancel` `any_owner` | `handoff_admission.rs` — cancel gate + **accept gate** (adversarial: non-admin `any_owner` accept refused) | STRONG |-| 4c | Turn-checkpoint baton is owner+scope-bound | `ai-memory-store/src/ops.rs` `checkpoint_session_handoff` — reads the session's own `(workspace, project, owner_user)` from `sessions WHERE id=?1 AND ended_at IS NULL`, refuses on scope/owner mismatch, refreshes only that session's own `state='open'` baton (id preserved), returns `None` when the session already ended | `ops.rs` `checkpoint_session_handoff_refreshes_only_the_live_sessions_own_baton` (#865) | STRONG |+| 4c | Turn-checkpoint baton is owner+scope-bound | `ai-memory-store/src/ops.rs` `checkpoint_session_handoff` — reads the session's own `(workspace, project, owner_user)` from `sessions WHERE id=?1 AND ended_at IS NULL`, refuses on scope/owner mismatch, refreshes only that session's own `state='open'` baton (id preserved), returns `None` when the session already ended | `ops.rs` `checkpoint_session_handoff_refreshes_only_the_live_sessions_own_baton` (#865); `router.rs` `antigravity_parallel_conversations_keep_owned_batons_claimed_once` (Antigravity checkpoints of two operators each stamp their own owner and reach only that operator), `antigravity_stop_checkpoint_requires_a_finished_idle_root_unmanaged_stop` (a busy, cancelled, failed, reasonless, subagent, managed or non-Antigravity `Stop` publishes nothing; the finished `NO_TOOL_CALL`/`model_stop` controls do) | STRONG || 4d | Native session rebind / drifted-end is owner+agent+cwd CAS | `ai-memory-store/src/ops.rs` — `session.moved` rebind gated on `agent==OpenCode` + `ended_at IS NULL` + lexical `normalize_cwd(stored)==normalize_cwd(from)`; `expire_same_cwd_auto_handoffs` AND-gated on `owner_user IS ?4 AND id IS NOT ?5` and on the source not being another still-open session (row 4e, #883); drifted `SessionEnd` ends only same owner+agent+cwd | `ops.rs` `native_move_rebinds_live_session_only_from_its_current_cwd`, `native_move_rejects_foreign_owner_and_ignores_completed_replay`, `drifted_session_end_ends_only_the_same_actor_agent_and_cwd` (#865) | STRONG |-| 4e | A live session's baton stays its own until the session is quiet | `ai-memory-store/src/ops.rs` - `expire_same_cwd_auto_handoffs` spares batons of other open sessions; `accept_handoff_in_transaction(.., busy_since)` re-checks inside the claim that the source is not an open session with observations after the cutoff, and its sweep `expire_superseded_auto_handoffs(.., busy_since)` spares a busy open session's baton (every open session's when `None`, the explicit MCP accept); `reader.rs` `startup_handoff` selects with the same cutoff; `ai-memory-hooks/src/router.rs` `LIVE_BATON_QUIET_PERIOD` | `multi_session.rs` `parallel_live_sessions_keep_their_own_checkpoint_batons`, `startup_claim_rechecks_the_source_and_sweeps_only_quiet_open_batons`; `router.rs` `opencode_parallel_live_batons_are_owned_and_wait_for_quiet` - each fails with its guard removed | STRONG |+| 4e | A live session's baton stays its own until the session is quiet | `ai-memory-store/src/ops.rs` - `expire_same_cwd_auto_handoffs` spares batons of other open sessions; `accept_handoff_in_transaction(.., busy_since)` re-checks inside the claim that the source is not an open session with observations after the cutoff, and its sweep `expire_superseded_auto_handoffs(.., busy_since)` spares a busy open session's baton (every open session's when `None`, the explicit MCP accept); `reader.rs` `startup_handoff` selects with the same cutoff; `ai-memory-hooks/src/router.rs` `LIVE_BATON_QUIET_PERIOD` | `multi_session.rs` `parallel_live_sessions_keep_their_own_checkpoint_batons`, `startup_claim_rechecks_the_source_and_sweeps_only_quiet_open_batons`; `router.rs` `opencode_parallel_live_batons_are_owned_and_wait_for_quiet`, `antigravity_parallel_conversations_keep_owned_batons_claimed_once` (Antigravity conversations never end, so every one holds a live baton: none is handed over while busy, a claim supersedes only the claimer's own older quiet baton, and each is claimed once) - each fails with its guard removed | STRONG || 4f | Finalize-on-exit closes only a session the run provably owns (invariant #16) | `ai-memory-cli/src/commands/run.rs` `finalize_hookless_session` runs only for `harness.lacks_session_end_hook()` harnesses (Command Code, Kiro v2/v3, Antigravity); `own_native_session` returns a session only when it is named, chosen before the spawn, or linked under this run's own id in this checkout — a merely *discovered* native session (possibly a concurrent launch's) is never finalized | `run.rs` `a_session_linked_during_the_run_wins_over_discovery` — `own_native_session` returns `None` for the unlinked and other-checkout (`nested`) cases, so a foreign/concurrent session is refused; the named/linked control is finalized (#944) | STRONG || 4g | `memory_handoff_accept` `status` never points a caller at another session's baton | `ai-memory-store/src/reader.rs` `handoff_claimed_by_live_session` — the caller-supplied session id (header or native `_meta`, routing-only per row 6b) selects which claim to check, but the answer is bounded by the resolved `(workspace_id, project_id)`, the authenticated `handoff_owner_sql` owner filter, `state='accepted'`, and a still-open receiving session; `ai-memory-mcp/src/server.rs` `unclaimed_handoff` reports `consumed_by_hook` only on that match (and, for a requested `handoff_id`, only when it is the matched row), `none_pending` otherwise | `handoff_ownership.rs` `a_session_start_claim_is_confirmed_only_to_its_own_live_session` (forged session id under another operator, unattributed reader, foreign project, sibling session and ended session all empty; owner and root controls see the claim); `ai-memory-mcp` `tests/suite/handoff_identity.rs` `consumed_by_hook_is_reported_only_to_the_session_that_claimed_it` (over the production transport: a colleague forwarding the session id, the owner from another session, and a request with no session id all get `none_pending`; the claiming session gets `consumed_by_hook`) | STRONG || 4h | Offer-mode SessionStart never consumes or injects handoff-controlled text | `ai-memory-hooks/src/router.rs` `fetch_and_accept_handoff_at` branches on the startup configuration before admission/claim and `render_handoff_notice` emits only typed metadata (`HandoffId`, `AgentKind`, computed age); the normal writer CAS remains the only later claim path | `router.rs` `handoff_notice_is_metadata_only_and_never_carries_the_summary` plants hostile summary/questions/steps/files; `offer_mode_leaves_the_baton_open_and_notice_omits_the_summary` exercises the production hook route, asserts the row remains open, then proves the legitimate exact-id writer claim still consumes it (#1030) | STRONG |@@ -136,6 +136,7 @@ means the boundary is not built yet.| 26 | Cross-harness native-history continuation stays checkout-scoped and client-local | `ai-memory-store/src/workstream.rs` `prepare_run` selects the newest current native session only when its harness differs from the destination and pins that typed identity on the run before destination linking can change recency; `ai-memory-cli/src/commands/run.rs` validates the returned `NativeSessionIdentity`, resolves only known adapter flavors, requires `native_session_in_checkout`, exports through the bounded read-only adapter, and writes an untrusted-history dossier to a private temporary directory exposed only to the child as `AI_MEMORY_PREVIOUS_SESSION_HISTORY`; the server wire type deliberately has no path/content field and same-harness launches select no source; `ai-memory-hooks/src/router.rs` keeps the server-authored resume directive outside the untrusted-history fence while fencing the transcript evidence itself, and `ai-memory-core/src/routing_snippet.rs` gives installed project instructions the same wrapper-variable-gated fallback | Core `prepare_response_carries_only_previous_native_identity`, `older_prepare_response_defaults_to_no_adoption`, and `snippets_route_managed_continue_to_the_previous_native_history`; store `managed_adoption_stops_after_any_harness_links_the_workstream` (switch control, destination-link recency cannot replace the pinned source, same-harness refusal); hooks `managed_context_points_at_local_history_on_a_harness_switch` (no session id rendered, directive precedes the untrusted fence); CLI `previous_session_history_is_private_local_and_checkout_scoped` (legitimate control, foreign checkout refused, private local file removed with its owner) | STRONG for checkout isolation, prompt-boundary placement, and server path/content privacy. The dossier is a bounded visible-history projection, not raw hidden reasoning; if the source store is absent, remote, unreadable, or over bounds, the child receives only the portable ledger and handoff || 27 | Plain-HTTP human authentication stays fail-closed beyond loopback unless the operator supplies the dedicated dangerous override (#1383) | `ai-memory-cli/src/cli.rs` exposes `serve --allow-insecure-human-auth` separately from `--allow-insecure-no-auth`; `serve.rs` `validate_http_exposure` accepts it only when authentication and human mode are both active and the listener is non-loopback with a Non-Secure cookie, while the ordinary unauthenticated guard still runs otherwise. `HttpExposure::InsecureHumanAuthByOverride` gives that path its own unconditional stderr banner and structured warning, naming passwords, API credentials, session cookies, and memory data as plaintext. The default remains refusal, and `secure_cookie=true` or loopback remains the safe path | `serve.rs` `human_auth_non_loopback_requires_secure_cookie_posture` (default refusal, the no-auth override cannot substitute, the dedicated override succeeds, and that override cannot expose a server with no authentication even under inconsistent human-mode input; secure-cookie and loopback controls), `every_unsafe_exposure_produces_an_operator_banner` (the dedicated banner names the flag and session-cookie risk), and `cli.rs` `serve_parses_insecure_transport_overrides` (both dangerous flags remain distinct) | STRONG for the startup boundary. This is an explicit operator acceptance of transport risk, not encryption; authorization, CSRF, rate limits, Host validation, and the unauthenticated exposure refusal are unchanged |+| 28 | An Antigravity hook reads, and uploads as prompts, only the named conversation's own transcript, within bounds | `ai-memory-hooks/src/antigravity.rs` `antigravity_transcript_path` accepts the payload's `transcriptPath` only when it is absolute, has no `..`, names `transcript.jsonl` or `transcript_full.jsonl`, and its canonical directory equals `canonical(<home>/.gemini/<app>/brain)/<conversationId>/.system_generated/logs` for `<app>` `antigravity`, `antigravity-cli` or `antigravity-ide`, with `conversationId` a plain id (`antigravity_conversation_id`); `read_transcript_prompts` opens only a regular, non-symlink file that is still the same file once open (`open_regular_file`), reads at most `MAX_TRANSCRIPT_SCAN_BYTES` per hook and parses lines up to `MAX_TRANSCRIPT_LINE_BYTES`, and returns only `USER_INPUT` steps whose `source` is absent or `USER_EXPLICIT`; `ai-memory-cli/src/commands/hook.rs` `antigravity_transcript_prompt_events` runs inside the spool block, so after the capture allowlist, routing, server-profile and external-capture gates, with the home `run_with_payload` resolved once; each prompt is capped and scrubbed client-side, keyed by conversation and step, and sanitized again by the server (row 7) | `antigravity.rs` `transcript_path_refuses_anything_outside_the_conversations_own_logs` (another conversation's transcript, the same layout outside the home, another file in the logs directory, an unknown app directory, `..`, a traversal or empty id, a relative path, a missing or non-string path; the conversation's own transcript is the control), `transcript_path_refuses_symlinked_directories_that_leave_the_conversation` (a symlinked `.system_generated` and `brain/<id>` refused; a symlinked `~/.gemini` accepted as the control), `transcript_reader_refuses_symlinks_and_special_files` (a symlinked transcript and a directory refused; the same bytes as a regular file are read), `skips_injected_malformed_empty_and_non_prompt_steps`, `a_line_longer_than_the_scan_budget_is_skipped_across_reads`, `one_read_returns_a_bounded_number_of_prompts`; `hook.rs` `antigravity_transcript_reads_are_confined_to_the_conversations_own_logs` (end to end through the native hook: a forged path outside the home, another conversation's transcript and an arbitrary JSONL file under the home spool no prompt; the conversation's own transcript spools one), `antigravity_transcript_prompts_follow_the_capture_allowlist` (a repository the allowlist leaves out is not read) | STRONG on Unix; the symlink cases are `cfg(unix)`, and elsewhere the canonical-directory check still runs |### IBM Bob evidencediff --git a/docs/support-matrix.md b/docs/support-matrix.mdindex 909e8d20..d0141567 100644--- a/docs/support-matrix.md+++ b/docs/support-matrix.md@@ -32,7 +32,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` 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). Skills: Antigravity reads workspace skills from `.agents/skills` and global skills from `~/.gemini/config/skills` (App and IDE) and `~/.gemini/antigravity-cli/skills` (CLI), not from `~/.agents/skills` ([Antigravity docs](https://antigravity.google/docs/skills/)); `install-skills --scope global --agent antigravity` and `setup` write the managed skills into both global roots, and `uninstall --only skills` sweeps them. |+| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias; per Antigravity's docs the desktop App and the IDE read the same global `~/.gemini/config/hooks.json`). `SessionStart` delivers the handoff as an `injectSteps` system message that stays in the conversation. `PreInvocation` with `invocationNum = 0` starts each user turn: the native hook records the turn's prompt from the conversation's own transcript, since no Antigravity hook payload carries it, and on builds without `SessionStart` the first turn's `PreInvocation` stands in for it, once per conversation. A `Stop` that finished the turn with nothing left running (`terminationReason` `NO_TOOL_CALL` or `model_stop`, `fullyIdle: true`) writes a turn checkpoint: the summary page and the conversation's one handoff are refreshed and the conversation stays open; a new session in the project receives that handoff once the conversation has been quiet for 10 minutes. There is still no conversation-end event: `ai-memory finalize-session --agent antigravity-cli` closes a conversation at once, hands its baton over and queues 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). Skills: Antigravity reads workspace skills from `.agents/skills` and global skills from `~/.gemini/config/skills` (App and IDE) and `~/.gemini/antigravity-cli/skills` (CLI), not from `~/.agents/skills` ([Antigravity docs](https://antigravity.google/docs/skills/)); `install-skills --scope global --agent antigravity` and `setup` write the managed skills into both global roots, and `uninstall --only skills` sweeps them. || 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). `install-hooks --agent grok --apply` and `install-skills --scope global --agent grok` also write `$GROK_HOME/rules/ai-memory-handoff.md` so the first turn calls `memory_handoff_list` through `use_tool` with the qualified catalog key `ai-memory__memory_handoff_list` (Grok reaches MCP tools only through that meta-tool) ahead of any file read, correcting `workspace`/`project` from `./.ai-memory.toml` only when that list is empty or a scope error; the first `PostToolUse` then prints `hookSpecificOutput.additionalContext` with the pending handoff and an opted-in `[briefing]`. If that rule is absent and 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`). A prompt starting with `reload context` receives a compaction recap on the next `PostToolUse` `additionalContext`, not with the prompt (see [`usage.md`](usage.md#reload-context-after-a-compaction)). || 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` when the token is passed explicitly; a token-file install gets a stdio `ai-memory mcp-bridge --no-session-id` entry instead) + 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`. Zero runs hooks in its sandbox, which by default denies network (loopback too) and writes outside the workspace, so events stay in the hook spool: allow `sandbox.network` and add the ai-memory data dir to `sandbox.additionalWriteRoots` in the global `~/.config/zero/config.json` (network allow covers every Zero shell command; `sessionEnd` then delivers in-process within a fixed 10-second budget, since the sandbox kills detached drainers), or run `ai-memory hook-drain` from a normal shell (see [`mcp-install.md`](mcp-install.md#zero-gitlawbzero)). |diff --git a/docs/usage.md b/docs/usage.mdindex 2f039bae..1c42a906 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -72,11 +72,11 @@ project. Root-authorized recovery can pass `any_owner: true` tothat switch.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.+are still running. In particular, Antigravity fetches a handoff only once per+conversation: on `SessionStart`, or on builds without it, on the first turn's+`PreInvocation` with invocation zero. Its later turns and model calls never+fetch one, so 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 bydiff --git a/hooks/antigravity-cli/pre-invocation.ps1 b/hooks/antigravity-cli/pre-invocation.ps1new file mode 100644index 00000000..190174d9--- /dev/null+++ b/hooks/antigravity-cli/pre-invocation.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "session-start" -Agent "antigravity-cli" -FetchHandoff -AntigravityStartOutput -AntigravityPreInvocation+exit 0diff --git a/hooks/antigravity-cli/pre-invocation.sh b/hooks/antigravity-cli/pre-invocation.shnew file mode 100755index 00000000..0e7fba88--- /dev/null+++ b/hooks/antigravity-cli/pre-invocation.sh@@ -0,0 +1,49 @@+#!/bin/sh+# antigravity-cli PreInvocation hook. Invocation zero starts a user turn; on+# an Antigravity build that fires no SessionStart, the first one starts the+# conversation the way session-start.sh does, and its per-conversation marker+# keeps every later turn a no-op. The native hook also records the turn's+# prompt from the transcript; this shell fallback does not parse it.+_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)+# A later invocation, or a missing or malformed counter, fails closed so it+# can never consume a handoff.+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")+# 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")+# Shared with session-start.sh: whichever start boundary comes first posts+# session-start and claims the 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"+fi+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}${SESSION_QS}${BRIEF_QS}" 2>/dev/null || true)+if [ -n "$HANDOFF" ]; then+ printf '{"injectSteps":[{"systemMessage":{"systemMessage":'+ printf '%s' "$HANDOFF" | ai_memory_json_string+ printf '}}]}\n'+else+ printf '{}\n'+fi+exit 0diff --git a/hooks/antigravity-cli/session-start.ps1 b/hooks/antigravity-cli/session-start.ps1index b659c880..e822f318 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 -AntigravityPreInvocationOutput+Invoke-AiMemoryHook -Event "session-start" -Agent "antigravity-cli" -FetchHandoff -AntigravityStartOutputexit 0diff --git a/hooks/antigravity-cli/session-start.sh b/hooks/antigravity-cli/session-start.shindex 45771e1b..393eeb75 100755--- a/hooks/antigravity-cli/session-start.sh+++ b/hooks/antigravity-cli/session-start.sh@@ -1,14 +1,18 @@#!/bin/sh-# 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.+# antigravity-cli SessionStart hook (and PreInvocation on installs from+# before SessionStart was wired). Forwards the event JSON to the ai-memory+# server, then injects any pending handoff as a system message that stays in+# the conversation, using Antigravity's JSON stdout contract._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)-if ! ai_memory_antigravity_is_initial_invocation "$PAYLOAD"; then+# Only SessionStart omits invocationNum. A PreInvocation payload is a start+# boundary only at invocation zero; a later or malformed counter fails closed.+if printf '%s' "$PAYLOAD" | ai_memory_after_key invocationNum >/dev/null \+ && ! ai_memory_antigravity_is_initial_invocation "$PAYLOAD"; thenprintf '{}\n'exit 0fi@@ -18,7 +22,7 @@ QS=$(ai_memory_marker_qs "$CWD")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.+# start boundary may post session-start and claim a handoff.if [ -n "$SESSION_ID" ]; thenSTART_MARKER=$(ai_memory_briefed_file "agy-start-$SESSION_ID")if [ -e "$START_MARKER" ]; then@@ -36,9 +40,9 @@ printf '%s' "$PAYLOAD" \| ai_memory_post_hook "$SERVER/hook?event=session-start&agent=antigravity-cli${QS}" >/dev/null 2>&1 || trueHANDOFF=$(ai_memory_get_handoff "$SERVER/handoff?agent=antigravity-cli${QS}${SESSION_QS}${BRIEF_QS}" 2>/dev/null || true)if [ -n "$HANDOFF" ]; then- printf '{"injectSteps":[{"ephemeralMessage":'+ printf '{"injectSteps":[{"systemMessage":{"systemMessage":'printf '%s' "$HANDOFF" | ai_memory_json_string- printf '}]}\n'+ printf '}}]}\n'elseprintf '{}\n'fidiff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index e5fa1825..73bff607 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -916,12 +916,15 @@ function Read-AiMemoryStdin {return ""}-function Test-AiMemoryAntigravityInitialInvocation {- param([string] $Payload)+# Parity with `antigravity_boundary` in the native hook: only SessionStart+# omits invocationNum, a PreInvocation is a start boundary at invocation zero,+# and a missing or malformed counter on a PreInvocation fails closed.+function Test-AiMemoryAntigravityStartBoundary {+ param([string] $Payload, [switch] $PreInvocation)try {$Parsed = $Payload | ConvertFrom-Json$Property = $Parsed.PSObject.Properties["invocationNum"]- if ($null -eq $Property) { return $false }+ if ($null -eq $Property) { return (-not $PreInvocation) }$Value = $Property.Valuereturn (($Value -is [int] -or $Value -is [long]) -and [long]$Value -eq 0)} catch {@@ -972,7 +975,11 @@ function Invoke-AiMemoryHook {# `{ "additionalContext": ... }` envelope rather than Claude Code's# nested hookSpecificOutput shape.[switch] $CopilotCliSessionStartOutput,- [switch] $AntigravityPreInvocationOutput,+ # Antigravity SessionStart output: a fetched handoff becomes an+ # `injectSteps` system message. With -AntigravityPreInvocation the+ # payload is a PreInvocation, a start boundary only at invocation 0.+ [switch] $AntigravityStartOutput,+ [switch] $AntigravityPreInvocation,# Deliver the `[briefing]` compiled project brief on the FIRST# handoff fetch of a session only (kimi-code's user-prompt path:# kimi discards SessionStart hook stdout, so the brief rides the@@ -987,13 +994,13 @@ 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)) {+ if ($AntigravityStartOutput -and -not (Test-AiMemoryAntigravityStartBoundary -Payload $Payload -PreInvocation:$AntigravityPreInvocation)) {[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) {+ # first start boundary may post session-start and claim a handoff.+ if ($AntigravityStartOutput) {$Conversation = $nulltry { $Conversation = [string](($Payload | ConvertFrom-Json).conversationId) } catch { }if ($Conversation -and $Conversation.Trim()) {@@ -1014,12 +1021,12 @@ function Invoke-AiMemoryHook {}$Cwd = Resolve-AiMemoryCwd -Payload $Payload -Agent $Agentif (Test-AiMemoryServerRouted -Cwd $Cwd) {- if ($AntigravityPreInvocationOutput) { [Console]::Out.Write("{}") }+ if ($AntigravityStartOutput) { [Console]::Out.Write("{}") }return}$QS = Get-AiMemoryMarkerQuery -Cwd $Cwdif ($Cwd -and $null -eq $QS) {- if ($AntigravityPreInvocationOutput -or $GrokPostTool) { [Console]::Out.Write("{}") }+ if ($AntigravityStartOutput -or $GrokPostTool) { [Console]::Out.Write("{}") }return}if ($env:AI_MEMORY_RUN_ID) {@@ -1188,19 +1195,21 @@ function Invoke-AiMemoryHook {} elseif ($CopilotCliSessionStartOutput) {$Payload = @{ additionalContext = $Response.Content }[Console]::Out.Write(($Payload | ConvertTo-Json -Depth 5 -Compress))- } elseif ($AntigravityPreInvocationOutput) {+ } elseif ($AntigravityStartOutput) {+ # A system message stays in the conversation for later+ # turns; an ephemeralMessage is dropped after the first.$Payload = @{- injectSteps = @(@{ ephemeralMessage = $Response.Content })+ injectSteps = @(@{ systemMessage = @{ systemMessage = $Response.Content } })}[Console]::Out.Write(($Payload | ConvertTo-Json -Depth 5 -Compress))} else {[Console]::Out.Write($Response.Content)}- } elseif ($AntigravityPreInvocationOutput -or $GrokPostTool -or $CopilotCliSessionStartOutput) {+ } elseif ($AntigravityStartOutput -or $GrokPostTool -or $CopilotCliSessionStartOutput) {[Console]::Out.Write("{}")}} catch {- if ($AntigravityPreInvocationOutput -or $GrokPostTool -or $CopilotCliSessionStartOutput) {+ if ($AntigravityStartOutput -or $GrokPostTool -or $CopilotCliSessionStartOutput) {[Console]::Out.Write("{}")}}@@ -1217,7 +1226,7 @@ function Invoke-AiMemoryHook {if ($ProfileFile) {Set-AiMemoryBriefed -Path $ProfileFile}- } elseif ($AntigravityPreInvocationOutput -or $GrokPostTool -or $CopilotCliSessionStartOutput) {+ } elseif ($AntigravityStartOutput -or $GrokPostTool -or $CopilotCliSessionStartOutput) {[Console]::Out.Write("{}")}}diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.shindex 8e6fd43e..03e0106f 100755--- a/scripts/install-hooks.sh+++ b/scripts/install-hooks.sh@@ -144,11 +144,12 @@ if [[ "$AGENT" == "command-code" ]]; then)fi-# Antigravity CLI wires only PreInvocation (session-start), PreToolUse,-# PostToolUse and Stop, and its bundle ships exactly those four scripts.+# Antigravity wires SessionStart, PreInvocation, PreToolUse, PostToolUse and+# Stop, and its bundle ships exactly those five scripts.if [[ "$AGENT" == "antigravity-cli" ]]; thenSCRIPTS=("session-start"+ "pre-invocation""pre-tool-use""post-tool-use""stop"diff --git a/scripts/managed-workstream-acceptance.sh b/scripts/managed-workstream-acceptance.shindex 5da8575e..c980b850 100755--- a/scripts/managed-workstream-acceptance.sh+++ b/scripts/managed-workstream-acceptance.sh@@ -456,7 +456,7 @@ case "${AI_MEMORY_ACCEPTANCE_FAKE_MODE:-argv}" inINSERT INTO trajectory_blob (data) VALUES (x'414d57532d505249564154452d5452414a4543544f5259');"fipayload=$(jq -nc --arg id "$session_id" --arg cwd "$PWD" \- '{invocationNum: 0, conversationId: $id, workspacePaths: [$cwd]}')+ '{conversationId: $id, workspacePaths: [$cwd]}')printf '%s' "$payload" | \AI_MEMORY_HOOK_URL="${AI_MEMORY_SERVER_URL:?}" \"$AI_MEMORY_ACCEPTANCE_ANTIGRAVITY_HOOK" \@@ -998,7 +998,7 @@ jq -e \}# Antigravity fake-mode fixture: `agy` owns the conversation id and SQLite-# database, while its real PreInvocation hook links that id and accepts any+# database, while its real SessionStart hook links that id and accepts any# pending workstream context. The private trajectory table is never decoded or# copied into the ledger.ANTIGRAVITY_FAKE_HOME="$CONFIG/antigravity-fake"@@ -1087,7 +1087,7 @@ if grep -q . "$TMP/antigravity-cross-argv.log"; thencat "$TMP/antigravity-cross-argv.log" >&2exit 1fi-jq -e '.injectSteps[0].ephemeralMessage | contains("AMWS-FAKE-KIMI")' \+jq -e '.injectSteps[0].systemMessage.systemMessage | contains("AMWS-FAKE-KIMI")' \"$TMP/antigravity-cross-hook.json" >/dev/null || {printf 'Antigravity hook did not receive the prior Kimi workstream history\n' >&2cat "$TMP/antigravity-cross-hook.json" >&2diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.shindex 0ca3689e..8685ed5c 100755--- a/tests/hooks/test_lib.sh+++ b/tests/hooks/test_lib.sh@@ -200,14 +200,68 @@ AGY_INITIAL_OUTPUT=$(printf '%s' '{"invocationNum":0,"conversationId":"agy","wor| 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"+ '{"injectSteps":[{"systemMessage":{"systemMessage":"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 \+# Native SessionStart: no invocationNum, so it is a start boundary.+rm -f "$FAKE_CURL_LOG"+AGY_SESSION_START_OUTPUT=$(printf '%s' '{"conversationId":"agy-native","workspacePaths":["/work"]}' \+ | PATH="$FAKE_CURL_BIN:$PATH" AI_MEMORY_CURL_LOG="$FAKE_CURL_LOG" \+ AI_MEMORY_DATA_DIR="$TMP/agy-native" AI_MEMORY_HOOK_URL='http://memory.test' \+ sh hooks/antigravity-cli/session-start.sh)+assert_eq "antigravity SessionStart injects a persistent handoff" \+ '{"injectSteps":[{"systemMessage":{"systemMessage":"next-session-context"}}]}' "$AGY_SESSION_START_OUTPUT"+assert_eq "antigravity SessionStart posts session-start" "yes" \+ "$(grep -q '/hook?event=session-start&agent=antigravity-cli' "$FAKE_CURL_LOG" && printf 'yes' || printf 'no')"++# PreInvocation: a later invocation, or one without its counter, does nothing.+for agy_payload in '{"invocationNum":2,"conversationId":"agy-pre","workspacePaths":["/work"]}' \+ '{"conversationId":"agy-pre","workspacePaths":["/work"]}'; do+ rm -f "$FAKE_CURL_LOG"+ AGY_PRE_OUTPUT=$(printf '%s' "$agy_payload" \+ | PATH="$FAKE_CURL_BIN:$PATH" AI_MEMORY_CURL_LOG="$FAKE_CURL_LOG" \+ AI_MEMORY_DATA_DIR="$TMP/agy-pre" AI_MEMORY_HOOK_URL='http://memory.test' \+ sh hooks/antigravity-cli/pre-invocation.sh)+ assert_eq "antigravity PreInvocation outside invocation zero is empty: $agy_payload" "{}" "$AGY_PRE_OUTPUT"+ assert_eq "antigravity PreInvocation outside invocation zero sends nothing: $agy_payload" "0" \+ "$([ -f "$FAKE_CURL_LOG" ] && wc -l <"$FAKE_CURL_LOG" | tr -d ' ' || printf '0')"+done+# Without a SessionStart, the first turn's PreInvocation starts the+# conversation; the conversation's second turn is a no-op.+rm -f "$FAKE_CURL_LOG"+AGY_PRE_FIRST=$(printf '%s' '{"invocationNum":0,"conversationId":"agy-pre","workspacePaths":["/work"]}' \+ | PATH="$FAKE_CURL_BIN:$PATH" AI_MEMORY_CURL_LOG="$FAKE_CURL_LOG" \+ AI_MEMORY_DATA_DIR="$TMP/agy-pre" AI_MEMORY_HOOK_URL='http://memory.test' \+ sh hooks/antigravity-cli/pre-invocation.sh)+assert_eq "antigravity first PreInvocation without SessionStart injects the handoff" \+ '{"injectSteps":[{"systemMessage":{"systemMessage":"next-session-context"}}]}' "$AGY_PRE_FIRST"+rm -f "$FAKE_CURL_LOG"+AGY_PRE_SECOND=$(printf '%s' '{"invocationNum":0,"conversationId":"agy-pre","workspacePaths":["/work"]}' \+ | PATH="$FAKE_CURL_BIN:$PATH" AI_MEMORY_CURL_LOG="$FAKE_CURL_LOG" \+ AI_MEMORY_DATA_DIR="$TMP/agy-pre" AI_MEMORY_HOOK_URL='http://memory.test' \+ sh hooks/antigravity-cli/pre-invocation.sh)+assert_eq "antigravity later turn PreInvocation is empty" "{}" "$AGY_PRE_SECOND"+assert_eq "antigravity later turn PreInvocation sends nothing" "0" \+ "$([ -f "$FAKE_CURL_LOG" ] && wc -l <"$FAKE_CURL_LOG" | tr -d ' ' || printf '0')"+# SessionStart then the first turn's PreInvocation: one start, one handoff.+rm -f "$FAKE_CURL_LOG"+for agy_step in 'session-start {"conversationId":"agy-once","workspacePaths":["/work"]}' \+ 'pre-invocation {"invocationNum":0,"conversationId":"agy-once","workspacePaths":["/work"]}'; do+ printf '%s' "${agy_step#* }" \+ | PATH="$FAKE_CURL_BIN:$PATH" AI_MEMORY_CURL_LOG="$FAKE_CURL_LOG" \+ AI_MEMORY_DATA_DIR="$TMP/agy-once" AI_MEMORY_HOOK_URL='http://memory.test' \+ sh "hooks/antigravity-cli/${agy_step%% *}.sh" >/dev/null+done+assert_eq "antigravity SessionStart plus first PreInvocation claims one handoff" "1" \+ "$(grep -c '/handoff?' "$FAKE_CURL_LOG")"++PS_ANTIGRAVITY_STATIC=$(grep -q 'function Test-AiMemoryAntigravityStartBoundary' hooks/lib/ai-memory-hook.ps1 \+ && grep -q '\$AntigravityStartOutput -and -not' hooks/lib/ai-memory-hook.ps1 \+ && grep -q 'systemMessage = @{ systemMessage =' hooks/lib/ai-memory-hook.ps1 \+ && grep -q -- '-AntigravityPreInvocation' hooks/antigravity-cli/pre-invocation.ps1 \&& printf 'ok' || printf 'missing')assert_eq "powershell antigravity hook has invocation guard" "ok" "$PS_ANTIGRAVITY_STATIC"