agengo 0.5.3

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
//! `agengo agent check [NAME]`: ask the agent to do, in a scratch repository
//! and through the same path a run uses, the three things a run needs, and
//! say which of them it did not do. Finding the agent on `PATH` and logged in
//! does not show that it can reply in the agreed format, write files or run
//! commands without asking, so this does one cheap real attempt.

use crate::{adapter, config, contract, process::run};
use anyhow::{bail, Context, Result};
use serde_json::{json, Value};
use std::{
    fs,
    path::Path,
    process::Command,
    time::{SystemTime, UNIX_EPOCH},
};

const FILE: &str = "agengo-check.txt";
/// Where the last results are kept, in the repository's data folder.
const RESULTS: &str = "agent-check.json";

/// What one attempt showed.
#[derive(Debug, PartialEq, Eq)]
pub struct Findings {
    pub replied: bool,
    pub wrote_file: bool,
    pub ran_command: bool,
}

impl Findings {
    pub fn passed(&self) -> bool {
        self.replied && self.wrote_file && self.ran_command
    }
}

/// Judge the agent's reply and the scratch worktree after the attempt.
fn judge(reply: &Value, worktree: &Path) -> Findings {
    let replied = matches!(reply["status"].as_str(), Some("ready" | "done"));
    let content = fs::read_to_string(worktree.join(FILE)).unwrap_or_default();
    let mut lines = content.lines();
    let wrote_file = lines.next().is_some_and(|line| line.trim() == "ok");
    let ran_command = lines
        .next()
        .is_some_and(|line| line.trim().starts_with("git version"));
    Findings {
        replied,
        wrote_file,
        ran_command,
    }
}

