Skip to content

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

Rust

fix(workstream): read Antigravity user prompts from history.jsonl

Peterson Salmeeebc47587103
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2c9359fc..ef56d745 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -54,6 +54,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
is now kept by both, and by the PreCompact and PostCompaction checkpoints,
which rewrote it the same way. The write no longer stamps
`observation_generation`. (#1138)
+- Fixed `ai-memory backfill` failing on every Antigravity CLI session: it and
+ `ai-memory run` now import the session's user prompts from `agy`'s
+ `history.jsonl`, keeping only lines whose conversation and workspace match
+ the checkout. (#1134)
- Fixed the hook spool charging a spooled event's retry budget while the
server was unreachable: an endpoint-level delivery failure (connection
refused, timeout, DNS — the existing `Unreachable` classification) no
diff --git a/crates/ai-memory-cli/tests/suite/backfill_e2e.rs b/crates/ai-memory-cli/tests/suite/backfill_e2e.rs
index 2473da11..36343c4e 100644
--- a/crates/ai-memory-cli/tests/suite/backfill_e2e.rs
+++ b/crates/ai-memory-cli/tests/suite/backfill_e2e.rs
@@ -38,7 +38,9 @@ mod slow {
use serde_json::{Value, json};
- use crate::e2e_support::{hermetic, run_cli, session_count, start_serve, write_jsonl};
+ use crate::e2e_support::{
+ ServerGuard, hermetic, run_cli, session_count, start_serve, write_jsonl,
+ };
const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");
const WORKSPACE: &str = "backfill-e2e-ws";
@@ -117,6 +119,56 @@ mod slow {
.join("\n")
}
+ /// Start the real server (loopback, no auth, hermetic: no embedder, no
+ /// wiki watcher — a machine-global inotify instance concurrent server
+ /// children can exhaust, #745).
+ async fn start_backfill_server(
+ client: &reqwest::Client,
+ data_dir: &Path,
+ home: &Path,
+ cwd: &Path,
+ ) -> (ServerGuard, String) {
+ start_serve(client, &data_dir.join("serve.log"), |port| {
+ let mut cmd = hermetic(BIN);
+ cmd.args([
+ "serve",
+ "--transport",
+ "http",
+ "--bind",
+ &format!("127.0.0.1:{port}"),
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ PROJECT,
+ "--no-watcher",
+ ])
+ .env("AI_MEMORY_DATA_DIR", data_dir)
+ .env("AI_MEMORY_HOME", home)
+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none");
+ cmd.current_dir(cwd);
+ cmd
+ })
+ .await
+ }
+
+ fn backfill_report(data_dir: &Path, home: &Path, cwd: &Path, base: &str) -> Value {
+ serde_json::from_str(&run_cli(
+ &[
+ "backfill",
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ PROJECT,
+ "--json",
+ ],
+ data_dir,
+ home,
+ Some(cwd),
+ base,
+ ))
+ .expect("backfill --json report")
+ }
+
#[tokio::test]
async fn backfill_imports_local_history_into_an_empty_store_and_is_searchable() {
let data_dir = tempfile::tempdir().expect("data dir");
@@ -156,31 +208,9 @@ mod slow {
],
);
- // Start the real server (loopback, no auth, hermetic: no embedder, no
- // wiki watcher — a machine-global inotify instance concurrent server
- // children can exhaust, #745).
let client = reqwest::Client::new();
- let (server, base) = start_serve(&client, &data_dir.path().join("serve.log"), |port| {
- let mut cmd = hermetic(BIN);
- cmd.args([
- "serve",
- "--transport",
- "http",
- "--bind",
- &format!("127.0.0.1:{port}"),
- "--workspace",
- WORKSPACE,
- "--project",
- PROJECT,
- "--no-watcher",
- ])
- .env("AI_MEMORY_DATA_DIR", data_dir.path())
- .env("AI_MEMORY_HOME", home.path())
- .env("AI_MEMORY_EMBEDDING_PROVIDER", "none");
- cmd.current_dir(&cwd);
- cmd
- })
- .await;
+ let (server, base) =
+ start_backfill_server(&client, data_dir.path(), home.path(), &cwd).await;
// Phase 1 — the store is empty before backfill.
assert_eq!(
@@ -298,4 +328,147 @@ mod slow {
drop(server);
}
+
+ const AG_MINE: &str = "a0d5ac62-2501-4780-b783-76d159c56cb3";
+ const AG_THEIRS: &str = "9576275f-7c4e-4709-b372-22d1ad2a0af8";
+ /// Rare, non-secret tokens: a secret-shaped canary would be redacted by the
+ /// sanitizer and could not show a leak from another project.
+ const AG_OWN: &str = "wombatnebulaagyown";
+ const AG_FOREIGN: &str = "pangolinquasaragyforeign";
+ const AG_RESUMED: &str = "ocelotpulsaragyresumed";
+
+ fn push_varint(output: &mut Vec<u8>, mut value: usize) {
+ while value >= 0x80 {
+ output.push(u8::try_from(value & 0x7f).unwrap() | 0x80);
+ value >>= 7;
+ }
+ output.push(u8::try_from(value).unwrap());
+ }
+
+ fn push_bytes_field(output: &mut Vec<u8>, field: u8, value: &[u8]) {
+ output.push((field << 3) | 2);
+ push_varint(output, value.len());
+ output.extend_from_slice(value);
+ }
+
+ /// Plant an `agy` conversation store whose metadata names `workspace`: the
+ /// workspace `file://` URI sits in field 1 of the message in field 1.
+ fn plant_antigravity_conversation(home: &Path, id: &str, workspace: &Path) {
+ let root = home.join(".gemini/antigravity-cli/conversations");
+ fs::create_dir_all(&root).expect("conversations dir");
+ let mut nested = Vec::new();
+ push_bytes_field(
+ &mut nested,
+ 1,
+ format!("file://{}", workspace.display()).as_bytes(),
+ );
+ let mut metadata = Vec::new();
+ push_bytes_field(&mut metadata, 1, &nested);
+ let connection =
+ rusqlite::Connection::open(root.join(format!("{id}.db"))).expect("conversation db");
+ connection
+ .execute_batch(
+ "CREATE TABLE trajectory_metadata_blob (id text DEFAULT \"main\", data blob, PRIMARY KEY (id))",
+ )
+ .expect("metadata table");
+ connection
+ .execute(
+ "INSERT INTO trajectory_metadata_blob (id, data) VALUES ('main', ?1)",
+ [metadata],
+ )
+ .expect("metadata row");
+ }
+
+ fn agy_prompt(id: &str, workspace: &Path, display: &str, millis: i64) -> Value {
+ json!({
+ "display": display,
+ "timestamp": millis,
+ "workspace": workspace.to_string_lossy(),
+ "conversationId": id,
+ })
+ }
+
+ /// `agy` keeps one `history.jsonl` for every project. Backfill imports this
+ /// conversation's prompts from it, in order, and nothing typed in another
+ /// conversation or another directory reaches the store.
+ #[tokio::test]
+ async fn backfill_imports_antigravity_prompts_from_history_and_nothing_foreign() {
+ let data_dir = tempfile::tempdir().expect("data dir");
+ let home = tempfile::tempdir().expect("home");
+ let project = tempfile::tempdir().expect("project cwd");
+ let elsewhere = tempfile::tempdir().expect("other project");
+ let cwd = fs::canonicalize(project.path()).expect("canonicalize project cwd");
+ let other = fs::canonicalize(elsewhere.path()).expect("canonicalize other project");
+ plant_antigravity_conversation(home.path(), AG_MINE, &cwd);
+ plant_antigravity_conversation(home.path(), AG_THEIRS, &other);
+ let past = 1_780_000_000_000;
+ write_jsonl(
+ &home.path().join(".gemini/antigravity-cli/history.jsonl"),
+ &[
+ agy_prompt(AG_MINE, &cwd, &format!("first {AG_OWN} prompt"), past),
+ agy_prompt(
+ AG_THEIRS,
+ &other,
+ &format!("{AG_FOREIGN} elsewhere"),
+ past + 1,
+ ),
+ agy_prompt(AG_THEIRS, &cwd, &format!("{AG_FOREIGN} here"), past + 2),
+ agy_prompt(AG_MINE, &other, &format!("{AG_RESUMED} resumed"), past + 3),
+ agy_prompt(AG_MINE, &cwd, "second prompt", past + 4),
+ ],
+ );
+ let client = reqwest::Client::new();
+ let (server, base) =
+ start_backfill_server(&client, data_dir.path(), home.path(), &cwd).await;
+
+ let report = backfill_report(data_dir.path(), home.path(), &cwd, &base);
+
+ assert_eq!(report["imported_sessions"], 1, "{report}");
+ assert_eq!(report["imported_events"], 2, "{report}");
+ assert_eq!(report["failed_sessions"], 0, "{report}");
+ let hits = call_tool(
+ &client,
+ &base,
+ "memory_query",
+ json!({ "query": AG_OWN, "limit": 10, "workspace": WORKSPACE, "project": PROJECT }),
+ )
+ .await;
+ assert!(
+ hits.contains(AG_OWN),
+ "imported prompt not searchable: {hits}"
+ );
+ assert!(
+ tree_contains(data_dir.path(), AG_OWN).is_some(),
+ "the own prompt must persist, or the absence checks prove nothing",
+ );
+ for foreign in [AG_FOREIGN, AG_RESUMED] {
+ if let Some(path) = tree_contains(data_dir.path(), foreign) {
+ panic!("{foreign} leaked into {}", path.display());
+ }
+ }
+
+ drop(server);
+ }
+
+ /// Without `history.jsonl` the session imports with no events instead of
+ /// failing the whole backfill.
+ #[tokio::test]
+ async fn backfill_succeeds_on_antigravity_without_history() {
+ let data_dir = tempfile::tempdir().expect("data dir");
+ let home = tempfile::tempdir().expect("home");
+ let project = tempfile::tempdir().expect("project cwd");
+ let cwd = fs::canonicalize(project.path()).expect("canonicalize project cwd");
+ plant_antigravity_conversation(home.path(), AG_MINE, &cwd);
+ let client = reqwest::Client::new();
+ let (server, base) =
+ start_backfill_server(&client, data_dir.path(), home.path(), &cwd).await;
+
+ let report = backfill_report(data_dir.path(), home.path(), &cwd, &base);
+
+ assert_eq!(report["imported_sessions"], 1, "{report}");
+ assert_eq!(report["imported_events"], 0, "{report}");
+ assert_eq!(report["failed_sessions"], 0, "{report}");
+
+ drop(server);
+ }
}
diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rs
index 20c9f03b..0cd83d25 100644
--- a/crates/ai-memory-workstream/src/transcript.rs
+++ b/crates/ai-memory-workstream/src/transcript.rs
@@ -2,7 +2,7 @@
use std::collections::HashSet;
use std::fs::{self, File};
-use std::io::{BufRead as _, BufReader, Read as _, Seek as _, SeekFrom};
+use std::io::{BufRead, BufReader, Read as _, Seek as _, SeekFrom};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
@@ -21,6 +21,12 @@ use crate::{ManagedHarness, clean_path};
const MAX_SCAN_FILES: usize = 50_000;
const MAX_EVENT_BYTES: usize = 128 * 1024;
+/// `agy` cuts `display` near 8 KiB; 4-byte UTF-8 and JSON escaping stay well
+/// under this.
+const MAX_ANTIGRAVITY_HISTORY_LINE_BYTES: usize = 64 * 1024;
+/// A new conversation's first prompt is logged without an id, within a second
+/// of its `.db` being created.
+const ANTIGRAVITY_OPENING_PROMPT_WINDOW: Duration = Duration::from_secs(5);
const LEGACY_MANAGED_WORKSTREAM_PACKET_PREFIX: &str = "> **ai-memory managed workstream:";
/// Checkout-local native session that can seed an otherwise-empty workstream.
@@ -56,9 +62,10 @@ struct FileCursor {
flavor: Option<FileFlavor>,
/// Hash of every committed byte through `offset`. Kimi Code and Grok can
/// rewrite their journals in place (Kimi on fork/compaction/resume, Grok
- /// on rewind); Kiro's append-only behavior is not documented. Those
- /// adapters validate this prefix before trusting the byte offset. Other
- /// JSONL adapters remain offset-only.
+ /// on rewind); Kiro's append-only behavior is not documented; `agy` may
+ /// trim its shared Antigravity history. Those adapters validate this
+ /// prefix before trusting the byte offset. Other JSONL adapters remain
+ /// offset-only.
#[serde(default, skip_serializing_if = "Option::is_none")]
prefix_sha256: Option<String>,
}
@@ -123,15 +130,7 @@ pub async fn export_transcript(
return export_crush(home, cwd, session_dir, native_session_id, source_cursor);
}
if harness == ManagedHarness::Antigravity {
- // The conversation store keeps every step as an undocumented protobuf
- // blob whose step-type enum is unversioned, so message text cannot be
- // decoded without guessing at a schema that changes between `agy`
- // releases. Conversation identity and workspace are read (they are
- // stable fields observed in current metadata); the visible-event
- // ledger for this harness comes from lifecycle-hook capture instead.
- return Err(anyhow!(
- "antigravity conversations expose no decodable transcript; this session's events come from hook capture"
- ));
+ return export_antigravity(home, cwd, session_dir, native_session_id, source_cursor);
}
let path = locate_session_file(harness, home, cwd, session_dir, native_session_id)?
.ok_or_else(|| anyhow!("native transcript for {native_session_id} was not found"))?;
@@ -2901,6 +2900,407 @@ fn grok_session_header(path: &Path) -> Result<Option<(String, PathBuf)>> {
Ok(Some((id.to_string(), PathBuf::from(cwd))))
}
+/// Antigravity's conversation store keeps every step as an undocumented
+/// protobuf blob whose step-type enum is unversioned, so assistant and tool
+/// steps are never decoded. `agy` also appends each typed prompt to
+/// `history.jsonl` beside the store, and that is the only source read here.
+///
+/// The file is shared by every conversation and workspace, so a line is kept
+/// only when both its `conversationId` and its `workspace` match the validated
+/// conversation: resuming a conversation from another directory keeps its id
+/// but records that directory. A new conversation's first prompt is written
+/// before its id exists; it is attributed only when exactly one unlabelled
+/// prompt from this workspace was typed as the conversation's `.db` appeared.
+fn export_antigravity(
+ home: &Path,
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ session: &str,
+ source_cursor: Option<&str>,
+) -> Result<ExportedTranscript> {
+ let db = locate_session_file(ManagedHarness::Antigravity, home, cwd, session_dir, session)?
+ .ok_or_else(|| anyhow!("native transcript for {session} was not found"))?;
+ let mut losses = Vec::new();
+ let history = session_root(ManagedHarness::Antigravity, home, session_dir)
+ .parent()
+ .map(|dir| dir.join("history.jsonl"));
+ let opened = history.and_then(|path| {
+ let file = File::open(&path).ok()?;
+ let len = file.metadata().ok()?.len();
+ Some((path, file, len))
+ });
+ let Some((history, mut file, len)) = opened else {
+ losses.push(
+ "Antigravity history.jsonl is missing or unreadable; no user prompts were imported"
+ .into(),
+ );
+ losses.push(ANTIGRAVITY_PROMPTS_ONLY.into());
+ return Ok(ExportedTranscript {
+ native_session_id: session.to_string(),
+ source_cursor: None,
+ events: Vec::new(),
+ losses,
+ });
+ };
+ // `agy` could trim or rewrite its history, so the offset is trusted only
+ // while the bytes before it are unchanged.
+ let cursor = source_cursor
+ .and_then(|raw| serde_json::from_str::<FileCursor>(raw).ok())
+ .filter(|cursor| Path::new(&cursor.path) == history && cursor.offset <= len);
+ let validated = if let Some(cursor) = cursor
+ && let Some(expected) = cursor.prefix_sha256.as_deref()
+ && let Some(hasher) = hash_file_prefix(&mut file, cursor.offset)?
+ && format!("{:x}", hasher.clone().finalize()) == expected
+ {
+ Some((cursor.offset, hasher))
+ } else {
+ None
+ };
+ let (start, mut prefix_hasher) = validated.unwrap_or_else(|| (0, Sha256::new()));
+ file.seek(SeekFrom::Start(start))?;
+
+ let created = birth_millis(&db);
+ let checkout = cwd.canonicalize().ok();
+ let in_checkout = |workspace: &str| {
+ checkout.is_some() && Path::new(workspace).canonicalize().ok() == checkout
+ };
+ let mut reader = BufReader::new(file);
+ let mut offset = start;
+ let mut line = Vec::new();
+ let mut prompts: Vec<HistoryPrompt> = Vec::new();
+ // Unlabelled prompts from this checkout that could have opened it.
+ let mut openers: Vec<HistoryPrompt> = Vec::new();
+ loop {
+ let read = match read_bounded_line(
+ &mut reader,
+ MAX_ANTIGRAVITY_HISTORY_LINE_BYTES,
+ session.as_bytes(),
+ &mut line,
+ &mut prefix_hasher,
+ )? {
+ BoundedLine::Eof | BoundedLine::Partial => break,
+ BoundedLine::Oversized { read, mentions } => {
+ offset += read;
+ if mentions {
+ losses.push("oversized Antigravity history records were skipped".into());
+ }
+ continue;
+ }
+ BoundedLine::Line(read) => read,
+ };
+ let line_offset = offset;
+ offset += read;
+ let raw = line.strip_suffix(b"\n").unwrap_or(&line);
+ // Only a record naming this conversation can be its loss; one naming
+ // another is skipped unparsed, and an unlabelled one is a possible
+ // opening prompt, skipped silently when unusable.
+ let names_session = contains_bytes(raw, session.as_bytes());
+ if !names_session && contains_bytes(raw, b"\"conversationId\"") {
+ continue;
+ }
+ let Ok(value) = serde_json::from_slice::<Value>(raw) else {
+ if names_session {
+ losses.push("malformed Antigravity history records were skipped".into());
+ }
+ continue;
+ };
+ if value
+ .get("conversationId")
+ .and_then(Value::as_str)
+ .is_some_and(|id| id != session)
+ {
+ continue;
+ }
+ let entry = match antigravity_history_entry(&value) {
+ Ok(entry) => entry,
+ Err(loss) => {
+ if value.get("conversationId").is_some() {
+ losses.push(loss.into());
+ }
+ continue;
+ }
+ };
+ let prompt = || HistoryPrompt {
+ offset: line_offset,
+ hash: format!("{:x}", Sha256::digest(raw)),
+ millis: entry.millis,
+ display: entry.display.to_string(),
+ metadata: json!({}),
+ };
+ match (entry.conversation, entry.kind) {
+ (Some(_), AntigravityHistoryKind::SlashCommand) => {
+ losses.push("Antigravity slash commands were intentionally excluded".into());
+ }
+ (Some(_), AntigravityHistoryKind::Shell) => {
+ losses.push("Antigravity shell commands were intentionally excluded".into());
+ }
+ (Some(_), AntigravityHistoryKind::Prompt) => {
+ if in_checkout(entry.workspace) {
+ prompts.push(prompt());
+ } else {
+ losses.push(
+ "Antigravity prompts typed in another workspace were excluded".into(),
+ );
+ }
+ }
+ // Without a creation time no window applies; only a read from
+ // the start can still hold the opening prompt worth reporting.
+ (None, AntigravityHistoryKind::Prompt)
+ if created.map_or(start == 0, |created| {
+ opening_window_contains(created, entry.millis)
+ }) && in_checkout(entry.workspace) =>
+ {
+ openers.push(prompt());
+ }
+ (None, _) => {}
+ }
+ }
+ let opening = antigravity_opening_prompt(created, openers, |millis| {
+ antigravity_conversation_started_near(&db, cwd, millis)
+ });
+ match opening {
+ Ok(Some(mut opener)) => {
+ opener.metadata = json!({"attribution": "inferred"});
+ prompts.push(opener);
+ prompts.sort_by_key(|prompt| prompt.offset);
+ }
+ Ok(None) => {}
+ Err(loss) => losses.push(loss.into()),
+ }
+ let mut events = Vec::new();
+ for prompt in prompts {
+ push_event(
+ &mut events,
+ AgentKind::AntigravityCli,
+ session,
+ &format!("{}-{}", prompt.millis, prompt.hash),
+ 0,
+ WorkstreamEventKind::Message,
+ Some("user"),
+ &prompt.display,
+ jiff::Timestamp::from_millisecond(prompt.millis)
+ .ok()
+ .map(|timestamp| timestamp.to_string()),
+ prompt.metadata,
+ );
+ }
+ losses.push(ANTIGRAVITY_PROMPTS_ONLY.into());
+ Ok(ExportedTranscript {
+ native_session_id: session.to_string(),
+ source_cursor: Some(serde_json::to_string(&FileCursor {
+ path: history.to_string_lossy().into_owned(),
+ offset,
+ flavor: None,
+ prefix_sha256: Some(format!("{:x}", prefix_hasher.finalize())),
+ })?),
+ events,
+ losses: deduplicate_losses(losses),
+ })
+}
+
+const ANTIGRAVITY_PROMPTS_ONLY: &str = "Antigravity assistant and tool steps are not decodable; only user prompts from history.jsonl were imported";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum AntigravityHistoryKind {
+ Prompt,
+ SlashCommand,
+ Shell,
+}
+
+#[derive(Debug)]
+struct AntigravityHistoryEntry<'a> {
+ conversation: Option<&'a str>,
+ kind: AntigravityHistoryKind,
+ workspace: &'a str,
+ display: &'a str,
+ millis: i64,
+}
+
+/// The file carries no version field, so each record is checked field by
+/// field; unknown keys are ignored and anything else unexpected is skipped.
+fn antigravity_history_entry(value: &Value) -> Result<AntigravityHistoryEntry<'_>, &'static str> {
+ let conversation = match value.get("conversationId") {
+ None => None,
+ Some(Value::String(id)) => Some(id.as_str()),
+ Some(_) => return Err("malformed Antigravity history records were skipped"),
+ };
+ let kind = match value.get("type").map(Value::as_str) {
+ None => AntigravityHistoryKind::Prompt,
+ Some(Some("slash_command")) => AntigravityHistoryKind::SlashCommand,
+ Some(Some("shell")) => AntigravityHistoryKind::Shell,
+ Some(_) => return Err("Antigravity history records of an unknown type were skipped"),
+ };
+ let display = value
+ .get("display")
+ .and_then(Value::as_str)
+ .filter(|display| !display.trim().is_empty())
+ .ok_or("Antigravity history records without a prompt were skipped")?;
+ let millis = value
+ .get("timestamp")
+ .and_then(Value::as_i64)
+ .filter(|millis| *millis > 0)
+ .ok_or("Antigravity history records without a valid timestamp were skipped")?;
+ let workspace = value
+ .get("workspace")
+ .and_then(Value::as_str)
+ .filter(|workspace| !workspace.is_empty())
+ .ok_or("Antigravity history records without a workspace were skipped")?;
+ Ok(AntigravityHistoryEntry {
+ conversation,
+ kind,
+ workspace,
+ display,
+ millis,
+ })
+}
+
+#[derive(Debug, PartialEq)]
+struct HistoryPrompt {
+ offset: u64,
+ hash: String,
+ millis: i64,
+ display: String,
+ metadata: Value,
+}
+
+fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
+ !needle.is_empty()
+ && haystack
+ .windows(needle.len())
+ .any(|window| window == needle)
+}
+
+fn birth_millis(path: &Path) -> Option<i64> {
+ let created = fs::metadata(path)
+ .and_then(|metadata| metadata.created())
+ .ok()?;
+ i64::try_from(created.duration_since(UNIX_EPOCH).ok()?.as_millis()).ok()
+}
+
+fn opening_window_contains(created_millis: i64, millis: i64) -> bool {
+ u128::from(created_millis.abs_diff(millis)) <= ANTIGRAVITY_OPENING_PROMPT_WINDOW.as_millis()
+}
+
+/// Pick the unlabelled prompt that opened the conversation from `candidates`,
+/// the ones from this checkout already inside the window around the `.db`
+/// creation time. It is attributed only when it is the single candidate and
+/// no other conversation of this checkout started near it, since that one
+/// could own it just as well. The first labelled prompt is no anchor: its
+/// time depends on how long the user took to type it.
+fn antigravity_opening_prompt(
+ created_millis: Option<i64>,
+ mut candidates: Vec<HistoryPrompt>,
+ other_started_near: impl FnOnce(i64) -> bool,
+) -> Result<Option<HistoryPrompt>, &'static str> {
+ if candidates.is_empty() {
+ return Ok(None);
+ }
+ if created_millis.is_none() {
+ return Err(
+ "Antigravity opening prompt was not attributed: the conversation store records no creation time",
+ );
+ }
+ if candidates.len() > 1 {
+ return Err(
+ "Antigravity opening prompt was not attributed: several unlabelled prompts match the conversation start",
+ );
+ }
+ if other_started_near(candidates[0].millis) {
+ return Err(
+ "Antigravity opening prompt was not attributed: another conversation in this workspace started at the same time",
+ );
+ }
+ Ok(candidates.pop())
+}
+
+/// Whether another conversation of this checkout had its store created within
+/// the opening window of `millis`. An unreadable store counts, so doubt never
+/// attributes a prompt.
+fn antigravity_conversation_started_near(db: &Path, cwd: &Path, millis: i64) -> bool {
+ let Some(entries) = db.parent().and_then(|dir| fs::read_dir(dir).ok()) else {
+ return false;
+ };
+ entries.flatten().take(MAX_SCAN_FILES).any(|entry| {
+ let path = entry.path();
+ let Some(id) = path.file_stem().and_then(|stem| stem.to_str()) else {
+ return false;
+ };
+ path != db
+ && path.extension().is_some_and(|extension| extension == "db")
+ && birth_millis(&path).is_some_and(|born| opening_window_contains(born, millis))
+ && session_path_matches(ManagedHarness::Antigravity, &path, id, cwd).unwrap_or(true)
+ })
+}
+
+enum BoundedLine {
+ Eof,
+ /// Bytes after the last newline: a record still being written.
+ Partial,
+ Line(u64),
+ /// A complete record longer than the limit, consumed without buffering;
+ /// `mentions` tells whether it contains the needle anywhere.
+ Oversized {
+ read: u64,
+ mentions: bool,
+ },
+}
+
+/// Read one newline-terminated record into `line`, buffering at most `max`
+/// bytes of it; an oversized record is only searched for `needle`. `hasher` takes every byte of a complete record and none of a
+/// partial one, so it always covers exactly the committed prefix.
+fn read_bounded_line(
+ reader: &mut impl BufRead,
+ max: usize,
+ needle: &[u8],
+ line: &mut Vec<u8>,
+ hasher: &mut Sha256,
+) -> std::io::Result<BoundedLine> {
+ line.clear();
+ let mut pending = hasher.clone();
+ let mut consumed = 0u64;
+ let mut oversized = false;
+ let mut mentions = false;
+ loop {
+ let buffer = reader.fill_buf()?;
+ if buffer.is_empty() {
+ return Ok(if consumed == 0 {
+ BoundedLine::Eof
+ } else {
+ BoundedLine::Partial
+ });
+ }
+ let (chunk, done) = match buffer.iter().position(|byte| *byte == b'\n') {
+ Some(index) => (&buffer[..=index], true),
+ None => (buffer, false),
+ };
+ let used = chunk.len();
+ pending.update(chunk);
+ if !oversized && line.len() + used <= max + 1 {
+ line.extend_from_slice(chunk);
+ } else {
+ // Past the limit only a tail one byte shorter than `needle` is
+ // kept, so a needle split across chunks is still found.
+ oversized = true;
+ line.extend_from_slice(chunk);
+ mentions |= contains_bytes(line, needle);
+ line.drain(..line.len().saturating_sub(needle.len().saturating_sub(1)));
+ }
+ consumed += used as u64;
+ reader.consume(used);
+ if done {
+ *hasher = pending;
+ return Ok(if oversized {
+ BoundedLine::Oversized {
+ read: consumed,
+ mentions,
+ }
+ } else {
+ BoundedLine::Line(consumed)
+ });
+ }
+ }
+}
+
/// Antigravity keeps one SQLite database per conversation, named
/// `<conversation-id>.db`, so the id comes from the file name. The workspace it
/// was opened on lives in `trajectory_metadata_blob`, a protobuf message whose
@@ -5881,23 +6281,538 @@ mod tests {
assert!(sessions.is_empty());
}
- /// Every step payload is an undocumented protobuf blob, so the ledger for
- /// this harness comes from hook capture. The failure has to say so.
- #[tokio::test]
- async fn antigravity_transcript_export_explains_why_it_is_unavailable() {
+ const AG_MINE: &str = "a0d5ac62-2501-4780-b783-76d159c56cb3";
+ const AG_THEIRS: &str = "9576275f-7c4e-4709-b372-22d1ad2a0af8";
+ /// Far from any fixture `.db` creation time, so unlabelled lines at this
+ /// time are never opening-prompt candidates.
+ const AG_PAST: i64 = 1_780_000_000_000;
+
+ struct AntigravityFixture {
+ temp: tempfile::TempDir,
+ root: PathBuf,
+ cwd: PathBuf,
+ other: PathBuf,
+ }
+
+ /// A fake home holding this checkout's conversation `AG_MINE`.
+ fn antigravity_fixture() -> AntigravityFixture {
let temp = tempfile::TempDir::new().unwrap();
+ let root = temp.path().join(".gemini/antigravity-cli/conversations");
+ let cwd = temp.path().join("checkout");
+ let other = temp.path().join("elsewhere");
+ for dir in [&root, &cwd, &other] {
+ fs::create_dir_all(dir).unwrap();
+ }
+ write_antigravity_conversation(&root, AG_MINE, &file_uri(&cwd));
+ AntigravityFixture {
+ temp,
+ root,
+ cwd,
+ other,
+ }
+ }
+
+ fn history_line(id: Option<&str>, workspace: &Path, display: &str, millis: i64) -> String {
+ let mut line = json!({
+ "display": display,
+ "timestamp": millis,
+ "workspace": workspace.to_string_lossy(),
+ });
+ if let Some(id) = id {
+ line["conversationId"] = json!(id);
+ }
+ line.to_string()
+ }
+
+ fn write_antigravity_history(root: &Path, lines: &[String]) {
+ let mut body = lines.join("\n");
+ body.push('\n');
+ fs::write(root.parent().unwrap().join("history.jsonl"), body).unwrap();
+ }
+
+ async fn export_antigravity_fixture(
+ fixture: &AntigravityFixture,
+ cursor: Option<&str>,
+ ) -> ExportedTranscript {
+ export_transcript(
+ ManagedHarness::Antigravity,
+ fixture.temp.path(),
+ &fixture.cwd,
+ None,
+ AG_MINE,
+ cursor,
+ )
+ .await
+ .unwrap()
+ }
+
+ fn prompts(exported: &ExportedTranscript) -> Vec<&str> {
+ exported
+ .events
+ .iter()
+ .map(|event| {
+ assert_eq!(event.role.as_deref(), Some("user"));
+ assert_eq!(event.agent, AgentKind::AntigravityCli);
+ event.content.as_str()
+ })
+ .collect()
+ }
+
+ /// `history.jsonl` holds every conversation of every workspace. Only this
+ /// conversation's prompts typed in this checkout may come out.
+ #[tokio::test]
+ async fn antigravity_history_exports_only_this_conversations_prompts_in_this_workspace() {
+ let fixture = antigravity_fixture();
+ let (cwd, other) = (&fixture.cwd, &fixture.other);
+ write_antigravity_history(
+ &fixture.root,
+ &[
+ history_line(Some(AG_MINE), cwd, "own first", AG_PAST),
+ history_line(Some(AG_THEIRS), cwd, "canary-same-workspace", AG_PAST + 1),
+ history_line(
+ Some(AG_THEIRS),
+ other,
+ "canary-other-workspace",
+ AG_PAST + 2,
+ ),
+ history_line(None, other, "canary-unlabelled", AG_PAST + 3),
+ history_line(Some(AG_MINE), cwd, "own second", AG_PAST + 4),
+ ],
+ );
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert_eq!(prompts(&exported), ["own first", "own second"]);
+ assert!(
+ !exported
+ .losses
+ .iter()
+ .any(|loss| loss.contains("another workspace")),
+ "other conversations are not this session's losses: {:?}",
+ exported.losses
+ );
+ }
+
+ /// `agy --conversation=<id>` run from another directory keeps the id but
+ /// records that directory, so the id alone must not admit the line.
+ #[tokio::test]
+ async fn antigravity_history_drops_prompts_from_a_resumed_conversation_in_another_workspace() {
+ let fixture = antigravity_fixture();
+ write_antigravity_history(
+ &fixture.root,
+ &[
+ history_line(Some(AG_MINE), &fixture.other, "canary-resumed", AG_PAST),
+ history_line(Some(AG_MINE), &fixture.cwd, "own", AG_PAST + 1),
+ ],
+ );
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert_eq!(prompts(&exported), ["own"]);
+ assert!(
+ exported
+ .losses
+ .iter()
+ .any(|loss| loss.contains("another workspace")),
+ "{:?}",
+ exported.losses
+ );
+ }
+
+ /// The conversation itself must belong to this checkout before any
+ /// history line is read, even when the history names this checkout.
+ #[tokio::test]
+ async fn antigravity_export_rejects_a_conversation_from_another_workspace() {
+ let fixture = antigravity_fixture();
+ write_antigravity_conversation(&fixture.root, AG_THEIRS, &file_uri(&fixture.other));
+ write_antigravity_history(
+ &fixture.root,
+ &[history_line(
+ Some(AG_THEIRS),
+ &fixture.cwd,
+ "canary",
+ AG_PAST,
+ )],
+ );
+
let error = export_transcript(
ManagedHarness::Antigravity,
- temp.path(),
- temp.path(),
+ fixture.temp.path(),
+ &fixture.cwd,
None,
- "a0d5ac62-2501-4780-b783-76d159c56cb3",
+ AG_THEIRS,
None,
)
.await
.unwrap_err()
.to_string();
- assert!(error.contains("hook capture"), "{error}");
+
+ assert!(error.contains("not found"), "{error}");
+ }
+
+ #[tokio::test]
+ async fn antigravity_export_rejects_unknown_or_traversal_ids() {
+ let fixture = antigravity_fixture();
+ write_antigravity_history(
+ &fixture.root,
+ &[history_line(Some("../x"), &fixture.cwd, "canary", AG_PAST)],
+ );
+ for id in ["11111111-1111-1111-1111-111111111111", "../x", "not-a-uuid"] {
+ let error = export_transcript(
+ ManagedHarness::Antigravity,
+ fixture.temp.path(),
+ &fixture.cwd,
+ None,
+ id,
+ None,
+ )
+ .await
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("not found"), "{id}: {error}");
+ }
+ }
+
+ /// The file has no version field: anything unexpected is skipped with a
+ /// loss, and unknown keys are ignored.
+ #[tokio::test]
+ async fn antigravity_history_skips_malformed_lines_with_losses() {
+ let fixture = antigravity_fixture();
+ let cwd = fixture.cwd.to_string_lossy();
+ let record = |extra: Value| {
+ let mut line = json!({
+ "conversationId": AG_MINE,
+ "workspace": cwd,
+ "display": "canary",
+ "timestamp": AG_PAST,
+ });
+ for (key, value) in extra.as_object().unwrap() {
+ if value.is_null() {
+ line.as_object_mut().unwrap().remove(key);
+ } else {
+ line[key] = value.clone();
+ }
+ }
+ line.to_string()
+ };
+ write_antigravity_history(
+ &fixture.root,
+ &[
+ format!(r#"{{"conversationId":"{AG_MINE}","display":"#),
+ record(json!({"timestamp": "1780000000000"})),
+ record(json!({"timestamp": -5})),
+ record(json!({"timestamp": 1.78e12})),
+ record(json!({"display": ""})),
+ record(json!({"display": null})),
+ record(json!({"workspace": null})),
+ record(json!({"type": "weird"})),
+ record(json!({"display": "own", "futureKey": {"nested": true}})),
+ ],
+ );
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert_eq!(prompts(&exported), ["own"]);
+ for expected in [
+ "malformed Antigravity history records",
+ "without a valid timestamp",
+ "without a prompt",
+ "without a workspace",
+ "of an unknown type",
+ ] {
+ assert!(
+ exported.losses.iter().any(|loss| loss.contains(expected)),
+ "missing {expected:?} in {:?}",
+ exported.losses
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn antigravity_history_drops_slash_and_shell_entries() {
+ let fixture = antigravity_fixture();
+ let typed = |kind: &str| {
+ let mut line: Value =
+ serde_json::from_str(&history_line(Some(AG_MINE), &fixture.cwd, "/x", AG_PAST))
+ .unwrap();
+ line["type"] = json!(kind);
+ line.to_string()
+ };
+ write_antigravity_history(&fixture.root, &[typed("slash_command"), typed("shell")]);
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert!(exported.events.is_empty());
+ for expected in ["slash commands", "shell commands"] {
+ assert!(
+ exported.losses.iter().any(|loss| loss.contains(expected)),
+ "missing {expected:?} in {:?}",
+ exported.losses
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn antigravity_history_skips_an_oversized_line_and_keeps_reading() {
+ let fixture = antigravity_fixture();
+ let huge = "x".repeat(MAX_ANTIGRAVITY_HISTORY_LINE_BYTES + 1);
+ write_antigravity_history(
+ &fixture.root,
+ &[
+ history_line(Some(AG_MINE), &fixture.cwd, &huge, AG_PAST),
+ history_line(Some(AG_MINE), &fixture.cwd, "own", AG_PAST + 1),
+ ],
+ );
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert_eq!(prompts(&exported), ["own"]);
+ assert!(
+ exported
+ .losses
+ .iter()
+ .any(|loss| loss.contains("oversized")),
+ "{:?}",
+ exported.losses
+ );
+ }
+
+ /// A missing history is a degraded source, not a failed import.
+ #[tokio::test]
+ async fn antigravity_history_missing_file_yields_no_events() {
+ let fixture = antigravity_fixture();
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert!(exported.events.is_empty());
+ assert!(
+ exported
+ .losses
+ .iter()
+ .any(|loss| loss.contains("history.jsonl is missing")),
+ "{:?}",
+ exported.losses
+ );
+ }
+
+ /// `agy` caps a prompt near 8 KiB; such a prompt in multibyte text stays
+ /// under the line limit and comes out whole, stamped from epoch ms.
+ #[tokio::test]
+ async fn antigravity_history_converts_millis_and_keeps_a_long_multibyte_prompt() {
+ let fixture = antigravity_fixture();
+ let long = "é🙂".repeat(4_096);
+ write_antigravity_history(
+ &fixture.root,
+ &[history_line(
+ Some(AG_MINE),
+ &fixture.cwd,
+ &long,
+ 1_780_000_000_123,
+ )],
+ );
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert_eq!(prompts(&exported), [long.as_str()]);
+ assert_eq!(
+ exported.events[0].occurred_at.as_deref(),
+ Some("2026-05-28T20:26:40.123Z")
+ );
+ assert_eq!(exported.events[0].metadata, json!({}));
+ }
+
+ fn opener(millis: i64) -> HistoryPrompt {
+ HistoryPrompt {
+ offset: 0,
+ hash: String::new(),
+ millis,
+ display: "opening".into(),
+ metadata: json!({}),
+ }
+ }
+
+ #[test]
+ fn antigravity_opening_prompt_takes_the_single_candidate() {
+ assert_eq!(
+ antigravity_opening_prompt(Some(AG_PAST), vec![opener(AG_PAST + 400)], |_| false),
+ Ok(Some(opener(AG_PAST + 400)))
+ );
+ assert_eq!(
+ antigravity_opening_prompt(Some(AG_PAST), Vec::new(), |_| true),
+ Ok(None)
+ );
+ }
+
+ #[test]
+ fn antigravity_opening_prompt_rejects_ambiguous_or_contested_candidates() {
+ assert!(
+ antigravity_opening_prompt(
+ Some(AG_PAST),
+ vec![opener(AG_PAST), opener(AG_PAST + 100)],
+ |_| false
+ )
+ .unwrap_err()
+ .contains("several")
+ );
+ assert!(
+ antigravity_opening_prompt(Some(AG_PAST), vec![opener(AG_PAST)], |millis| {
+ millis == AG_PAST
+ })
+ .unwrap_err()
+ .contains("another conversation")
+ );
+ }
+
+ /// The missing creation time is reported only when a prompt was left
+ /// unattributed because of it.
+ #[test]
+ fn antigravity_opening_prompt_needs_a_creation_time_only_for_a_candidate() {
+ assert!(
+ antigravity_opening_prompt(None, vec![opener(AG_PAST)], |_| false)
+ .unwrap_err()
+ .contains("no creation time")
+ );
+ assert_eq!(
+ antigravity_opening_prompt(None, Vec::new(), |_| false),
+ Ok(None)
+ );
+ }
+
+ /// A conversation of one prompt has no labelled line at all; its prompt is
+ /// found from the `.db` creation time alone. Skipped where the filesystem
+ /// records no birth time.
+ #[tokio::test]
+ async fn antigravity_opening_prompt_covers_a_single_prompt_conversation() {
+ let fixture = antigravity_fixture();
+ let db = fixture.root.join(format!("{AG_MINE}.db"));
+ let Ok(created) = fs::metadata(&db).and_then(|metadata| metadata.created()) else {
+ return;
+ };
+ let created =
+ i64::try_from(created.duration_since(UNIX_EPOCH).unwrap().as_millis()).unwrap();
+ write_antigravity_history(
+ &fixture.root,
+ &[
+ history_line(None, &fixture.cwd, "canary-before-window", created - 6_000),
+ history_line(None, &fixture.other, "canary-other-workspace", created),
+ history_line(None, &fixture.cwd, "opening", created + 300),
+ ],
+ );
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert_eq!(prompts(&exported), ["opening"]);
+ assert_eq!(
+ exported.events[0].metadata,
+ json!({"attribution": "inferred"})
+ );
+ }
+
+ /// A conversation opened without a typed prompt (`agy -p`) must not take
+ /// the opening prompt of another conversation of this checkout started at
+ /// the same moment. Skipped where the filesystem records no birth time.
+ #[tokio::test]
+ async fn antigravity_opening_prompt_is_refused_when_another_conversation_started_with_it() {
+ let fixture = antigravity_fixture();
+ write_antigravity_conversation(&fixture.root, AG_THEIRS, &file_uri(&fixture.cwd));
+ let Some(created) = birth_millis(&fixture.root.join(format!("{AG_MINE}.db"))) else {
+ return;
+ };
+ write_antigravity_history(
+ &fixture.root,
+ &[history_line(
+ None,
+ &fixture.cwd,
+ "canary-theirs-opening",
+ created,
+ )],
+ );
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert!(exported.events.is_empty(), "{:?}", exported.events);
+ assert!(
+ exported
+ .losses
+ .iter()
+ .any(|loss| loss.contains("another conversation")),
+ "{:?}",
+ exported.losses
+ );
+ }
+
+ /// Unusable records of other conversations, or unlabelled ones, are not
+ /// this conversation's losses.
+ #[tokio::test]
+ async fn antigravity_history_reports_no_losses_for_foreign_records() {
+ let fixture = antigravity_fixture();
+ let huge = "x".repeat(MAX_ANTIGRAVITY_HISTORY_LINE_BYTES + 1);
+ write_antigravity_history(
+ &fixture.root,
+ &[
+ format!(r#"{{"conversationId":"{AG_THEIRS}","display":"#),
+ history_line(Some(AG_THEIRS), &fixture.cwd, &huge, AG_PAST),
+ json!({"conversationId": AG_THEIRS, "display": "x", "timestamp": AG_PAST})
+ .to_string(),
+ json!({"display": "shell", "timestamp": AG_PAST, "type": "shell"}).to_string(),
+ history_line(Some(AG_MINE), &fixture.cwd, "own", AG_PAST + 1),
+ ],
+ );
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert_eq!(prompts(&exported), ["own"]);
+ assert_eq!(
+ exported.losses,
+ [ANTIGRAVITY_PROMPTS_ONLY],
+ "{:?}",
+ exported.losses
+ );
+ }
+
+ #[tokio::test]
+ async fn antigravity_history_cursor_returns_only_appended_prompts() {
+ let fixture = antigravity_fixture();
+ let first = history_line(Some(AG_MINE), &fixture.cwd, "first", AG_PAST);
+ write_antigravity_history(&fixture.root, std::slice::from_ref(&first));
+ let initial = export_antigravity_fixture(&fixture, None).await;
+ assert_eq!(prompts(&initial), ["first"]);
+
+ write_antigravity_history(
+ &fixture.root,
+ &[
+ first,
+ history_line(Some(AG_MINE), &fixture.cwd, "second", AG_PAST + 1),
+ ],
+ );
+ let next = export_antigravity_fixture(&fixture, initial.source_cursor.as_deref()).await;
+
+ assert_eq!(prompts(&next), ["second"]);
+ }
+
+ /// A trimmed or rewritten history invalidates the byte offset, so the
+ /// read starts over instead of skipping or splitting records.
+ #[tokio::test]
+ async fn antigravity_history_cursor_restarts_after_truncation_or_rewrite() {
+ let fixture = antigravity_fixture();
+ let line =
+ |display: &str, millis: i64| history_line(Some(AG_MINE), &fixture.cwd, display, millis);
+ write_antigravity_history(
+ &fixture.root,
+ &[line("aaaa", AG_PAST), line("bbbb", AG_PAST + 1)],
+ );
+ let cursor = export_antigravity_fixture(&fixture, None)
+ .await
+ .source_cursor;
+
+ write_antigravity_history(&fixture.root, &[line("cccc", AG_PAST + 2)]);
+ let truncated = export_antigravity_fixture(&fixture, cursor.as_deref()).await;
+ assert_eq!(prompts(&truncated), ["cccc"]);
+
+ let cursor = truncated.source_cursor;
+ write_antigravity_history(&fixture.root, &[line("dddd", AG_PAST + 3)]);
+ let rewritten = export_antigravity_fixture(&fixture, cursor.as_deref()).await;
+ assert_eq!(prompts(&rewritten), ["dddd"]);
}
const KIRO_SESSION_A: &str = "3f6d1c2a-0000-4000-8000-000000000aaa";
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index 6394349e..5ba892f9 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -602,7 +602,7 @@ change does not add an atomic disk/SQL seal or change lease/retry policy.
| Kiro CLI v3 | native default creation with `--v3` | `--v3 --resume-id <sess_uuid>` | `$KIRO_HOME/sessions/<checkout-bucket>/<sess_uuid>/messages.jsonl` (+ sibling `session.json` metadata) |
| OMP | native default creation | `--resume=<id>` | `<agent dir>/sessions/**/*.jsonl`, or the XDG session directory described below |
| Grok Build CLI | generated `--session-id` | `--resume <id>` | `$GROK_HOME/sessions/*/*/chat_history.jsonl` |
-| Antigravity CLI | native default creation | `--conversation <id>` | `~/.gemini/antigravity-cli/conversations/<id>.db` metadata plus lifecycle-hook capture |
+| Antigravity CLI | native default creation | `--conversation <id>` | `~/.gemini/antigravity-cli/conversations/<id>.db` metadata; user prompts only from `~/.gemini/antigravity-cli/history.jsonl` (assistant and tool steps come from lifecycle-hook capture) |
OMP's agent directory is `~/.omp/agent` for the default profile and
`~/.omp/profiles/<name>/agent` for a named profile. `PI_CONFIG_DIR` changes the
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index aa1c1d9f..f80f8b74 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -78,6 +78,7 @@ boundary not yet built.
| 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_attached_background_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050); `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `claude_attached_background_session_follows_only_this_checkouts_bg_records` (a concurrent launch's background session, another checkout's, and a non-background record refused; own attachment control); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`; `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous |
| 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet |
| 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `interactive_launch_waits_out_a_lapsing_lease_then_proceeds`, and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users |
+| 13c | A native store shared by every project yields only this checkout's records (Antigravity `history.jsonl`) | `ai-memory-workstream/src/transcript.rs` `export_antigravity` — the conversation must first pass `locate_session_file` (UUID file name + `.db` workspace == `cwd`); every `history.jsonl` line must match both that `conversationId` and, by `same_path`, this `cwd` (a conversation resumed in another directory keeps its id but records that directory, so the id alone is not enough); an id-less opening prompt is attributed only when exactly one same-workspace candidate falls within 5 s of the `.db` creation time and no other conversation of this checkout was created within 5 s of it; slash/shell entries and oversized lines are dropped, and only records naming this conversation are reported as its losses | `transcript.rs` `antigravity_history_exports_only_this_conversations_prompts_in_this_workspace` (other conversation in this and another workspace refused; own control passes), `antigravity_history_drops_prompts_from_a_resumed_conversation_in_another_workspace` (same id, foreign workspace refused), `antigravity_export_rejects_a_conversation_from_another_workspace`, `antigravity_export_rejects_unknown_or_traversal_ids`, `antigravity_opening_prompt_is_refused_when_another_conversation_started_with_it` (an opener another conversation of this checkout could own is refused), `antigravity_opening_prompt_covers_a_single_prompt_conversation` (control), `antigravity_history_reports_no_losses_for_foreign_records`; `backfill_e2e.rs` `backfill_imports_antigravity_prompts_from_history_and_nothing_foreign` (foreign prompts absent from wiki and db) | STRONG |
| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor; batch outcomes do not bypass the capture grant or session owner check | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository` (foreign raw workstream id refuses populated provenance; granted reader receives the source record and tool correlation); `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |
| 14aa | Companion capture privacy before persistence and delivery | `companions/ai-memory-client/src/lib.rs` `reject_sensitive`, `sanitize_external_value`, `check_body`; `src/scrub.rs` `sanitize_external_text`; relay `identity::validate`, `check_scope`, `relay::init` and `flush_locked`; importer `plan_external_conversation`, `planned_hook_event`, `truncate_utf8`, `ImportClient::post_hook_batch` | SDK secret-position, nested key, numeric metric (11 names plus numeric `*_tokens` counts; string values still redact), bounded schema and literal-marker tests; relay `sensitive_envelope_is_rejected_before_enqueue_with_clean_control`, `new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry`, `unsafe_legacy_pending_is_dropped_locally_and_never_blocks_its_session`, `unsafe_legacy_native_identity_is_dropped_and_its_session_continues`, `legacy_binding_scope_spaces_are_preserved_on_delivery`; importer `sensitive_native_identity_is_refused_before_manifest_and_http_with_unicode_control`, `shared_key_sanitation_precedes_plan_manifest_transport_and_exact_retry`, `preview_and_manifest_use_scrubbed_bodies_and_digest`, `forged_body_authority_is_refused_before_transport`, `sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles`. Controls preserve opaque native Unicode IDs, metric representation and untrusted provenance. An unsafe item queued before these checks never reaches the wire (body or request line); it leaves the queue as a local `dropped_policy` receipt so the rest of its session ships. Guard-removal runtime probes target the final formatted sources and restore identical hashes. | Client-side privacy only; server scope, auth, admission and capture-policy guards remain authoritative |
| 14ap | Managed-run mutation owner and current project access (finish, cancel, heartbeat, native-session link, context acceptance) | `hooks/src/workstream.rs` `authorize_run_owner` derives `ManagedRunAuthority` only from authenticated middleware extensions and checks the real run before any mutation — for finish before status/payload/segment handling; cancel, heartbeat, link and context acceptance go through the same helper, so none is a side door around finish's rule; `ReaderPool::authorize_managed_run` and `store/src/workstream.rs` `authorize_run_mutation` use a read snapshot and the existing writer transaction, respectively. Strict resolution (`project_authz.rs` `resolve_project_authz_strict`, the canonical decision with a fail-closed resolution mode, so the reserved global-scope write gate applies here too) requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`; hooks `workstream.rs` `run_mutation_routes_refuse_another_operator` (another operator and root under another identity refused on heartbeat/link/accept/cancel, run left active; owner admitted); store `project_authz.rs` `strict_resolution_shares_the_global_gate_and_fails_closed_on_a_gap`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within finish's writer transaction; a revocation after preflight can leave an unindexed raw segment. Cancel, heartbeat, link and acceptance check one read snapshot immediately before a single-row update (a run's owner never changes). A later hook event carrying `AI_MEMORY_RUN_ID` links its native session only through `link_native_session_in_scope`, which applies the SessionStart boundary (`ManagedRunBoundaryRow::admits`: the run's own project and operator) and refuses a foreign run id while the event itself is still captured (`router.rs` `hook_event_links_a_managed_run_only_from_its_operator`, `hook_event_in_another_project_does_not_link_the_run`, control `hook_event_links_a_shared_run_on_a_single_operator_server`; #1082). Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional |
diff --git a/docs/support-matrix.md b/docs/support-matrix.md
index 9ebf4b9e..4a450b6b 100644
--- a/docs/support-matrix.md
+++ b/docs/support-matrix.md
@@ -26,7 +26,7 @@
| `--yolo` safety + ai-jail | Linux/macOS; Windows partial | `ai-memory run --yolo` warns before it disarms an agent's permission prompts and, on Linux/macOS, offers to re-exec the session inside [ai-jail](https://github.com/akitaonrails/ai-jail) when it is usable — installed and with its sandbox backend present (`bwrap` / `sandbox-exec`); otherwise it asks nothing and proceeds (`--network`, forwarding only already-set credential/config env vars). Accepting the offer shows a checklist of ai-jail toggles pre-marked with smart defaults (credentials present on the host, SSH for an SSH `origin`, worktree metadata in a linked worktree; Docker socket, GPU, display, Pictures, Tailscale unchecked). `--jail` re-runs inside ai-jail without asking (also without `--yolo` and non-interactively; it errors when ai-jail is not usable), `--jail=github,aws,no-mise` is exact (every unnamed checklist row is forced off with `--no-X`; `all`/`none` too; the checklist likewise passes unchecked rows as `--no-X`, while bare `--jail` leaves unmarked rows to your ai-jail config), and `--no-jail` skips the offer. Only toggles the installed ai-jail supports are offered; the credential mounts (`github`, `aws`, `kube`, `gcloud`, `docker-config`) need ai-jail 2.5.0. A project `.ai-jail` in the launch directory replaces the checklist and the bare-`--jail` defaults (ai-jail loads it as-is; `--jail=…` still overrides), and every re-exec passes `--no-save-config` so ai-jail never writes the run's flags into it. Both prompts are skipped on a non-interactive stdin/stderr and when already detected inside ai-jail. Windows gets the warning but never the ai-jail offer (ai-jail is Linux/macOS-only). Opt-in `--true-yolo` implies `--yolo` and, for Claude only, additionally forces `bypassPermissions` over any settings `defaultMode` (interchangeable with `--yolo` for other harnesses); `claude_true_yolo` applies the same Claude extra to `--yolo` launches. Claude's own explicit `ask` rules and command-safety checks still prompt in every mode. See [`docs/design-yolo-safety-ai-jail.md`](design-yolo-safety-ai-jail.md). |
| Claude Desktop (Chat) | MCP-only | Uses `mcp-remote`; the ordinary Chat surface does not run plugin hooks. Cowork plugins can run hooks, but ai-memory does not yet ship a Cowork plugin integration; see the explicit boundary in [`mcp-install.md`](mcp-install.md#claude-desktop). |
| OpenClaw | Supported | MCP config + native plugin lifecycle hooks; generated plugin enforces capture exclusions. |
-| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). Only `PreInvocation` with `invocationNum = 0` maps to SessionStart; later model calls cannot consume a next-session handoff. No automatic true session-end hook, so run `ai-memory finalize-session --agent antigravity-cli` after the final turn when you need a summary, handoff, and opt-in SessionEnd consolidation; an interactive session launched with `ai-memory run antigravity` is finalized automatically when it exits if the run can tie the session to itself (see [`docs/managed-workstreams.md`](managed-workstreams.md)). `ai-memory run antigravity` (aliases `antigravity-cli`, `agy`) adds managed workstream resume via `--conversation`; conversation text is not decoded, so the ledger for this harness comes from hook capture. Tool outputs (`run_command`, `view_file`, `list_dir`, etc.) are resolved directly from `.system_generated/steps/<stepIdx>/output.txt` during `post-tool-use` while mutation tools preserve code from arguments (#966). |
+| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). Only `PreInvocation` with `invocationNum = 0` maps to SessionStart; later model calls cannot consume a next-session handoff. No automatic true session-end hook, so run `ai-memory finalize-session --agent antigravity-cli` after the final turn when you need a summary, handoff, and opt-in SessionEnd consolidation; an interactive session launched with `ai-memory run antigravity` is finalized automatically when it exits if the run can tie the session to itself (see [`docs/managed-workstreams.md`](managed-workstreams.md)). `ai-memory run antigravity` (aliases `antigravity-cli`, `agy`) adds managed workstream resume via `--conversation`; its conversation store is not decoded, so the ledger takes user prompts from `agy`'s `history.jsonl` (only this conversation's lines typed in this checkout) and assistant and tool steps from hook capture. Tool outputs (`run_command`, `view_file`, `list_dir`, etc.) are resolved directly from `.system_generated/steps/<stepIdx>/output.txt` during `post-tool-use` while mutation tools preserve code from arguments (#966). |
| Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works. `SessionStart` and `UserPromptSubmit` do not accept the handoff (Grok discards that stdout). The first `PostToolUse` prints `hookSpecificOutput.additionalContext` with the pending handoff and an opted-in `[briefing]`; the model sees it after that tool result. If no tool runs, recover via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. `ai-memory run grok` adds managed workstream resume with the context packet delivered natively through `--rules`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). |
| Swival CLI | MCP-only | `install-mcp --client swival --apply` merges a native HTTP entry into the project-root `.swival/mcp.json`, preserving sibling servers. Lifecycle and managed-workstream support are not claimed because Swival's callback contract does not expose a stable session identifier. |
| Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. |