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, store::Store, usage};
use anyhow::Result;
use serde_json::{json, Value};

const USAGE_SUMS: &str = "COUNT(u.attempt_id) AS metered_count,
    SUM(u.input_tokens) AS input_tokens, SUM(u.output_tokens) AS output_tokens,
    SUM(u.cache_read_tokens) AS cache_read_tokens, SUM(u.cache_write_tokens) AS cache_write_tokens,
    SUM(u.cost_usd) AS cost_usd";

/// Drop SQL NULL sums so JSON shows only values that were reported.
fn compact(mut row: Value) -> Value {
    if let Some(object) = row.as_object_mut() {
        object.retain(|_, value| !value.is_null());
    }
    row
}

pub fn show(store: &Store, run: &str, machine: bool) -> Result<()> {
    store.run(run)?;
    let roles: Vec<Value> = store
        .rows(
            &format!(
                "SELECT a.role, COUNT(*) AS attempt_count, COUNT(t.duration_ms) AS timed_count,
                SUM(t.duration_ms) AS total_duration_ms, {USAGE_SUMS}
                FROM attempts a LEFT JOIN attempt_timings t ON t.attempt_id=a.id
                LEFT JOIN attempt_usage u ON u.attempt_id=a.id
                WHERE a.run_id=? GROUP BY a.role ORDER BY a.role"
            ),
            &[&run],
        )?
        .into_iter()
        .map(compact)
        .collect();
    let tasks: Vec<Value> = store
        .rows(
            &format!(
                "SELECT a.task_id, COUNT(*) AS agent_attempts, {USAGE_SUMS}
                FROM attempts a LEFT JOIN attempt_usage u ON u.attempt_id=a.id
                WHERE a.run_id=? AND a.role IN ('build','review') AND a.task_id IS NOT NULL
                GROUP BY a.task_id ORDER BY a.task_id"
            ),
            &[&run],
        )?
        .into_iter()
        .map(compact)
        .collect();
    let total = compact(
        store
            .one(
                &format!(
                    "SELECT {USAGE_SUMS} FROM attempts a JOIN attempt_usage u ON u.attempt_id=a.id
                    WHERE a.run_id=?"
                ),
                &[&run],
            )?
            .unwrap_or(Value::Null),
    );
    let repeated: i64 = store.0.query_row(
        "SELECT COALESCE(SUM(n-1),0) FROM (
            SELECT COUNT(*) AS n FROM attempts WHERE run_id=? AND role IN ('build','review')
            AND task_id IS NOT NULL GROUP BY task_id,role
        )",
        [run],
        |row| row.get(0),
    )?;
    if machine {
        println!(
            "{}",
            serde_json::to_string_pretty(&json!({"run_id":run,"roles":roles,"tasks":tasks,
                "usage_total":total,"additional_task_attempts":repeated}))?
        );
        return Ok(());
    }
    println!("[METRICS] {run}");
    for row in &roles {
        let elapsed = row["total_duration_ms"]
            .as_i64()
            .map_or_else(|| "not timed".into(), |ms| format!("{ms} ms total"));
        let mut line = format!(
            "- {} · {}/{} attempts timed · {elapsed}",
            string_or_empty(&row["role"]),
            row["timed_count"],
            row["attempt_count"]
        );
        if let Some(summary) = usage::describe(row) {
            line.push_str(&format!(
                " · {summary} ({}/{} attempts with usage)",
                row["metered_count"], row["attempt_count"]
            ));
        }
        println!("{line}");
    }
    for row in &tasks {
        if let Some(summary) = usage::describe(row) {
            println!(
                "- Task {} · {} agent attempts · {summary}",
                string_or_empty(&row["task_id"]),
                row["agent_attempts"]
            );
        }
    }
    match usage::describe(&total) {
        Some(summary) => println!("- Total · {summary}"),
        None => println!("- Usage · no agent reported token usage"),
    }
    println!("- Extra build/review attempts across tasks · {repeated}");
    Ok(())
}