use crate::{
context,
contract::{array_or_empty, string_or_empty},
store::{parse, Store},
usage,
};
use anyhow::Result;
use serde_json::{json, Map, Value};
use std::collections::BTreeMap;
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";
fn compact(mut row: Value) -> Value {
if let Some(object) = row.as_object_mut() {
object.retain(|_, value| !value.is_null());
}
row
}
fn collect(store: &Store, run: &str) -> Result<Value> {
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),
)?;
let reliability = reliability(store, run)?;
Ok(json!({"run_id":run,"roles":roles,"tasks":tasks,
"usage_total":total,"additional_task_attempts":repeated,
"reliability":reliability}))
}
pub fn show(store: &Store, run: &str, machine: bool) -> Result<()> {
let report = collect(store, run)?;
if machine {
println!("{}", serde_json::to_string_pretty(&report)?);
return Ok(());
}
let (roles, tasks, total, repeated) = (
array_or_empty(&report["roles"]),
array_or_empty(&report["tasks"]),
&report["usage_total"],
&report["additional_task_attempts"],
);
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}");
print_reliability(&report["reliability"]);
Ok(())
}
fn add(object: &mut Value, key: &str, value: &Value) {
let sum = match (object[key].as_i64(), value.as_i64()) {
(Some(left), Some(right)) => json!(left + right),
_ => match (object[key].as_f64(), value.as_f64()) {
(left, Some(right)) => json!(left.unwrap_or_default() + right),
(_, None) => return,
},
};
object[key] = sum;
}
pub fn show_all(store: &Store, machine: bool) -> Result<()> {
let mut runs = Vec::new();
let mut combined = json!({"runs":0,"tasks":0,"agent_attempts":0,
"tasks_reviewed":0,"first_review_pass":0,"gate_failures":0});
let mut models = BTreeMap::<String, Value>::new();
for listed in store.rows("SELECT id FROM runs ORDER BY rowid", &[])? {
let id = string_or_empty(&listed["id"]);
let run = store.run(id)?;
let report = collect(store, id)?;
let reliability = &report["reliability"];
let attempts: i64 = array_or_empty(&report["tasks"])
.iter()
.filter_map(|row| row["agent_attempts"].as_i64())
.sum();
let mut row = json!({"run_id":id,"state":run["state"],
"tasks":store.plan(&run)?.tasks.len(),"agent_attempts":attempts,
"tasks_reviewed":reliability["tasks_reviewed"],
"first_review_pass":reliability["first_review_pass"],
"gate_failures":reliability["gate_failures"]});
put(
&mut row,
"first_review_pass_rate",
reliability["first_review_pass_rate"].as_f64(),
);
if !report["usage_total"]["cost_usd"].is_null() {
row["cost_usd"] = report["usage_total"]["cost_usd"].clone();
}
combined["runs"] = json!(runs.len() + 1);
for key in [
"tasks",
"agent_attempts",
"tasks_reviewed",
"first_review_pass",
"gate_failures",
"cost_usd",
] {
add(&mut combined, key, &row[key]);
}
for model in array_or_empty(&reliability["by_model"]) {
let item = models.entry(model["model"].to_string()).or_insert_with(|| {
json!({"model":model["model"],"runs":0,"attempts":0,
"tasks_first_built":0,"tasks_reviewed":0,"first_review_pass":0})
});
add(item, "runs", &json!(1));
for key in [
"attempts",
"cost_usd",
"tasks_first_built",
"tasks_reviewed",
"first_review_pass",
] {
add(item, key, &model[key]);
}
}
runs.push(row);
}
let pass_rate = |row: &mut Value| {
let (passed, reviewed) = (
row["first_review_pass"].as_u64().unwrap_or_default(),
row["tasks_reviewed"].as_u64().unwrap_or_default(),
);
put(
row,
"first_review_pass_rate",
rate(passed as usize, reviewed as usize),
);
};
pass_rate(&mut combined);
let by_model: Vec<Value> = models
.into_values()
.map(|mut item| {
pass_rate(&mut item);
item
})
.collect();
if machine {
println!(
"{}",
serde_json::to_string_pretty(
&json!({"runs":runs,"combined":combined,"by_model":by_model})
)?
);
return Ok(());
}
println!("[METRICS] all runs");
let line = |label: String, row: &Value| {
let cost = cost_suffix(&row["cost_usd"]);
println!(
"- {label} ยท {} tasks ยท {} agent attempts ยท first-review pass {}/{} ({}) ยท gate failures {}{cost}",
row["tasks"],
row["agent_attempts"],
row["first_review_pass"],
row["tasks_reviewed"],
percent(&row["first_review_pass_rate"]),
row["gate_failures"]
);
};
for row in &runs {
line(
format!(
"Run {} ({})",
string_or_empty(&row["run_id"]),
string_or_empty(&row["state"])
),
row,
);
}
line(format!("Combined ยท {} runs", combined["runs"]), &combined);
for row in &by_model {
let model = row["model"].as_str().unwrap_or("unknown model");
let cost = cost_suffix(&row["cost_usd"]);
println!(
"- Model {model} ยท {} runs ยท {} attempts{cost} ยท first-review pass {}/{} ({})",
row["runs"],
row["attempts"],
row["first_review_pass"],
row["tasks_reviewed"],
percent(&row["first_review_pass_rate"])
);
}
Ok(())
}
fn rate(part: usize, whole: usize) -> Option<f64> {
(whole > 0).then(|| part as f64 / whole as f64)
}
fn put(object: &mut Value, key: &str, value: Option<f64>) {
if let Some(value) = value {
object[key] = json!(value);
}
}
fn first_per_task(rows: Vec<Value>, field: &str) -> BTreeMap<String, (Value, usize)> {
let mut tasks = BTreeMap::<String, (Value, usize)>::new();
for row in rows {
tasks
.entry(string_or_empty(&row["task_id"]).to_owned())
.or_insert_with(|| (row[field].clone(), 0))
.1 += 1;
}
tasks
}
pub fn reliability(store: &Store, run: &str) -> Result<Value> {
let reviews = first_per_task(
store.rows(
"SELECT task_id, state FROM attempts WHERE run_id=? AND role='review'
AND task_id IS NOT NULL AND state IN ('pass','changes_requested') ORDER BY rowid",
&[&run],
)?,
"state",
);
let passed_first = |task: &str| reviews.get(task).is_some_and(|(state, _)| state == "pass");
let tasks_reviewed = reviews.len();
let first_review_pass = reviews.keys().filter(|task| passed_first(task)).count();
let mut report = json!({"tasks_reviewed":tasks_reviewed,"first_review_pass":first_review_pass});
put(
&mut report,
"first_review_pass_rate",
rate(first_review_pass, tasks_reviewed),
);
if let Some(max) = reviews.values().map(|(_, rounds)| *rounds).max() {
let total: usize = reviews.values().map(|(_, rounds)| rounds).sum();
report["review_rounds"] = json!({"mean":total as f64 / tasks_reviewed as f64,"max":max});
}
let builds = store.rows(
"SELECT a.task_id, u.model FROM attempts a LEFT JOIN attempt_usage u ON u.attempt_id=a.id
WHERE a.run_id=? AND a.role='build' AND a.task_id IS NOT NULL ORDER BY a.rowid",
&[&run],
)?;
let build_attempts = builds.len();
let first_builds = first_per_task(builds, "model");
let integrated: i64 = store.0.query_row(
"SELECT COUNT(*) FROM integrated_tasks WHERE run_id=?",
[run],
|row| row.get(0),
)?;
let integrated = usize::try_from(integrated)?;
report["build_attempts"] = json!(build_attempts);
report["integrated_tasks"] = json!(integrated);
put(
&mut report,
"build_attempts_per_integrated_task",
rate(build_attempts, integrated),
);
let failures = store
.one(
"SELECT COALESCE(SUM(gate_failures),0) AS gate_failures,
COALESCE(SUM(review_failures),0) AS review_failures FROM tasks WHERE run_id=?",
&[&run],
)?
.unwrap_or_default();
report["gate_failures"] = failures["gate_failures"].clone();
report["review_failures"] = failures["review_failures"].clone();
let mut by_state = BTreeMap::<String, usize>::new();
let mut by_severity = BTreeMap::<String, usize>::new();
let findings = store.rows(
"SELECT state, detail FROM review_findings WHERE run_id=?",
&[&run],
)?;
for finding in &findings {
*by_state
.entry(string_or_empty(&finding["state"]).to_owned())
.or_default() += 1;
let severity = context::severity(&parse(&finding["detail"])?);
*by_severity
.entry(json!(severity).as_str().unwrap_or_default().to_owned())
.or_default() += 1;
}
report["findings"] =
json!({"total":findings.len(),"by_state":by_state,"by_severity":by_severity});
let mut by_model = Vec::new();
for row in store.rows(
"SELECT u.model, COUNT(*) AS attempts, SUM(u.cost_usd) AS cost_usd
FROM attempts a JOIN attempt_usage u ON u.attempt_id=a.id
WHERE a.run_id=? GROUP BY u.model ORDER BY u.model",
&[&run],
)? {
let built: Vec<_> = first_builds
.iter()
.filter(|(_, (model, _))| *model == row["model"])
.map(|(task, _)| task.as_str())
.collect();
let reviewed = built
.iter()
.filter(|task| reviews.contains_key(**task))
.count();
let passed = built.iter().filter(|task| passed_first(task)).count();
let mut item = json!({"model":row["model"],"attempts":row["attempts"],
"tasks_first_built":built.len(),"tasks_reviewed":reviewed,"first_review_pass":passed});
if !row["cost_usd"].is_null() {
item["cost_usd"] = row["cost_usd"].clone();
}
put(&mut item, "first_review_pass_rate", rate(passed, reviewed));
by_model.push(item);
}
report["by_model"] = json!(by_model);
Ok(report)
}
fn percent(value: &Value) -> String {
value
.as_f64()
.map_or_else(|| "n/a".into(), |rate| format!("{:.0}%", rate * 100.0))
}
fn cost_suffix(value: &Value) -> String {
value
.as_f64()
.map_or_else(String::new, |cost| format!(" ยท {}", usage::dollars(cost)))
}
fn counts(value: &Value) -> String {
let parts: Vec<_> = value
.as_object()
.map(Map::iter)
.into_iter()
.flatten()
.map(|(key, count)| format!("{key} {count}"))
.collect();
if parts.is_empty() {
"none".into()
} else {
parts.join(", ")
}
}
fn print_reliability(report: &Value) {
println!("[RELIABILITY]");
println!(
"- First-review pass ยท {}/{} tasks ({})",
report["first_review_pass"],
report["tasks_reviewed"],
percent(&report["first_review_pass_rate"])
);
if let Some(rounds) = report.get("review_rounds") {
println!(
"- Review rounds ยท mean {:.2}, max {}",
rounds["mean"].as_f64().unwrap_or_default(),
rounds["max"]
);
}
let per_task = report["build_attempts_per_integrated_task"]
.as_f64()
.map_or_else(|| "n/a".into(), |value| format!("{value:.2}"));
println!(
"- Build attempts ยท {} for {} integrated tasks ({per_task} per task)",
report["build_attempts"], report["integrated_tasks"]
);
println!(
"- Failures ยท gate {}, review {}",
report["gate_failures"], report["review_failures"]
);
let findings = &report["findings"];
println!(
"- Findings ยท {} ยท by state: {} ยท by severity: {}",
findings["total"],
counts(&findings["by_state"]),
counts(&findings["by_severity"])
);
for row in report["by_model"].as_array().into_iter().flatten() {
let model = row["model"].as_str().unwrap_or("unknown model");
let cost = cost_suffix(&row["cost_usd"]);
println!(
"- Model {model} ยท {} attempts{cost} ยท first-review pass {}/{} ({})",
row["attempts"],
row["first_review_pass"],
row["tasks_reviewed"],
percent(&row["first_review_pass_rate"])
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::contract::STATE_SQL;
use rusqlite::Connection;
fn store() -> Result<Store> {
let db = Connection::open_in_memory()?;
db.execute_batch(STATE_SQL)?;
Ok(Store(db))
}
#[test]
fn a_run_without_reviews_omits_the_pass_rate() -> Result<()> {
let store = store()?;
store.0.execute_batch(
"INSERT INTO tasks (run_id,id,gate_failures) VALUES ('r','a',1);
INSERT INTO attempts VALUES ('b1','r','a','build','done','{}',NULL);
INSERT INTO attempts VALUES ('v1','r','a','review','active','{}',NULL);
INSERT INTO attempt_usage (attempt_id,cost_usd,model) VALUES ('b1',0.25,'m');",
)?;
let report = reliability(&store, "r")?;
assert_eq!(report["tasks_reviewed"], 0);
assert_eq!(report["first_review_pass"], 0);
for key in [
"first_review_pass_rate",
"review_rounds",
"build_attempts_per_integrated_task",
] {
assert!(report.get(key).is_none(), "{key} has no denominator");
}
assert_eq!(report["gate_failures"], 1);
assert_eq!(report["findings"]["total"], 0);
let model = &report["by_model"][0];
assert_eq!(
*model,
json!({"model":"m","attempts":1,"cost_usd":0.25,"tasks_first_built":1,
"tasks_reviewed":0,"first_review_pass":0})
);
Ok(())
}
#[test]
fn reviews_without_a_verdict_are_not_counted() -> Result<()> {
let store = store()?;
store.0.execute_batch(
"INSERT INTO tasks (run_id,id) VALUES ('r','a');
INSERT INTO attempts VALUES ('b1','r','a','build','done','{}',NULL);
INSERT INTO attempts VALUES ('v1','r','a','review','interrupted','{}',NULL);
INSERT INTO attempts VALUES ('v2','r','a','review','superseded','{}',NULL);
INSERT INTO attempts VALUES ('v3','r','a','review','blocked','{}',NULL);
INSERT INTO attempts VALUES ('v4','r','a','review','error','{}',NULL);
INSERT INTO attempts VALUES ('v5','r','a','review','pass','{}',NULL);",
)?;
let report = reliability(&store, "r")?;
assert_eq!(report["tasks_reviewed"], 1);
assert_eq!(report["first_review_pass"], 1);
assert_eq!(report["first_review_pass_rate"], 1.0);
assert_eq!(report["review_rounds"], json!({"mean":1.0,"max":1}));
Ok(())
}
#[test]
fn cost_suffix_matches_the_usage_format() {
assert_eq!(cost_suffix(&json!(0.5)), " ยท $0.5000");
assert_eq!(cost_suffix(&Value::Null), "");
assert_eq!(
usage::describe(&json!({"cost_usd":0.5})).as_deref(),
Some("$0.5000")
);
}
#[test]
fn first_review_verdict_and_finding_severity_are_counted() -> Result<()> {
let store = store()?;
store.0.execute_batch(
"INSERT INTO tasks (run_id,id,review_failures) VALUES ('r','a',1),('r','b',0);
INSERT INTO attempts VALUES ('b1','r','a','build','done','{}',NULL);
INSERT INTO attempts VALUES ('v1','r','a','review','changes_requested','{}',NULL);
INSERT INTO attempts VALUES ('b2','r','a','build','done','{}',NULL);
INSERT INTO attempts VALUES ('v2','r','a','review','pass','{}',NULL);
INSERT INTO attempts VALUES ('b3','r','b','build','done','{}',NULL);
INSERT INTO attempts VALUES ('v3','r','b','review','pass','{\"status\":\"changes_requested\"}',NULL);
INSERT INTO integrated_tasks VALUES ('r','a','x'),('r','b','y');
INSERT INTO review_findings VALUES ('r','a','F-01','resolved','{}','v1','x',1,NULL);
INSERT INTO review_findings VALUES ('r','a','F-02','advisory','{\"severity\":\"low\"}','v1','x',1,NULL);",
)?;
let report = reliability(&store, "r")?;
assert_eq!(report["tasks_reviewed"], 2);
assert_eq!(report["first_review_pass"], 1);
assert_eq!(report["first_review_pass_rate"], 0.5);
assert_eq!(report["review_rounds"], json!({"mean":1.5,"max":2}));
assert_eq!(report["build_attempts_per_integrated_task"], 1.5);
assert_eq!(report["review_failures"], 1);
assert_eq!(
report["findings"],
json!({"total":2,"by_state":{"advisory":1,"resolved":1},
"by_severity":{"high":1,"low":1}})
);
Ok(())
}
}