hird 0.3.1

Cross-harness agent work queue and shared assertion memory, backed by one local SQLite database
Documentation
//! Where a task's work lives: branch, worktree, pull request.
//!
//! `task_links` holds the current values only. Every change also lands on
//! the append-only trail as one `linked` event naming what changed, so the
//! table can be overwritten without losing history.

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

use super::audit::{append, Move};
use super::tasks::fetch_task_by_seq;
use crate::error::{Error, Result};
use crate::model::{now_ts, EventKind, TaskLinks};

const BRANCH_MAX: usize = 255;
const WORKTREE_MAX: usize = 1024;
const PR_URL_MAX: usize = 2048;

/// A change to a task's links. `None` leaves a link as it is; an empty string
/// clears it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LinkChange {
    pub branch: Option<String>,
    pub worktree: Option<String>,
    pub pr_url: Option<String>,
}

impl LinkChange {
    /// Whether the change asks for nothing.
    pub fn is_empty(&self) -> bool {
        self.branch.is_none() && self.worktree.is_none() && self.pr_url.is_none()
    }

    /// The change with every value trimmed and checked, or a refusal saying
    /// which value is wrong and why. Checked before any transaction opens, so
    /// a typo never costs the caller the rest of its call.
    pub fn normalized(&self) -> Result<LinkChange> {
        Ok(LinkChange {
            branch: check(self.branch.as_deref(), "branch", BRANCH_MAX, |v| {
                if v.chars().any(char::is_whitespace) {
                    return Err("a branch name has no whitespace".into());
                }
                Ok(())
            })?,
            worktree: check(self.worktree.as_deref(), "worktree", WORKTREE_MAX, |_| {
                Ok(())
            })?,
            pr_url: check(self.pr_url.as_deref(), "pr_url", PR_URL_MAX, |v| {
                if !(v.starts_with("https://") || v.starts_with("http://")) {
                    return Err("a pull request link is an http(s) URL".into());
                }
                if v.chars().any(char::is_whitespace) {
                    return Err("a URL has no whitespace".into());
                }
                Ok(())
            })?,
        })
    }
}

fn check(
    value: Option<&str>,
    name: &str,
    max: usize,
    rule: impl Fn(&str) -> std::result::Result<(), String>,
) -> Result<Option<String>> {
    let Some(value) = value else {
        return Ok(None);
    };
    let value = value.trim();
    if value.is_empty() {
        return Ok(Some(String::new()));
    }
    if value.chars().count() > max {
        return Err(Error::invalid(format!(
            "{name} is longer than {max} characters"
        )));
    }
    if value.chars().any(char::is_control) {
        return Err(Error::invalid(format!(
            "{name} must not contain control characters"
        )));
    }
    rule(value).map_err(|why| Error::invalid(format!("{name} {value:?} refused: {why}")))?;
    Ok(Some(value.to_string()))
}

pub struct Links<'a> {
    conn: &'a Connection,
}

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

    /// Task `seq`'s links, if any were ever set and not all cleared.
    pub fn for_task(&self, seq: i64) -> Result<Option<TaskLinks>> {
        let task = fetch_task_by_seq(self.conn, seq)?.ok_or(Error::TaskNotFound { seq })?;
        for_id(self.conn, &task.id)
    }

    /// Set or clear task `seq`'s links, whoever holds it: the human's path,
    /// for fixing a link after the fact. Agents set links through their
    /// check-in, which is holder-only.
    pub fn set(&self, seq: i64, actor: &str, change: &LinkChange) -> Result<Option<TaskLinks>> {
        let change = change.normalized()?;
        if change.is_empty() {
            return Err(Error::invalid(
                "nothing to link: give a branch, a worktree or a pull request URL",
            ));
        }
        let tx = super::immediate_tx(self.conn)?;
        let task = fetch_task_by_seq(&tx, seq)?.ok_or(Error::TaskNotFound { seq })?;
        let links = set_in(&tx, &task.id, actor, &change, &now_ts())?;
        tx.commit()?;
        Ok(links)
    }
}

pub(crate) fn for_id(conn: &Connection, task_id: &str) -> Result<Option<TaskLinks>> {
    let links = conn
        .query_row(
            "SELECT branch, worktree, pr_url, updated_by, at FROM task_links WHERE task_id = ?1",
            [task_id],
            |row| {
                let some = |s: String| (!s.is_empty()).then_some(s);
                Ok(TaskLinks {
                    branch: some(row.get(0)?),
                    worktree: some(row.get(1)?),
                    pr_url: some(row.get(2)?),
                    updated_by: row.get(3)?,
                    at: row.get(4)?,
                })
            },
        )
        .optional()?;
    Ok(links.filter(|l| !l.is_empty()))
}

