use rusqlite::{params, Connection, OptionalExtension, Transaction};
use super::deps::id_for_seq;
use crate::error::{Error, Result};
use crate::identity::actor_harness;
use crate::model::{now_ts, EventKind, Recusal};
pub struct Recusals<'a> {
conn: &'a Connection,
}
impl<'a> Recusals<'a> {
pub(crate) fn new(conn: &'a Connection) -> Recusals<'a> {
Recusals { conn }
}
pub fn add(&self, seq: i64, from_seq: i64, reason: &str, actor: &str) -> Result<()> {
if seq == from_seq {
return Err(Error::invalid(format!(
"task {seq} cannot be recused from itself"
)));
}
let tx = super::immediate_tx(self.conn)?;
add_in_tx(&tx, seq, from_seq, reason, actor)?;
tx.commit()?;
Ok(())
}
pub fn clear(&self, seq: i64, actor: &str) -> Result<usize> {
let tx = super::immediate_tx(self.conn)?;
let task_id = id_for_seq(&tx, seq)?;
let removed = tx.execute("DELETE FROM task_recusals WHERE task_id = ?1", [&task_id])?;
if removed > 0 {
super::tasks::insert_event(
&tx,
&task_id,
&now_ts(),
actor,
EventKind::Recused,
"recusals lifted",
)?;
}
tx.commit()?;
Ok(removed)
}
pub fn for_task(&self, seq: i64) -> Result<Vec<Recusal>> {
let task_id = id_for_seq(self.conn, seq)?;
recusals_in(self.conn, &task_id)
}
pub fn reviews(
&self,
scope: &super::ProjectScope,
) -> Result<std::collections::BTreeMap<i64, i64>> {
let (project_clause, project_value) = scope.clause("t.project");
let sql = format!(
"SELECT t.seq, MIN(f.seq) FROM task_recusals r
JOIN tasks t ON t.id = r.task_id
JOIN tasks f ON f.id = r.from_task_id
WHERE {project_clause}
GROUP BY t.seq"
);
let mut stmt = self.conn.prepare(&sql)?;
let binds: Vec<&str> = project_value.into_iter().collect();
let rows = stmt.query_map(rusqlite::params_from_iter(binds), |row| {
Ok((row.get(0)?, row.get(1)?))
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn bars(&self, seq: i64, actor: &str) -> Result<Option<Recusal>> {
let task_id = id_for_seq(self.conn, seq)?;
bars_in(self.conn, &task_id, actor)
}
}
pub(super) fn recusals_in(conn: &Connection, task_id: &str) -> Result<Vec<Recusal>> {
let mut stmt = conn.prepare(
"SELECT t.seq, t.title, r.reason FROM task_recusals r
JOIN tasks t ON t.id = r.from_task_id
WHERE r.task_id = ?1 ORDER BY t.seq",
)?;
let rows = stmt.query_map([task_id], |row| {
Ok(Recusal {
from_seq: row.get(0)?,
from_title: row.get(1)?,
reason: row.get(2)?,
worker: None,
earlier: Vec::new(),
})
})?;
let mut out: Vec<Recusal> = rows.collect::<rusqlite::Result<Vec<_>>>()?;
for recusal in &mut out {
let from_id = id_for_seq(conn, recusal.from_seq)?;
recusal.worker = worker_of(conn, &from_id)?;
recusal.earlier = holders_of(conn, &from_id)?
.into_iter()
.filter(|holder| Some(holder) != recusal.worker.as_ref())
.collect();
}
Ok(out)
}
pub(super) fn barred_harnesses(conn: &Connection, task_id: &str) -> Result<Vec<String>> {
let mut out: Vec<String> = recusals_in(conn, task_id)?
.into_iter()
.flat_map(|recusal| {
recusal
.holders()
.map(|holder| actor_harness(holder).to_string())
.collect::<Vec<_>>()
})
.collect();
out.sort();
out.dedup();
Ok(out)
}
pub(super) fn bars_in(conn: &Connection, task_id: &str, actor: &str) -> Result<Option<Recusal>> {
let mine = actor_harness(actor);
for recusal in recusals_in(conn, task_id)? {
let barring = recusal
.holders()
.find(|holder| actor_harness(holder) == mine)
.map(str::to_string);
if let Some(holder) = barring {
return Ok(Some(Recusal {
worker: Some(holder),
..recusal
}));
}
}
Ok(None)
}
pub(super) fn worker_of(conn: &Connection, task_id: &str) -> Result<Option<String>> {
Ok(conn
.query_row(
"SELECT actor FROM task_events
WHERE task_id = ?1 AND kind IN ('claimed','completed','failed')
ORDER BY at DESC, id DESC LIMIT 1",
[task_id],
|row| row.get(0),
)
.optional()?)
}
pub(super) fn holders_of(conn: &Connection, task_id: &str) -> Result<Vec<String>> {
let mut stmt = conn.prepare(
"SELECT actor FROM task_events
WHERE task_id = ?1 AND kind IN ('claimed','completed','failed')
GROUP BY actor ORDER BY MIN(rowid)",
)?;
let rows = stmt.query_map([task_id], |row| row.get(0))?;
Ok(rows.collect::<rusqlite::Result<Vec<String>>>()?)
}
fn is_review(conn: &Connection, task_id: &str) -> Result<bool> {
Ok(conn.query_row(
"SELECT EXISTS (SELECT 1 FROM task_recusals WHERE task_id = ?1)",
[task_id],
|row| row.get(0),
)?)
}
pub(super) fn file_review(
tx: &Transaction<'_>,
task: &crate::model::Task,
actor: &str,
result: &str,
exhibit: Option<&str>,
forced: bool,
) -> Result<Option<i64>> {
if !(task.review || forced) || already_under_review(tx, &task.id)? {
return Ok(None);
}
if !task.review && is_review(tx, &task.id)? {
return Ok(None);
}
let observed: Vec<String> = super::witness::Witnessed::new(tx)
.touched(task.seq)?
.into_iter()
.map(|o| o.describe())
.collect();
let declared = super::scope::Scopes::new(tx).for_task(task.seq)?;
if observed.is_empty() && declared.is_empty() && !forced {
return Ok(None);
}
let body = review_body(task, result, &observed, &declared, exhibit);
let review = super::tasks::create_in_tx(
tx,
&task.project,
&format!("Review: {}", task.title),
&body,
task.priority,
actor,
)?;
let required = super::requirements::for_id(tx, &task.id)?;
super::requirements::set_in_tx(tx, &review.id, &required, actor, &now_ts())?;
let paths: Vec<String> = super::witness::Witnessed::new(tx)
.touched(task.seq)?
.into_iter()
.map(|o| o.path)
.collect();
let scope = if paths.is_empty() { declared } else { paths };
super::scope::declare_in_tx(tx, review.seq, &scope, actor, super::OnConflict::Report)?;
add_in_tx(
tx,
review.seq,
task.seq,
"no agent reviews its own work",
actor,
)?;
let now = now_ts();
super::tasks::insert_event(
tx,
&task.id,
&now,
actor,
EventKind::Reviewed,
&format!("review filed as task {}", review.seq),
)?;
Ok(Some(review.seq))
}
fn already_under_review(tx: &Transaction<'_>, task_id: &str) -> Result<bool> {
Ok(tx.query_row(
"SELECT COUNT(*) FROM task_recusals r JOIN tasks t ON t.id = r.task_id
WHERE r.from_task_id = ?1 AND t.status NOT IN ('done','failed','cancelled')",
[task_id],
|row| row.get::<_, i64>(0),
)? > 0)
}
fn review_body(
task: &crate::model::Task,
result: &str,
observed: &[String],
declared: &[String],
exhibit: Option<&str>,
) -> String {
let mut out = format!(
"Review the work done on task {} ({}).\n\nWhat its agent said it did:\n\n> {}\n",
task.seq,
task.title,
result.replace('\n', "\n> "),
);
if !observed.is_empty() {
out.push_str(&format!(
"\nWhat the working tree was seen to do while it was held:\n\n- {}\n",
observed.join("\n- ")
));
} else if !declared.is_empty() {
out.push_str(&format!(
"\nThe files it said it would touch (nothing was witnessed):\n\n- {}\n",
declared.join("\n- ")
));
}
if let Some(diff) = exhibit.map(str::trim).filter(|d| !d.is_empty()) {
out.push_str(&format!(
"\nThe change under review, as the witness kept it:\n\n```diff\n{diff}\n```\n"
));
}
if !task.body.trim().is_empty() {
out.push_str(&format!("\nThe original brief:\n\n{}\n", task.body.trim()));
}
out.push_str(
"\nRead the code, not the summary — the summary is what is under review. \
Complete this task with what you found and a verdict: `upheld` if the work \
stands, `sent_back` if it does not. Sending it back reopens the work with \
your findings appended to its brief, so write the result as instructions \
for whoever redoes it — they will not see your session. Do not fix the \
work here either way, and `mem_store` anything durable you learn.\n",
);
out
}
pub(super) fn add_in_tx(
tx: &Transaction<'_>,
seq: i64,
from_seq: i64,
reason: &str,
actor: &str,
) -> Result<()> {
let task_id = id_for_seq(tx, seq)?;
let from_id = id_for_seq(tx, from_seq)?;
let now = now_ts();
let changed = tx.execute(
"INSERT INTO task_recusals (task_id, from_task_id, reason, actor, at)
VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(task_id, from_task_id) DO NOTHING",
params![task_id, from_id, reason.trim(), actor, now],
)?;
if changed > 0 {
super::tasks::insert_event(
tx,
&task_id,
&now,
actor,
EventKind::Recused,
&format!("recused from task {from_seq}"),
)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::db::Db;
use std::time::Duration;
const PROJECT: &str = "/tmp/project";
const TTL: Duration = Duration::from_secs(900);
fn db() -> Db {
Db::open_in_memory().unwrap()
}
fn task(db: &Db, title: &str) -> i64 {
db.tasks().create(PROJECT, title, "", 0, "cli").unwrap().seq
}
fn worked(db: &Db, seq: i64, actor: &str) {
db.tasks().claim(seq, actor, TTL).unwrap();
db.tasks().complete(seq, actor, "done").unwrap();
}
#[test]
fn the_agent_that_did_the_work_cannot_claim_the_review_of_it() {
let db = db();
let work = task(&db, "Port the loader");
let review = task(&db, "Review the loader port");
worked(&db, work, "codex:9f2c");
db.recusals()
.add(review, work, "reviews its own work", "cli")
.unwrap();
let barred = db.recusals().bars(review, "codex:9f2c").unwrap().unwrap();
assert_eq!(barred.from_seq, work);
assert_eq!(barred.worker.as_deref(), Some("codex:9f2c"));
let err = db
.tasks()
.claim(review, "codex:9f2c", TTL)
.unwrap_err()
.to_string();
assert!(err.contains(&format!("task {work}")), "{err}");
assert!(err.contains("codex:9f2c worked"), "{err}");
assert!(err.contains("a different harness"), "{err}");
}
#[test]
fn another_session_of_the_same_harness_is_barred_too() {
let db = db();
let work = task(&db, "Port the loader");
let review = task(&db, "Review the loader port");
worked(&db, work, "codex:9f2c");
db.recusals().add(review, work, "", "cli").unwrap();
assert!(db.recusals().bars(review, "codex:1a2b").unwrap().is_some());
assert!(db
.recusals()
.bars(review, "claude-code:af31")
.unwrap()
.is_none());
db.tasks().claim(review, "claude-code:af31", TTL).unwrap();
}
#[test]
fn a_recusal_on_work_nobody_has_done_bars_nobody() {
let db = db();
let work = task(&db, "Port the loader");
let review = task(&db, "Review the loader port");
db.recusals().add(review, work, "", "cli").unwrap();
assert!(db.recusals().bars(review, "codex:9f2c").unwrap().is_none());
db.tasks().claim(review, "codex:9f2c", TTL).unwrap();
}
#[test]
fn the_worker_is_whoever_last_held_the_task_and_every_holder_is_barred() {
let db = db();
let work = task(&db, "Port the loader");
db.tasks().claim(work, "codex:9f2c", TTL).unwrap();
db.tasks()
.release(work, "codex:9f2c", "out of my depth")
.unwrap();
worked(&db, work, "claude-code:af31");
let review = task(&db, "Review the loader port");
db.recusals().add(review, work, "", "cli").unwrap();
assert!(db
.recusals()
.bars(review, "claude-code:af31")
.unwrap()
.is_some());
let barred = db.recusals().bars(review, "codex:9f2c").unwrap().unwrap();
assert_eq!(barred.worker.as_deref(), Some("codex:9f2c"));
let listed = db.recusals().for_task(review).unwrap();
assert_eq!(listed[0].worker.as_deref(), Some("claude-code:af31"));
assert_eq!(listed[0].earlier, vec!["codex:9f2c".to_string()]);
}
#[test]
fn an_earlier_holder_whose_lease_lapsed_cannot_review() {
let db = db();
let work = task(&db, "Port the loader");
db.tasks().claim(work, "codex:9f2c", TTL).unwrap();
db.conn()
.execute(
"UPDATE tasks SET lease_expires_at = '2000-01-01T00:00:00Z' WHERE seq = ?1",
[work],
)
.unwrap();
db.tasks().sweep_leases().unwrap();
worked(&db, work, "claude-code:af31");
let review = task(&db, "Review the loader port");
db.recusals().add(review, work, "", "cli").unwrap();
let err = db
.tasks()
.claim(review, "codex:other", TTL)
.unwrap_err()
.to_string();
assert!(err.contains("codex:9f2c worked"), "{err}");
assert_eq!(
barred_harnesses(db.conn(), &id_for_seq(db.conn(), review).unwrap()).unwrap(),
vec!["claude-code".to_string(), "codex".to_string()]
);
db.tasks().claim(review, "copilot:1", TTL).unwrap();
}
#[test]
fn recusals_are_listed_with_who_they_bar_and_can_be_lifted() {
let db = db();
let a = task(&db, "Port the loader");
let b = task(&db, "Port the renderer");
let review = task(&db, "Review both");
worked(&db, a, "codex:9f2c");
worked(&db, b, "claude-code:af31");
db.recusals().add(review, a, "wrote it", "cli").unwrap();
db.recusals().add(review, b, "", "cli").unwrap();
let listed = db.recusals().for_task(review).unwrap();
assert_eq!(listed.len(), 2);
assert_eq!(listed[0].from_seq, a);
assert_eq!(listed[0].worker.as_deref(), Some("codex:9f2c"));
assert_eq!(listed[0].reason, "wrote it");
assert!(listed[0].describe().contains("codex:9f2c"), "{listed:?}");
assert_eq!(db.recusals().clear(review, "cli").unwrap(), 2);
assert!(db.recusals().for_task(review).unwrap().is_empty());
db.tasks().claim(review, "codex:9f2c", TTL).unwrap();
}
#[test]
fn adding_the_same_recusal_twice_is_a_no_op() {
let db = db();
let work = task(&db, "Port the loader");
let review = task(&db, "Review it");
db.recusals().add(review, work, "", "cli").unwrap();
db.recusals().add(review, work, "", "cli").unwrap();
assert_eq!(db.recusals().for_task(review).unwrap().len(), 1);
}
#[test]
fn a_task_cannot_be_recused_from_itself_or_from_nothing() {
let db = db();
let seq = task(&db, "Port the loader");
assert!(db
.recusals()
.add(seq, seq, "", "cli")
.unwrap_err()
.to_string()
.contains("itself"));
assert_eq!(
db.recusals()
.add(seq, 404, "", "cli")
.unwrap_err()
.to_string(),
"task 404 not found"
);
}
#[test]
fn finishing_reviewed_work_files_the_review_and_hands_it_on() {
let db = db();
let seq = db
.tasks()
.create(
PROJECT,
"Port the config loader",
"keep the precedence",
3,
"cli",
)
.unwrap()
.seq;
db.tasks().set_review(seq, true, "cli").unwrap();
db.tasks().claim(seq, "codex:9f2c", TTL).unwrap();
db.witnessed()
.begin(seq, &crate::witness::Tree::default(), "codex:9f2c")
.unwrap();
db.witnessed()
.record(
seq,
&[
crate::witness::Change {
path: "src/config.rs".into(),
kind: crate::witness::ChangeKind::Modified,
hash: "h1".into(),
},
crate::witness::Change {
path: "tests/config.rs".into(),
kind: crate::witness::ChangeKind::Added,
hash: "h2".into(),
},
],
"codex:9f2c",
)
.unwrap();
let finished = db
.tasks()
.complete(seq, "codex:9f2c", "ported it, env still wins")
.unwrap();
let review = finished.review.expect("a review was filed");
let filed = db.tasks().get(review).unwrap();
assert_eq!(filed.title, "Review: Port the config loader");
assert_eq!(filed.priority, 3, "it matters as much as the work did");
assert!(
filed.body.contains("ported it, env still wins"),
"{}",
filed.body
);
assert!(
filed.body.contains("src/config.rs (modified)"),
"{}",
filed.body
);
assert!(filed.body.contains("keep the precedence"), "{}", filed.body);
assert!(
filed.body.contains("not the summary"),
"the reviewer has to be told what is under review: {}",
filed.body
);
assert_eq!(
db.scopes().for_task(review).unwrap(),
vec!["src/config.rs", "tests/config.rs"]
);
assert!(db.tasks().claim(review, "codex:1a2b", TTL).is_err());
db.tasks().claim(review, "claude-code:af31", TTL).unwrap();
}
#[test]
fn the_review_brief_carries_the_diff_when_the_completion_brought_one() {
let db = db();
let seq = task(&db, "Port the config loader");
db.tasks().set_review(seq, true, "cli").unwrap();
db.tasks().claim(seq, "codex:9f2c", TTL).unwrap();
db.witnessed()
.begin(seq, &crate::witness::Tree::default(), "codex:9f2c")
.unwrap();
db.witnessed()
.record(
seq,
&[crate::witness::Change {
path: "src/config.rs".into(),
kind: crate::witness::ChangeKind::Modified,
hash: "h1".into(),
}],
"codex:9f2c",
)
.unwrap();
let diff = "--- a/src/config.rs\n+++ b/src/config.rs\n-old\n+new\n";
let finished = db
.tasks()
.complete_showing(seq, "codex:9f2c", "ported", None, Some(diff))
.unwrap();
let filed = db
.tasks()
.get(finished.review.expect("a review was filed"))
.unwrap();
assert!(
filed.body.contains("as the witness kept it"),
"{}",
filed.body
);
assert!(filed.body.contains("```diff"), "{}", filed.body);
assert!(filed.body.contains("+new"), "{}", filed.body);
let quiet = task(&db, "Port it again");
db.tasks().set_review(quiet, true, "cli").unwrap();
db.tasks().claim(quiet, "codex:9f2c", TTL).unwrap();
db.witnessed()
.begin(quiet, &crate::witness::Tree::default(), "codex:9f2c")
.unwrap();
db.witnessed()
.record(
quiet,
&[crate::witness::Change {
path: "src/config.rs".into(),
kind: crate::witness::ChangeKind::Modified,
hash: "h2".into(),
}],
"codex:9f2c",
)
.unwrap();
let finished = db
.tasks()
.complete_showing(quiet, "codex:9f2c", "ported", None, Some(" "))
.unwrap();
let filed = db
.tasks()
.get(finished.review.expect("a review was filed"))
.unwrap();
assert!(!filed.body.contains("```diff"), "{}", filed.body);
}
#[test]
fn a_filed_review_is_announced_with_its_author_barred() {
let db = db();
let seq = task(&db, "Port the loader");
db.tasks().set_review(seq, true, "cli").unwrap();
db.scopes()
.declare(
seq,
&["src/loader.rs".to_string()],
"cli",
super::super::OnConflict::Report,
)
.unwrap();
db.tasks().claim(seq, "codex:9f2c", TTL).unwrap();
let finished = db.tasks().complete(seq, "codex:9f2c", "ported").unwrap();
let review = finished.review.expect("a review was filed");
let claimable = db
.deps()
.claimable(review, crate::model::Clearance::Done)
.unwrap()
.expect("the review is claimable");
assert_eq!(claimable.recused, vec!["codex"]);
let work = db
.deps()
.claimable(seq, crate::model::Clearance::Done)
.unwrap();
assert!(work.is_none(), "finished work is not claimable");
}
#[test]
fn a_filed_review_inherits_the_capabilities_needed_to_check_the_work() {
let db = db();
let seq = task(&db, "visual QA");
db.scopes()
.declare(
seq,
&["src/ui.rs".into()],
"cli",
crate::repo::OnConflict::Report,
)
.unwrap();
db.requirements()
.set(seq, &["browser".into()], "cli")
.unwrap();
db.tasks().set_review(seq, true, "cli").unwrap();
db.tasks()
.claim_scoped_with_capabilities(
seq,
"codex:9f2c",
TTL,
&[],
crate::repo::OnConflict::Report,
crate::model::Clearance::Done,
&["browser".into()],
)
.unwrap();
let review = db
.tasks()
.complete(seq, "codex:9f2c", "checked the UI")
.unwrap()
.review
.unwrap();
assert_eq!(db.requirements().for_task(review).unwrap(), vec!["browser"]);
}
#[test]
fn work_that_left_no_trace_files_no_review() {
let db = db();
let seq = task(&db, "Think about the problem");
db.tasks().set_review(seq, true, "cli").unwrap();
db.tasks().claim(seq, "codex:9f2c", TTL).unwrap();
let finished = db.tasks().complete(seq, "codex:9f2c", "thought").unwrap();
assert_eq!(finished.review, None);
}
#[test]
fn failed_work_files_no_review() {
let db = db();
let seq = task(&db, "Port the loader");
db.tasks().set_review(seq, true, "cli").unwrap();
db.scopes()
.declare(
seq,
&["src/config.rs".to_string()],
"cli",
super::super::OnConflict::Report,
)
.unwrap();
db.tasks().claim(seq, "codex:9f2c", TTL).unwrap();
let finished = db
.tasks()
.fail(seq, "codex:9f2c", "no credentials")
.unwrap();
assert_eq!(finished.review, None);
}
#[test]
fn a_second_completion_does_not_file_a_second_review() {
let db = db();
let seq = task(&db, "Port the loader");
db.tasks().set_review(seq, true, "cli").unwrap();
db.scopes()
.declare(
seq,
&["src/config.rs".to_string()],
"cli",
super::super::OnConflict::Report,
)
.unwrap();
db.tasks().claim(seq, "codex:9f2c", TTL).unwrap();
let first = db.tasks().complete(seq, "codex:9f2c", "ported").unwrap();
let review = first.review.expect("filed once");
db.tasks().reopen(seq, "cli", "not quite").unwrap();
db.tasks().claim(seq, "codex:9f2c", TTL).unwrap();
let again = db
.tasks()
.complete(seq, "codex:9f2c", "ported again")
.unwrap();
assert_eq!(again.review, None, "the first review is still open");
db.tasks().claim(review, "claude-code:af31", TTL).unwrap();
db.tasks()
.complete_with(
review,
"claude-code:af31",
"looks right",
Some(crate::model::Verdict::Upheld),
)
.unwrap();
db.tasks().reopen(seq, "cli", "one more thing").unwrap();
db.tasks().claim(seq, "codex:9f2c", TTL).unwrap();
let third = db.tasks().complete(seq, "codex:9f2c", "and again").unwrap();
assert!(third.review.is_some());
}
#[test]
fn recusals_are_written_into_the_task_history() {
let db = db();
let work = task(&db, "Port the loader");
let review = task(&db, "Review it");
db.recusals().add(review, work, "", "cli").unwrap();
let task = db.tasks().get(review).unwrap();
let events = db.tasks().events(&task.id, 20).unwrap();
let recorded: Vec<&str> = events
.iter()
.filter(|e| e.kind == EventKind::Recused)
.map(|e| e.detail.as_str())
.collect();
assert_eq!(recorded, vec![format!("recused from task {work}")]);
}
}