hird 0.3.1

Cross-harness agent work queue and shared assertion memory, backed by one local SQLite database
Documentation
//! Attempts: the record of every time a task's work was rejected.
//!
//! A send-back used to leave one trace the next agent could use: findings
//! appended to the brief, in prose, with nothing counting the rounds. A factory
//! needs the rounds counted โ€” so that work rejected again and again stops
//! churning through agents and goes to a human โ€” and needs the gate's own
//! words kept apart from the brief, so the next claimant is handed exactly
//! what each judge said.
//!
//! An attempt is written by whatever rejected the work, inside that move's
//! transaction: a `sent_back` verdict, a failing gate report, a human
//! rejection, or the holder failing its own task. A lapsed lease is not an
//! attempt โ€” nothing judged the work.
//!
//! Escalation reuses the question gate (ยง24) rather than adding a status: on
//! every `escalate_after`-th rejection the queue asks a human how to proceed,
//! and the task stays unclaimable until they answer.

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

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

/// Who rejected the work, and how.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
    SentBack,
    CiFailed,
    Failed,
    HumanRejected,
}

impl Outcome {
    pub fn as_str(self) -> &'static str {
        match self {
            Outcome::SentBack => "sent_back",
            Outcome::CiFailed => "ci_failed",
            Outcome::Failed => "failed",
            Outcome::HumanRejected => "human_rejected",
        }
    }
}

/// What recording a rejection did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Recorded {
    pub n: i64,
    /// True when this rejection sent the task to a human.
    pub escalated: bool,
}

/// Typed access to attempts.
pub struct Attempts<'a> {
    conn: &'a Connection,
}

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

    /// Every rejected attempt at task `seq`, oldest first.
    pub fn for_task(&self, seq: i64) -> Result<Vec<Attempt>> {
        let id = super::deps::id_for_seq(self.conn, seq)?;
        for_id(self.conn, &id)
    }
}

pub(crate) fn for_id(conn: &Connection, task_id: &str) -> Result<Vec<Attempt>> {
    let mut stmt = conn.prepare(
        "SELECT n, holder, model, outcome, source, actor, output, at
         FROM task_attempts WHERE task_id = ?1 ORDER BY n",
    )?;
    let rows = stmt.query_map([task_id], |row| {
        Ok(Attempt {
            n: row.get(0)?,
            holder: row.get(1)?,
            model: row.get(2)?,
            outcome: row.get(3)?,
            source: row.get(4)?,
            actor: row.get(5)?,
            output: row.get(6)?,
            at: row.get(7)?,
        })
    })?;
    Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}

/// Record that `task_id`'s work was rejected, and escalate it to a human when
/// this is the `escalate_after`-th rejection since the last escalation.
/// `escalate_after = 0` never escalates.
#[allow(clippy::too_many_arguments)]
pub(crate) fn record_in(
    tx: &Transaction<'_>,
    task_id: &str,
    holder: &str,
    outcome: Outcome,
    source: &str,
    actor: &str,
    output: &str,
    escalate_after: u32,
) -> Result<Recorded> {
    let n: i64 = tx.query_row(
        "SELECT COALESCE(MAX(n), 0) + 1 FROM task_attempts WHERE task_id = ?1",
        [task_id],
        |row| row.get(0),
    )?;
    let model: String = tx
        .query_row(
            "SELECT model FROM agent_sessions WHERE actor = ?1",
            [holder],
            |row| row.get(0),
        )
        .optional()?
        .unwrap_or_default();
    let now = now_ts();
    tx.execute(
        "INSERT INTO task_attempts (id, task_id, n, holder, model, outcome, source, actor, output, at)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
        params![
            new_id(),
            task_id,
            n,
            holder,
            model,
            outcome.as_str(),
            source,
            actor,
            output.trim(),
            now
        ],
    )?;
    let escalate = escalate_after > 0 && n % i64::from(escalate_after) == 0;
    // A task that already waits on a human needs no second question; the
    // attempt is still counted.
    let escalated = escalate && super::questions::unanswered_in(tx, task_id)?.is_none() && {
        super::questions::ask_in_tx(
            tx,
            task_id,
            "hird",
            &format!(
                "This work has been rejected {n} times (most recently: {} by {source}). \
                 Should it be tried again as it is, rescoped, or dropped?",
                outcome.as_str()
            ),
            &now,
        )?;
        true
    };
    Ok(Recorded { n, escalated })
}

