neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Mistral Vibe's hooks as the recorder's events (A1c, measured on Vibe
//! 3.1.5). `session_start` asks for startup context. `pre_agent` opens the
//! turn with its prompt once per `turn_id`. `post_tool` fires only for a tool
//! that ran and carries its output or error; it is filed at once, once per
//! `tool_call_id`. `post_agent` gives a candidate a later hook may reject, so
//! it is only kept; the turn closes with its committed answer from the
//! session directory (`vibe_journal`) when `notification` (`turn_completed`)
//! or `session_end` shows it committed, or at the next `pre_agent`, which
//! drops a turn never shown committed. A payload with a `parent_session_id`
//! is a subagent's and is not recorded. The caller has checked consent and
//! pause and holds the session lock.

use super::stage::{self, record_of, text};
use super::vibe_journal;
use crate::conversation::Error;
use crate::profile::model::Capture;
use crate::pyfmt::py_str;
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;

const IGNORED: &str = "VibeCallback";
const SUBAGENT: &str = "VibeSubagent";
const GAP: &str = "neosian: this Vibe turn is not recorded";

/// The native payload in the recorder's vocabulary; the native keys stay
/// and `vibe_event` keeps the hook's own name.
pub fn payload(mut raw: Payload) -> Payload {
    let event = text(&raw, "hook_event_name");
    let subagent = raw.get("parent_session_id").is_some_and(|v| !v.is_null());
    let mapped = match event.as_str() {
        _ if subagent => SUBAGENT,
        "session_start" => SESSION_START_EVENT,
        "pre_agent" => PROMPT_EVENT,
        "post_tool" => TOOL_EVENT,
        // Kept or looked at by `land`, never closing a span by themselves.
        "post_agent" | "notification" | "session_end" => STOP_EVENT,
        _ => IGNORED,
    };
    let output = match raw.get("tool_output_text") {
        Some(Value::String(output)) => output.clone(),
        _ => raw.get("tool_output").map_or_else(String::new, py_str),
    };
    let response = match text(&raw, "tool_status").as_str() {
        "failure" => format!("error: {}", text(&raw, "tool_error")),
        _ => output,
    };
    let pairs = [
        ("vibe_event", json!(event)),
        ("hook_event_name", json!(mapped)),
        (
            "tool_use_id",
            raw.get("tool_call_id").cloned().unwrap_or_default(),
        ),
        ("tool_response", json!(response)),
        ("last_assistant_message", json!("")),
    ];
    for (key, value) in pairs {
        raw.insert(key.into(), value);
    }
    raw
}

/// The open turn (review findings 3, 6 and 7): its id; the filtered prompt
/// record while its filing is pending; each tool call's filed record id with
/// whether its filing finished; whether a close began (`closing`) and whether
/// the turn has ended (`closed`, after which only the id is kept). The
/// candidate answer of `post_agent` is never kept: the committed one is filed.
#[derive(Default, Serialize, Deserialize)]
struct Stage {
    turn: Option<String>,
    pending: Option<Record>,
    calls: Vec<(String, bool)>,
    closing: bool,
    closed: bool,
}

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

/// `$VIBE_HOME`, resolved as Vibe resolves it, else `~/.vibe`.
fn vibe_home() -> io::Result<PathBuf> {
    let home = std::env::home_dir().ok_or_else(|| io::Error::other("no home directory"))?;
    Ok(
        match std::env::var("VIBE_HOME").ok().filter(|v| !v.is_empty()) {
            Some(value) => {
                let cwd = std::env::current_dir()?;
                let expanded = crate::clients::context::expand(&value, &home);
                crate::clients::context::absolute(&cwd, &expanded)
            }
            None => home.join(".vibe"),
        },
    )
}

/// One recorder call's place: the span's settings, spool and id, its writer,
/// the payload, the capture policy and the stage file.
struct Call<'a> {
    settings: &'a Settings,
    spool: &'a Spool,
    id: &'a str,
    actor: &'a Actor,
    payload: &'a Payload,
    policy: Option<&'a Capture>,
    path: PathBuf,
}

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

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

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

    fn drop_turn(
        &self,
        stage: &mut Stage,
        err: &mut dyn Write,
        why: &str,
    ) -> Result<Landed, Error> {
        discard(self.settings, self.spool, self.id)?;
        self.end(stage)?;
        Ok(gap(err, why))
    }

    /// 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)
    }

    /// The open turn closed with its committed answer once shown committed;
    /// dropped when the session shows it ended otherwise (only evidence for
    /// its own `turn_id` counts); `None` while it is neither.
    fn close(&self, stage: &mut Stage, err: &mut dyn Write) -> Result<Option<Landed>, Error> {
        let Some(turn) = stage.turn.clone().filter(|_| !stage.closed) else {
            return Ok(None);
        };
        self.prompt(stage)?;
        let resumed = stage.closing;
        if resumed && !self.spool.file(self.id).try_exists()? {
            self.end(stage)?;
            return Ok(Some(only("duplicate")));
        }
        let native = text(self.payload, "session_id");
        let given = text(self.payload, "transcript_path");
        let answer = match vibe_journal::committed(&vibe_home()?, &native, &given, &turn) {
            Ok(None) => return Ok(None),
            Ok(Some(answer)) => answer,
            Err(reason) => return self.drop_turn(stage, err, &reason).map(Some),
        };
        stage.closing = true;
        self.save(stage)?;
        let end = json!({"hook_event_name": STOP_EVENT, "session_id": native,
            "last_assistant_message": answer, "status": "completed"});
        let landed = match record_of(end.as_object().expect("an object"), self.policy) {
            Some(record) => self.file(STOP_EVENT, &record)?,
            None => only("excluded"),
        };
        self.end(stage)?;
        Ok(Some(landed))
    }

    /// A tool call that ran, filed once by its record's id: an interrupted
    /// filing is finished from what the span holds, never repeated.
    fn tool(&self, stage: &mut Stage, err: &mut dyn Write) -> Result<Landed, Error> {
        self.prompt(stage)?;
        let Some(record) = record_of(self.payload, self.policy) else {
            return Ok(only("excluded"));
        };
        let id = text(&record, "id");
        match stage.calls.iter().position(|(c, _)| *c == id) {
            Some(at) if stage.calls[at].1 => return Ok(only("duplicate")),
            Some(at) if stage::holds(self.spool, self.id, "tool", Some(&id))? => {
                stage.calls[at].1 = true;
                self.save(stage)?;
                return Ok(only("duplicate"));
            }
            Some(_) => {}
            None => {
                stage.calls.push((id.clone(), false));
                if !self.save(stage)? {
                    return self.drop_turn(stage, err, "the keep limit left no room for the turn");
                }
            }
        }
        let landed = self.file(TOOL_EVENT, &record)?;
        if let Some(call) = stage.calls.iter_mut().find(|(c, _)| *c == id) {
            call.1 = true;
        }
        self.save(stage)?;
        Ok(landed)
    }
}

