hird 0.3.1

Cross-harness agent work queue and shared assertion memory, backed by one local SQLite database
Documentation
//! The audit: the event trail read as a record of transitions.
//!
//! `task_events` has always said who did what and when. A factory needs it to
//! say more, and to be unable to say anything else later: which model and role
//! acted, which state the task moved between, and on what evidence — in rows
//! that triggers refuse to update or delete (migration 13).
//!
//! Model and role are properties of a *session*, not of a call, so they are
//! declared once into `agent_sessions` and every event that session writes is
//! stamped from there. That keeps the dozens of places that write events
//! unchanged: an actor string is all any of them ever had to hand.

use rusqlite::{params, Connection, OptionalExtension, Transaction};
use serde::Serialize;

use super::new_id;
use crate::error::Result;
use crate::model::{now_ts, EventKind};

/// One row of a task's trail, every column of it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AuditEntry {
    pub at: String,
    pub actor: String,
    pub model: String,
    pub role: String,
    pub kind: String,
    pub from_state: String,
    pub to_state: String,
    pub detail: String,
    pub evidence: String,
}

/// One row of a project's trail, as a live view follows it: the row's place
/// in the trail (`cursor`, strictly increasing), the task it belongs to, and
/// every audit column.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TrailEntry {
    pub cursor: i64,
    pub seq: i64,
    pub title: String,
    #[serde(flatten)]
    pub entry: AuditEntry,
}

/// What a session was running as, declared once.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Stamp {
    pub model: Option<String>,
    pub role: Option<String>,
}

impl Stamp {
    pub fn is_empty(&self) -> bool {
        self.model.is_none() && self.role.is_none()
    }
}

/// Typed access to the audit.
pub struct Audit<'a> {
    conn: &'a Connection,
}

impl<'a> Audit<'a> {
    pub(crate) fn new(conn: &'a Connection) -> Audit<'a> {
        Audit { conn }
    }

    /// Declare what `actor` runs as. The first declaration wins and is never
    /// rewritten: a session cannot change its model or role after acting.
    /// Declaring nothing writes nothing.
    pub fn declare(&self, actor: &str, stamp: &Stamp) -> Result<()> {
        if stamp.is_empty() {
            return Ok(());
        }
        self.conn.execute(
            "INSERT OR IGNORE INTO agent_sessions (actor, model, role, first_seen)
             VALUES (?1, ?2, ?3, ?4)",
            params![
                actor,
                stamp.model.as_deref().unwrap_or(""),
                stamp.role.as_deref().unwrap_or(""),
                now_ts()
            ],
        )?;
        Ok(())
    }

    /// What `actor` declared, if it declared anything.
    pub fn stamp(&self, actor: &str) -> Result<Stamp> {
        let row: Option<(String, String)> = self
            .conn
            .query_row(
                "SELECT model, role FROM agent_sessions WHERE actor = ?1",
                [actor],
                |row| Ok((row.get(0)?, row.get(1)?)),
            )
            .optional()?;
        let non_empty = |s: String| (!s.is_empty()).then_some(s);
        Ok(row.map_or_else(Stamp::default, |(model, role)| Stamp {
            model: non_empty(model),
            role: non_empty(role),
        }))
    }

    /// A task's whole trail, oldest first, with every audit column.
    pub fn for_task(&self, seq: i64) -> Result<Vec<AuditEntry>> {
        let task_id = super::deps::id_for_seq(self.conn, seq)?;
        let mut stmt = self.conn.prepare(
            "SELECT at, actor, model, role, kind, from_state, to_state, detail, evidence
             FROM task_events WHERE task_id = ?1 ORDER BY at ASC, rowid ASC",
        )?;
        let rows = stmt.query_map([task_id], |row| {
            Ok(AuditEntry {
                at: row.get(0)?,
                actor: row.get(1)?,
                model: row.get(2)?,
                role: row.get(3)?,
                kind: row.get(4)?,
                from_state: row.get(5)?,
                to_state: row.get(6)?,
                detail: row.get(7)?,
                evidence: row.get(8)?,
            })
        })?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }
}

impl Audit<'_> {
    /// The trail of `project` (or of every project), in the order it was
    /// written. With `after`, the rows written since that cursor, oldest
    /// first, at most `limit` of them; without it, the latest `limit` rows,
    /// oldest first — where a view starts before it follows.
    pub fn trail(
        &self,
        project: Option<&str>,
        after: Option<i64>,
        limit: usize,
    ) -> Result<Vec<TrailEntry>> {
        let limit = limit.clamp(1, 1_000) as i64;
        let sql = "SELECT e.rowid, t.seq, t.title, e.at, e.actor, e.model, e.role, e.kind,
                          e.from_state, e.to_state, e.detail, e.evidence
                   FROM task_events e JOIN tasks t ON t.id = e.task_id
                   WHERE (?1 IS NULL OR t.project = ?1) AND e.rowid > ?2
                   ORDER BY e.rowid DESC LIMIT ?3";
        let following = "SELECT * FROM (SELECT e.rowid, t.seq, t.title, e.at, e.actor, e.model,
                          e.role, e.kind, e.from_state, e.to_state, e.detail, e.evidence
                   FROM task_events e JOIN tasks t ON t.id = e.task_id
                   WHERE (?1 IS NULL OR t.project = ?1) AND e.rowid > ?2
                   ORDER BY e.rowid ASC LIMIT ?3)";
        let mut stmt = self
            .conn
            .prepare(if after.is_some() { following } else { sql })?;
        let rows = stmt.query_map(params![project, after.unwrap_or(0), limit], |row| {
            Ok(TrailEntry {
                cursor: row.get(0)?,
                seq: row.get(1)?,
                title: row.get(2)?,
                entry: AuditEntry {
                    at: row.get(3)?,
                    actor: row.get(4)?,
                    model: row.get(5)?,
                    role: row.get(6)?,
                    kind: row.get(7)?,
                    from_state: row.get(8)?,
                    to_state: row.get(9)?,
                    detail: row.get(10)?,
                    evidence: row.get(11)?,
                },
            })
        })?;
        let mut out = rows.collect::<rusqlite::Result<Vec<_>>>()?;
        out.sort_by_key(|e| e.cursor);
        Ok(out)
    }

    /// When an actor whose name starts with `prefix` last wrote to the trail.
    pub fn last_seen(&self, prefix: &str) -> Result<Option<String>> {
        Ok(self.conn.query_row(
            "SELECT MAX(at) FROM task_events WHERE substr(actor, 1, length(?1)) = ?1",
            [prefix],
            |row| row.get(0),
        )?)
    }
}