#[cfg(test)]
mod tests {
    use crate::db::Db;
    use crate::model::{Status, Verdict};
    use std::time::Duration;

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

    fn reviewed(db: &Db) -> i64 {
        let work = db.tasks().create("/p", "w", "", 0, "cli").unwrap().seq;
        db.tasks().set_review(work, true, "cli").unwrap();
        db.scopes()
            .declare(
                work,
                &["src/a.rs".to_string()],
                "cli",
                super::super::OnConflict::Report,
            )
            .unwrap();
        work
    }

    /// Build, review, send back: one round.
    fn round(db: &Db, work: i64, max: u32) -> i64 {
        let tasks = db.tasks().escalating_after(max);
        tasks.claim(work, "codex:b", TTL).unwrap();
        let review = tasks
            .complete(work, "codex:b", "built")
            .unwrap()
            .review
            .unwrap();
        tasks.claim(review, "claude-code:r", TTL).unwrap();
        tasks
            .complete_with(
                review,
                "claude-code:r",
                "the lock leaks",
                Some(Verdict::SentBack),
            )
            .unwrap();
        review
    }

    #[test]
    fn a_send_back_records_an_attempt_with_the_reviewers_findings() {
        let db = Db::open_in_memory().unwrap();
        let work = reviewed(&db);
        let review = round(&db, work, 0);
        let attempts = db.attempts().for_task(work).unwrap();
        assert_eq!(attempts.len(), 1);
        let a = &attempts[0];
        assert_eq!((a.n, a.outcome.as_str()), (1, "sent_back"));
        assert_eq!(a.holder, "codex:b");
        assert_eq!(a.actor, "claude-code:r");
        assert_eq!(a.source, format!("review {review}"));
        assert_eq!(a.output, "the lock leaks");
    }

    #[test]
    fn failing_your_own_task_is_an_attempt_too() {
        let db = Db::open_in_memory().unwrap();
        let seq = db.tasks().create("/p", "w", "", 0, "cli").unwrap().seq;
        db.tasks().claim(seq, "codex:b", TTL).unwrap();
        db.tasks().fail(seq, "codex:b", "cannot reproduce").unwrap();
        let a = &db.attempts().for_task(seq).unwrap()[0];
        assert_eq!(
            (a.outcome.as_str(), a.output.as_str()),
            ("failed", "cannot reproduce")
        );
    }

    #[test]
    fn without_a_limit_rejections_are_counted_and_never_escalate() {
        let db = Db::open_in_memory().unwrap();
        let work = reviewed(&db);
        for _ in 0..4 {
            round(&db, work, 0);
        }
        assert_eq!(db.attempts().for_task(work).unwrap().len(), 4);
        assert!(db.questions().unanswered(work).unwrap().is_none());
    }

    #[test]
    fn every_nth_rejection_asks_a_human_and_holds_the_task() {
        let db = Db::open_in_memory().unwrap();
        let work = reviewed(&db);
        round(&db, work, 2);
        assert!(db.questions().unanswered(work).unwrap().is_none());
        round(&db, work, 2);
        let question = db.questions().unanswered(work).unwrap().expect("escalated");
        assert_eq!(question.asked_by, "hird");
        assert!(
            question.question.contains("rejected 2 times"),
            "{}",
            question.question
        );
        assert_eq!(db.tasks().get(work).unwrap().status, Status::Open);
        assert!(db.tasks().claim(work, "codex:b", TTL).is_err());

        // The human answers; the count goes on, and the next escalation comes
        // two rejections later, not at the next one.
        db.questions().answer(work, "cli", "try once more").unwrap();
        round(&db, work, 2);
        assert!(db.questions().unanswered(work).unwrap().is_none());
        round(&db, work, 2);
        assert!(db.questions().unanswered(work).unwrap().is_some());
    }

    #[test]
    fn the_record_refuses_to_be_rewritten() {
        let db = Db::open_in_memory().unwrap();
        let work = reviewed(&db);
        round(&db, work, 0);
        for sql in [
            "UPDATE task_attempts SET output = ''",
            "DELETE FROM task_attempts",
        ] {
            let err = db.conn().execute(sql, []).unwrap_err();
            assert!(err.to_string().contains("append-only"), "{sql}: {err}");
        }
    }
}