Skip to content

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

Rust

feat(hooks): extract Antigravity tool output from step logs

Gabrigasd11c31c7d497
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index 46c0abf7..46e8af92 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -34,7 +34,7 @@ use super::hook_capture::{
};
use super::hook_drain_process;
use super::hook_spool;
-use super::path_util::strip_windows_verbatim_prefix;
+use super::path_util::{home_dir, strip_windows_verbatim_prefix};
// All drain/handoff timings default to the current short values and can be
// overridden by whole-minute env vars for very high-latency or large-backlog
@@ -623,6 +623,15 @@ where
if ai_memory_hooks::cap_lifecycle_body_for_client(&mut json, hook_event) {
payload = serde_json::to_string(&json)?;
}
+ if agent_kind == AgentKind::AntigravityCli
+ && ai_memory_hooks::enrich_antigravity_step_output(
+ &mut json,
+ hook_event,
+ home_dir().as_deref(),
+ )
+ {
+ payload = serde_json::to_string(&json)?;
+ }
let (policy_cwd, canonical_session_id) = hook_context(&args.agent, &json);
let inspection_cwd = policy_cwd.as_deref().map(lexical_capture_cwd);
let policy = policy_cwd.as_deref().map(capture_policy);
@@ -2595,6 +2604,67 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn antigravity_post_tool_use_spools_enriched_output() {
+ let tmp = tempfile::tempdir().unwrap();
+ let artifact_dir = tmp.path().join("brain").join("conv-123");
+ let step_dir = artifact_dir
+ .join(".system_generated")
+ .join("steps")
+ .join("7");
+ std::fs::create_dir_all(&step_dir).unwrap();
+ std::fs::write(
+ step_dir.join("output.txt"),
+ "npm test passed with 0 errors\n",
+ )
+ .unwrap();
+
+ let data_dir = tmp.path().join("data");
+ let raw = serde_json::json!({
+ "conversationId": "conv-123",
+ "workspacePaths": [tmp.path().to_str().unwrap()],
+ "toolCall": {
+ "name": "run_command",
+ "args": {
+ "CommandLine": "npm test"
+ }
+ },
+ "stepIdx": 7,
+ "artifactDirectoryPath": artifact_dir.to_str().unwrap()
+ });
+
+ let mut stdout = Vec::new();
+ let args = HookArgs {
+ event: "post-tool-use".into(),
+ agent: "antigravity-cli".into(),
+ server_url: "http://127.0.0.1:41399".into(),
+ auth_token: None,
+ project_strategy: None,
+ check_capture: false,
+ capture_assistant: false,
+ capture_mode: None,
+ };
+
+ run_with_payload(
+ Some(data_dir.clone()),
+ args,
+ raw.to_string(),
+ &mut stdout,
+ |_, _| Ok(()),
+ )
+ .await
+ .unwrap();
+
+ let spooled = read_spooled_entries(&hook_spool::spool_dir(&data_dir));
+ assert_eq!(spooled.len(), 1);
+ let body: serde_json::Value = serde_json::from_str(&spooled[0].body).unwrap();
+ assert_eq!(
+ body.get("tool_response")
+ .and_then(serde_json::Value::as_str),
+ Some("npm test passed with 0 errors")
+ );
+ }
+
fn kimi_hook_args(event: &str, server_url: &str) -> HookArgs {
HookArgs {
event: event.into(),
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 595a9d17..e95aad8f 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -288,14 +288,14 @@ function captureCharEq(a: string, b: string, insensitive: boolean): boolean { re
function captureLiteralPrefix(path: string): string { const glob = path.search(/[*?]/); if (glob < 0) return path; const slash = path.lastIndexOf("/", glob); if (slash < 0) return ""; const head = path.slice(0, slash + 1); const trimmed = head.slice(0, -1); return trimmed && !trimmed.endsWith(":") ? trimmed : head; }
function captureStartsWith(path: string, prefix: string, insensitive: boolean): boolean { const p = path[Symbol.iterator](); for (const x of prefix) { const c = p.next(); if (c.done || !captureCharEq(x, c.value, insensitive)) return false; } return true; }
function captureGlobReaches(glob: string, prefix: string, insensitive: boolean, budget: { work: number }): boolean | undefined { const target = prefix.replace(/\/+$/, ""); const depth = target.split("/").filter(Boolean).length; if (!depth) return true; let seen = 0; let offset = 0; for (const part of glob.split("/")) { offset += part.length; if (part && ++seen === depth) return captureGlob(glob.slice(0, offset), target, insensitive, budget); offset++; } return false; }
-function captureShellCommand(args: Record<string, unknown> | undefined): string | undefined { if (!args || typeof args !== "object" || Array.isArray(args)) return undefined; const value = "command" in args ? args.command : args.cmd; if (typeof value === "string") return value; if (Array.isArray(value) && value.every((x) => typeof x === "string")) return value.join(" "); return undefined; }
+function captureShellCommand(args: Record<string, unknown> | undefined): string | undefined { if (!args || typeof args !== "object" || Array.isArray(args)) return undefined; const value = "command" in args ? args.command : ("cmd" in args ? args.cmd : args.CommandLine); if (typeof value === "string") return value; if (Array.isArray(value) && value.every((x) => typeof x === "string")) return value.join(" "); return undefined; }
function captureShellWords(command: string): string[] { const special = (c: string) => /\s/.test(c) || "|&;<>()".includes(c); const chars = [...command]; const words: string[] = []; let word = ""; let inWord = false; let quote = ""; for (let i = 0; i < chars.length; i++) { const c = chars[i]; const next = chars[i + 1]; if (quote) { if (c === quote) quote = ""; else if (quote === '"' && c === "\\" && (next === '"' || next === "\\")) { word += next; i++; } else word += c; } else if (c === "'" || c === '"') { quote = c; inWord = true; } else if (c === "\\" && next !== undefined && (special(next) || next === "'" || next === '"' || next === "\\")) { word += next; i++; inWord = true; } else if (special(c)) { if (inWord) words.push(word); word = ""; inWord = false; } else { word += c; inWord = true; } } if (inWord) words.push(word); return words; }
function captureShellArguments(word: string): string[] { const out = word.startsWith("-") ? [] : [word]; const eq = word.indexOf("="); if (eq >= 0) out.push(word.slice(eq + 1)); return out.filter((argument) => argument.trim() !== ""); }
// Lexical only, like the native hook: nothing is expanded or executed, so
// variables, command substitution, and `cd` state are not followed. A tool's
// own `workdir` replaces the event cwd for relative arguments.
function captureMatchCommand(command: string, config: CaptureConfig, workdir?: string): boolean | undefined { const budget = { work: 0 }; const home = homedir(); const base = workdir === undefined ? config.base : /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(workdir) ? workdir : config.base && captureJoin(config.base, workdir); for (const word of captureShellWords(command)) for (const argument of captureShellArguments(word)) { const expanded = argument.startsWith("~/") ? captureJoin(home, argument.slice(2)) : argument; if ([...expanded].length > CAPTURE_MAX_PATH_CHARS) continue; const absolute = /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(expanded); if (!absolute && !base) continue; const candidate = captureNormalize(absolute ? expanded : captureJoin(base, expanded)); if (!candidate) continue; const glob = /[*?]/.test(candidate.path); for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; const under = captureStartsWith(candidate.path, pattern.prefix, pattern.windows); if (!under && !glob) continue; if (under) { const directory = pattern.directory ? captureGlob(pattern.directory, candidate.path, pattern.windows, budget) : false; if (directory !== false) return directory; const match = captureGlob(pattern.path, candidate.path, pattern.windows, budget); if (match !== false) return match; } if (glob) { const reaches = captureGlobReaches(candidate.path, pattern.prefix, pattern.windows, budget); if (reaches !== false) return reaches; } } } return false; }
-function captureTool(payload: Record<string, unknown>): { family: CaptureProtocol["tool_family"]; paths?: string[]; extraction: CaptureProtocol["extraction_state"]; callID?: string; command?: string; workdir?: string } { const name = typeof payload.tool === "string" ? payload.tool.toLowerCase() : ""; const args = payload.args as Record<string, unknown> | undefined; const call = ["tool_use_id","toolUseId","tool_call_id","toolCallId","call_id","callId","callID"].map((k) => payload[k]).find((v): v is string => typeof v === "string" && /^[A-Za-z0-9_.-]{1,128}$/.test(v)); if (["search","grep","glob","find","list","ls","list_files","read_dir"].includes(name)) return { family: "search-list", extraction: "not-applicable", callID: call }; if (["bash","shell","shell_command","exec","execute","run_command","web_search","terminal","execute_bash","execute_cmd"].includes(name)) return { family: "non-file", extraction: "extracted", callID: call, command: captureShellCommand(args), workdir: typeof args?.workdir === "string" && args.workdir.trim() ? args.workdir : undefined }; if (!["read","write","edit","apply_patch","notebookedit","notebook_edit","create_file","delete_file","rename_file","move_file","multi_edit","multiedit","replace","replace_all"].includes(name)) return { family: "unknown", extraction: "extracted", callID: call }; const direct = (o: any): string[] | undefined => { if (!o || typeof o !== "object") return undefined; const r: string[] = []; for (const k of ["file_path","filePath","path","absolute_path","AbsolutePath","notebook_path"]) if (k in o) { if (typeof o[k] !== "string") return undefined; r.push(o[k]); } if ("paths" in o) { if (!Array.isArray(o.paths) || o.paths.some((x: unknown) => typeof x !== "string")) return undefined; r.push(...o.paths); } return r.length && r.length <= CAPTURE_MAX_CANDIDATES ? r : undefined; }; let paths = direct(args); if (["multi_edit","multiedit","replace_all"].includes(name)) { const entries = args?.edits ?? args?.replacements; if (!Array.isArray(entries) || !entries.length || entries.length > CAPTURE_MAX_CANDIDATES) paths = undefined; else { paths = paths ?? []; for (const entry of entries) { const more = direct(entry); if (!more || paths.length + more.length > CAPTURE_MAX_CANDIDATES) { paths = undefined; break; } paths.push(...more); } } } if (!paths || paths.some((p) => !p.trim() || [...p].length > CAPTURE_MAX_PATH_CHARS)) return { family: "file", extraction: "missing-or-malformed", callID: call }; return { family: "file", paths, extraction: "extracted", callID: call }; }
+function captureTool(payload: Record<string, unknown>): { family: CaptureProtocol["tool_family"]; paths?: string[]; extraction: CaptureProtocol["extraction_state"]; callID?: string; command?: string; workdir?: string } { const name = typeof payload.tool === "string" ? payload.tool.toLowerCase() : ""; const args = payload.args as Record<string, unknown> | undefined; const call = ["tool_use_id","toolUseId","tool_call_id","toolCallId","call_id","callId","callID"].map((k) => payload[k]).find((v): v is string => typeof v === "string" && /^[A-Za-z0-9_.-]{1,128}$/.test(v)); if (["search","grep","glob","find","list","ls","list_files","read_dir","list_dir","grep_search","search_files","find_by_name"].includes(name)) return { family: "search-list", extraction: "not-applicable", callID: call }; if (["bash","shell","shell_command","exec","execute","run_command","web_search","search_web","manage_task","manage_subagents","terminal","execute_bash","execute_cmd"].includes(name)) return { family: "non-file", extraction: "extracted", callID: call, command: captureShellCommand(args), workdir: typeof args?.workdir === "string" && args.workdir.trim() ? args.workdir : undefined }; if (!["read","write","edit","apply_patch","notebookedit","notebook_edit","create_file","delete_file","rename_file","move_file","multi_edit","multiedit","replace","replace_all"].includes(name)) return { family: "unknown", extraction: "extracted", callID: call }; const direct = (o: any): string[] | undefined => { if (!o || typeof o !== "object") return undefined; const r: string[] = []; for (const k of ["file_path","filePath","path","absolute_path","AbsolutePath","notebook_path","TargetFile"]) if (k in o) { if (typeof o[k] !== "string") return undefined; r.push(o[k]); } if ("paths" in o) { if (!Array.isArray(o.paths) || o.paths.some((x: unknown) => typeof x !== "string")) return undefined; r.push(...o.paths); } return r.length && r.length <= CAPTURE_MAX_CANDIDATES ? r : undefined; }; let paths = direct(args); if (["multi_edit","multiedit","replace_all"].includes(name)) { const entries = args?.edits ?? args?.replacements; if (!Array.isArray(entries) || !entries.length || entries.length > CAPTURE_MAX_CANDIDATES) paths = undefined; else { paths = paths ?? []; for (const entry of entries) { const more = direct(entry); if (!more || paths.length + more.length > CAPTURE_MAX_CANDIDATES) { paths = undefined; break; } paths.push(...more); } } } if (!paths || paths.some((p) => !p.trim() || [...p].length > CAPTURE_MAX_PATH_CHARS)) return { family: "file", extraction: "missing-or-malformed", callID: call }; return { family: "file", paths, extraction: "extracted", callID: call }; }
// An external lifecycle owner (`AI_MEMORY_CAPTURE_OWNER`, any value that is
// non-empty after trimming) takes over capture for this process: the gate runs
// before the capture-policy marker scan, so no disposition work, no marker read
diff --git a/crates/ai-memory-hooks/src/antigravity.rs b/crates/ai-memory-hooks/src/antigravity.rs
new file mode 100644
index 00000000..9e320ffd
--- /dev/null
+++ b/crates/ai-memory-hooks/src/antigravity.rs
@@ -0,0 +1,476 @@
+//! Antigravity CLI lifecycle hook output extraction and enrichment.
+//!
+//! Antigravity CLI's native `PostToolUse` event payload carries invocation
+//! metadata (`toolCall`, `conversationId`, `stepIdx`, `artifactDirectoryPath`)
+//! but omits command/tool stdout and stderr from the event JSON itself.
+//! Instead, the CLI writes step execution logs to:
+//! `<artifactDirectoryPath>/.system_generated/steps/<stepIdx>/output.txt`.
+//!
+//! This module resolves and reads that output file for output-eligible tools
+//! (e.g. `run_command`, `view_file`, `list_dir`, etc.) while strictly
+//! preserving the code extraction behavior for file-editing tools (`write_to_file`,
+//! `replace_file_content`, etc.), which extract actual code changes from `args`.
+
+use std::fs::File;
+use std::io::Read;
+use std::path::{Path, PathBuf};
+
+use crate::payload::HookEvent;
+
+/// Maximum number of bytes read from Antigravity's `output.txt`.
+/// Matches the standard tool excerpt upper bound (2 KB) so spooled events
+/// remain compact and within bounded limits.
+pub const MAX_ANTIGRAVITY_OUTPUT_BYTES: usize = 2048;
+
+/// Check if a tool is eligible for output extraction from `output.txt`.
+///
+/// Whitelist rationale:
+/// - Tools like `run_command`, `view_file`, and search tools produce valuable
+/// execution logs or inspection output in `output.txt`.
+/// - Mutation tools (`write_to_file`, `replace_file_content`) must NEVER be
+/// enriched here because their `output.txt` only contains generic confirmation
+/// strings ("Created file..."), whereas `ai-memory` extracts the real code
+/// from `args.CodeContent` / `args.ReplacementContent`. Overwriting with
+/// `tool_response` would destroy that code capture.
+/// - Unproven generic tools (`read_url_content`, `read_resource`, `call_mcp_tool`)
+/// fail closed to `ToolFamily::Unknown`.
+#[must_use]
+pub fn is_output_eligible(tool_name: &str) -> bool {
+ matches!(
+ tool_name.to_ascii_lowercase().as_str(),
+ "run_command"
+ | "view_file"
+ | "list_dir"
+ | "find_by_name"
+ | "grep_search"
+ | "search_web"
+ | "manage_task"
+ | "manage_subagents"
+ )
+}
+
+/// Resolves an artifact directory path, expanding leading `~` or `~/`
+/// if `home_dir` is provided.
+#[must_use]
+pub fn resolve_artifact_dir(raw_path: &str, home_dir: Option<&Path>) -> Option<PathBuf> {
+ let trimmed = raw_path.trim();
+ if trimmed.is_empty() {
+ return None;
+ }
+ if let Some(stripped) = trimmed
+ .strip_prefix("~/")
+ .or_else(|| trimmed.strip_prefix("~\\"))
+ {
+ home_dir.map(|h| h.join(stripped))
+ } else if trimmed == "~" {
+ home_dir.map(Path::to_path_buf)
+ } else {
+ Some(PathBuf::from(trimmed))
+ }
+}
+
+/// Builds the absolute path to a step's `output.txt` file given the artifact directory
+/// and the step index.
+#[must_use]
+pub fn step_output_file_path(artifact_dir: &Path, step_idx: u64) -> PathBuf {
+ artifact_dir
+ .join(".system_generated")
+ .join("steps")
+ .join(step_idx.to_string())
+ .join("output.txt")
+}
+
+/// Reads up to `max_bytes` from `output_path`, ensuring it is a regular file
+/// (preventing symlink traversal and blocking on FIFOs/special devices). Slices
+/// cleanly on multi-byte UTF-8 code point boundaries and trims trailing whitespace.
+/// Returns `None` if the file cannot be read, is not a regular file, or contains
+/// only whitespace.
+#[must_use]
+pub fn read_step_output(output_path: &Path, max_bytes: usize) -> Option<String> {
+ let metadata = std::fs::symlink_metadata(output_path).ok()?;
+ if !metadata.is_file() {
+ return None;
+ }
+
+ let file = File::open(output_path).ok()?;
+ let mut reader = Read::take(file, max_bytes as u64);
+ let mut buffer = Vec::new();
+ reader.read_to_end(&mut buffer).ok()?;
+ if buffer.is_empty() {
+ return None;
+ }
+
+ let text = match std::str::from_utf8(&buffer) {
+ Ok(valid) => valid,
+ Err(err) => {
+ let valid = &buffer[..err.valid_up_to()];
+ std::str::from_utf8(valid).unwrap_or_default()
+ }
+ };
+ let trimmed = text.trim_end();
+ if trimmed.trim().is_empty() {
+ None
+ } else {
+ Some(trimmed.to_string())
+ }
+}
+
+fn extract_step_idx(raw: &serde_json::Value) -> Option<u64> {
+ if let Some(idx) = raw.get("stepIdx").and_then(serde_json::Value::as_u64) {
+ return Some(idx);
+ }
+ raw.get("stepIdx")
+ .and_then(serde_json::Value::as_str)
+ .and_then(|s| s.parse::<u64>().ok())
+}
+
+fn extract_artifact_dir_str(raw: &serde_json::Value) -> Option<&str> {
+ let path = raw
+ .get("artifactDirectoryPath")
+ .and_then(serde_json::Value::as_str)?;
+ let trimmed = path.trim();
+ if trimmed.is_empty() {
+ None
+ } else {
+ Some(trimmed)
+ }
+}
+
+fn artifact_dir_from_transcript(
+ raw: &serde_json::Value,
+ home_dir: Option<&Path>,
+) -> Option<PathBuf> {
+ let transcript = raw
+ .get("transcriptPath")
+ .and_then(serde_json::Value::as_str)?;
+ let resolved = resolve_artifact_dir(transcript, home_dir)?;
+ let logs_dir = resolved.parent()?;
+ let sys_dir = logs_dir.parent()?;
+ if sys_dir.file_name()? != ".system_generated" {
+ return None;
+ }
+ sys_dir.parent().map(Path::to_path_buf)
+}
+
+fn extract_tool_name(raw: &serde_json::Value) -> Option<&str> {
+ raw.get("toolCall")
+ .and_then(|tc| tc.get("name"))
+ .and_then(serde_json::Value::as_str)
+ .or_else(|| raw.get("tool").and_then(serde_json::Value::as_str))
+}
+
+/// Enriches an Antigravity hook payload by reading output from the step's `output.txt`
+/// if eligible and unpopulated. Returns `true` if `tool_response` was populated.
+pub fn enrich_antigravity_step_output(
+ raw: &mut serde_json::Value,
+ event: HookEvent,
+ home_dir: Option<&Path>,
+) -> bool {
+ if event != HookEvent::PostToolUse {
+ return false;
+ }
+ if raw
+ .get("tool_response")
+ .and_then(serde_json::Value::as_str)
+ .is_some_and(|s| !s.trim().is_empty())
+ {
+ return false;
+ }
+ let Some(tool_name) = extract_tool_name(raw) else {
+ return false;
+ };
+ if !is_output_eligible(tool_name) {
+ return false;
+ }
+ let Some(step_idx) = extract_step_idx(raw) else {
+ return false;
+ };
+ let artifact_dir = extract_artifact_dir_str(raw)
+ .and_then(|p| resolve_artifact_dir(p, home_dir))
+ .or_else(|| artifact_dir_from_transcript(raw, home_dir));
+ let Some(artifact_dir) = artifact_dir else {
+ return false;
+ };
+ let output_file = step_output_file_path(&artifact_dir, step_idx);
+ let Some(output) = read_step_output(&output_file, MAX_ANTIGRAVITY_OUTPUT_BYTES) else {
+ return false;
+ };
+ if let Some(obj) = raw.as_object_mut() {
+ obj.insert("tool_response".into(), serde_json::Value::String(output));
+ true
+ } else {
+ false
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::fs;
+ use tempfile::tempdir;
+
+ #[test]
+ fn test_is_output_eligible() {
+ // Arrange & Assert: Eligible tools (case-insensitive)
+ assert!(is_output_eligible("run_command"));
+ assert!(is_output_eligible("RUN_COMMAND"));
+ assert!(is_output_eligible("view_file"));
+ assert!(is_output_eligible("View_File"));
+ assert!(is_output_eligible("list_dir"));
+ assert!(is_output_eligible("find_by_name"));
+ assert!(is_output_eligible("grep_search"));
+ assert!(is_output_eligible("search_web"));
+ assert!(is_output_eligible("manage_task"));
+ assert!(is_output_eligible("manage_subagents"));
+
+ // Arrange & Assert: Ineligible tools (edit tools, UI, media, unproven)
+ assert!(!is_output_eligible("write_to_file"));
+ assert!(!is_output_eligible("replace_file_content"));
+ assert!(!is_output_eligible("multi_replace_file_content"));
+ assert!(!is_output_eligible("generate_image"));
+ assert!(!is_output_eligible("ask_question"));
+ assert!(!is_output_eligible("schedule"));
+ assert!(!is_output_eligible("read_url_content"));
+ assert!(!is_output_eligible("read_resource"));
+ assert!(!is_output_eligible("call_mcp_tool"));
+ assert!(!is_output_eligible("unknown_tool"));
+ }
+
+ #[test]
+ fn test_resolve_artifact_dir() {
+ let fake_home = Path::new("/custom/home");
+
+ // Act & Assert
+ assert_eq!(
+ resolve_artifact_dir("/abs/path", Some(fake_home)),
+ Some(PathBuf::from("/abs/path"))
+ );
+ assert_eq!(
+ resolve_artifact_dir("~/workspace/dir", Some(fake_home)),
+ Some(PathBuf::from("/custom/home/workspace/dir"))
+ );
+ assert_eq!(
+ resolve_artifact_dir("~", Some(fake_home)),
+ Some(PathBuf::from("/custom/home"))
+ );
+ assert_eq!(resolve_artifact_dir("~/workspace/dir", None), None);
+ assert_eq!(resolve_artifact_dir("", Some(fake_home)), None);
+ assert_eq!(resolve_artifact_dir(" ", Some(fake_home)), None);
+ }
+
+ #[test]
+ fn test_read_step_output_bounds_and_trims() {
+ // Arrange
+ let dir = tempdir().unwrap();
+ let file_path = dir.path().join("output.txt");
+ let content = "Hello from output.txt \n\n";
+ fs::write(&file_path, content).unwrap();
+
+ // Act
+ let read = read_step_output(&file_path, 1024);
+
+ // Assert
+ assert_eq!(read, Some("Hello from output.txt".to_string()));
+
+ // Act: max_bytes truncate
+ let truncated = read_step_output(&file_path, 5);
+ assert_eq!(truncated, Some("Hello".to_string()));
+ }
+
+ #[test]
+ #[cfg(unix)]
+ fn test_read_step_output_rejects_symlink() {
+ use std::os::unix::fs::symlink;
+ let dir = tempdir().unwrap();
+ let target = dir.path().join("real_output.txt");
+ let link = dir.path().join("output.txt");
+ fs::write(&target, "secret content").unwrap();
+ symlink(&target, &link).unwrap();
+
+ assert_eq!(read_step_output(&link, 1024), None);
+ }
+
+ #[test]
+ fn test_read_step_output_handles_multibyte_utf8_truncation() {
+ let dir = tempdir().unwrap();
+ let file_path = dir.path().join("output.txt");
+ // "🦀" is 4 bytes. "abc🦀def" with limit 5 truncates inside the emoji.
+ fs::write(&file_path, "abc🦀def").unwrap();
+
+ let read = read_step_output(&file_path, 5);
+ assert_eq!(read, Some("abc".to_string()));
+ }
+
+ #[test]
+ fn test_read_step_output_missing_or_empty() {
+ // Arrange
+ let dir = tempdir().unwrap();
+ let file_path = dir.path().join("empty.txt");
+ fs::write(&file_path, " \n\t").unwrap();
+
+ // Act & Assert
+ assert_eq!(read_step_output(&file_path, 1024), None);
+ assert_eq!(
+ read_step_output(&dir.path().join("nonexistent.txt"), 1024),
+ None
+ );
+ }
+
+ #[test]
+ fn test_enrich_antigravity_step_output_success() {
+ // Arrange
+ let dir = tempdir().unwrap();
+ let step_dir = dir.path().join(".system_generated").join("steps").join("5");
+ fs::create_dir_all(&step_dir).unwrap();
+ fs::write(
+ step_dir.join("output.txt"),
+ "npm test passed: 42 tests OK\n",
+ )
+ .unwrap();
+
+ let mut payload = serde_json::json!({
+ "toolCall": {
+ "name": "run_command",
+ "args": {
+ "CommandLine": "npm test"
+ }
+ },
+ "stepIdx": 5,
+ "artifactDirectoryPath": dir.path().to_str().unwrap()
+ });
+
+ // Act
+ let enriched = enrich_antigravity_step_output(&mut payload, HookEvent::PostToolUse, None);
+
+ // Assert
+ assert!(enriched);
+ assert_eq!(
+ payload
+ .get("tool_response")
+ .and_then(serde_json::Value::as_str),
+ Some("npm test passed: 42 tests OK")
+ );
+ }
+
+ #[test]
+ fn test_enrich_antigravity_step_output_falls_back_to_transcript_path() {
+ // Arrange
+ let dir = tempdir().unwrap();
+ let logs_dir = dir.path().join(".system_generated").join("logs");
+ let step_dir = dir
+ .path()
+ .join(".system_generated")
+ .join("steps")
+ .join("12");
+ fs::create_dir_all(&logs_dir).unwrap();
+ fs::create_dir_all(&step_dir).unwrap();
+ let transcript = logs_dir.join("transcript.jsonl");
+ fs::write(&transcript, "").unwrap();
+ fs::write(step_dir.join("output.txt"), "found file content").unwrap();
+
+ let mut payload = serde_json::json!({
+ "toolCall": {
+ "name": "view_file",
+ "args": {"AbsolutePath": "/workspace/src/lib.rs"}
+ },
+ "stepIdx": "12",
+ "transcriptPath": transcript.to_str().unwrap()
+ });
+
+ // Act
+ let enriched = enrich_antigravity_step_output(&mut payload, HookEvent::PostToolUse, None);
+
+ // Assert
+ assert!(enriched);
+ assert_eq!(
+ payload
+ .get("tool_response")
+ .and_then(serde_json::Value::as_str),
+ Some("found file content")
+ );
+ }
+
+ #[test]
+ fn test_enrich_antigravity_step_output_bypasses_ineligible_tools() {
+ // Arrange: write_to_file must NEVER be enriched with output.txt
+ let dir = tempdir().unwrap();
+ let step_dir = dir.path().join(".system_generated").join("steps").join("1");
+ fs::create_dir_all(&step_dir).unwrap();
+ fs::write(step_dir.join("output.txt"), "Created file test.rs").unwrap();
+
+ let mut payload = serde_json::json!({
+ "toolCall": {
+ "name": "write_to_file",
+ "args": {
+ "TargetFile": "/workspace/test.rs",
+ "CodeContent": "fn main() {}"
+ }
+ },
+ "stepIdx": 1,
+ "artifactDirectoryPath": dir.path().to_str().unwrap()
+ });
+
+ // Act
+ let enriched = enrich_antigravity_step_output(&mut payload, HookEvent::PostToolUse, None);
+
+ // Assert
+ assert!(!enriched);
+ assert!(payload.get("tool_response").is_none());
+ }
+
+ #[test]
+ fn test_enrich_antigravity_step_output_ignores_non_post_tool_use() {
+ // Arrange
+ let dir = tempdir().unwrap();
+ let step_dir = dir.path().join(".system_generated").join("steps").join("1");
+ fs::create_dir_all(&step_dir).unwrap();
+ fs::write(step_dir.join("output.txt"), "output").unwrap();
+
+ let mut payload = serde_json::json!({
+ "toolCall": {
+ "name": "run_command",
+ "args": {"CommandLine": "ls"}
+ },
+ "stepIdx": 1,
+ "artifactDirectoryPath": dir.path().to_str().unwrap()
+ });
+
+ // Act: PreToolUse
+ let enriched = enrich_antigravity_step_output(&mut payload, HookEvent::PreToolUse, None);
+
+ // Assert
+ assert!(!enriched);
+ assert!(payload.get("tool_response").is_none());
+ }
+
+ #[test]
+ fn test_enrich_antigravity_step_output_does_not_overwrite_existing_response() {
+ // Arrange
+ let dir = tempdir().unwrap();
+ let step_dir = dir.path().join(".system_generated").join("steps").join("1");
+ fs::create_dir_all(&step_dir).unwrap();
+ fs::write(step_dir.join("output.txt"), "from disk").unwrap();
+
+ let mut payload = serde_json::json!({
+ "toolCall": {
+ "name": "run_command",
+ "args": {"CommandLine": "ls"}
+ },
+ "stepIdx": 1,
+ "artifactDirectoryPath": dir.path().to_str().unwrap(),
+ "tool_response": "already populated"
+ });
+
+ // Act
+ let enriched = enrich_antigravity_step_output(&mut payload, HookEvent::PostToolUse, None);
+
+ // Assert
+ assert!(!enriched);
+ assert_eq!(
+ payload
+ .get("tool_response")
+ .and_then(serde_json::Value::as_str),
+ Some("already populated")
+ );
+ }
+}
diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rs
index 5903f58d..d483718e 100644
--- a/crates/ai-memory-hooks/src/capture_policy.rs
+++ b/crates/ai-memory-hooks/src/capture_policy.rs
@@ -782,9 +782,10 @@ fn family(name: &str) -> ToolFamily {
| "fs_write" => ToolFamily::File,
"read_file" | "write_file" | "edit_file" | "patch" => ToolFamily::File,
"search" | "grep" | "glob" | "find" | "list" | "ls" | "list_files" | "read_dir"
- | "list_dir" | "grep_search" | "search_files" => ToolFamily::SearchList,
+ | "list_dir" | "grep_search" | "search_files" | "find_by_name" => ToolFamily::SearchList,
"bash" | "shell" | "shell_command" | "exec" | "execute" | "run_command" | "web_search"
- | "terminal" | "execute_bash" | "execute_cmd" => ToolFamily::NonFile,
+ | "search_web" | "manage_task" | "manage_subagents" | "terminal" | "execute_bash"
+ | "execute_cmd" => ToolFamily::NonFile,
_ => ToolFamily::Unknown,
}
}
@@ -884,7 +885,11 @@ fn direct_paths(object: &Map<String, Value>) -> Option<Vec<String>> {
/// The command line of a shell tool. Argument vectors (Codex exec) are
/// joined so a `bash -lc "<script>"` element is tokenized like any script.
fn shell_command(args: &Value) -> Option<String> {
- match args.get("command").or_else(|| args.get("cmd"))? {
+ match args
+ .get("command")
+ .or_else(|| args.get("cmd"))
+ .or_else(|| args.get("CommandLine"))?
+ {
Value::String(command) => Some(command.clone()),
Value::Array(items) => items
.iter()
diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rs
index 4b8d00e7..5c9e6bc0 100644
--- a/crates/ai-memory-hooks/src/lib.rs
+++ b/crates/ai-memory-hooks/src/lib.rs
@@ -21,6 +21,7 @@
//! This crate does not read process environment directly; server configuration
//! is resolved once by `ai-memory-cli` and threaded in as typed state.
+pub mod antigravity;
mod assistant_capture;
pub mod capture_policy;
mod grants;
@@ -30,6 +31,10 @@ pub mod router;
pub mod synth;
pub mod workstream;
+pub use antigravity::{
+ MAX_ANTIGRAVITY_OUTPUT_BYTES, enrich_antigravity_step_output, is_output_eligible,
+};
+
// Re-export the sanitizer types from core so callers that grew up
// pointing at this crate's `sanitize` module keep working.
pub use ai_memory_core::{SanitizeConfig, Sanitized, Sanitizer};
diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rs
index 9b484059..d77834b9 100644
--- a/crates/ai-memory-hooks/src/payload.rs
+++ b/crates/ai-memory-hooks/src/payload.rs
@@ -457,7 +457,7 @@ impl HookEnvelope {
/// from common shapes used by Claude Code, Codex, and OpenCode hook
/// payloads.
#[must_use]
- pub fn from_query_and_body(query: HookQuery, raw: serde_json::Value) -> Self {
+ pub fn from_query_and_body(query: HookQuery, mut raw: serde_json::Value) -> Self {
let event = HookEvent::parse(&query.event);
let agent = agent_from_payload(&raw)
.unwrap_or_else(|| query.agent.as_deref().map_or(AgentKind::Other, parse_agent));
@@ -556,6 +556,9 @@ impl HookEnvelope {
} else {
None
};
+ if agent == AgentKind::AntigravityCli {
+ crate::antigravity::enrich_antigravity_step_output(&mut raw, event, None);
+ }
let tool_metadata = tool_observation_metadata(agent, &raw, event == HookEvent::PreToolUse);
let closed_tool_event = matches!(event, HookEvent::PreToolUse | HookEvent::PostToolUse)
&& closed_tool_agent(agent);
@@ -2948,6 +2951,69 @@ mod tests {
assert!(notification.body_excerpt.is_none());
}
+ #[test]
+ fn antigravity_post_tool_use_extracts_output_txt_content() {
+ let dir = tempfile::tempdir().unwrap();
+ let step_dir = dir
+ .path()
+ .join(".system_generated")
+ .join("steps")
+ .join("42");
+ std::fs::create_dir_all(&step_dir).unwrap();
+ std::fs::write(step_dir.join("output.txt"), "cargo test: 10 passed\n").unwrap();
+
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "post-tool-use".into(),
+ agent: Some("antigravity-cli".into()),
+ ..Default::default()
+ },
+ serde_json::json!({
+ "conversationId": "conv-1",
+ "toolCall": {
+ "name": "run_command",
+ "args": {"CommandLine": "cargo test"}
+ },
+ "stepIdx": 42,
+ "artifactDirectoryPath": dir.path().to_str().unwrap()
+ }),
+ );
+ let body = env.body_excerpt.expect("body excerpt should be present");
+ assert!(body.contains("tool_family: non-file"));
+ assert!(body.contains("cargo test: 10 passed"));
+ }
+
+ #[test]
+ fn antigravity_post_tool_use_preserves_edit_tool_code_content() {
+ let dir = tempfile::tempdir().unwrap();
+ let step_dir = dir.path().join(".system_generated").join("steps").join("1");
+ std::fs::create_dir_all(&step_dir).unwrap();
+ std::fs::write(step_dir.join("output.txt"), "Created file test.rs\n").unwrap();
+
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "post-tool-use".into(),
+ agent: Some("antigravity-cli".into()),
+ ..Default::default()
+ },
+ serde_json::json!({
+ "conversationId": "conv-1",
+ "toolCall": {
+ "name": "write_to_file",
+ "args": {
+ "TargetFile": "/workspace/test.rs",
+ "CodeContent": "fn preserved_code() {}"
+ }
+ },
+ "stepIdx": 1,
+ "artifactDirectoryPath": dir.path().to_str().unwrap()
+ }),
+ );
+ let body = env.body_excerpt.expect("body excerpt should be present");
+ assert!(body.contains("fn preserved_code() {}"));
+ assert!(!body.contains("Created file test.rs"));
+ }
+
#[test]
fn pi_and_omp_post_outcomes_and_stable_id_are_rendered() {
for agent in ["pi", "omp"] {