/// A state change worth recording as one: from where, to where, on what.
#[derive(Debug, Clone, Copy, Default)]
pub struct Move<'a> {
    pub from: &'a str,
    pub to: &'a str,
    pub evidence: &'a str,
}

/// Append one event, stamped with whatever its actor declared.
#[allow(clippy::too_many_arguments)]
pub(crate) fn append(
    tx: &Transaction<'_>,
    task_id: &str,
    at: &str,
    actor: &str,
    kind: EventKind,
    detail: &str,
    moved: Move<'_>,
) -> Result<()> {
    tx.execute(
        "INSERT INTO task_events
           (id, task_id, at, actor, kind, detail, from_state, to_state, evidence, model, role)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9,
           COALESCE((SELECT model FROM agent_sessions WHERE actor = ?4), ''),
           COALESCE((SELECT role  FROM agent_sessions WHERE actor = ?4), ''))",
        params![
            new_id(),
            task_id,
            at,
            actor,
            kind.as_str(),
            detail,
            moved.from,
            moved.to,
            moved.evidence
        ],
    )?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::Db;
    use std::time::Duration;

    const TTL: Duration = Duration::from_secs(900);

    fn stamp(model: &str, role: &str) -> Stamp {
        Stamp {
            model: Some(model.to_string()),
            role: Some(role.to_string()),
        }
    }

    #[test]
    fn events_carry_the_model_and_role_their_session_declared() {
        let db = Db::open_in_memory().unwrap();
        db.audit()
            .declare("codex:aa", &stamp("gpt-6", "builder"))
            .unwrap();
        let seq = db.tasks().create("/p", "t", "", 0, "cli").unwrap().seq;
        db.tasks().claim(seq, "codex:aa", TTL).unwrap();
        let trail = db.audit().for_task(seq).unwrap();
        let created = &trail[0];
        assert_eq!(
            (created.actor.as_str(), created.model.as_str()),
            ("cli", "")
        );
        let claimed = trail.iter().find(|e| e.kind == "claimed").unwrap();
        assert_eq!(claimed.model, "gpt-6");
        assert_eq!(claimed.role, "builder");
        assert_eq!(
            (claimed.from_state.as_str(), claimed.to_state.as_str()),
            ("open", "claimed")
        );
    }

    #[test]
    fn a_session_cannot_redeclare_what_it_runs_as() {
        let db = Db::open_in_memory().unwrap();
        db.audit()
            .declare("codex:aa", &stamp("gpt-6", "builder"))
            .unwrap();
        db.audit()
            .declare("codex:aa", &stamp("other", "reviewer"))
            .unwrap();
        assert_eq!(
            db.audit().stamp("codex:aa").unwrap(),
            stamp("gpt-6", "builder")
        );
        let err = db
            .conn()
            .execute("UPDATE agent_sessions SET role = 'human'", [])
            .unwrap_err();
        assert!(err.to_string().contains("written once"), "{err}");
    }

    #[test]
    fn declaring_nothing_writes_nothing() {
        let db = Db::open_in_memory().unwrap();
        db.audit().declare("codex:aa", &Stamp::default()).unwrap();
        let n: i64 = db
            .conn()
            .query_row("SELECT COUNT(*) FROM agent_sessions", [], |r| r.get(0))
            .unwrap();
        assert_eq!(n, 0);
    }

    #[test]
    fn the_trail_refuses_to_be_rewritten_or_erased() {
        let db = Db::open_in_memory().unwrap();
        db.tasks().create("/p", "t", "", 0, "cli").unwrap();
        for sql in [
            "UPDATE task_events SET actor = 'someone-else'",
            "DELETE FROM task_events",
        ] {
            let err = db.conn().execute(sql, []).unwrap_err();
            assert!(err.to_string().contains("append-only"), "{sql}: {err}");
        }
    }

    #[test]
    fn every_status_change_records_where_it_came_from_and_went() {
        let db = Db::open_in_memory().unwrap();
        let t = db.tasks();
        let seq = t.create("/p", "t", "", 0, "cli").unwrap().seq;
        t.claim(seq, "codex:aa", TTL).unwrap();
        t.update(seq, "codex:aa", true, "going", TTL).unwrap();
        t.complete(seq, "codex:aa", "done it").unwrap();
        t.reopen(seq, "cli", "again").unwrap();
        t.cancel(seq, "cli", "never mind").unwrap();
        let moves: Vec<(String, String)> = db
            .audit()
            .for_task(seq)
            .unwrap()
            .into_iter()
            .filter(|e| !e.to_state.is_empty())
            .map(|e| (e.from_state, e.to_state))
            .collect();
        let want = [
            ("", "open"),
            ("open", "claimed"),
            ("claimed", "in_progress"),
            ("in_progress", "done"),
            ("done", "open"),
            ("open", "cancelled"),
        ];
        let want: Vec<(String, String)> = want
            .iter()
            .map(|(a, b)| (a.to_string(), b.to_string()))
            .collect();
        assert_eq!(moves, want);
    }
}

