agengo 0.5.0

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

/// Namespace for pinned build candidates: `<BUILD_REFS>/<run>/<attempt>`.
pub const BUILD_REFS: &str = "refs/agengo/builds";
/// Namespace used for build candidates by agengo 0.3.x and earlier.
const LEGACY_BUILD_REFS: &str = "refs/agent-flow/builds";

pub fn reference(request: &Assignment) -> String {
    format!("{BUILD_REFS}/{}/{}", request.run_id, request.attempt_id)
}

/// Move build candidates pinned by older versions to `BUILD_REFS`, so that
/// runs started before the rename can still be resumed and cleaned.
/// Returns how many refs were moved.
pub fn migrate_legacy_refs(repo: &Repo) -> Result<usize> {
    let legacy = repo.git(&[
        "for-each-ref",
        "--format=%(refname) %(objectname)",
        &format!("{LEGACY_BUILD_REFS}/"),
    ])?;
    let mut moved = 0;
    for (name, sha) in legacy.lines().filter_map(|line| line.split_once(' ')) {
        let Some(suffix) = name.strip_prefix(LEGACY_BUILD_REFS) else {
            continue;
        };
        let target = format!("{BUILD_REFS}{suffix}");
        match repo.current(&target)? {
            None => repo.set_ref(&target, sha, None)?,
            Some(current) if current == sha => {}
            Some(current) => {
                bail!("cannot move {name} to {target}: {target} already points to {current}")
            }
        }
        // Delete only if the legacy ref still points where it did.
        repo.git(&["update-ref", "-d", name, sha])?;
        moved += 1;
    }
    Ok(moved)
}

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: &Assignment, path: &Path) -> Result<()> {
    if let Some(parent) = request.merge_parent.as_deref() {
        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: &[String]) -> 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: &Assignment,
    output: &Outcome,
    setup_artifacts: &BTreeSet<String>,
) -> Result<Value> {
    let path = request.worktree.as_path();
    let start = request.head.as_str();
    if repo.git_at(&["branch", "--show-current"], path)?.trim()
        != request.branch.as_deref().unwrap_or_default()
        || repo.sha_at("HEAD", path)? != start
    {
        bail!("builder changed its assigned branch or HEAD during worktree handoff");
    }
    if output.head.as_deref().is_some_and(|head| head != start) {
        bail!("builder reported a head different from its assigned starting commit");
    }
    let parent = request.merge_parent.as_deref().unwrap_or_default();
    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(
                git_command()
                    .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();
    for excluded in leftovers(repo, path, setup_artifacts, &request.task.owns)? {
        exclusions.push_str(":(top,exclude,literal)");
        exclusions.push_str(&excluded);
        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: BTreeSet<_> = output.resolved_conflicts.iter().collect();
        if resolved != conflicts.iter().collect() {
            bail!(
                "builder must confirm resolution of each merge conflict: {}",
                conflicts.iter().cloned().collect::<Vec<_>>().join(", ")
            );
        }
    }
    let base = request.integration_sha.as_str();
    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}))
}

/// Untracked paths in the worktree at `path` that are not task output: setup
/// artifacts, and well-known build artifacts (see [`artifact_root`]) unless
/// an `owns` entry names the artifact itself or a path inside it (owning
/// `pkg` does not claim `pkg/__pycache__`). Files tracked by the prepared
/// merge are never listed. An artifact directory is listed whole when it
/// holds no tracked or owned files, which keeps the pathspec short for trees
/// like `node_modules`.
fn leftovers(
    repo: &Repo,
    path: &Path,
    setup_artifacts: &BTreeSet<String>,
    owns_paths: &[String],
) -> Result<BTreeSet<String>> {
    let mut excluded = BTreeSet::new();
    let mut roots = BTreeMap::<String, Vec<String>>::new();
    for name in repo.untracked(path, true)? {
        if setup_artifacts.contains(&name) {
            excluded.insert(name);
        } else if let Some(root) = artifact_root(&name) {
            roots.entry(root.to_owned()).or_default().push(name);
        }
    }
    for (root, names) in roots {
        let named: Vec<_> = owns_paths
            .iter()
            .filter(|scope| owns(scope, &[&root]))
            .collect();
        let names: Vec<_> = names
            .into_iter()
            .filter(|name| !owns(name, &named))
            .collect();
        let whole = names.len() > 1
            && named.is_empty()
            && repo
                .git_at(
                    &["ls-files", "-z", "--", &format!(":(top,literal){root}")],
                    path,
                )?
                .is_empty();
        if whole {
            excluded.insert(root);
        } else {
            excluded.extend(names);
        }
    }
    Ok(excluded)
}

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: &Assignment, 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 {}/{}", request.run_id, 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)
}