neosian 3.0.1

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Antigravity CLI's hooks as the recorder's events (A1b, measured on agy
//! 1.5.15). `SessionStart` asks for startup context only. The first
//! `PreInvocation` of a generation (`invocationNum` 0) opens the turn with
//! `lastUserInput`, and its `initialNumSteps` is the generation's identity:
//! a repeated callback opens nothing, and the same text in a later turn is a
//! new turn. `PostToolUse` stages its call. A terminal `Stop` (no tool call,
//! fully idle, no continuation, no error) reads this turn's transcript window
//! (`agy_window`), files each staged call with its real output in callback
//! order and then the answer, through the recorder's own landing. A turn
//! whose window does not verify records nothing and says so on stderr; no
//! part of it is carried into the next turn. The staging file beside the span
//! is written under the session lock, and the caller has already checked
//! capture consent and pause, so no transcript is opened before that.

pub use super::agy_window::project;
use super::agy_window::{self, Call};
use super::stage::{self, output_of, record_of, text};
use crate::conversation::Error;
use crate::profile::model::Capture;
use crate::record::land::{Landed, discard, land as file, only};
use crate::record::payload::{
    PROMPT_EVENT, Payload, Record, SESSION_START_EVENT, STOP_EVENT, TOOL_EVENT,
};
use crate::record::settings::Settings;
use crate::record::spool::Spool;
use crate::store::grammar::Actor;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::io::{self, Write};
use std::path::PathBuf;

/// A callback the recorder does not track (a later `PreInvocation`,
/// `PreToolUse`, `PostInvocation`).
const IGNORED: &str = "AgyCallback";
const GAP: &str = "neosian: this Antigravity turn is not recorded";

/// The native payload in the recorder's vocabulary; the native keys stay.
pub fn payload(mut raw: Payload) -> Payload {
    let event = text(&raw, "hookEventName");
    let first = raw.get("invocationNum").and_then(Value::as_u64) == Some(0);
    let mapped = match event.as_str() {
        "SessionStart" => SESSION_START_EVENT,
        "PreInvocation" if first => PROMPT_EVENT,
        "PostToolUse" => TOOL_EVENT,
        "Stop" => STOP_EVENT,
        _ => IGNORED,
    };
    let call = raw.get("toolCall").cloned().unwrap_or(Value::Null);
    let pairs = [
        ("session_id", raw.get("conversationId").cloned()),
        ("hook_event_name", Some(json!(mapped))),
        ("prompt", Some(json!(text(&raw, "lastUserInput")))),
        ("tool_use_id", call.get("id").cloned()),
        ("tool_name", call.get("name").cloned()),
        ("tool_input", call.get("args").cloned()),
        ("tool_response", Some(json!(""))),
        ("last_assistant_message", Some(json!(""))),
    ];
    for (key, value) in pairs {
        raw.insert(key.into(), value.unwrap_or(Value::Null));
    }
    raw
}

/// The open generation (review findings 3 and 7): its watermark; the
/// prompt's SHA-256 and length, which the Stop checks the transcript's user
/// step against (the text is never kept); the filtered prompt record while
/// its filing is pending; the filtered staged calls; whether a terminal Stop
/// began filing (`closing`) and whether the turn has ended (`closed`, after
/// which nothing but the watermark is kept).
#[derive(Default, Serialize, Deserialize)]
struct Stage {
    generation: Option<u64>,
    digest: String,
    length: usize,
    pending: Option<Record>,
    closing: bool,
    closed: bool,
    calls: Vec<Call>,
}

fn digest(prompt: &str) -> String {
    crate::clients::receipt::sha256(prompt.trim().as_bytes())
}

fn gap(err: &mut dyn Write, reason: &str) -> Landed {
    let _ = writeln!(err, "{GAP}: {reason}");
    only("not_recorded")
}

/// One hook call's place: settings, spool, span id, writer, payload, policy.
struct Here<'a> {
    settings: &'a Settings,
    spool: &'a Spool,
    id: &'a str,
    actor: &'a Actor,
    payload: &'a Payload,
    policy: Option<&'a Capture>,
    path: PathBuf,
}

impl Here<'_> {
    fn save(&self, stage: &Stage) -> io::Result<bool> {
        stage::save(self.settings, self.id, &self.path, stage)
    }

    /// The turn ended: only its watermark stays, so a repeat files nothing.
    fn end(&self, stage: &mut Stage) -> io::Result<()> {
        *stage = Stage {
            generation: stage.generation,
            closed: true,
            ..Stage::default()
        };
        self.save(stage).map(|_| ())
    }

    fn file(&self, event: &str, record: &Record) -> Result<Landed, Error> {
        file(
            self.settings,
            self.spool,
            self.id,
            self.actor,
            event,
            record,
        )
    }

    /// Files the pending prompt unless the span already holds it; marks it
    /// filed only after the write.
    fn prompt(&self, stage: &mut Stage) -> Result<Option<Landed>, Error> {
        let Some(record) = stage.pending.clone() else {
            return Ok(None);
        };
        let landed = if stage::holds(self.spool, self.id, "prompt", None)? {
            None
        } else {
            Some(self.file(PROMPT_EVENT, &record)?)
        };
        stage.pending = None;
        self.save(stage)?;
        Ok(landed)
    }
}

