agengo 0.3.0

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
use crate::contract::{string_or_empty, STATE_SQL};
use anyhow::{bail, Context, Result};
use rusqlite::{params, types::ValueRef, Connection, ToSql};
use serde_json::{json, Map, Value};
use std::{
    fs::{self, File, OpenOptions},
    path::Path,
    time::Duration,
};

pub fn lock(data: &Path, id: &str) -> Result<File> {
    let directory = data.join("locks");
    fs::create_dir_all(&directory)?;
    let file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(directory.join(id))?;
    fs2::FileExt::try_lock_exclusive(&file)
        .with_context(|| format!("run {id} already has an active coordinator"))?;
    Ok(file)
}

pub struct Store(pub Connection);

/// Typed view of the per-run settings stored in the `runs` table.
#[derive(Clone, Debug, PartialEq)]
pub struct Settings {
    pub timeout: u64,
    pub jobs: usize,
    pub review_limit: i64,
    pub gate_limit: i64,
    pub revision: i64,
    /// Custom adapter executable; `None` means Claude Code.
    pub agent: Option<String>,
}

impl Settings {
    pub fn from_row(run: &Value) -> Result<Self> {
        let number = |key: &str| {
            run[key]
                .as_i64()
                .filter(|value| *value > 0)
                .with_context(|| format!("run setting {key} is missing or not positive"))
        };
        Ok(Self {
            timeout: number("timeout")?.unsigned_abs(),
            jobs: usize::try_from(number("jobs")?)?,
            review_limit: number("review_limit")?,
            gate_limit: number("gate_limit")?,
            revision: number("revision")?,
            agent: run["agent"].as_str().map(str::to_owned),
        })
    }
}

pub fn parse(value: &Value) -> Result<Value> {
    value
        .as_str()
        .map_or(Ok(Value::Null), |body| Ok(serde_json::from_str(body)?))
}

impl Store {
    pub fn open(data: &Path) -> Result<Self> {
        fs::create_dir_all(data)?;
        let db = Connection::open(data.join("state.sqlite3"))?;
        db.busy_timeout(Duration::from_secs(10))?;
        let version: u32 = db.query_row("PRAGMA user_version", [], |row| row.get(0))?;
        if version > 1 {
            bail!("unsupported agengo state schema {version}; expected at most 1");
        }
        db.execute_batch(STATE_SQL)?;
        Ok(Self(db))
    }

    pub fn atomic<T>(&self, operation: impl FnOnce() -> Result<T>) -> Result<T> {
        self.0.execute_batch("BEGIN IMMEDIATE")?;
        let result = operation().and_then(|value| {
            self.0.execute_batch("COMMIT")?;
            Ok(value)
        });
        if result.is_err() {
            let _ = self.0.execute_batch("ROLLBACK");
        }
        result
    }

    pub fn rows(&self, sql: &str, args: &[&dyn ToSql]) -> Result<Vec<Value>> {
        let mut stmt = self.0.prepare(sql)?;
        let columns: Vec<_> = stmt.column_names().into_iter().map(str::to_owned).collect();
        let mut rows = stmt.query(args)?;
        let mut results = Vec::new();
        while let Some(row) = rows.next()? {
            let mut result = Map::new();
            for (index, name) in columns.iter().enumerate() {
                let value = match row.get_ref(index)? {
                    ValueRef::Null => Value::Null,
                    ValueRef::Integer(value) => json!(value),
                    ValueRef::Real(value) => json!(value),
                    ValueRef::Text(value) => json!(std::str::from_utf8(value)?),
                    ValueRef::Blob(_) => bail!("unexpected binary column {name}"),
                };
                result.insert(name.clone(), value);
            }
            results.push(Value::Object(result));
        }
        Ok(results)
    }

    pub fn one(&self, sql: &str, args: &[&dyn ToSql]) -> Result<Option<Value>> {
        Ok(self.rows(sql, args)?.into_iter().next())
    }

    pub fn run(&self, id: &str) -> Result<Value> {
        self.one("SELECT * FROM runs WHERE id = ?", &[&id])?
            .with_context(|| format!("unknown run: {id}"))
    }

    pub fn plan(&self, run: &Value) -> Result<Value> {
        let row = self
            .one(
                "SELECT body FROM plans WHERE run_id = ? AND revision = ?",
                &[&string_or_empty(&run["id"]), &run["revision"].as_i64()],
            )?
            .context("missing stored plan")?;
        parse(&row["body"])
    }