/// Apply an already-normalized `change` inside the caller's transaction, and
/// put one `linked` event on the trail naming what moved. A change that moves
/// nothing writes nothing. Returns the links as they now stand.
pub(crate) fn set_in(
    tx: &Transaction<'_>,
    task_id: &str,
    actor: &str,
    change: &LinkChange,
    now: &str,
) -> Result<Option<TaskLinks>> {
    let before = for_id(tx, task_id)?.unwrap_or_default();
    let pick = |new: &Option<String>, old: &Option<String>| match new {
        Some(v) => v.clone(),
        None => old.clone().unwrap_or_default(),
    };
    let branch = pick(&change.branch, &before.branch);
    let worktree = pick(&change.worktree, &before.worktree);
    let pr_url = pick(&change.pr_url, &before.pr_url);

    let mut moved = Vec::new();
    for (name, old, new) in [
        ("branch", &before.branch, &branch),
        ("worktree", &before.worktree, &worktree),
        ("pr", &before.pr_url, &pr_url),
    ] {
        if old.as_deref().unwrap_or("") != new.as_str() {
            moved.push(if new.is_empty() {
                format!("{name} cleared")
            } else {
                format!("{name} {new}")
            });
        }
    }
    if moved.is_empty() {
        return for_id(tx, task_id);
    }

    tx.execute(
        "INSERT INTO task_links (task_id, branch, worktree, pr_url, updated_by, at)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6)
         ON CONFLICT (task_id) DO UPDATE SET
           branch = excluded.branch, worktree = excluded.worktree,
           pr_url = excluded.pr_url, updated_by = excluded.updated_by, at = excluded.at",
        params![task_id, branch, worktree, pr_url, actor, now],
    )?;
    append(
        tx,
        task_id,
        now,
        actor,
        EventKind::Linked,
        &moved.join("; "),
        Move {
            evidence: &pr_url,
            ..Move::default()
        },
    )?;
    for_id(tx, task_id)
}

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

    fn change(branch: Option<&str>, worktree: Option<&str>, pr: Option<&str>) -> LinkChange {
        LinkChange {
            branch: branch.map(str::to_string),
            worktree: worktree.map(str::to_string),
            pr_url: pr.map(str::to_string),
        }
    }

    fn linked_events(db: &Db, seq: i64) -> Vec<String> {
        db.audit()
            .for_task(seq)
            .unwrap()
            .into_iter()
            .filter(|e| e.kind == "linked")
            .map(|e| e.detail)
            .collect()
    }

    #[test]
    fn links_are_set_merged_and_cleared_with_every_change_on_the_trail() {
        let db = Db::open_in_memory().unwrap();
        let seq = db.tasks().create("/p", "t", "", 0, "cli").unwrap().seq;
        assert_eq!(db.links().for_task(seq).unwrap(), None);

        let links = db
            .links()
            .set(
                seq,
                "cli",
                &change(Some(" feat/lexer "), Some("/w/lexer"), None),
            )
            .unwrap()
            .unwrap();
        assert_eq!(links.branch.as_deref(), Some("feat/lexer"));
        assert_eq!(links.worktree.as_deref(), Some("/w/lexer"));
        assert_eq!(links.pr_url, None);

        // Only what is named changes; the rest stands.
        let pr = "https://github.com/acme/app/pull/7";
        let links = db
            .links()
            .set(seq, "codex:1", &change(None, None, Some(pr)))
            .unwrap()
            .unwrap();
        assert_eq!(links.branch.as_deref(), Some("feat/lexer"));
        assert_eq!(links.pr_url.as_deref(), Some(pr));
        assert_eq!(links.updated_by, "codex:1");

        // Setting what is already there writes nothing.
        db.links()
            .set(seq, "cli", &change(Some("feat/lexer"), None, None))
            .unwrap();

        db.links()
            .set(seq, "cli", &change(None, Some(""), None))
            .unwrap();
        assert_eq!(
            linked_events(&db, seq),
            vec![
                "branch feat/lexer; worktree /w/lexer".to_string(),
                format!("pr {pr}"),
                "worktree cleared".to_string(),
            ]
        );
        let pr_event = db
            .audit()
            .for_task(seq)
            .unwrap()
            .into_iter()
            .find(|e| e.detail.starts_with("pr "))
            .unwrap();
        assert_eq!(pr_event.evidence, pr);

        // Clearing everything leaves no links, and the trail keeps them all.
        db.links()
            .set(seq, "cli", &change(Some(""), None, Some("")))
            .unwrap();
        assert_eq!(db.links().for_task(seq).unwrap(), None);
        assert_eq!(linked_events(&db, seq).len(), 4);
    }

    #[test]
    fn bad_links_are_refused_before_anything_is_written() {
        let db = Db::open_in_memory().unwrap();
        let seq = db.tasks().create("/p", "t", "", 0, "cli").unwrap().seq;
        for bad in [
            change(Some("two words"), None, None),
            change(None, None, Some("github.com/acme/app/pull/7")),
            change(None, Some("/w/\u{7}bell"), None),
            change(Some(&"b".repeat(BRANCH_MAX + 1)), None, None),
            change(None, None, None),
        ] {
            assert!(db.links().set(seq, "cli", &bad).is_err(), "{bad:?}");
        }
        assert!(linked_events(&db, seq).is_empty());
        assert!(matches!(
            db.links().set(99, "cli", &change(Some("b"), None, None)),
            Err(Error::TaskNotFound { seq: 99 })
        ));
    }

    #[test]
    fn link_history_cannot_be_rewritten() {
        let db = Db::open_in_memory().unwrap();
        let seq = db.tasks().create("/p", "t", "", 0, "cli").unwrap().seq;
        db.links()
            .set(seq, "cli", &change(Some("feat/a"), None, None))
            .unwrap();
        let err = db
            .conn()
            .execute("DELETE FROM task_events WHERE kind = 'linked'", [])
            .unwrap_err();
        assert!(err.to_string().contains("append-only"), "{err}");
    }
}