fn git(dir: &Path, args: &[&str]) -> Result<String> {
    let output = run(
        Command::new("git")
            .current_dir(dir)
            .args([
                "-c",
                "user.name=agengo",
                "-c",
                "user.email=agengo@example.invalid",
            ])
            .args(args),
        None,
        Some(30),
    )?;
    if !output.status.success() {
        bail!(
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
}

fn request(head: &str, worktree: &Path) -> Value {
    json!({
        "schema_version": 1,
        "role": "build",
        "builder_handoff": "worktree",
        "message_id": "check-1",
        "attempt_id": "check-1",
        "run_id": "check",
        "plan_revision": 1,
        "worktree": worktree.to_string_lossy(),
        "head": head,
        "task": {
            "id": "check",
            "goal": format!(
                "Create the file {FILE} with exactly two lines. Line 1: the word ok. Line 2: the output of running `git --version` in a shell (run the command, do not guess it)."
            ),
            "owns": [FILE],
            "acceptance": [format!("{FILE} exists; its first line is ok and its second line starts with `git version`")],
            "verify": []
        },
        "relationships": {"depends_on": [], "required_by": [], "related_to": [], "conflicts_with": []}
    })
}

/// What to do about each thing that went wrong.
fn advice(findings: &Findings, name: &str) -> Vec<String> {
    let mut out = Vec::new();
    if !findings.replied {
        out.push(format!("[fail] {name} did not end with a reply agengo can read (a JSON object with status ready or done); see its output above"));
    }
    if !findings.wrote_file {
        out.push(format!("[fail] {name} did not write `{FILE}` in the worktree; it may be denied file edits when run without a terminal. For agy, allow edits in its settings.json `permissions.allow`; for Codex check `--sandbox workspace-write` works here"));
    }
    if !findings.ran_command {
        out.push(format!("[fail] {name} did not run `git --version`; it may be denied shell commands without a terminal. For agy, add `command(*)` (or a narrower `command(git *)`) to `permissions.allow` in its settings.json"));
    }
    out
}

pub fn run_check(repo_root: &Path, data: &Path, name: Option<&str>) -> Result<bool> {
    let agent = adapter::select(name, repo_root)?;
    let label = crate::driver::stored_name(agent.as_deref());
    if crate::driver::is_experimental(&label) {
        println!("agengo: note: {label} is experimental; its flags come from documentation only");
    }
    let scratch = tempfile::tempdir().context("could not create a scratch folder")?;
    let repo = scratch.path().join("repo");
    fs::create_dir_all(&repo)?;
    git(&repo, &["init", "-q"])?;
    fs::write(
        repo.join("README.md"),
        "scratch repository for agengo agent check\n",
    )?;
    git(&repo, &["add", "-A"])?;
    git(&repo, &["commit", "-q", "-m", "Initial commit"])?;
    let head = git(&repo, &["rev-parse", "HEAD"])?;

    let config = config::load(repo_root)?;
    let profile = contract::profile(None)?;
    println!("[AGENT CHECK] {label}: asking it to write a file and run a command in a scratch repository");
    let invocation = adapter::invoke_measured(
        agent.as_deref(),
        adapter::Auth::Subscription,
        &request(&head, &repo),
        &repo,
        300,
        &profile,
        &config,
    );
    let (findings, error) = match &invocation.reply {
        Ok(reply) => (judge(reply, &repo), None),
        Err(error) => (judge(&Value::Null, &repo), Some(format!("{error:#}"))),
    };
    if let Some(error) = &error {
        println!("- [fail] {label} could not complete the request: {error}");
    }
    let report = |ok: bool, text: &str| {
        if ok {
            println!("- [ok] {text}");
        }
    };
    report(findings.replied, "replies in the format agengo reads");
    report(findings.wrote_file, "writes a file in the worktree");
    report(
        findings.ran_command,
        "runs a shell command (`git --version`)",
    );
    if error.is_none() {
        for line in advice(&findings, &label) {
            println!("- {line}");
        }
    }
    let passed = findings.passed();
    record(data, &label, passed);
    println!(
        "- {}",
        if passed {
            format!("{label} is ready for runs on this machine.")
        } else {
            format!("{label} is not ready: fix the failed lines above, then run `agengo agent check {label}` again.")
        }
    );
    Ok(passed)
}

fn record(data: &Path, name: &str, passed: bool) {
    let path = data.join(RESULTS);
    let mut all: Value = fs::read_to_string(&path)
        .ok()
        .and_then(|text| serde_json::from_str(&text).ok())
        .unwrap_or_else(|| json!({}));
    let at = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    all[name] = json!({"passed": passed, "at": at});
    let _ = fs::create_dir_all(data);
    let _ = fs::write(path, all.to_string());
}

/// Whether `agengo agent check` last passed for this agent here.
pub fn has_passed(data: &Path, name: &str) -> bool {
    fs::read_to_string(data.join(RESULTS))
        .ok()
        .and_then(|text| serde_json::from_str::<Value>(&text).ok())
        .is_some_and(|all| all[name]["passed"] == true)
}

/// Before a run: an experimental agent that has not passed
/// `agengo agent check` here gets a warning, because its flags have only
/// been read from documentation.
pub fn warn_if_unchecked(data: &Path, agent: Option<&str>) {
    let name = crate::driver::stored_name(agent);
    if crate::driver::is_experimental(&name) && !has_passed(data, &name) {
        eprintln!("agengo: warning: {name} is experimental and has not passed `agengo agent check {name}` here; run it first to find out cheaply whether {name} can reply, write files and run commands");
    }
}

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

    #[test]
    fn judges_the_reply_and_the_files() {
        let dir = tempfile::tempdir().unwrap();
        let ready = json!({"status": "ready"});
        let none = judge(&ready, dir.path());
        assert_eq!(
            none,
            Findings {
                replied: true,
                wrote_file: false,
                ran_command: false
            }
        );
        fs::write(dir.path().join(FILE), "ok\n").unwrap();
        let wrote = judge(&ready, dir.path());
        assert!(wrote.wrote_file && !wrote.ran_command);
        fs::write(dir.path().join(FILE), "ok\ngit version 2.43.0\n").unwrap();
        let all = judge(&ready, dir.path());
        assert!(all.passed());
        assert!(!judge(&json!({"status": "blocked"}), dir.path()).passed());
        assert!(!judge(&Value::Null, dir.path()).replied);
        // A guessed first line without the command output is not a pass.
        fs::write(dir.path().join(FILE), "ok\ngit version\n").unwrap();
        assert!(judge(&ready, dir.path()).passed());
        fs::write(dir.path().join(FILE), "ok\nI could not run it\n").unwrap();
        assert!(!judge(&ready, dir.path()).passed());
    }

    #[test]
    fn advice_names_what_to_change() {
        let nothing = Findings {
            replied: false,
            wrote_file: false,
            ran_command: false,
        };
        let lines = advice(&nothing, "agy");
        assert_eq!(lines.len(), 3);
        assert!(lines.iter().any(|l| l.contains("command(*)")));
        assert!(advice(
            &Findings {
                replied: true,
                wrote_file: true,
                ran_command: true
            },
            "x"
        )
        .is_empty());
    }

    #[test]
    fn results_are_remembered_per_agent() {
        let dir = tempfile::tempdir().unwrap();
        assert!(!has_passed(dir.path(), "agy"));
        record(dir.path(), "agy", true);
        record(dir.path(), "codex", false);
        assert!(has_passed(dir.path(), "agy"));
        assert!(!has_passed(dir.path(), "codex"));
    }
}