    pub fn handoff_mode(&self, id: &str) -> Result<String> {
        Ok(self
            .one("SELECT mode FROM run_handoff WHERE run_id = ?", &[&id])?
            .map_or_else(
                || "commit".into(),
                |row| string_or_empty(&row["mode"]).into(),
            ))
    }

    pub fn notice(
        &self,
        run: &str,
        task: Option<&str>,
        kind: &str,
        title: &str,
        detail: Value,
        checkpoint: Option<Value>,
    ) -> Result<Value> {
        self.0.execute(
            "INSERT INTO notices (run_id,task_id,kind,title,detail,state) VALUES (?,?,?,?,?,?)",
            params![
                run,
                task,
                kind,
                title,
                detail.to_string(),
                if checkpoint.is_some() { "open" } else { "info" }
            ],
        )?;
        let id = self.0.last_insert_rowid();
        if let Some(checkpoint) = checkpoint {
            self.0.execute(
                "INSERT INTO request_context VALUES (?,?,?,NULL)",
                params![
                    id,
                    self.run(run)?["revision"].as_i64(),
                    checkpoint.to_string()
                ],
            )?;
        }
        self.one(&format!("{NOTICES} AND n.id = ?"), &[&run, &id])?
            .context("missing notice")
    }

    pub fn pending(&self, run: &str, task: Option<&str>) -> Result<Option<Value>> {
        self.one(&format!("{NOTICES} AND n.task_id IS ? AND n.state IN ('open','received') ORDER BY n.id DESC LIMIT 1"),
            &[&run, &task])
    }

    pub fn transition(
        &self,
        request: &Value,
        state: &str,
        reply: Option<&Value>,
        outcome: Option<&str>,
    ) -> Result<()> {
        let id = request["id"].as_i64();
        self.0.execute(
            "UPDATE notices SET state = ?, reply = COALESCE(?,reply) WHERE id = ?",
            params![state, reply.map(Value::to_string), id],
        )?;
        self.0.execute(
            "UPDATE request_context SET outcome = ? WHERE notice_id = ?",
            params![outcome, id],
        )?;
        Ok(())
    }

    pub fn decision(
        &self,
        run: &str,
        task: Option<&str>,
        note: &str,
        source: Option<i64>,
        revision: i64,
    ) -> Result<()> {
        self.0.execute(
            "INSERT INTO decisions (run_id,task_id,note) VALUES (?,?,?)",
            params![run, task, note],
        )?;
        self.0.execute(
            "INSERT INTO decision_sources VALUES (?,?,?)",
            params![self.0.last_insert_rowid(), source, revision],
        )?;
        Ok(())
    }

    pub fn findings(&self, run: &str, task: Option<&str>) -> Result<Vec<Value>> {
        let mut rows = self.rows("SELECT * FROM review_findings WHERE run_id = ? AND (? IS NULL OR task_id = ?) ORDER BY task_id,id",
            &[&run,&task,&task])?;
        for row in &mut rows {
            let detail = parse(&row["detail"])?;
            let resolution = parse(&row["resolution"])?;
            let object = row.as_object_mut().unwrap();
            object.remove("detail");
            if let Value::Object(detail) = detail {
                object.extend(detail);
            }
            object.insert("resolution".into(), resolution);
        }
        Ok(rows)
    }

    /// Store normalized usage for an attempt. A `None` usage records nothing.
    pub fn record_usage(&self, attempt: &str, usage: Option<&Value>) -> Result<()> {
        let Some(usage) = usage else {
            return Ok(());
        };
        self.0.execute(
            "INSERT OR REPLACE INTO attempt_usage
             (attempt_id,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,cost_usd,model)
             VALUES (?,?,?,?,?,?,?)",
            params![
                attempt,
                usage["input_tokens"].as_i64(),
                usage["output_tokens"].as_i64(),
                usage["cache_read_tokens"].as_i64(),
                usage["cache_write_tokens"].as_i64(),
                usage["cost_usd"].as_f64(),
                usage["model"].as_str()
            ],
        )?;
        Ok(())
    }

    pub fn record_duration(&self, attempt: &str, elapsed: Duration) -> Result<()> {
        let millis = i64::try_from(elapsed.as_millis()).unwrap_or(i64::MAX);
        self.0.execute(
            "INSERT OR IGNORE INTO attempt_timings (attempt_id,duration_ms) VALUES (?,?)",
            params![attempt, millis],
        )?;
        Ok(())
    }
}

pub const NOTICES: &str = "SELECT n.*,c.revision,c.checkpoint,c.outcome FROM notices n LEFT JOIN request_context c ON c.notice_id=n.id WHERE n.run_id=?";
pub const HANDOFFS: &str = "SELECT h.*,a.task_id,a.request,a.result FROM build_handoffs h JOIN attempts a ON a.id=h.attempt_id WHERE a.run_id=?";

