use rusqlite::{params, Connection, OptionalExtension, Transaction};
use super::new_id;
use crate::error::Result;
use crate::model::{now_ts, Attempt};
#[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",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Recorded {
pub n: i64,
pub escalated: bool,
}
pub struct Attempts<'a> {
conn: &'a Connection,
}
impl<'a> Attempts<'a> {
pub(crate) fn new(conn: &'a Connection) -> Attempts<'a> {
Attempts { conn }
}
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<_>>>()?)
}
#[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;
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
}
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());
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}");
}
}
}