/// One Vibe hook call (the span's id, the writer, the event and the payload).
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, "vibe");
    let call = Call {
        settings,
        spool,
        id,
        actor,
        payload,
        policy,
        path,
    };
    let mut stage: Stage = stage::load(&call.path);
    let turn = text(payload, "turn_id");
    let open = stage.turn.is_some() && !stage.closed;
    match (event, text(payload, "vibe_event").as_str()) {
        (PROMPT_EVENT, _) => {
            if turn.is_empty() {
                return Ok(gap(err, "pre_agent named no turn_id"));
            }
            if stage.turn.as_deref() == Some(turn.as_str()) {
                return Ok(call
                    .prompt(&mut stage)?
                    .unwrap_or_else(|| only("duplicate")));
            }
            // The earlier turn closes now if it is committed, else it is dropped.
            if open && call.close(&mut stage, err)?.is_none() {
                discard(settings, spool, id)?;
                let _ = writeln!(err, "{GAP}: the earlier turn was never shown committed");
            }
            if spool.file(id).try_exists()? {
                spool.clear(id)?;
            }
            stage = Stage {
                turn: Some(turn),
                pending: record_of(payload, policy),
                ..Stage::default()
            };
            if !call.save(&stage)? {
                return Ok(gap(err, "the keep limit left no room for the turn"));
            }
            Ok(call.prompt(&mut stage)?.unwrap_or_else(|| only("excluded")))
        }
        (TOOL_EVENT, _) if !open || stage.closing => {
            Ok(gap(err, "a tool call came outside an open turn"))
        }
        (TOOL_EVENT, _) => call.tool(&mut stage, err),
        // Only kept as a candidate: the committed answer is filed at the close.
        (STOP_EVENT, "post_agent") if open => Ok(only("candidate")),
        // `turn_completed`, `turn_failed` and `session_end` are wake-ups: a
        // failure notification names no turn, so it drops nothing by itself.
        (STOP_EVENT, "notification" | "session_end") => Ok(call
            .close(&mut stage, err)?
            .unwrap_or_else(|| only(if open { "awaiting_commit" } else { "ignored" }))),
        _ => Ok(only("ignored")),
    }
}