pub fn request_kind(row: &Value) -> bool {
    matches!(
        string_or_empty(&row["kind"]),
        "approval" | "decision" | "action" | "information"
    )
}

pub fn code(row: &Value) -> Option<String> {
    row["id"]
        .as_i64()
        .filter(|_| request_kind(row))
        .map(|id| format!("Y-{id:02}"))
}

/// The exact command that answers an open request.
pub fn respond_hint(row: &Value) -> Option<String> {
    let code = code(row)?;
    let run = string_or_empty(&row["run_id"]);
    Some(match string_or_empty(&row["kind"]) {
        "approval" => format!("agengo respond {run} {code} --choice approve (or reject)"),
        "decision" => format!(
            "agengo respond {run} {code} --choice A --note \"<guidance>\" | --choice B --note \"<reason>\" --plan <new-plan>"
        ),
        "action" => format!("agengo respond {run} {code} --note \"<what you did>\""),
        _ => format!("agengo respond {run} {code} --note \"<answer>\""),
    })
}

pub fn notice_json(mut row: Value) -> Result<Value> {
    row["code"] = json!(code(&row));
    row["respond_command"] = json!(respond_hint(&row).filter(|_| row["state"] == "open"));
    row["legacy_code"] = match string_or_empty(&row["kind"]) {
        "action" => json!(format!("A-{:02}", row["id"].as_i64().unwrap_or(0))),
        "decision" => json!(format!("D-{:02}", row["id"].as_i64().unwrap_or(0))),
        _ => Value::Null,
    };
    for field in ["detail", "reply", "checkpoint"] {
        row[field] = parse(&row[field])?;
    }
    Ok(row)
}

pub fn show(row: &Value) -> Result<()> {
    let kind = match string_or_empty(&row["kind"]) {
        "progress" => "PROGRESS",
        "approval" => "APPROVAL",
        "decision" => "DECISION",
        "information" => "QUESTION",
        "action" => "ACTION",
        "control" => "CONTROL",
        "delivery" => "DELIVERED",
        "incident" => "INCIDENT",
        _ => "EVENT",
    };
    let subject = row["task_id"]
        .as_str()
        .unwrap_or(string_or_empty(&row["run_id"]));
    let code = code(row).map_or(String::new(), |code| format!(" · {code}"));
    println!(
        "[{kind}] {subject} · {}{code}",
        line(string_or_empty(&row["title"]))
    );
    let detail = parse(&row["detail"])?;
    if row["state"] == "received" {
        let next = if row["kind"] == "action" {
            "the condition to be re-checked"
        } else {
            "it to be applied to the next attempt"
        };
        println!("- Situation — Response received. Waiting for {next}.");
        return Ok(());
    }
    for (key, label) in [
        ("situation", "Situation"),
        ("recommendation", "Recommendation"),
        ("reason", "Reason"),
    ] {
        if let Some(value) = detail[key].as_str() {
            println!("- {label} — {}", line(value));
        }
    }
    for option in crate::contract::array_or_empty(&detail["options"]) {
        if option["id"] != detail["recommended_choice"] {
            println!(
                "- {} — {}",
                string_or_empty(&option["id"]),
                line(string_or_empty(&option["label"]))
            );
        }
    }
    for (key, label) in [("response", "Response"), ("impact", "Impact")] {
        if let Some(value) = detail[key].as_str() {
            println!("- {label} — {}", line(value));
        }
    }
    if row["state"] == "open" {
        if let Some(hint) = respond_hint(row) {
            println!("- Command — {hint}");
        }
    }
    Ok(())
}

pub fn line(value: &str) -> String {
    value.split_whitespace().collect::<Vec<_>>().join(" ")
}

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

    #[test]
    fn settings_are_read_from_a_run_row() -> Result<()> {
        let row = json!({"timeout":900,"jobs":2,"review_limit":3,"gate_limit":2,"revision":4,"agent":null});
        let settings = Settings::from_row(&row)?;
        assert_eq!(
            settings,
            Settings {
                timeout: 900,
                jobs: 2,
                review_limit: 3,
                gate_limit: 2,
                revision: 4,
                agent: None
            }
        );
        let mut broken = row.clone();
        broken["jobs"] = json!(0);
        assert!(Settings::from_row(&broken).is_err());
        broken["jobs"] = Value::Null;
        assert!(Settings::from_row(&broken).is_err());
        Ok(())
    }
}