agengo 0.5.4

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
//! Detects changes to repository files that Git executes or obeys.
//!
//! Agent worktrees share hooks, configuration and refs with the user's
//! repository. agengo's own Git commands ignore hooks (see
//! `process::git_command`), but a hook or configuration planted by an agent
//! would still run in the user's later Git commands. A run therefore records
//! these files when it starts and stops for a person when they change.

use crate::{adapter::Action, process::Repo};
use anyhow::{Context, Result};
use std::{
    collections::BTreeMap,
    fs, io,
    path::{Path, PathBuf},
    sync::Mutex,
};

/// Paths below the Git common directory that can make Git run commands.
const GUARDED: &[&str] = &["config", "config.worktree", "hooks", "info/attributes"];

/// Branch prefixes that agengo itself creates and moves.
const OWN_BRANCHES: &[&str] = &["refs/heads/agengo/", "refs/heads/agengo-work/"];

pub struct Baseline {
    common: PathBuf,
    files: BTreeMap<String, Vec<u8>>,
    refs: Mutex<BTreeMap<String, String>>,
}

impl Baseline {
    pub fn capture(repo: &Repo) -> Result<Self> {
        let common = repo
            .data
            .parent()
            .context("repository data directory has no parent")?
            .to_owned();
        Ok(Self {
            files: files(&common)?,
            refs: Mutex::new(refs(repo)?),
            common,
        })
    }

