agengo 0.3.0

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
use crate::{
    contract::{array_or_empty, owns, string_or_empty},
    process::{checked, run, Repo},
    store::parse,
};
use anyhow::{bail, Context, Result};
use serde_json::{json, Value};
use std::{collections::BTreeSet, path::Path, process::Command};

pub fn reference(request: &Value) -> String {
    format!(
        "refs/agent-flow/builds/{}/{}",
        string_or_empty(&request["run_id"]),
        string_or_empty(&request["attempt_id"])
    )
}

fn conflicts(repo: &Repo, path: &Path) -> Result<BTreeSet<String>> {
    Ok(repo
        .git_at(&["ls-files", "--unmerged", "-z"], path)?
        .split('\0')
        .filter_map(|entry| entry.split_once('\t').map(|(_, path)| path.to_owned()))
        .collect())
}

pub fn prepare(repo: &Repo, request: &Value, path: &Path) -> Result<()> {
    if let Some(parent) = request["merge_parent"].as_str() {
        let output = repo.raw(
            &["merge", "--no-ff", "--no-commit", "--no-edit", parent],
            path,
        )?;
        if !output.status.success() {
            let unresolved = conflicts(repo, path)?;
            if unresolved.is_empty() {
                checked(output, "could not prepare the integration merge")?;
            }
            let outside: Vec<_> = unresolved
                .iter()
                .filter(|name| !owns(name, &request["task"]["owns"]))
                .cloned()
                .collect();
            if !outside.is_empty() {
                bail!("integration conflicts outside owns: {}", outside.join(", "));
            }
        }
    }
    Ok(())
}

pub fn scope(repo: &Repo, base: &str, head: &str, owns_paths: &Value) -> Result<Vec<String>> {
    let changed = repo.changed(base, head)?;
    let outside: Vec<_> = changed
        .iter()
        .filter(|name| !owns(name, owns_paths))
        .cloned()
        .collect();
    if !outside.is_empty() {
        bail!("files outside owns: {}", outside.join(", "));
    }
    Ok(changed)
}

pub fn capture(
    repo: &Repo,
    request: &Value,
    output: &Value,
    setup_artifacts: &BTreeSet<String>,
) -> Result<Value> {
    let path = Path::new(string_or_empty(&request["worktree"]));
    let start = string_or_empty(&request["head"]);
    if repo.git_at(&["branch", "--show-current"], path)?.trim()
        != string_or_empty(&request["branch"])
        || repo.sha_at("HEAD", path)? != start
    {
        bail!("builder changed its assigned branch or HEAD during worktree handoff");
    }
    if !output["head"].is_null() && output["head"] != start {
        bail!("builder reported a head different from its assigned starting commit");
    }
    let parent = string_or_empty(&request["merge_parent"]);
    let merge_head = repo.raw(&["rev-parse", "--verify", "--quiet", "MERGE_HEAD"], path)?;
    if std::str::from_utf8(&merge_head.stdout)?.trim() != parent {
        bail!("builder changed the prepared merge state");
    }
    let conflicts = conflicts(repo, path)?;
    let index = tempfile::tempdir_in(&repo.data)?;
    let git = |args: &[&str], input: Option<&[u8]>| {
        checked(
            run(
                Command::new("git")
                    .current_dir(path)
                    .env("GIT_INDEX_FILE", index.path().join("index"))
                    .args(args),
                input,
                None,
            )?,
            "capture tree",
        )
    };
    git(&["read-tree", start], None)?;
    let mut exclusions = String::new();
    if !setup_artifacts.is_empty() {
        // Keep files tracked by the prepared merge. Exclude only setup paths still untracked.
        for path in repo.untracked(path, true)?.intersection(setup_artifacts) {
            exclusions.push_str(":(top,exclude,literal)");
            exclusions.push_str(path);
            exclusions.push('\0');
        }
    }
    if exclusions.is_empty() {
        git(&["add", "--all"], None)?;
    } else {
        git(
            &[
                "add",
                "--all",
                "--pathspec-from-file=-",
                "--pathspec-file-nul",
            ],
            Some(exclusions.as_bytes()),
        )?;
    }
    let tree = git(&["write-tree"], None)?.trim().to_owned();
    if !conflicts.is_empty() {
        for name in &conflicts {
            let blob = repo.raw(&["show", &format!("{tree}:{name}")], &repo.root)?;
            if blob.status.success()
                && String::from_utf8_lossy(&blob.stdout)
                    .lines()
                    .any(conflict_marker)
            {
                bail!("unresolved merge markers in {name}");
            }
        }
        let resolved = array_or_empty(&output["resolved_conflicts"])
            .iter()
            .map(Value::as_str)
            .collect::<Option<BTreeSet<_>>>()
            .context("resolved_conflicts must be a list of paths")?;
        if resolved != conflicts.iter().map(String::as_str).collect() {
            bail!(
                "builder must confirm resolution of each merge conflict: {}",
                conflicts.iter().cloned().collect::<Vec<_>>().join(", ")
            );
        }
    }
    let base = string_or_empty(&request["integration_sha"]);
    let paths = scope(repo, base, &tree, &request["task"]["owns"])?;
    let parents = if parent.is_empty() {
        vec![start]
    } else {
        vec![start, parent]
    };
    Ok(json!({"tree":tree,"parents":parents,"review_base":base,"paths":paths}))
}

fn conflict_marker(line: &str) -> bool {
    let mark = line.chars().next().unwrap_or(' ');
    if !matches!(mark, '<' | '=' | '>' | '|') {
        return false;
    }
    let len = line.chars().take_while(|value| *value == mark).count();
    len >= 7 && (line.len() == len || (mark != '=' && line.as_bytes()[len] == b' '))
}

pub fn pin(repo: &Repo, request: &Value, record: &Value) -> Result<String> {
    let reference = reference(request);
    let parents = parse(&record["parents"])?;
    let parents: Vec<_> = array_or_empty(&parents)
        .iter()
        .map(string_or_empty)
        .collect();
    let tree = string_or_empty(&record["tree"]);
    let unchanged = parents.len() == 1
        && repo
            .git(&["rev-parse", &format!("{}^{{tree}}", parents[0])])?
            .trim()
            == tree;
    let current = repo.current(&reference)?;
    if record["candidate"]
        .as_str()
        .is_some_and(|candidate| current.as_deref() != Some(candidate))
    {
        bail!("handoff candidate ref differs from the recorded commit");
    }
    let candidate = if let Some(current) = current {
        current
    } else {
        let candidate = if unchanged {
            parents[0].to_owned()
        } else {
            let subject = format!(
                "Build {}/{}",
                string_or_empty(&request["run_id"]),
                string_or_empty(&request["task"]["id"])
            );
            let mut args = vec!["commit-tree", tree];
            for parent in &parents {
                args.extend(["-p", parent]);
            }
            args.extend(["-m", &subject]);
            repo.git(&args)?.trim().into()
        };
        repo.set_ref(&reference, &candidate, None)?;
        candidate
    };
    let info = repo.git(&["show", "-s", "--format=%T%n%P", &candidate])?;
    let mut lines = info.lines();
    let actual_tree = lines.next();
    let actual_parents = lines
        .next()
        .unwrap_or("")
        .split_whitespace()
        .collect::<Vec<_>>();
    if actual_tree != Some(tree)
        || if unchanged {
            candidate != parents[0]
        } else {
            actual_parents != parents
        }
    {
        bail!("handoff candidate does not match the captured tree and parents");
    }
    Ok(candidate)
}