/// One Antigravity hook call (the span's id, the writer, the event and the
/// payload), under the session lock.
pub fn land(
    settings: &Settings,
    spool: &Spool,
    (id, actor, event, payload): (&str, &Actor, &str, &Payload),
    policy: Option<&Capture>,
    err: &mut dyn Write,
) -> Result<Landed, Error> {
    let path = stage::file(settings, id, "agy");
    let here = Here {
        settings,
        spool,
        id,
        actor,
        payload,
        policy,
        path,
    };
    let mut stage: Stage = stage::load(&here.path);
    let open = stage.generation.is_some() && !stage.closed;
    match event {
        PROMPT_EVENT => {
            let count = payload.get("initialNumSteps").and_then(Value::as_u64);
            let Some(generation) = count.filter(|n| *n > 0) else {
                return Ok(gap(err, "the first model call names no step count"));
            };
            if stage.generation == Some(generation) {
                return Ok(here
                    .prompt(&mut stage)?
                    .unwrap_or_else(|| only("duplicate")));
            }
            // An open span is an earlier turn that never completed.
            if spool.file(id).try_exists()? {
                spool.clear(id)?;
                let _ = writeln!(err, "{GAP}: the earlier turn did not complete");
            }
            let prompt = text(payload, "prompt");
            stage = Stage {
                generation: Some(generation),
                digest: digest(&prompt),
                length: prompt.trim().chars().count(),
                pending: record_of(payload, policy),
                ..Stage::default()
            };
            if !here.save(&stage)? {
                return Ok(gap(err, "the keep limit left no room for the turn"));
            }
            Ok(here.prompt(&mut stage)?.unwrap_or_else(|| only("excluded")))
        }
        TOOL_EVENT => {
            if !open || stage.closing {
                return Ok(gap(err, "a tool call came outside an open turn"));
            }
            here.prompt(&mut stage)?;
            let step = payload
                .get("stepIdx")
                .and_then(Value::as_u64)
                .unwrap_or(u64::MAX);
            if stage.calls.iter().any(|c| c.step == step) {
                return Ok(only("duplicate"));
            }
            // The filter runs before anything of the call is kept; an error
            // is kept only as the filter keeps a tool's output.
            let call = match record_of(payload, policy) {
                Some(record) => Call {
                    id: text(&record, "id"),
                    name: text(&record, "name"),
                    args: record.get("input").cloned().unwrap_or(Value::Null),
                    step,
                    error: output_of(&text(payload, "error"), policy),
                    kept: true,
                },
                None => Call {
                    step,
                    ..Call::default()
                },
            };
            stage.calls.push(call);
            if !here.save(&stage)? {
                discard(settings, spool, id)?;
                here.end(&mut stage)?;
                return Ok(gap(err, "the keep limit left no room for the turn"));
            }
            Ok(only("staged"))
        }
        STOP_EVENT if !open => Ok(only("duplicate")),
        STOP_EVENT => stop(&here, stage, err),
        _ => Ok(only("ignored")),
    }
}

/// A terminal Stop: the window is read and checked, the stage marked
/// `closing`, each kept call filed with its output and then the answer, and
/// only then the turn ended. A Stop that finds `closing` from an interrupted
/// one finishes it: what the span holds is not filed again, and a span
/// already closed into the queue means the turn was filed.
fn stop(here: &Here, mut stage: Stage, err: &mut dyn Write) -> Result<Landed, Error> {
    let generation = stage.generation.expect("an open generation");
    here.prompt(&mut stage)?;
    let resumed = stage.closing;
    if resumed && !here.spool.file(here.id).try_exists()? {
        here.end(&mut stage)?;
        return Ok(only("duplicate"));
    }
    let native = text(here.payload, "session_id");
    let home = std::env::home_dir().ok_or_else(|| io::Error::other("no home directory"))?;
    let (want, length) = (stage.digest.clone(), stage.length);
    let verify = |request: &str| request.chars().count() == length && digest(request) == want;
    let read = match agy_window::not_terminal(here.payload) {
        Some(why) => Err(why),
        None => agy_window::read(
            &home,
            &native,
            &text(here.payload, "transcriptPath"),
            generation - 1,
            &verify,
            &stage.calls,
        ),
    };
    let turn = match read {
        Ok(turn) => turn,
        Err(reason) => {
            discard(here.settings, here.spool, here.id)?;
            here.end(&mut stage)?;
            return Ok(gap(err, &reason));
        }
    };
    stage.closing = true;
    here.save(&stage)?;
    for (call, output) in stage.calls.iter().zip(turn.outputs) {
        if !call.kept || (resumed && stage::holds(here.spool, here.id, "tool", Some(&call.id))?) {
            continue;
        }
        let record = json!({"kind": "tool", "id": call.id, "name": call.name,
            "input": call.args, "response": output_of(&output, here.policy)});
        here.file(TOOL_EVENT, record.as_object().expect("an object"))?;
    }
    let end = json!({"hook_event_name": STOP_EVENT, "session_id": native,
        "last_assistant_message": turn.answer, "status": "completed"});
    let record = record_of(end.as_object().expect("object"), here.policy)
        .ok_or_else(|| io::Error::other("a stop always reduces"))?;
    let landed = here.file(STOP_EVENT, &record)?;
    here.end(&mut stage)?;
    Ok(landed)
}