neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! One Antigravity turn read back from its transcript (A1b, measured on agy
//! 1.5.15): `PostToolUse` carries no output and `Stop` no final text, so both
//! come from `transcript_full.jsonl`. Only the canonical file of this session
//! is read, through `bounded`, and only its window from this turn's user
//! step: that step must be a `USER_INPUT` whose request is the prompt the
//! turn began with, each staged tool call must find its `GENERIC` result step
//! and each result step its call, and the turn must end with a completed
//! `PLANNER_RESPONSE` holding text and no tool call. Injected system steps are
//! passed over. Anything else is a gap: the turn records nothing.

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};

/// The most transcript one turn's window may hold.
pub const CAP: u64 = 16 << 20;

/// A tool call as `PostToolUse` staged it, in callback order, after the
/// profile's capture filter: a call the filter drops keeps only its step
/// (`kept` false), to be matched to its result step and never filed.
#[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,
}

/// What the window gives the turn: each call's output, then the answer.
#[derive(Debug)]
pub struct Turn {
    pub outputs: Vec<String>,
    pub answer: String,
}

/// The one transcript this session's hooks may name.
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()
}

/// The request inside the `USER_INPUT` wrapper Antigravity writes.
fn request(content: &str) -> &str {
    content
        .split_once("<USER_REQUEST>")
        .and_then(|(_, rest)| rest.split_once("</USER_REQUEST>"))
        .map_or(content, |(inner, _)| inner)
        .trim()
}

/// The turn that began at `user` with the prompt `prompt` accepts, from the
/// file the hook named (`given`), which must be the canonical one.
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")?;
        // A later line for the same step supersedes an earlier one.
        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(),
    })
}

/// The session's project: the payload's absolute working directory (the
/// hook itself runs in the configuration directory), else its one
/// workspace, else `/`.
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("/"))
}

/// Why this Stop does not end the turn, when it does not.
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;