hird 0.3.1

Cross-harness agent work queue and shared assertion memory, backed by one local SQLite database
Documentation
//! Moves a policy layer composes: the public, in-transaction primitives a
//! crate outside core (`hird-factory`) builds its transitions from.
//!
//! A factory decides *whether* a move is allowed — which role, which stage,
//! which evidence. Core still owns *how* the move is written, so the trail,
//! the audit columns and the status machine stay one implementation. Each
//! primitive takes the caller's transaction: the policy reads the state it
//! checks and writes the move in one `IMMEDIATE` transaction, so two callers
//! racing for the same move cannot both win.
//!
//! None of these know about roles. They are the queue's own verbs, named for
//! what they do to a task.

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

use super::attempts::{record_in, Outcome, Recorded};
use super::audit::{append, Move};
use super::tasks::{fetch_task_by_seq, insert_move};
use super::verdict::{deliver_in_tx, Delivered};
use crate::error::{Error, Result};
use crate::identity::actor_harness;
use crate::model::{now_ts, EventKind, Status, Task, Verdict};

/// Entry point for composing moves.
pub struct Moves<'a> {
    conn: &'a Connection,
}

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

    /// Open the `IMMEDIATE` transaction a policy checks and moves within.
    pub fn begin(&self) -> Result<Transaction<'a>> {
        super::immediate_tx(self.conn)
    }
}

/// The task as the transaction sees it.
pub fn task_in(tx: &Transaction<'_>, seq: i64) -> Result<Task> {
    fetch_task_by_seq(tx, seq)?.ok_or(Error::TaskNotFound { seq })
}

/// Record what a gate outside the queue — CI — said about a task's work.
/// Changes no status; a failure is acted on with [`send_back_in`].
pub fn report_in(
    tx: &Transaction<'_>,
    seq: i64,
    actor: &str,
    passed: bool,
    output: &str,
    evidence: &str,
) -> Result<()> {
    let task = task_in(tx, seq)?;
    let verdict = if passed { "pass" } else { "fail" };
    let detail = if output.trim().is_empty() {
        verdict.to_string()
    } else {
        format!("{verdict}: {}", crate::fmt::truncate(output.trim(), 200))
    };
    let moved = Move {
        evidence,
        ..Move::default()
    };
    append(
        tx,
        &task.id,
        &now_ts(),
        actor,
        EventKind::Reported,
        &detail,
        moved,
    )
}

/// The latest gate report on a task: `Some(true)` for a pass.
pub fn latest_report_in(conn: &Connection, seq: i64) -> Result<Option<bool>> {
    use rusqlite::OptionalExtension;
    let detail: Option<String> = conn
        .query_row(
            "SELECT e.detail FROM task_events e JOIN tasks t ON t.id = e.task_id
             WHERE t.seq = ?1 AND e.kind = 'reported'
             ORDER BY e.at DESC, e.rowid DESC LIMIT 1",
            [seq],
            |row| row.get(0),
        )
        .optional()?;
    Ok(detail.map(|d| d.starts_with("pass")))
}

/// Send finished work back to the pool with the reason it does not stand,
/// the way a `sent_back` verdict does — for a judge that is not a review.
///
/// The findings are appended to the brief, so the next claimant is handed
/// them without knowing to ask. Any review of the work still unfinished is
/// cancelled: it would be reading work that is about to change.
pub fn send_back_in(
    tx: &Transaction<'_>,
    seq: i64,
    actor: &str,
    source: &str,
    findings: &str,
    evidence: &str,
    escalate_after: u32,
) -> Result<(Task, Recorded)> {
    let task = task_in(tx, seq)?;
    if task.status != Status::Done {
        return Err(Error::InvalidTransition {
            seq,
            status: task.status,
            transition: "send back",
        });
    }
    let holder = super::recusal::worker_of(tx, &task.id)?.unwrap_or_default();
    let now = now_ts();
    let note = format!(
        "\n\n---\n\nSent back by {source} ({}):\n\n{}\n",
        actor_harness(actor),
        findings.trim()
    );
    tx.execute(
        "UPDATE tasks
         SET status = 'open', claimed_by = NULL, lease_expires_at = NULL,
             result = NULL, body = body || ?2, updated_at = ?3
         WHERE id = ?1",
        params![task.id, note, now],
    )?;
    let moved = Move {
        from: Status::Done.as_str(),
        to: Status::Open.as_str(),
        evidence,
    };
    append(
        tx,
        &task.id,
        &now,
        actor,
        EventKind::Reopened,
        &format!(
            "sent back by {source}: {}",
            crate::fmt::truncate(findings.trim(), 120)
        ),
        moved,
    )?;
    for (review_id, status) in unfinished_reviews(tx, &task.id)? {
        tx.execute(
            "UPDATE tasks SET status = 'cancelled', claimed_by = NULL,
                    lease_expires_at = NULL, updated_at = ?2
             WHERE id = ?1",
            params![review_id, now],
        )?;
        insert_move(
            tx,
            &review_id,
            &now,
            actor,
            EventKind::Cancelled,
            &format!("the work under review was sent back by {source}"),
            status.as_str(),
            Status::Cancelled,
        )?;
    }
    let recorded = record_in(
        tx,
        &task.id,
        &holder,
        Outcome::CiFailed,
        source,
        actor,
        findings,
        escalate_after,
    )?;
    Ok((task_in(tx, seq)?, recorded))
}

