use crate::{adapter::Action, process::Repo};
use anyhow::{Context, Result};
use std::{
collections::BTreeMap,
fs, io,
path::{Path, PathBuf},
sync::Mutex,
};
const GUARDED: &[&str] = &["config", "config.worktree", "hooks", "info/attributes"];
const OWN_BRANCHES: &[&str] = &["refs/heads/af/", "refs/heads/af-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,
})
}
pub fn check(&self, repo: &Repo) -> Result<()> {
let current = files(&self.common)?;
let changed = changes(&self.files, ¤t);
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, ¤t) {
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)
}
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();
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(())
}
#[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/agent-flow"),
worktrees: temp.path().join("worktrees"),
};
let baseline = Baseline::capture(&repo)?;
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/agent-flow"),
worktrees: temp.path().join("worktrees"),
};
let baseline = Baseline::capture(&repo)?;
baseline.check(&repo)?;
git(&root, &["commit", "-q", "--allow-empty", "-m", "user work"]);
git(&root, &["branch", "af/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(())
}
}