hird 0.3.1

Cross-harness agent work queue and shared assertion memory, backed by one local SQLite database
Documentation
//! The gate: a policy the process serving a connection may put in front of
//! the queue's own transitions.
//!
//! Core hird has no roles and wants none. A factory does — builders, reviewers,
//! CI, humans — and its rules have to bind the twelve tools agents already
//! call, or a builder could take a review through plain `task_claim`. So core
//! offers one seam: a [`Gate`] consulted *inside* the transactions that claim
//! and finish work, after every core check has passed and before anything is
//! written. A refusal rolls back exactly like a recusal does, leaving no
//! trace.
//!
//! Locally there is no gate and nothing changes. `hird-server` builds one per
//! roster entry, with that entry's role baked in, from the `hird-factory`
//! crate. Core never learns what a role is.

use rusqlite::Connection;

use crate::model::Task;

/// How a holder is finishing a task.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Finish {
    Complete,
    Fail,
}

/// A policy over claims and finishes. Every method is called inside the
/// transaction deciding the move, with that transaction's connection, so a
/// gate reads exactly the state the move will commit against.
///
/// A refusal is a sentence for the agent to relay, in the same voice as every
/// other refusal hird gives.
pub trait Gate: Send + Sync {
    /// May `actor` claim `task`? Called for a named claim and, as a filter,
    /// for every candidate `task_next` considers.
    fn may_claim(&self, _conn: &Connection, _task: &Task, _actor: &str) -> Result<(), String> {
        Ok(())
    }

    /// Why nobody may claim `task` right now, whoever asks: a hold on the
    /// task itself rather than on a caller. The herald reads it so it never
    /// summons an agent to work every connection would be refused; a gate's
    /// `may_claim` should refuse whatever this holds.
    fn holds(&self, _conn: &Connection, _task: &Task) -> Option<String> {
        None
    }

    /// May `actor`, the holder, finish `task` this way?
    fn may_finish(
        &self,
        _conn: &Connection,
        _task: &Task,
        _actor: &str,
        _how: Finish,
    ) -> Result<(), String> {
        Ok(())
    }

    /// Whether every completed task must be put in front of a reviewer, even
    /// one not marked for review and even when nothing was seen to change —
    /// which is the ordinary case for a connection whose tree is elsewhere.
    fn requires_review(&self) -> bool {
        false
    }

    /// After how many rejections a task escalates to a human, overriding the
    /// queue's own setting. `None` leaves the queue's setting in force.
    fn escalate_after(&self) -> Option<u32> {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::Db;
    use crate::error::Error;
    use crate::model::{Clearance, Status};
    use crate::repo::{OnConflict, ProjectScope};
    use std::time::Duration;

    const TTL: Duration = Duration::from_secs(900);
    const PROJECT: &str = "/p";

    /// Refuses claims of tasks whose title starts with "no", and failing.
    struct Picky;

    impl Gate for Picky {
        fn may_claim(&self, _: &Connection, task: &Task, actor: &str) -> Result<(), String> {
            if task.title.starts_with("no") {
                return Err(format!("{actor} may not take {:?}", task.title));
            }
            Ok(())
        }

        fn may_finish(&self, _: &Connection, _: &Task, _: &str, how: Finish) -> Result<(), String> {
            match how {
                Finish::Fail => Err("failing is for humans here".into()),
                Finish::Complete => Ok(()),
            }
        }

        fn requires_review(&self) -> bool {
            true
        }
    }

    fn task(db: &Db, title: &str) -> i64 {
        db.tasks().create(PROJECT, title, "", 0, "cli").unwrap().seq
    }

    #[test]
    fn a_refused_claim_names_the_reason_and_leaves_no_trace() {
        let db = Db::open_in_memory().unwrap();
        let seq = task(&db, "no thanks");
        let err = db
            .tasks()
            .gated(Some(&Picky))
            .claim_scoped(
                seq,
                "codex:1",
                TTL,
                &[],
                OnConflict::Report,
                Clearance::Done,
            )
            .unwrap_err();
        assert!(matches!(err, Error::Gated { .. }), "{err:?}");
        assert!(err.to_string().contains("codex:1 may not take"), "{err}");
        let task = db.tasks().get(seq).unwrap();
        assert_eq!(task.status, Status::Open);
        assert_eq!(db.tasks().events(&task.id, 10).unwrap().len(), 1);
    }

    #[test]
    fn the_same_repository_without_a_gate_is_unchanged() {
        let db = Db::open_in_memory().unwrap();
        let seq = task(&db, "no thanks");
        db.tasks().claim(seq, "codex:1", TTL).unwrap();
        db.tasks().fail(seq, "codex:1", "could not").unwrap();
    }

    #[test]
    fn dispatch_routes_around_what_the_gate_refuses_and_says_so() {
        let db = Db::open_in_memory().unwrap();
        let refused = task(&db, "no thanks");
        let allowed = task(&db, "yes please");
        let dispatch = db
            .tasks()
            .gated(Some(&Picky))
            .claim_next(
                "codex:1",
                TTL,
                &ProjectScope::Only(PROJECT.into()),
                false,
                Clearance::Done,
            )
            .unwrap();
        assert_eq!(dispatch.claim.unwrap().task.seq, allowed);
        assert_eq!(dispatch.gated.len(), 1);
        assert_eq!(dispatch.gated[0].0, refused);
    }

    #[test]
    fn a_refused_finish_leaves_the_task_held() {
        let db = Db::open_in_memory().unwrap();
        let seq = task(&db, "yes please");
        let tasks = db.tasks().gated(Some(&Picky));
        tasks.claim(seq, "codex:1", TTL).unwrap();
        let err = tasks.fail(seq, "codex:1", "stuck").unwrap_err();
        assert!(err.to_string().contains("failing is for humans"), "{err}");
        assert_eq!(db.tasks().get(seq).unwrap().status, Status::Claimed);
    }

    #[test]
    fn a_gate_that_requires_review_files_one_with_nothing_to_point_at() {
        let db = Db::open_in_memory().unwrap();
        let seq = task(&db, "yes please");
        let tasks = db.tasks().gated(Some(&Picky));
        tasks.claim(seq, "codex:1", TTL).unwrap();
        let finished = tasks.complete(seq, "codex:1", "built it").unwrap();
        let review = finished.review.expect("a review is filed");
        let bar = db.recusals().bars(review, "codex:2").unwrap();
        assert!(bar.is_some(), "the review is recused from its author");
        // Ungated, unmarked, unscoped work files nothing, as before.
        let other = task(&db, "plain");
        db.tasks().claim(other, "codex:1", TTL).unwrap();
        assert!(db
            .tasks()
            .complete(other, "codex:1", "done")
            .unwrap()
            .review
            .is_none());
    }
}