agengo 0.5.1

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
//! Adversarial verification of review findings (`quality.verify_findings`).
//!
//! When a Reviewer requests changes, a verifier tries to refute each new
//! blocking finding at the reviewed commit. A finding is cleared only when the
//! verifier refutes it with a confidence of at least [`REFUTE_CONFIDENCE`]. An
//! unsure verdict, a missing verdict or a failed verifier leaves the finding
//! blocking: uncertainty never clears a finding.

use crate::{
    adapter::{invoke_measured, Auth},
    agent::{Assignment, Severity},
    config::Config,
    context,
    contract::array_or_empty,
};
use anyhow::{anyhow, bail, Result};
use serde::Deserialize;
use serde_json::{json, Value};
use std::{collections::BTreeSet, path::Path};

pub const REFUTE_CONFIDENCE: f64 = 0.8;

/// The reply's blocking findings with their position in its `findings` list,
/// or nothing when the reply does not request changes.
fn blocking(reply: &Value) -> Vec<(usize, &Value)> {
    if reply["status"] != "changes_requested" {
        return Vec::new();
    }
    array_or_empty(&reply["findings"])
        .iter()
        .enumerate()
        .filter(|(_, item)| {
            Severity::deserialize(&item["severity"])
                .unwrap_or_default()
                .is_blocking()
        })
        .collect()
}

#[derive(Deserialize)]
struct Verdict {
    finding: usize,
    refuted: bool,
    confidence: f64,
    reasoning: String,
}

#[derive(Deserialize)]
struct Verdicts {
    verdicts: Vec<Verdict>,
}

/// Check a verifier reply against the findings it was sent.
fn verdicts(reply: &Value, sent: &BTreeSet<usize>) -> Result<Value> {
    let reply =
        Verdicts::deserialize(reply).map_err(|error| anyhow!("invalid verifier reply: {error}"))?;
    let mut seen = BTreeSet::new();
    let mut result = Vec::new();
    for verdict in reply.verdicts {
        if !sent.contains(&verdict.finding) || !seen.insert(verdict.finding) {
            bail!(
                "verifier reply does not give one verdict for finding {}",
                verdict.finding
            );
        }
        if !(0.0..=1.0).contains(&verdict.confidence) {
            bail!("verifier confidence must be between 0 and 1");
        }
        result.push(json!({"finding":verdict.finding,"refuted":verdict.refuted,
            "confidence":verdict.confidence,"reasoning":verdict.reasoning}));
    }
    Ok(json!(result))
}

/// Ask the verifier about the blocking findings in a review `reply`, from the
/// worktree at the reviewed commit. Returns the verifier's usage and a report
/// holding either `verdicts` or the `error` that kept every finding blocking;
/// `None` when there is nothing to verify.
// Each argument is a separate input of the verifier call.
#[allow(clippy::too_many_arguments)]
pub fn verify(
    review: &Assignment,
    reply: &Value,
    cwd: &Path,
    agent: Option<&str>,
    auth: Auth,
    timeout: u64,
    profile: &Value,
    config: &Config,
) -> Option<(Option<Value>, Value)> {
    let findings = blocking(reply);
    if findings.is_empty() {
        return None;
    }
    let sent: BTreeSet<_> = findings.iter().map(|(index, _)| *index).collect();
    let mut request = review.to_value();
    request["role"] = json!("verify");
    request["findings"] = json!(findings
        .iter()
        .map(|(index, item)| {
            let mut item = (*item).clone();
            item["finding"] = json!(index);
            item
        })
        .collect::<Vec<_>>());
    let invocation = invoke_measured(agent, auth, &request, cwd, timeout, profile, config);
    let report = match invocation.reply.and_then(|reply| verdicts(&reply, &sent)) {
        Ok(verdicts) => json!({"verdicts": verdicts}),
        Err(error) => json!({"error": format!("{error:#}")}),
    };
    Some((invocation.usage, report))
}

/// Mark the findings a `report` refutes with enough confidence. `additions` are
/// the review's new findings in reply order, as `context::changes` returns
/// them. Returns how many blocking findings were cleared.
pub fn apply(additions: &mut [Value], report: &Value) -> usize {
    let mut cleared = 0;
    for verdict in array_or_empty(&report["verdicts"]) {
        let confidence = verdict["confidence"].as_f64().unwrap_or(0.0);
        if verdict["refuted"] != true || confidence < REFUTE_CONFIDENCE {
            continue;
        }
        let Some(finding) = verdict["finding"]
            .as_u64()
            .and_then(|index| additions.get_mut(usize::try_from(index).ok()?))
        else {
            continue;
        };
        if context::is_blocking(finding) {
            finding["refuted"] = json!({"confidence":confidence,"reasoning":verdict["reasoning"]});
            cleared += 1;
        }
    }
    cleared
}

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

    fn finding(severity: &str) -> Value {
        json!({"acceptance_id":"AC-1","severity":severity,"location":"a","evidence":"e",
            "required_outcome":"r"})
    }

    #[test]
    fn only_blocking_findings_of_a_change_request_are_sent() {
        let reply = json!({"status":"changes_requested","findings":[finding("low"),
            {"acceptance_id":"AC-1"}, finding("critical")]});
        let sent: Vec<_> = blocking(&reply).iter().map(|(index, _)| *index).collect();
        assert_eq!(sent, [1, 2]);
        let pass = json!({"status":"pass","findings":[finding("high")]});
        assert!(blocking(&pass).is_empty());
    }

    #[test]
    fn verifier_replies_must_answer_findings_that_were_sent() {
        let sent = BTreeSet::from([1, 2]);
        let verdict = |finding: usize, confidence: f64| json!({"finding":finding,"refuted":true,"confidence":confidence,"reasoning":"r"});
        assert!(verdicts(&json!({"verdicts":[verdict(1, 0.9)]}), &sent).is_ok());
        assert!(verdicts(&json!({"verdicts":[verdict(0, 0.9)]}), &sent).is_err());
        assert!(verdicts(
            &json!({"verdicts":[verdict(1, 0.9), verdict(1, 0.9)]}),
            &sent
        )
        .is_err());
        assert!(verdicts(&json!({"verdicts":[verdict(1, 1.5)]}), &sent).is_err());
        assert!(verdicts(&json!({"result":"done"}), &sent).is_err());
    }

    #[test]
    fn only_confident_refutations_clear_blocking_findings() {
        let mut additions = vec![
            finding("high"),
            finding("critical"),
            finding("medium"),
            finding("high"),
        ];
        let report = json!({"verdicts":[
            {"finding":0,"refuted":true,"confidence":0.9,"reasoning":"Handled at a.rs:3"},
            {"finding":1,"refuted":true,"confidence":0.6,"reasoning":"Probably fine"},
            {"finding":2,"refuted":true,"confidence":0.9,"reasoning":"Not blocking anyway"},
            {"finding":3,"refuted":false,"confidence":0.95,"reasoning":"Real"},
            {"finding":9,"refuted":true,"confidence":0.9,"reasoning":"Out of range"}]});
        assert_eq!(apply(&mut additions, &report), 1);
        assert_eq!(additions[0]["refuted"]["reasoning"], "Handled at a.rs:3");
        assert!(!context::is_blocking(&additions[0]));
        assert!(additions[1..].iter().all(|item| item["refuted"].is_null()));
        assert!(context::is_blocking(&additions[1]));
        assert_eq!(apply(&mut additions, &json!({"error":"crashed"})), 0);
    }
}