Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(workstream): manage Antigravity CLI as a launcher harness
Vivaldo Junior30b9040b42ac
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f5c4e153..1b15f281 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -105,6 +105,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0pages reinforced by several operators without changing existing scores atthe default or for pages with zero or one identified reader (#336).+- `run` and `show` accept `antigravity` (aliases `antigravity-cli`, `agy`) as a+ managed harness, so an Antigravity session joins the same workstream as the+ Claude Code or Codex sessions on the same checkout. `agy` accepts no+ caller-chosen id for a new conversation, so a fresh launch injects nothing and+ the id is linked by the hooks or discovered afterwards; a linked resume passes+ `--conversation <id>`, and `--continue` / `-c` is respected as an explicit user+ choice. `--yolo` maps to `--dangerously-skip-permissions`, and the utility+ subcommands (`models`, `plugin`, `update`, …) pass through without a selector.+ Conversation discovery reads the per-conversation SQLite databases under+ `~/.gemini/antigravity-cli/conversations/`: the id is the file name and the+ workspace comes from two self-describing protobuf fields, so only conversations+ opened on the current directory are offered and a database from another `agy`+ version is skipped instead of failing the listing. Step payloads are+ undocumented, unversioned protobuf, so conversation text is deliberately not+ decoded — the visible-event ledger for this harness comes from lifecycle-hook+ capture, and transcript export fails with a message saying so. Antigravity is+ not part of the no-argument auto-detection pool. (#NNN)+### Fixed- `run` on Windows now resolves npm-style harness installs through `PATHEXT`and starts the resolved wrapper. This avoids accepting an extensionless Unixdiff --git a/README.md b/README.mdindex 56349fbb..202c7f53 100644--- a/README.md+++ b/README.md@@ -31,10 +31,10 @@| Oh My Pi / OMP | Supported | Use `--client omp` / `--agent omp` (or `oh-my-pi`) for native `.omp` MCP config + TypeScript extension; generated extension enforces capture exclusions. || Pi | Supported | Generated `~/.pi/agent/extensions/ai-memory.ts` extension provides lifecycle capture and an HTTP MCP bridge; generated extension enforces capture exclusions. || Crush | Managed-only | `ai-memory run crush` resumes its project-local session database and supplies portable context through a temporary supported global-context file; no lifecycle-hook installer is provided. |-| Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, OMP, and Grok Build CLI. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](docs/managed-workstreams.md). |+| Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, OMP, Grok Build CLI, and Antigravity CLI. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](docs/managed-workstreams.md). || Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. || OpenClaw | Supported | MCP config + native plugin lifecycle hooks; generated plugin enforces capture exclusions. |-| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). 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. |+| 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. `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. || Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works; no hook handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. `ai-memory run grok` adds managed workstream resume with the context packet delivered natively through `--rules`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). || Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. || Kimi Code | Supported | MCP config (`url` entry in `~/.kimi-code/mcp.json`) + lifecycle hooks (`[[hooks]]` in `~/.kimi-code/config.toml`, 10 events including subagent start/stop and `PostToolUseFailure` for tool-failure capture); both paths honor `$KIMI_CODE_HOME`. Handoffs inject via `UserPromptSubmit` stdout (Kimi Code discards `SessionStart` hook stdout); `ai-memory run kimi` adds managed workstream resume. |diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 7ab8a213..a1c183ff 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -231,6 +231,9 @@ pub enum RunHarnessChoice {/// Grok Build CLI (xAI).#[value(alias = "grok-build")]Grok,+ /// Google Antigravity CLI (`agy`).+ #[value(name = "antigravity", alias = "antigravity-cli", alias = "agy")]+ Antigravity,}/// Arguments for `workstream-search`.diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex 020264a3..6d1c4467 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -1195,6 +1195,7 @@ const fn managed_harness(choice: RunHarnessChoice) -> ManagedHarness {RunHarnessChoice::Omp => ManagedHarness::Omp,RunHarnessChoice::Kimi => ManagedHarness::Kimi,RunHarnessChoice::Grok => ManagedHarness::Grok,+ RunHarnessChoice::Antigravity => ManagedHarness::Antigravity,}}@@ -1207,6 +1208,7 @@ const fn managed_harness_from_agent(agent: AgentKind) -> Option<ManagedHarness>AgentKind::Crush => Some(ManagedHarness::Crush),AgentKind::KimiCode => Some(ManagedHarness::Kimi),AgentKind::Grok => Some(ManagedHarness::Grok),+ AgentKind::AntigravityCli => Some(ManagedHarness::Antigravity),_ => None,}}diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rsindex 54672a29..03c2b763 100644--- a/crates/ai-memory-hooks/src/workstream.rs+++ b/crates/ai-memory-hooks/src/workstream.rs@@ -137,6 +137,7 @@ async fn prepare_run(| AgentKind::Omp| AgentKind::KimiCode| AgentKind::Grok+ | AgentKind::AntigravityCli) {return error(StatusCode::BAD_REQUEST,@@ -958,6 +959,72 @@ mod tests {assert_eq!(automatic.status(), StatusCode::BAD_REQUEST);}+ /// The launcher offers `agy` explicitly, so the server has to accept it —+ /// a missing arm here rejects the launch with "requires a supported+ /// command-line harness" after the user already picked the harness.+ #[tokio::test]+ async fn antigravity_is_accepted_explicitly_but_not_in_the_automatic_pool() {+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());++ let explicit = prepare_run(+ State(state.clone()),+ None,+ Json(PrepareManagedRunRequest {+ workspace: "default".into(),+ project: "managed".into(),+ cwd: "/repo".into(),+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ agent: AgentKind::AntigravityCli,+ automatic_harness: false,+ available_agents: Vec::new(),+ workstream: None,+ new_workstream: None,+ lease_owner: "explicit".into(),+ }),+ )+ .await;+ assert_eq!(explicit.status(), StatusCode::OK);+ let body = to_bytes(explicit.into_body(), 64 * 1024).await.unwrap();+ let prepared: PrepareManagedRunResponse = serde_json::from_slice(&body).unwrap();+ assert_eq!(prepared.resolved_agent, Some(AgentKind::AntigravityCli));+ store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: prepared.run_id,+ native_session_id: Some("a0d5ac62-2501-4780-b783-76d159c56cb3".into()),+ source_cursor: None,+ events: Vec::new(),+ complete: true,+ segment_path: None,+ exit_code: Some(0),+ })+ .await+ .unwrap();++ let automatic = prepare_run(+ State(state),+ None,+ Json(PrepareManagedRunRequest {+ workspace: "default".into(),+ project: "managed".into(),+ cwd: "/repo".into(),+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ agent: AgentKind::AntigravityCli,+ automatic_harness: true,+ available_agents: vec![AgentKind::AntigravityCli],+ workstream: None,+ new_workstream: None,+ lease_owner: "automatic".into(),+ }),+ )+ .await;+ assert_eq!(automatic.status(), StatusCode::BAD_REQUEST);+ }+#[tokio::test]async fn grok_run_context_uses_the_direct_delivery_gate() {let temp = TempDir::new().unwrap();diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rsindex 8d20d367..e5ae6364 100644--- a/crates/ai-memory-workstream/src/harness.rs+++ b/crates/ai-memory-workstream/src/harness.rs@@ -26,6 +26,8 @@ pub enum ManagedHarness {Kimi,/// Grok Build CLI (xAI).Grok,+ /// Google Antigravity CLI (`agy`).+ Antigravity,}impl ManagedHarness {@@ -41,6 +43,7 @@ impl ManagedHarness {"omp" | "oh-my-pi" => Some(Self::Omp),"kimi" | "kimi-code" | "kimi-cli" => Some(Self::Kimi),"grok" | "grok-build" => Some(Self::Grok),+ "antigravity" | "antigravity-cli" | "agy" => Some(Self::Antigravity),_ => None,}}@@ -57,6 +60,7 @@ impl ManagedHarness {Self::Omp => AgentKind::Omp,Self::Kimi => AgentKind::KimiCode,Self::Grok => AgentKind::Grok,+ Self::Antigravity => AgentKind::AntigravityCli,}}@@ -72,6 +76,7 @@ impl ManagedHarness {Self::Omp => "omp",Self::Kimi => "kimi",Self::Grok => "grok",+ Self::Antigravity => "agy",}}@@ -87,6 +92,7 @@ impl ManagedHarness {Self::Omp => "omp",Self::Kimi => "kimi",Self::Grok => "grok",+ Self::Antigravity => "antigravity",}}}@@ -227,6 +233,16 @@ pub fn build_launch_plan(args.extend([OsString::from(selector), OsString::from(&id)]);expected = Some(id);}+ ManagedHarness::Antigravity => {+ // `agy` accepts no caller-chosen id for a fresh conversation,+ // so only a linked resume injects a selector. The fresh+ // conversation is linked by the hooks or discovered from the+ // conversation store after exit.+ if let Some(id) = linked_session_id {+ args.extend([OsString::from("--conversation"), OsString::from(id)]);+ expected = Some(id.to_string());+ }+ }}}@@ -252,6 +268,7 @@ pub fn apply_yolo(harness: ManagedHarness, args: &mut Vec<OsString>) {ManagedHarness::Omp => None,ManagedHarness::Kimi => Some("--yolo"),ManagedHarness::Grok => Some("--yolo"),+ ManagedHarness::Antigravity => Some("--dangerously-skip-permissions"),};if let Some(flag) = flag {// Kimi's `--yolo` has hidden aliases (`--yes`, `--auto-approve`) and@@ -290,6 +307,10 @@ fn noninteractive_invocation(harness: ManagedHarness, args: &[OsString]) -> boolManagedHarness::Grok => {has_flag(args, &["--single", "-p", "--prompt-file", "--prompt-json"])}+ // `--prompt` is a documented alias of `--print`. `--prompt-interactive`+ // / `-i` is NOT: it seeds a prompt and then keeps the session open, so+ // it stays adoptable.+ ManagedHarness::Antigravity => has_flag(args, &["--print", "-p", "--prompt"]),}}@@ -453,6 +474,18 @@ fn launch_mode(harness: ManagedHarness, args: &[OsString]) -> LaunchMode {"wrap",].as_slice(),+ ManagedHarness::Antigravity => [+ "agent",+ "agents",+ "changelog",+ "help",+ "install",+ "models",+ "plugin",+ "plugins",+ "update",+ ]+ .as_slice(),};let first = args.first().and_then(|arg| arg.to_str());if first.is_some_and(|value| utility.contains(&value)) {@@ -524,6 +557,10 @@ pub fn has_native_session_selector(harness: ManagedHarness, args: &[OsString]) -"--fork-session",],),+ // `--continue` / `-c` resumes the most recent conversation without+ // naming one; that is still an explicit user choice, so nothing may be+ // injected over it.+ ManagedHarness::Antigravity => has_flag(args, &["--conversation", "--continue", "-c"]),}}@@ -550,6 +587,9 @@ fn explicit_session_id(harness: ManagedHarness, args: &[OsString]) -> Option<Str// returns `None` when no value follows, as intended.ManagedHarness::Kimi => flag_value(args, &["--session", "-S", "--resume", "-r"]),ManagedHarness::Grok => flag_value(args, &["--resume", "-r", "--session-id", "-s"]),+ // A bare `--continue` names no conversation: the id is only known+ // after the fact, from the conversation store.+ ManagedHarness::Antigravity => flag_value(args, &["--conversation"]),}}@@ -633,6 +673,8 @@ fn environment_session_dir_with(ManagedHarness::Kimi => value("KIMI_CODE_HOME").map(|dir| dir.join("sessions")),// Sessions live under `<GROK_HOME>/sessions/<encoded-cwd>/<id>/`.ManagedHarness::Grok => value("GROK_HOME").map(|dir| dir.join("sessions")),+ // `agy` exposes no environment override for its conversation store.+ ManagedHarness::Antigravity => None,}}@@ -868,6 +910,10 @@ mod tests {(ManagedHarness::Omp, None),(ManagedHarness::Kimi, Some("--yolo")),(ManagedHarness::Grok, Some("--yolo")),+ (+ ManagedHarness::Antigravity,+ Some("--dangerously-skip-permissions"),+ ),] {let mut args = Vec::new();apply_yolo(harness, &mut args);@@ -1185,4 +1231,120 @@ mod tests {Some(std::path::Path::new("/stores/kimi-code/sessions")));}++ #[test]+ fn antigravity_names_parse_to_one_variant() {+ for name in ["antigravity", "antigravity-cli", "agy"] {+ assert_eq!(+ ManagedHarness::from_name(name),+ Some(ManagedHarness::Antigravity)+ );+ }+ assert_eq!(ManagedHarness::Antigravity.executable(), "agy");+ }++ /// `agy` rejects a caller-chosen id for a new conversation, so a fresh+ /// launch must leave argv untouched even though the harness is managed.+ #[test]+ fn antigravity_fresh_launch_injects_no_selector() {+ let plan = build_launch_plan(+ ManagedHarness::Antigravity,+ None,+ vec![OsString::from("--model"), OsString::from("gemini-3-pro")],+ None,+ )+ .unwrap();+ assert_eq!(strings(&plan.args), ["--model", "gemini-3-pro"]);+ assert_eq!(plan.expected_session_id, None);+ assert_eq!(plan.mode, LaunchMode::Session);+ }++ #[test]+ fn antigravity_resume_appends_conversation_selector_after_user_arguments() {+ let plan = build_launch_plan(+ ManagedHarness::Antigravity,+ None,+ vec![OsString::from("--effort"), OsString::from("high")],+ Some("a0d5ac62-2501-4780-b783-76d159c56cb3"),+ )+ .unwrap();+ assert_eq!(+ strings(&plan.args),+ [+ "--effort",+ "high",+ "--conversation",+ "a0d5ac62-2501-4780-b783-76d159c56cb3"+ ]+ );+ assert_eq!(+ plan.expected_session_id.as_deref(),+ Some("a0d5ac62-2501-4780-b783-76d159c56cb3")+ );+ }++ #[test]+ fn antigravity_explicit_selector_always_wins() {+ for native in [+ vec![OsString::from("--conversation"), OsString::from("chosen")],+ vec![OsString::from("--conversation=chosen")],+ // `--continue` names no conversation but is still the user's+ // explicit choice, so nothing may be injected over it.+ vec![OsString::from("--continue")],+ vec![OsString::from("-c")],+ ] {+ let plan = build_launch_plan(+ ManagedHarness::Antigravity,+ None,+ native.clone(),+ Some("linked"),+ )+ .unwrap();+ assert_eq!(plan.args, native, "{native:?} must stay byte-identical");+ assert_ne!(plan.expected_session_id.as_deref(), Some("linked"));+ }+ }++ #[test]+ fn antigravity_utility_subcommands_are_passed_through() {+ for utility in [+ "models",+ "plugin",+ "update",+ "agents",+ "install",+ "changelog",+ ] {+ let plan = build_launch_plan(+ ManagedHarness::Antigravity,+ None,+ vec![OsString::from(utility)],+ Some("linked"),+ )+ .unwrap();+ assert_eq!(plan.mode, LaunchMode::Passthrough, "{utility}");+ assert_eq!(strings(&plan.args), [utility]);+ }+ }++ /// `--print` and its `--prompt` alias answer and exit; `-i`+ /// (`--prompt-interactive`) seeds a prompt and keeps the session open, so+ /// it must stay adoptable.+ #[test]+ fn antigravity_print_blocks_adoption_but_interactive_prompt_does_not() {+ for blocked in [+ vec![OsString::from("-p"), OsString::from("summarize")],+ vec![OsString::from("--print"), OsString::from("summarize")],+ vec![OsString::from("--prompt"), OsString::from("summarize")],+ ] {+ assert!(!allows_native_session_adoption(+ ManagedHarness::Antigravity,+ &blocked+ ));+ }+ assert!(allows_native_session_adoption(+ ManagedHarness::Antigravity,+ &[OsString::from("-i"), OsString::from("start here")]+ ));+ }}diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rsindex 9d9ccd75..174c15ee 100644--- a/crates/ai-memory-workstream/src/transcript.rs+++ b/crates/ai-memory-workstream/src/transcript.rs@@ -83,6 +83,17 @@ pub async fn export_transcript(if harness == ManagedHarness::Crush {return export_crush(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, self-describing fields); 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"+ ));+ }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"))?;export_jsonl(harness, &path, native_session_id, source_cursor)@@ -331,7 +342,7 @@ fn export_jsonl(&mut events,&mut losses,),- ManagedHarness::OpenCode | ManagedHarness::Crush => {+ ManagedHarness::OpenCode | ManagedHarness::Crush | ManagedHarness::Antigravity => {return Err(anyhow!("{} transcripts must use their SQLite adapter",harness.as_str()@@ -1562,6 +1573,11 @@ fn locate_session_file(id: &str,) -> Result<Option<PathBuf>> {let root = session_root(harness, home, session_dir);+ if harness == ManagedHarness::Antigravity {+ // The conversation id is the file name, so no scan is ever needed.+ let exact = root.join(format!("{id}.db"));+ return Ok(exact.is_file().then_some(exact));+ }if harness == ManagedHarness::Claude {let encoded = cwd.to_string_lossy().replace('/', "-");let exact = root.join(encoded).join(format!("{id}.jsonl"));@@ -1614,6 +1630,10 @@ fn transcript_file(harness: ManagedHarness, path: &Path) -> bool {.and_then(|name| name.to_str())== Some("main");}+ if harness == ManagedHarness::Antigravity {+ // One SQLite database per conversation, named by its id.+ return path.extension().is_some_and(|ext| ext == "db");+ }path.extension().is_some_and(|ext| ext == "jsonl")|| matches!(harness, ManagedHarness::Pi | ManagedHarness::Omp) && temporary_transcript(path)}@@ -1633,6 +1653,9 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(Stringif harness == ManagedHarness::Grok {return grok_session_header(path);}+ if harness == ManagedHarness::Antigravity {+ return antigravity_session_header(path);+ }let mut reader = BufReader::new(File::open(path)?);let mut line = String::new();for _ in 0..64 {@@ -1662,7 +1685,8 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(StringManagedHarness::OpenCode| ManagedHarness::Crush| ManagedHarness::Kimi- | ManagedHarness::Grok => (None, None),+ | ManagedHarness::Grok+ | ManagedHarness::Antigravity => (None, None),};if let (Some(id), Some(cwd)) = (id, cwd) {return Ok(Some((id.to_string(), PathBuf::from(cwd))));@@ -1722,6 +1746,125 @@ fn grok_session_header(path: &Path) -> Result<Option<(String, PathBuf)>> {Ok(Some((id.to_string(), PathBuf::from(cwd))))}+/// 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+/// first field holds a nested message whose first field is the workspace+/// `file://` URI. Only those two fields are read: every other field is a step+/// payload with an undocumented, unversioned schema.+///+/// A database that does not carry both is unusable for checkout matching, not+/// an error — the conversations directory may hold databases from an `agy`+/// version whose metadata is shaped differently.+fn antigravity_session_header(path: &Path) -> Result<Option<(String, PathBuf)>> {+ let Some(id) = path.file_stem().and_then(|stem| stem.to_str()) else {+ return Ok(None);+ };+ if !valid_native_session_id(id) {+ return Ok(None);+ }+ let Ok(connection) = Connection::open_with_flags(+ path,+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,+ ) else {+ return Ok(None);+ };+ let blob = connection.query_row(+ "SELECT data FROM trajectory_metadata_blob LIMIT 1",+ [],+ |row| row.get::<_, Vec<u8>>(0),+ );+ let Ok(blob) = blob else {+ return Ok(None);+ };+ let Some(workspace) = protobuf_field(&blob, 1)+ .and_then(|nested| protobuf_field(nested, 1))+ .and_then(|bytes| std::str::from_utf8(bytes).ok())+ .and_then(path_from_file_uri)+ else {+ return Ok(None);+ };+ Ok(Some((id.to_string(), workspace)))+}++/// Bytes of the first length-delimited field numbered `field`, or `None` when+/// the message does not contain one. Non-matching fields are skipped by wire+/// type; an unknown wire type ends the walk rather than guessing a length.+fn protobuf_field(message: &[u8], field: u64) -> Option<&[u8]> {+ let mut cursor = 0usize;+ while cursor < message.len() {+ let (key, used) = protobuf_varint(&message[cursor..])?;+ cursor += used;+ match key & 0b111 {+ 0 => cursor += protobuf_varint(&message[cursor..])?.1,+ 1 => cursor = cursor.checked_add(8)?,+ 2 => {+ let (length, used) = protobuf_varint(&message[cursor..])?;+ cursor += used;+ let end = cursor.checked_add(usize::try_from(length).ok()?)?;+ let bytes = message.get(cursor..end)?;+ if key >> 3 == field {+ return Some(bytes);+ }+ cursor = end;+ }+ 5 => cursor = cursor.checked_add(4)?,+ _ => return None,+ }+ }+ None+}++/// Decode one base-128 varint, returning its value and the bytes consumed.+fn protobuf_varint(bytes: &[u8]) -> Option<(u64, usize)> {+ let mut value = 0u64;+ for (index, byte) in bytes.iter().take(10).enumerate() {+ value |= u64::from(byte & 0x7f) << (index * 7);+ if byte & 0x80 == 0 {+ return Some((value, index + 1));+ }+ }+ None+}++/// Local path behind a `file://` URI, or `None` for any other scheme.+///+/// Windows records `file:///C:/dir`, whose leading slash is part of the URI+/// grammar and not of the path; POSIX records `file:///home/dir`, where it is.+/// The drive-letter shape tells them apart without a `#[cfg]` split, so a+/// database copied between platforms still parses.+fn path_from_file_uri(uri: &str) -> Option<PathBuf> {+ let rest = percent_decode(uri.strip_prefix("file://")?);+ let bytes = rest.as_bytes();+ let drive_prefixed = bytes.first() == Some(&b'/')+ && bytes.get(2) == Some(&b':')+ && bytes.get(1).is_some_and(u8::is_ascii_alphabetic);+ let path = if drive_prefixed { &rest[1..] } else { &rest };+ (!path.is_empty()).then(|| PathBuf::from(path))+}++/// Decode `%XX` escapes; invalid escapes are kept verbatim so a path that was+/// never encoded survives unchanged.+fn percent_decode(value: &str) -> String {+ let bytes = value.as_bytes();+ let mut out = Vec::with_capacity(bytes.len());+ let mut index = 0;+ while index < bytes.len() {+ if bytes[index] == b'%'+ && let Some(hex) = bytes.get(index + 1..index + 3)+ && let Ok(hex) = std::str::from_utf8(hex)+ && let Ok(byte) = u8::from_str_radix(hex, 16)+ {+ out.push(byte);+ index += 3;+ continue;+ }+ out.push(bytes[index]);+ index += 1;+ }+ String::from_utf8_lossy(&out).into_owned()+}+fn discover_opencode(home: &Path,session_dir: Option<&Path>,@@ -1910,6 +2053,7 @@ fn session_root(harness: ManagedHarness, home: &Path, override_dir: Option<&PathManagedHarness::Omp => home.join(".omp/agent/sessions"),ManagedHarness::Kimi => home.join(".kimi-code/sessions"),ManagedHarness::Grok => home.join(".grok/sessions"),+ ManagedHarness::Antigravity => home.join(".gemini/antigravity-cli/conversations"),}}@@ -2073,7 +2217,8 @@ mod tests {ManagedHarness::OpenCode| ManagedHarness::Crush| ManagedHarness::Kimi- | ManagedHarness::Grok => {+ | ManagedHarness::Grok+ | ManagedHarness::Antigravity => {unreachable!()}},@@ -3088,4 +3233,169 @@ mod tests {"identical lines must keep identical event ids across rewrites");}++ /// Build the two protobuf layers `agy` writes: an outer message whose+ /// field 1 holds a nested message whose field 1 is the workspace URI.+ fn antigravity_metadata(uri: &str) -> Vec<u8> {+ let mut nested = vec![0x0a];+ nested.push(u8::try_from(uri.len()).unwrap());+ nested.extend_from_slice(uri.as_bytes());+ let mut outer = vec![0x0a];+ outer.push(u8::try_from(nested.len()).unwrap());+ outer.extend_from_slice(&nested);+ outer+ }++ /// `file://` URI for a local path, the way `agy` records its workspace.+ /// Windows paths carry a drive letter and need the extra leading slash.+ fn file_uri(path: &Path) -> String {+ let text = path.to_string_lossy().replace('\\', "/");+ if text.starts_with('/') {+ format!("file://{text}")+ } else {+ format!("file:///{text}")+ }+ }++ fn write_antigravity_conversation(root: &Path, id: &str, uri: &str) -> PathBuf {+ let path = root.join(format!("{id}.db"));+ let connection = Connection::open(&path).unwrap();+ connection+ .execute(+ "CREATE TABLE trajectory_metadata_blob (id text DEFAULT \"main\", data blob, PRIMARY KEY (id))",+ [],+ )+ .unwrap();+ connection+ .execute(+ "INSERT INTO trajectory_metadata_blob (id, data) VALUES ('main', ?1)",+ params![antigravity_metadata(uri)],+ )+ .unwrap();+ path+ }++ /// The conversation id is the file name and the workspace comes from the+ /// metadata blob, so a checkout only sees its own conversations.+ #[tokio::test]+ async fn antigravity_lists_only_conversations_from_this_workspace() {+ let temp = tempfile::TempDir::new().unwrap();+ let root = temp.path().join(".gemini/antigravity-cli/conversations");+ fs::create_dir_all(&root).unwrap();+ let cwd = temp.path().join("checkout");+ fs::create_dir_all(&cwd).unwrap();+ let mine = "a0d5ac62-2501-4780-b783-76d159c56cb3";+ let theirs = "9576275f-7c4e-4709-b372-22d1ad2a0af8";+ write_antigravity_conversation(&root, mine, &file_uri(&cwd));+ write_antigravity_conversation(&root, theirs, "file:///somewhere/else");++ let sessions =+ list_native_sessions(ManagedHarness::Antigravity, temp.path(), &cwd, None, 8)+ .await+ .unwrap();++ assert_eq!(+ sessions+ .iter()+ .map(|s| s.native_session_id.as_str())+ .collect::<Vec<_>>(),+ [mine]+ );+ assert!(+ native_session_exists(ManagedHarness::Antigravity, temp.path(), &cwd, None, mine)+ .unwrap()+ );+ assert!(+ !native_session_exists(+ ManagedHarness::Antigravity,+ temp.path(),+ &cwd,+ None,+ "11111111-1111-1111-1111-111111111111"+ )+ .unwrap()+ );+ }++ /// A database whose metadata is shaped differently — an older or newer+ /// `agy` — is skipped, never an error: it would otherwise take the whole+ /// listing down with it.+ #[tokio::test]+ async fn antigravity_skips_conversations_without_readable_metadata() {+ let temp = tempfile::TempDir::new().unwrap();+ let root = temp.path().join(".gemini/antigravity-cli/conversations");+ fs::create_dir_all(&root).unwrap();+ let cwd = temp.path().join("checkout");+ fs::create_dir_all(&cwd).unwrap();+ // Right name, no metadata table at all.+ Connection::open(root.join("53fb8b64-76c5-4fd8-91d2-dfabe2be4188.db")).unwrap();+ fs::write(root.join("not-a-database.db"), b"garbage").unwrap();++ let sessions =+ list_native_sessions(ManagedHarness::Antigravity, temp.path(), &cwd, None, 8)+ .await+ .unwrap();++ 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() {+ let temp = tempfile::TempDir::new().unwrap();+ let error = export_transcript(+ ManagedHarness::Antigravity,+ temp.path(),+ temp.path(),+ None,+ "a0d5ac62-2501-4780-b783-76d159c56cb3",+ None,+ )+ .await+ .unwrap_err()+ .to_string();+ assert!(error.contains("hook capture"), "{error}");+ }++ #[test]+ fn file_uris_decode_on_both_platform_shapes() {+ assert_eq!(+ path_from_file_uri("file:///C:/Users/me/Projetos"),+ Some(PathBuf::from("C:/Users/me/Projetos"))+ );+ assert_eq!(+ path_from_file_uri("file:///home/me/projects"),+ Some(PathBuf::from("/home/me/projects"))+ );+ assert_eq!(+ path_from_file_uri("file:///C:/Users/me/My%20Projects"),+ Some(PathBuf::from("C:/Users/me/My Projects"))+ );+ // A stray percent that is not an escape must not eat the next bytes.+ assert_eq!(+ path_from_file_uri("file:///tmp/100%done"),+ Some(PathBuf::from("/tmp/100%done"))+ );+ assert_eq!(path_from_file_uri("https://example.com/x"), None);+ assert_eq!(path_from_file_uri("file://"), None);+ }++ #[test]+ fn protobuf_walk_skips_other_fields_and_wire_types() {+ // field 1 varint, field 2 length-delimited, field 3 fixed64,+ // then field 4 length-delimited — only field 4 must come back.+ let mut message = vec![0x08, 0x96, 0x01];+ message.extend_from_slice(&[0x12, 0x02, b'h', b'i']);+ message.extend_from_slice(&[0x19, 0, 0, 0, 0, 0, 0, 0, 0]);+ message.extend_from_slice(&[0x22, 0x03, b'y', b'e', b's']);++ assert_eq!(protobuf_field(&message, 4), Some(&b"yes"[..]));+ assert_eq!(protobuf_field(&message, 2), Some(&b"hi"[..]));+ // A varint field is not length-delimited, so it is never returned.+ assert_eq!(protobuf_field(&message, 1), None);+ assert_eq!(protobuf_field(&message, 9), None);+ // Truncated input ends the walk instead of panicking on a slice.+ assert_eq!(protobuf_field(&[0x22, 0x10, b'x'], 4), None);+ }}diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 2899b128..5a4403b8 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -1,8 +1,8 @@# Managed cross-harness workstreams`ai-memory run` is an opt-in launcher that lets one logical coding session move-between Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, OMP, and Grok-Build CLI. Direct agent launches+between Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, OMP, Grok+Build CLI, and Antigravity CLI. Direct agent launcheskeep their existing ai-memory behavior. There is no global mode toggle and no`switch` command: using `run` selects the current workstream and transparentlycreates or resumes the correct native session for the requested harness.@@ -37,7 +37,8 @@ file, and the current checkout remain authoritative.ai-memory run [--workspace NAME] [--project NAME][--workstream NAME | --new NAME] [--executable PATH][--yolo] [--fresh]- [claude|codex|opencode|pi|crush|omp|kimi|grok] [native arguments...]+ [claude|codex|opencode|pi|crush|omp|kimi|grok|antigravity]+ [native arguments...]```The default is the most recently selected workstream for the current repository@@ -53,8 +54,8 @@ it resumesthe newest session automatically. For an established workstream, server statetakes precedence: ai-memory resumes the most recently linked harness that stillhas a usable local session. It never chooses a newer but obsolete session from-another harness merely because that file has a later timestamp. OMP and Grok-remain available explicitly but are not in the automatic pool.+another harness merely because that file has a later timestamp. OMP, Grok, and+Antigravity remain available explicitly but are not in the automatic pool.Bare mode accepts wrapper options but not harness-native arguments or`--executable`, because their meaning depends on the selected harness. In a new@@ -248,6 +249,27 @@ internals and are never read as transcripts; discovery readsmanaged launcher accepts `grok` and `grok-build`. The native contract wasverified against Grok Build CLI v0.2.111.+Antigravity keeps one SQLite database per conversation at+`~/.gemini/antigravity-cli/conversations/<conversation-id>.db`, so the id is the+file name and no scan is needed to locate one. The workspace a conversation was+opened on comes from `trajectory_metadata_blob`, a protobuf message whose first+field holds a nested message whose first field is the workspace `file://` URI;+only those two fields are read. A database that does not carry them — an older+or newer `agy` — is skipped rather than failing the listing. Note the recorded+workspace is the directory `agy` was launched from, not a checkout root, so a+conversation started one level up is not offered inside a subdirectory.++`agy` accepts no caller-chosen id for a new conversation, so a fresh launch+injects nothing and the id is linked by the hooks or discovered after exit; a+linked resume passes `--conversation <id>`. `--continue` / `-c` is treated as an+explicit user choice and is never overridden. `--yolo` maps to+`--dangerously-skip-permissions`. Step payloads are undocumented, unversioned+protobuf blobs, so ai-memory does not decode conversation text: the visible-event+ledger for this harness comes from lifecycle-hook capture, and transcript export+fails with a message saying so. The managed launcher accepts `antigravity`,+`antigravity-cli`, and `agy`. Antigravity is not part of the no-argument+auto-detection set; name it explicitly or pick it from `ai-memory show`.+Crush needs no ai-memory hook installation for managed mode. The launcher readsits one-time context from the server, copies the existing global Crush JSON intoa private temporary directory, appends an ephemeral context path, and points the