/// Record that finished work is in, with what proves it.
pub fn merge_in(tx: &Transaction<'_>, seq: i64, actor: &str, evidence: &str) -> Result<()> {
    let task = task_in(tx, seq)?;
    let evidence = evidence.trim();
    if evidence.is_empty() {
        return Err(Error::invalid(
            "a merge needs evidence: the commit SHA or the PR URL that shows the work is in",
        ));
    }
    let now = now_ts();
    tx.execute(
        "INSERT INTO task_merges (id, task_id, actor, model, evidence, at)
         VALUES (?1, ?2, ?3,
           COALESCE((SELECT model FROM agent_sessions WHERE actor = ?3), ''), ?4, ?5)",
        params![super::new_id(), task.id, actor, evidence, now],
    )?;
    let moved = Move {
        evidence,
        ..Move::default()
    };
    append(
        tx,
        &task.id,
        &now,
        actor,
        EventKind::Merged,
        &format!("merged: {evidence}"),
        moved,
    )
}

/// Whether the task's current round of work is merged: a merge was recorded
/// after the work's latest completion. Merges are append-only, so work that
/// was merged, reopened and built again is not merged until it is merged
/// again. Order is the audit log's, not the clock's, so a merge and a
/// completion in the same millisecond still read in the order they happened.
pub fn merged_in(conn: &Connection, seq: i64) -> Result<bool> {
    Ok(conn
        .query_row(
            "SELECT COALESCE(
           (SELECT MAX(e.rowid) FROM task_events e WHERE e.task_id = t.id AND e.kind = 'merged')
             > COALESCE((SELECT MAX(e.rowid) FROM task_events e
                         WHERE e.task_id = t.id AND e.kind = 'completed'), 0),
           0)
         FROM tasks t WHERE t.seq = ?1",
            [seq],
            |row| row.get(0),
        )
        .optional()?
        .unwrap_or(false))
}

/// Close a review on a human's word: the review ends `done` with the human's
/// findings as its result, and the verdict is delivered exactly as if its
/// reviewer had — `sent_back` reopens the work, `upheld` lets it stand.
pub fn rule_in(
    tx: &Transaction<'_>,
    review_seq: i64,
    actor: &str,
    verdict: Verdict,
    findings: &str,
    escalate_after: u32,
) -> Result<Vec<Delivered>> {
    let findings = findings.trim();
    if findings.is_empty() {
        return Err(Error::invalid(
            "a ruling needs a reason the builder can act on",
        ));
    }
    let review = task_in(tx, review_seq)?;
    if !matches!(
        review.status,
        Status::Open | Status::Claimed | Status::InProgress
    ) {
        return Err(Error::InvalidTransition {
            seq: review_seq,
            status: review.status,
            transition: "rule",
        });
    }
    let now = now_ts();
    tx.execute(
        "UPDATE tasks SET status = 'done', claimed_by = NULL, lease_expires_at = NULL,
                result = ?2, updated_at = ?3
         WHERE id = ?1",
        params![review.id, findings, now],
    )?;
    insert_move(
        tx,
        &review.id,
        &now,
        actor,
        EventKind::Completed,
        &format!("ruled {verdict} by {actor}: {findings}"),
        review.status.as_str(),
        Status::Done,
    )?;
    deliver_in_tx(
        tx,
        &review,
        Some(verdict),
        actor,
        findings,
        Outcome::HumanRejected,
        escalate_after,
    )
}

/// The reviews of `work_id` not yet finished, each with its status. A review
/// is a task recused from the work (§15).
pub fn unfinished_reviews(conn: &Connection, work_id: &str) -> Result<Vec<(String, Status)>> {
    let mut stmt = conn.prepare(
        "SELECT t.id, t.status FROM task_recusals r JOIN tasks t ON t.id = r.task_id
         WHERE r.from_task_id = ?1 AND t.status IN ('open','claimed','in_progress')
         ORDER BY t.seq",
    )?;
    let rows = stmt.query_map([work_id], |row| {
        Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
    })?;
    let mut out = Vec::new();
    for row in rows {
        let (id, status) = row?;
        out.push((id, status.parse().unwrap_or(Status::Open)));
    }
    Ok(out)
}

/// Everyone who ever held a task, oldest first.
pub fn holders_in(conn: &Connection, seq: i64) -> Result<Vec<String>> {
    let id = super::deps::id_for_seq(conn, seq)?;
    super::recusal::holders_of(conn, &id)
}