#[cfg(test)]
mod trail_tests {
    use crate::db::Db;

    #[test]
    fn the_trail_starts_at_its_tail_and_then_follows_from_a_cursor() {
        let db = Db::open_in_memory().unwrap();
        let a = db.tasks().create("/p", "a", "", 0, "cli").unwrap().seq;
        db.tasks().create("/elsewhere", "x", "", 0, "cli").unwrap();
        let b = db.tasks().create("/p", "b", "", 0, "cli").unwrap().seq;
        let tail = db.audit().trail(Some("/p"), None, 1).unwrap();
        assert_eq!(tail.len(), 1);
        assert_eq!((tail[0].seq, tail[0].entry.kind.as_str()), (b, "created"));

        let all = db.audit().trail(Some("/p"), None, 50).unwrap();
        assert_eq!(all.iter().map(|e| e.seq).collect::<Vec<_>>(), vec![a, b]);
        assert!(all[0].cursor < all[1].cursor);

        let ttl = std::time::Duration::from_secs(60);
        db.tasks().claim(a, "ana/codex:1", ttl).unwrap();
        let since = db
            .audit()
            .trail(Some("/p"), Some(all[1].cursor), 50)
            .unwrap();
        assert_eq!(since.len(), 1);
        assert_eq!(since[0].entry.kind, "claimed");
        assert_eq!(since[0].entry.to_state, "claimed");
        assert!(db
            .audit()
            .trail(Some("/p"), Some(since[0].cursor), 50)
            .unwrap()
            .is_empty());

        assert!(db.audit().last_seen("ana/codex:").unwrap().is_some());
        assert!(db.audit().last_seen("ben/").unwrap().is_none());
    }
}