    /// Fail with a request for a person when hooks or configuration changed.
    /// Branch and tag moves only warn: people keep working in the
    /// repository while a run is in progress.
    pub fn check(&self, repo: &Repo) -> Result<()> {
        let current = files(&self.common)?;
        let changed = changes(&self.files, &current);
        if !changed.is_empty() {
            return Err(Action {
                message: format!(
                    "Git hooks or configuration changed while agents were running: {}",
                    changed
                        .iter()
                        .map(|name| self.common.join(name).display().to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
                recommendation: "Inspect these files and remove anything you did not add yourself, then resume the run.".into(),
                reason: "Git runs hooks and obeys repository configuration in every worktree, so a change made by an agent could run code outside agengo's checks.".into(),
            }
            .into());
        }
        let current = refs(repo)?;
        let mut known = self
            .refs
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        for name in changes(&known, &current) {
            eprintln!(
                "agengo: warning: {name} changed while agents were running ({} -> {}). If you did not do this, check `git reflog {name}`.",
                known.get(&name).map_or("missing", String::as_str),
                current.get(&name).map_or("deleted", String::as_str),
            );
        }
        *known = current;
        Ok(())
    }
}

fn changes<T: PartialEq>(before: &BTreeMap<String, T>, after: &BTreeMap<String, T>) -> Vec<String> {
    let mut names: Vec<_> = before
        .iter()
        .filter(|(name, value)| after.get(*name) != Some(*value))
        .map(|(name, _)| name.clone())
        .collect();
    names.extend(
        after
            .keys()
            .filter(|name| !before.contains_key(*name))
            .cloned(),
    );
    names.sort();
    names
}

fn files(common: &Path) -> Result<BTreeMap<String, Vec<u8>>> {
    let mut found = BTreeMap::new();
    for name in GUARDED {
        record(common, Path::new(name), &mut found)?;
    }
    Ok(found)
}

/// Record a file's mode and contents (or a symlink's target), recursing
/// into directories. Missing paths, and empty files outside `hooks`, are
/// recorded as absent.
fn record(common: &Path, name: &Path, found: &mut BTreeMap<String, Vec<u8>>) -> Result<()> {
    let path = common.join(name);
    let info = match fs::symlink_metadata(&path) {
        Ok(info) => info,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(error) => return Err(error).with_context(|| format!("cannot read {}", path.display())),
    };
    let key = name.to_string_lossy().into_owned();
    // An empty configuration file changes nothing Git does, and a sandbox may
    // create one while masking the path (bubblewrap binds /dev/null over it).
    // Hooks are different: the file's presence and mode matter there.
    if info.is_file() && info.len() == 0 && !name.starts_with("hooks") {
        return Ok(());
    }
    if info.is_dir() {
        let mut entries = fs::read_dir(&path)?
            .map(|entry| entry.map(|entry| entry.file_name()))
            .collect::<io::Result<Vec<_>>>()?;
        entries.sort();
        found.insert(key, b"directory".to_vec());
        for entry in entries {
            record(common, &name.join(entry), found)?;
        }
        return Ok(());
    }
    let mut value = format!("{}\n", mode(&info)).into_bytes();
    if info.file_type().is_symlink() {
        value.extend_from_slice(fs::read_link(&path)?.to_string_lossy().as_bytes());
    } else {
        value.extend(fs::read(&path).with_context(|| format!("cannot read {}", path.display()))?);
    }
    found.insert(key, value);
    Ok(())
}

/// The permission bits Git cares about. Windows has only the read-only flag;
/// Git for Windows runs hooks through its own shell whatever their mode.
#[cfg(unix)]
fn mode(info: &fs::Metadata) -> String {
    use std::os::unix::fs::PermissionsExt;
    format!("{:o}", info.permissions().mode())
}

#[cfg(not(unix))]
fn mode(info: &fs::Metadata) -> String {
    if info.permissions().readonly() {
        "readonly".into()
    } else {
        "writable".into()
    }
}

fn refs(repo: &Repo) -> Result<BTreeMap<String, String>> {
    Ok(repo
        .git(&[
            "for-each-ref",
            "--format=%(refname) %(objectname)",
            "refs/heads",
            "refs/tags",
        ])?
        .lines()
        .filter_map(|line| line.split_once(' '))
        .filter(|(name, _)| !OWN_BRANCHES.iter().any(|prefix| name.starts_with(prefix)))
        .map(|(name, sha)| (name.to_owned(), sha.to_owned()))
        .collect())
}

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

    fn git(dir: &Path, args: &[&str]) {
        let status = Command::new("git")
            .current_dir(dir)
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .args(["-c", "user.name=t", "-c", "user.email=t@example.invalid"])
            .args(args)
            .status()
            .unwrap();
        assert!(status.success(), "git {args:?}");
    }

    #[test]
    fn an_empty_configuration_file_is_not_a_change() -> Result<()> {
        let temp = tempfile::tempdir()?;
        let root = temp.path().join("repo");
        fs::create_dir(&root)?;
        git(&root, &["init", "-q", "-b", "main"]);
        git(&root, &["commit", "-q", "--allow-empty", "-m", "base"]);
        let repo = Repo {
            root: root.clone(),
            data: root.join(".git/agengo"),
            worktrees: temp.path().join("worktrees"),
        };
        let baseline = Baseline::capture(&repo)?;
        // A sandbox masking the path leaves an empty file behind.
        fs::write(root.join(".git/config.worktree"), "")?;
        baseline.check(&repo)?;
        fs::write(
            root.join(".git/config.worktree"),
            "[core]\n\tfsmonitor = x\n",
        )?;
        assert!(baseline.check(&repo).is_err());
        Ok(())
    }

    #[test]
    fn detects_hooks_and_configuration_but_only_warns_on_branches() -> Result<()> {
        let temp = tempfile::tempdir()?;
        let root = temp.path().join("repo");
        fs::create_dir(&root)?;
        git(&root, &["init", "-q", "-b", "main"]);
        git(&root, &["commit", "-q", "--allow-empty", "-m", "base"]);
        let repo = Repo {
            root: root.clone(),
            data: root.join(".git/agengo"),
            worktrees: temp.path().join("worktrees"),
        };
        let baseline = Baseline::capture(&repo)?;
        baseline.check(&repo)?;

        // Branch moves and agengo's own branches never block.
        git(&root, &["commit", "-q", "--allow-empty", "-m", "user work"]);
        git(&root, &["branch", "agengo/demo"]);
        baseline.check(&repo)?;

        let hook = root.join(".git/hooks/post-checkout");
        fs::write(&hook, "#!/bin/sh\n")?;
        let error = baseline.check(&repo).unwrap_err();
        assert!(error.is::<Action>());
        assert!(error.to_string().contains("post-checkout"));
        fs::remove_file(&hook)?;
        baseline.check(&repo)?;

        git(&root, &["config", "core.fsmonitor", "touch /tmp/never"]);
        let error = baseline.check(&repo).unwrap_err();
        assert!(error.to_string().contains("config"));
        Ok(())
    }
}