use super::bounded;
use crate::record::payload::Payload;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
pub const CAP: u64 = 16 << 20;
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Call {
pub id: String,
pub name: String,
pub args: Value,
pub step: u64,
pub error: String,
pub kept: bool,
}
#[derive(Debug)]
pub struct Turn {
pub outputs: Vec<String>,
pub answer: String,
}
pub fn canonical(home: &Path, native: &str) -> PathBuf {
home.join(".gemini/antigravity-cli/brain")
.join(native)
.join(".system_generated/logs/transcript_full.jsonl")
}
fn step_index(line: &[u8]) -> Option<u64> {
serde_json::from_slice::<Value>(line).ok()?["step_index"].as_u64()
}
fn request(content: &str) -> &str {
content
.split_once("<USER_REQUEST>")
.and_then(|(_, rest)| rest.split_once("</USER_REQUEST>"))
.map_or(content, |(inner, _)| inner)
.trim()
}
pub fn read(
home: &Path,
native: &str,
given: &str,
user: u64,
prompt: &dyn Fn(&str) -> bool,
calls: &[Call],
) -> Result<Turn, String> {
let path = canonical(home, native);
let named = given
.strip_prefix("~/")
.map_or_else(|| PathBuf::from(given), |rest| home.join(rest));
if named != path {
return Err("the hook named a transcript other than this session's own".into());
}
let checked = bounded::plain(home, &path)?;
let window = bounded::tail(&path, &checked, CAP, |lines| {
let first = lines.split(|b| *b == b'\n').find(|l| !l.is_empty());
first.and_then(step_index).is_some_and(|i| i <= user)
})?;
turn(&window, user, prompt, calls)
}
fn turn(
window: &[u8],
user: u64,
prompt: &dyn Fn(&str) -> bool,
calls: &[Call],
) -> Result<Turn, String> {
let text = std::str::from_utf8(window).map_err(|_| "the transcript is not UTF-8")?;
let mut steps: BTreeMap<u64, Value> = BTreeMap::new();
for line in text.split('\n').filter(|l| !l.trim().is_empty()) {
let step: Value = serde_json::from_str(line)
.map_err(|_| "a transcript line is not whole JSON".to_string())?;
let index = step["step_index"]
.as_u64()
.ok_or("a transcript step has no step_index")?;
if index >= user {
steps.insert(index, step);
}
}
let first = steps
.get(&user)
.ok_or("the turn's user step is not in the transcript")?;
let content = first["content"].as_str().unwrap_or_default();
if first["type"] != "USER_INPUT" || !prompt(request(content)) {
return Err("the turn's user step does not hold the prompt it began with".into());
}
let (mut results, mut answer, mut last) = (BTreeMap::new(), None, user);
for (index, step) in steps.range(user + 1..) {
if step["source"] == "SYSTEM_SDK" || step["type"] == "SYSTEM_MESSAGE" {
continue;
}
if step["status"] != "DONE" {
return Err(format!("step {index} is not complete"));
}
match step["type"].as_str() {
Some("GENERIC") => {
results.insert(*index, step["content"].as_str().unwrap_or_default());
}
Some("PLANNER_RESPONSE") => answer = Some((*index, step)),
Some("USER_INPUT") => return Err("another user step follows this turn's".into()),
other => return Err(format!("step {index} is of a type not verified: {other:?}")),
}
last = *index;
}
let mut outputs = vec![];
for call in calls {
let content = results
.get(&call.step)
.ok_or_else(|| format!("tool call {} has no result step", call.id))?;
outputs.push(match (call.error.as_str(), *content) {
("", content) => content.to_string(),
(error, "") => format!("error: {error}"),
(error, content) => format!("error: {error}\n{content}"),
});
}
let staged: std::collections::BTreeSet<u64> = calls.iter().map(|c| c.step).collect();
if let Some(step) = results.keys().find(|s| !staged.contains(s)) {
return Err(format!("result step {step} has no staged tool call"));
}
let (index, step) = answer.ok_or("the turn has no completed answer")?;
let text = step["content"].as_str().unwrap_or_default();
let calling = step["tool_calls"].as_array().is_some_and(|c| !c.is_empty());
if index != last || text.is_empty() || calling {
return Err("the turn does not end with a completed answer".into());
}
Ok(Turn {
outputs,
answer: text.to_string(),
})
}
pub fn project(payload: &Payload) -> PathBuf {
let cwd = payload
.get("cwd")
.and_then(Value::as_str)
.map(PathBuf::from);
let workspaces = payload.get("workspacePaths").and_then(Value::as_array);
let single = workspaces
.filter(|w| w.len() == 1)
.and_then(|w| w[0].as_str())
.map(PathBuf::from);
[cwd, single]
.into_iter()
.flatten()
.find(|p| p.is_absolute())
.unwrap_or_else(|| PathBuf::from("/"))
}
pub fn not_terminal(payload: &Payload) -> Option<String> {
let reason = super::stage::text(payload, "terminationReason");
if payload.get("continuationActive") != Some(&json!(false)) {
return Some("a Stop hook continued this turn".into());
}
if reason != "NO_TOOL_CALL" {
return Some(format!("it ended with {reason:?}, not a completed answer"));
}
if payload.get("fullyIdle") != Some(&json!(true)) {
return Some("background work was still running at its stop".into());
}
let error = super::stage::text(payload, "error");
(!error.is_empty()).then(|| format!("it stopped on an error: {error}"))
}
#[cfg(test)]
#[path = "agy_window_tests.rs"]
mod tests;