agengo 0.5.1

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
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";

/// 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
}

/// Every figure `metrics RUN` reports for one run, as its JSON document.
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(())
}

/// Add a JSON number to `object[key]`, keeping integers exact.
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;
}

/// One row per run, a combined row and per-model rows across every run.
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"];
        // Build and review attempts, as the per-task rows of `metrics RUN` count them.
        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(())
}

/// `part/whole`, or `None` so a rate with no denominator is omitted.
fn rate(part: usize, whole: usize) -> Option<f64> {
    (whole > 0).then(|| part as f64 / whole as f64)
}

/// Insert `value` only when it exists, so absent rates stay out of the JSON.
fn put(object: &mut Value, key: &str, value: Option<f64>) {
    if let Some(value) = value {
        object[key] = json!(value);
    }
}

/// The first value per task in rowid order, plus how many rows each task had.
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
}

/// Review and gate outcomes of one run, read from existing tables only.
///
/// The review verdict is the attempt state `engine::complete` passes to
/// `engine::result`: `pass` or `changes_requested`. It already counts a
/// review whose blocking findings the verifier refuted as `pass`, which the
/// agent's raw `result.status` does not. Attempts without a verdict (still
/// active, interrupted, superseded, blocked or failed) are skipped, so an
/// interrupted or broken review is neither a failed first review nor a round.
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))
}

/// ` ยท $cost` for a reported cost, or nothing.
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(())
    }
}