use anyhow::{anyhow, bail, Context, Result};
use std::{
collections::BTreeSet,
ffi::OsStr,
fs,
io::{self, Read, Write},
path::{Path, PathBuf},
process::{Command, Output, Stdio},
sync::{
atomic::{AtomicBool, Ordering},
mpsc::{self, RecvTimeoutError, Sender},
},
thread,
time::{Duration, Instant},
};
pub static INTERRUPTED: AtomicBool = AtomicBool::new(false);
pub static CANCEL_ASSIGNMENTS: AtomicBool = AtomicBool::new(false);
const OUTPUT_LIMIT: usize = 16 * 1024 * 1024;
const EXIT_GRACE: Duration = Duration::from_secs(2);
pub fn git_command() -> Command {
let mut command = Command::new("git");
command.args([
"-c",
"core.hooksPath=/dev/null",
"-c",
"core.fsmonitor=false",
]);
#[cfg(windows)]
command.args(["-c", "core.longpaths=true"]);
command
}
pub fn run(command: &mut Command, input: Option<&[u8]>, timeout: Option<u64>) -> Result<Output> {
run_with_limit(command, input, timeout, OUTPUT_LIMIT)
}
#[derive(Clone, Copy)]
enum Pipe {
Stdout,
Stderr,
}
impl Pipe {
fn name(self) -> &'static str {
match self {
Self::Stdout => "stdout",
Self::Stderr => "stderr",
}
}
}
enum Event {
Data(Pipe, Vec<u8>),
Closed(Pipe, Option<io::Error>),
InputFailed(io::Error),
}
fn pump(pipe: Pipe, mut reader: impl Read + Send + 'static, events: Sender<Event>) {
thread::spawn(move || {
let mut chunk = vec![0; 16 * 1024];
loop {
match reader.read(&mut chunk) {
Ok(0) => {
let _ = events.send(Event::Closed(pipe, None));
return;
}
Ok(count) => {
if events
.send(Event::Data(pipe, chunk[..count].to_vec()))
.is_err()
{
return;
}
}
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(error) => {
let _ = events.send(Event::Closed(pipe, Some(error)));
return;
}
}
}
});
}
fn feed(mut writer: impl Write + Send + 'static, input: Vec<u8>, events: Sender<Event>) {
thread::spawn(move || {
if let Err(error) = writer.write_all(&input) {
if error.kind() != io::ErrorKind::BrokenPipe {
let _ = events.send(Event::InputFailed(error));
}
}
});
}
pub fn run_with_limit(
command: &mut Command,
input: Option<&[u8]>,
timeout: Option<u64>,
limit: usize,
) -> Result<Output> {
command
.stdin(if input.is_some() {
Stdio::piped()
} else {
Stdio::null()
})
.stdout(Stdio::piped())
.stderr(Stdio::piped());
group::prepare(command);
let program = command.get_program().to_owned();
let mut child = command
.spawn()
.with_context(|| format!("cannot launch {program:?}"))?;
let group = match group::attach(&child) {
Ok(group) => group,
Err(error) => {
let _ = child.kill();
let _ = child.wait();
return Err(error).with_context(|| format!("cannot start {program:?}"));
}
};
let (events, received) = mpsc::channel();
if let Some(stdin) = child.stdin.take() {
if let Some(input) = input.filter(|input| !input.is_empty()) {
feed(stdin, input.to_vec(), events.clone());
}
}
let mut open = 0;
if let Some(stdout) = child.stdout.take() {
pump(Pipe::Stdout, stdout, events.clone());
open += 1;
}
if let Some(stderr) = child.stderr.take() {
pump(Pipe::Stderr, stderr, events.clone());
open += 1;
}
drop(events);
let result = (|| -> Result<Output> {
let mut out = Vec::new();
let mut err = Vec::new();
let start = Instant::now();
let mut status = None;
let mut exited = None;
let mut stopped = false;
loop {
if INTERRUPTED.load(Ordering::Relaxed) {
bail!("run interrupted");
}
if CANCEL_ASSIGNMENTS.load(Ordering::Relaxed) {
bail!("assignment cancelled");
}
if timeout.is_some_and(|seconds| start.elapsed().as_secs() >= seconds) {
bail!("{program:?} exceeded the timeout");
}
if status.is_none() {
status = child.try_wait()?;
if status.is_some() {
exited = Some(Instant::now());
}
}
if let Some(status) = status {
let lingering = exited.map_or(Duration::ZERO, |time| time.elapsed());
if open == 0 || lingering >= EXIT_GRACE * 2 {
return Ok(Output {
status,
stdout: out,
stderr: err,
});
}
if lingering >= EXIT_GRACE && !stopped {
group.kill(&mut child);
stopped = true;
}
}
match received.recv_timeout(Duration::from_millis(10)) {
Ok(Event::Data(pipe, bytes)) => {
let output = match pipe {
Pipe::Stdout => &mut out,
Pipe::Stderr => &mut err,
};
if bytes.len() > limit - output.len() {
return Err(anyhow!("output exceeded the {limit}-byte limit"))
.with_context(|| format!("{program:?} {}", pipe.name()));
}
output.extend_from_slice(&bytes);
}
Ok(Event::Closed(pipe, error)) => {
open -= 1;
if let Some(error) = error {
return Err(error).with_context(|| format!("{program:?} {}", pipe.name()));
}
}
Ok(Event::InputFailed(error)) => {
return Err(error).with_context(|| format!("{program:?} stdin"));
}
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => thread::sleep(Duration::from_millis(2)),
}
}
})();
if result.is_err() {
group.kill(&mut child);
let _ = child.wait();
}
result
}
#[cfg(unix)]
mod group {
use std::{
io,
os::unix::process::CommandExt,
process::{Child, Command},
};
pub fn prepare(command: &mut Command) {
command.process_group(0);
}
pub struct Group(i32);
pub fn attach(child: &Child) -> io::Result<Group> {
Ok(Group(child.id() as i32))
}
impl Group {
pub fn kill(&self, _child: &mut Child) {
unsafe {
libc::kill(-self.0, libc::SIGKILL);
}
}
}
}
#[cfg(windows)]
mod group {
use std::{
io,
os::windows::{io::AsRawHandle, process::CommandExt},
process::{Child, Command},
ptr,
};
use windows_sys::Win32::{
Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE},
System::{
Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD,
THREADENTRY32,
},
JobObjects::{AssignProcessToJobObject, CreateJobObjectW, TerminateJobObject},
Threading::{
OpenThread, ResumeThread, CREATE_NEW_PROCESS_GROUP, CREATE_SUSPENDED,
THREAD_SUSPEND_RESUME,
},
},
};
pub fn prepare(command: &mut Command) {
command.creation_flags(CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP);
}
pub struct Group {
job: Option<HANDLE>,
}
unsafe impl Send for Group {}
pub fn attach(child: &Child) -> io::Result<Group> {
let process = child.as_raw_handle() as HANDLE;
let job = unsafe { CreateJobObjectW(ptr::null(), ptr::null()) };
let job = if job.is_null() {
None
} else if unsafe { AssignProcessToJobObject(job, process) } == 0 {
unsafe { CloseHandle(job) };
None
} else {
Some(job)
};
resume(child.id())?;
Ok(Group { job })
}
fn resume(pid: u32) -> io::Result<()> {
let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
if snapshot == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
let mut entry: THREADENTRY32 = unsafe { std::mem::zeroed() };
entry.dwSize = std::mem::size_of::<THREADENTRY32>() as u32;
let mut resumed = 0;
let mut more = unsafe { Thread32First(snapshot, &mut entry) } != 0;
while more {
if entry.th32OwnerProcessID == pid {
let thread = unsafe { OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID) };
if !thread.is_null() {
if unsafe { ResumeThread(thread) } != u32::MAX {
resumed += 1;
}
unsafe { CloseHandle(thread) };
}
}
more = unsafe { Thread32Next(snapshot, &mut entry) } != 0;
}
unsafe { CloseHandle(snapshot) };
if resumed == 0 {
return Err(io::Error::other("cannot resume the new process"));
}
Ok(())
}
impl Group {
pub fn kill(&self, child: &mut Child) {
match self.job {
Some(job) => unsafe {
TerminateJobObject(job, 1);
},
None => {
let _ = child.kill();
}
}
}
}
impl Drop for Group {
fn drop(&mut self) {
if let Some(job) = self.job {
unsafe { CloseHandle(job) };
}
}
}
}
pub fn resolve(program: &OsStr, base: &Path) -> Option<PathBuf> {
let path = Path::new(program);
if path.components().count() > 1 || path.is_absolute() {
return candidates(&base.join(path)).find(|candidate| executable(candidate));
}
std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
.flat_map(|directory| candidates(&base.join(directory).join(path)).collect::<Vec<_>>())
.find(|candidate| executable(candidate))
}
#[cfg(unix)]
fn candidates(path: &Path) -> impl Iterator<Item = PathBuf> {
std::iter::once(path.to_owned())
}
#[cfg(windows)]
fn candidates(path: &Path) -> impl Iterator<Item = PathBuf> {
let extensions = std::env::var("PATHEXT")
.ok()
.filter(|value| !value.is_empty())
.unwrap_or_else(|| ".COM;.EXE;.BAT;.CMD".into());
let known = path.extension().is_some_and(|extension| {
extensions.split(';').any(|known| {
known
.trim_start_matches('.')
.eq_ignore_ascii_case(&extension.to_string_lossy())
})
});
let mut found = Vec::new();
if known {
found.push(path.to_owned());
} else {
for extension in extensions.split(';').filter(|value| !value.is_empty()) {
let mut name = path.as_os_str().to_owned();
name.push(extension.to_ascii_lowercase());
found.push(PathBuf::from(name));
}
}
found.into_iter()
}
#[cfg(unix)]
fn executable(path: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
path.metadata()
.is_ok_and(|info| info.is_file() && info.permissions().mode() & 0o111 != 0)
}
#[cfg(windows)]
fn executable(path: &Path) -> bool {
path.is_file()
}
pub fn checked(output: Output, label: &str) -> Result<String> {
if !output.status.success() {
let error = String::from_utf8_lossy(&output.stderr);
let detail = if error.trim().is_empty() {
String::from_utf8_lossy(&output.stdout)
} else {
error
};
bail!("{label}: {}", detail.trim());
}
String::from_utf8(output.stdout).with_context(|| format!("{label}: invalid UTF-8 output"))
}
#[derive(Clone)]
pub struct Repo {
pub root: PathBuf,
pub data: PathBuf,
pub worktrees: PathBuf,
}
const ARTIFACT_DIRS: &[&str] = &[
"__pycache__",
".pytest_cache",
".mypy_cache",
".ruff_cache",
"node_modules",
];
const ARTIFACT_FILES: &[&str] = &[".DS_Store", "Thumbs.db"];
const ARTIFACT_SUFFIXES: &[&str] = &[".pyc", ".pyo", ".pyd"];
pub fn artifact_root(path: &str) -> Option<&str> {
let mut start = 0;
for part in path.split('/') {
let end = start + part.len();
let artifact = if end == path.len() {
ARTIFACT_FILES.contains(&part)
|| ARTIFACT_SUFFIXES
.iter()
.any(|suffix| part.ends_with(suffix))
} else {
ARTIFACT_DIRS.contains(&part)
};
if artifact {
return Some(&path[..end]);
}
start = end + 1;
}
None
}
pub const WORKTREES_ENV: &str = "AGENGO_WORKTREES";
fn worktree_base() -> Result<PathBuf> {
if let Some(base) = std::env::var_os(WORKTREES_ENV).filter(|value| !value.is_empty()) {
return Ok(PathBuf::from(base));
}
if let Some(cache) = std::env::var_os("XDG_CACHE_HOME").filter(|value| !value.is_empty()) {
return Ok(PathBuf::from(cache).join("agengo").join("worktrees"));
}
#[cfg(windows)]
if let Some(local) = std::env::var_os("LOCALAPPDATA").filter(|value| !value.is_empty()) {
return Ok(PathBuf::from(local).join("agengo").join("worktrees"));
}
let home = std::env::var_os("HOME")
.filter(|value| !value.is_empty())
.ok_or_else(|| anyhow!("set HOME, XDG_CACHE_HOME or {WORKTREES_ENV}"))?;
Ok(PathBuf::from(home)
.join(".cache")
.join("agengo")
.join("worktrees"))
}
fn worktree_root(data: &Path, root: &Path) -> Result<PathBuf> {
let record = data.join("worktree-root");
if let Ok(saved) = fs::read_to_string(&record) {
let saved = saved.trim_end_matches('\n');
if !saved.is_empty() {
return Ok(PathBuf::from(saved));
}
}
let name: String = root
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("repo")
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'_'
}
})
.take(40)
.collect();
let unique = uuid::Uuid::new_v4().simple().to_string();
let chosen = worktree_base()?.join(format!("{name}-{}", &unique[..8]));
let chosen = if chosen.is_absolute() {
chosen
} else {
std::env::current_dir()?.join(chosen)
};
fs::create_dir_all(data)?;
fs::write(&record, format!("{}\n", chosen.display()))?;
Ok(chosen)
}
impl Repo {
pub fn open(cwd: &Path) -> Result<Self> {
let query = |args: &[&str]| {
checked(
run(git_command().current_dir(cwd).args(args), None, None)?,
"git",
)
.map_err(|error| {
if error.to_string().contains("not a git repository") {
anyhow!("{error}\nhint: agengo works inside a Git repository; run `git init` and make a first commit (`agengo doctor` checks the rest)")
} else {
error
}
})
};
let root = PathBuf::from(query(&["rev-parse", "--show-toplevel"])?.trim_end_matches('\n'));
let common = query(&["rev-parse", "--path-format=absolute", "--git-common-dir"])?;
let data = Path::new(common.trim_end_matches('\n')).join("agent-flow");
let worktrees = worktree_root(&data, &root)?;
Ok(Self {
root,
data,
worktrees,
})
}
pub fn run_worktree_roots(&self, run: &str) -> [PathBuf; 2] {
[
self.worktrees.join(run),
self.data.join("worktrees").join(run),
]
}
pub fn raw(&self, args: &[&str], cwd: &Path) -> Result<Output> {
run(git_command().current_dir(cwd).args(args), None, None)
}
pub fn git_at(&self, args: &[&str], cwd: &Path) -> Result<String> {
checked(
self.raw(args, cwd)?,
&format!("git {}", args.first().unwrap_or(&"")),
)
}
pub fn git(&self, args: &[&str]) -> Result<String> {
self.git_at(args, &self.root)
}
pub fn sha_at(&self, rev: &str, cwd: &Path) -> Result<String> {
Ok(self
.git_at(
&[
"rev-parse",
"--verify",
"--end-of-options",
&format!("{rev}^{{commit}}"),
],
cwd,
)?
.trim()
.into())
}
pub fn sha(&self, rev: &str) -> Result<String> {
self.sha_at(rev, &self.root)
}
pub fn current(&self, name: &str) -> Result<Option<String>> {
let result = self.raw(
&["rev-parse", "--verify", "--quiet", "--end-of-options", name],
&self.root,
)?;
if result.status.code() == Some(1) {
return Ok(None);
}
Ok(Some(checked(result, "read ref")?.trim().into()))
}
pub fn set_ref(&self, name: &str, sha: &str, expected: Option<&str>) -> Result<()> {
let zero = "0".repeat(sha.len());
self.git(&["update-ref", name, sha, expected.unwrap_or(&zero)])?;
Ok(())
}
pub fn worktree(&self, path: &Path, sha: &str, branch: Option<&str>) -> Result<()> {
fs::create_dir_all(path.parent().unwrap())?;
let path = path
.to_str()
.ok_or_else(|| anyhow!("invalid worktree path"))?;
let mut args = vec!["worktree", "add"];
if let Some(branch) = branch {
args.extend(["-b", branch]);
} else {
args.push("--detach");
}
args.extend([path, sha]);
self.git(&args)?;
Ok(())
}
pub fn remove_worktree(&self, path: &Path) -> Result<()> {
if !path.exists() {
return Ok(());
}
let text = path
.to_str()
.ok_or_else(|| anyhow!("invalid worktree path"))?;
if let Err(error) = self.git(&["worktree", "remove", "--force", "--force", text]) {
if path.exists() && fs::remove_dir_all(path).is_err() {
return Err(error).with_context(|| {
format!(
"cannot delete {}; close programs that use files in it, then run agengo clean again",
path.display()
)
});
}
self.git(&["worktree", "prune"])?;
}
Ok(())
}
pub fn remove_worktrees_under(&self, root: &Path) -> Result<usize> {
let mut removed = 0;
let resolved = fs::canonicalize(root).ok();
for field in self
.git(&["worktree", "list", "--porcelain", "-z"])?
.split('\0')
{
if let Some(path) = field.strip_prefix("worktree ") {
let path = Path::new(path);
if path.starts_with(root)
|| resolved.as_ref().is_some_and(|real| {
path.starts_with(real)
|| fs::canonicalize(path).is_ok_and(|own| own.starts_with(real))
})
{
self.remove_worktree(path)?;
removed += 1;
}
}
}
if root.exists() {
fs::remove_dir_all(root)?;
}
self.git(&["worktree", "prune"])?;
Ok(removed)
}
pub fn delete_refs(&self, prefixes: &[&str]) -> Result<Vec<String>> {
let mut args = vec!["for-each-ref", "--format=%(refname)"];
args.extend(prefixes);
let names: Vec<String> = self
.git(&args)?
.lines()
.filter(|name| !name.is_empty())
.map(str::to_owned)
.collect();
for name in &names {
self.git(&["update-ref", "-d", name])?;
}
Ok(names)
}
pub fn checked_out(&self, reference: &str) -> Result<bool> {
Ok(self
.git(&["worktree", "list", "--porcelain", "-z"])?
.split('\0')
.any(|field| field.strip_prefix("branch ") == Some(reference)))
}
pub fn ancestor(&self, ancestor: &str, child: &str) -> Result<bool> {
let output = self.raw(
&["merge-base", "--is-ancestor", ancestor, child],
&self.root,
)?;
if output.status.code() == Some(1) {
return Ok(false);
}
checked(output, "git merge-base")?;
Ok(true)
}
pub fn changed(&self, base: &str, head: &str) -> Result<Vec<String>> {
Ok(self
.git(&[
"diff",
"--no-renames",
"--name-only",
"-z",
base,
head,
"--",
])?
.split('\0')
.filter(|path| !path.is_empty())
.map(str::to_owned)
.collect())
}
pub fn untracked(&self, path: &Path, respect_ignores: bool) -> Result<BTreeSet<String>> {
let mut args = vec!["ls-files", "--others", "-z"];
if respect_ignores {
args.push("--exclude-standard");
}
Ok(self
.git_at(&args, path)?
.split('\0')
.filter(|name| !name.is_empty())
.map(str::to_owned)
.collect())
}
pub fn clean_head(&self, path: &Path, setup_artifacts: &BTreeSet<String>) -> Result<String> {
if self.differs(&["diff", "--quiet", "--cached", "HEAD", "--"], path)?
|| self.differs(&["diff", "--quiet", "HEAD", "--"], path)?
|| self
.untracked(path, true)?
.iter()
.any(|name| !setup_artifacts.contains(name) && artifact_root(name).is_none())
{
bail!("worktree has uncommitted changes");
}
self.sha_at("HEAD", path)
}
fn differs(&self, args: &[&str], path: &Path) -> Result<bool> {
let output = self.raw(args, path)?;
match output.status.code() {
Some(0) => Ok(false),
Some(1) => Ok(true),
_ => checked(output, "git").map(|_| true),
}
}
pub fn snapshot(&self, path: &Path, head: &str) -> Result<()> {
if self.sha_at("HEAD", path)? != head {
bail!("command changed the worktree HEAD");
}
if !self
.raw(&["diff", "--quiet", head, "--"], path)?
.status
.success()
{
bail!("command modified tracked files");
}
Ok(())
}
}
pub fn argv(command: &[String], cwd: &Path) -> Result<Command> {
let (executable, arguments) = command
.split_first()
.ok_or_else(|| anyhow!("empty command"))?;
#[cfg(windows)]
let executable = resolve(executable.as_ref(), cwd)
.map_or_else(|| executable.into(), PathBuf::into_os_string);
let mut result = Command::new(executable);
result.current_dir(cwd).args(arguments);
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
fn shell(unix: &str, windows: &str) -> Command {
if cfg!(windows) {
let mut command = Command::new("cmd");
command.args(["/d", "/c", windows]);
command
} else {
let mut command = Command::new("sh");
command.args(["-c", unix]);
command
}
}
#[test]
fn process_passes_input_and_collects_both_pipes() -> Result<()> {
let mut command = shell("cat; echo oops >&2", "findstr x & echo oops 1>&2");
let output = run(&mut command, Some(b"x1\nx2\n"), Some(30))?;
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout)?;
assert_eq!(stdout.lines().collect::<Vec<_>>(), ["x1", "x2"]);
assert_eq!(String::from_utf8(output.stderr)?.trim(), "oops");
Ok(())
}
#[test]
fn artifact_root_names_the_artifact_part() {
for (path, root) in [
(
"pkg/__pycache__/mod.cpython-312.pyc",
Some("pkg/__pycache__"),
),
("__pycache__/x.pyc", Some("__pycache__")),
(
"app/node_modules/left-pad/index.js",
Some("app/node_modules"),
),
(".pytest_cache/v/cache/nodeids", Some(".pytest_cache")),
("lib/fast.pyd", Some("lib/fast.pyd")),
("docs/.DS_Store", Some("docs/.DS_Store")),
("Thumbs.db", Some("Thumbs.db")),
("src/main.py", None),
("src/pyc", None),
("node_modules", None),
("build/out.o", None),
("target/debug/agengo", None),
] {
assert_eq!(artifact_root(path), root, "{path}");
}
}
#[test]
fn process_reports_output_limit_instead_of_truncating() -> Result<()> {
let mut command = shell(
"printf 'more than eight bytes'",
"echo more than eight bytes",
);
let error = run_with_limit(&mut command, None, Some(5), 8)
.expect_err("output larger than the limit should fail");
assert!(format!("{error:#}").contains("output exceeded the 8-byte limit"));
Ok(())
}
#[test]
fn background_processes_do_not_turn_success_into_a_timeout() -> Result<()> {
let mut command = shell(
"sleep 30 & echo $!",
"start /b ping -n 30 127.0.0.1 & echo started",
);
let started = Instant::now();
let output = run(&mut command, None, Some(30))?;
assert!(output.status.success());
assert!(started.elapsed() < Duration::from_secs(10));
#[cfg(unix)]
{
let pid = String::from_utf8(output.stdout)?.trim().parse::<i32>()?;
let state = Command::new("ps")
.args(["-o", "stat=", "-p", &pid.to_string()])
.output()?;
let state = String::from_utf8_lossy(&state.stdout);
assert!(state.trim().is_empty() || state.trim_start().starts_with('Z'));
}
Ok(())
}
#[test]
fn line_ending_rewrites_do_not_count_as_uncommitted_changes() -> Result<()> {
let temp = tempfile::tempdir()?;
let root = temp.path().to_owned();
let git = |args: &[&str]| -> Result<String> {
checked(
run(
git_command()
.current_dir(&root)
.args(["-c", "user.name=t", "-c", "user.email=t@example.invalid"])
.args(args),
None,
Some(30),
)?,
"git",
)
};
git(&["init", "-q", "-b", "main"])?;
git(&["config", "core.autocrlf", "true"])?;
fs::write(root.join("a.txt"), "one\ntwo\n")?;
git(&["add", "a.txt"])?;
git(&["commit", "-q", "-m", "base"])?;
fs::remove_file(root.join("a.txt"))?;
git(&["checkout", "--", "a.txt"])?;
assert_eq!(fs::read(root.join("a.txt"))?, b"one\r\ntwo\r\n");
let repo = Repo {
root: root.clone(),
data: root.join(".git/agent-flow"),
worktrees: temp.path().join("worktrees"),
};
fs::write(root.join("a.txt"), "one\ntwo\n")?;
assert!(!git(&["status", "--porcelain"])?.is_empty(), "Git's quirk");
assert_eq!(
repo.clean_head(&root, &BTreeSet::new())?,
git(&["rev-parse", "HEAD"])?.trim()
);
fs::write(root.join("a.txt"), "one\nthree\n")?;
assert!(repo.clean_head(&root, &BTreeSet::new()).is_err());
git(&["checkout", "--", "a.txt"])?;
fs::write(root.join("b.txt"), "new\n")?;
assert!(repo.clean_head(&root, &BTreeSet::new()).is_err());
git(&["add", "b.txt"])?;
fs::remove_file(root.join("b.txt"))?;
assert!(
repo.clean_head(&root, &BTreeSet::new()).is_err(),
"a staged change counts even when the worktree file is gone"
);
Ok(())
}
#[cfg(windows)]
#[test]
fn worktrees_with_open_files_are_removed_once_the_files_close() -> Result<()> {
use std::os::windows::fs::OpenOptionsExt;
let temp = tempfile::tempdir()?;
let root = temp.path().join("repo");
fs::create_dir(&root)?;
let git = |args: &[&str]| -> Result<String> {
checked(
run(
git_command()
.current_dir(&root)
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.env("GIT_CONFIG_NOSYSTEM", "1")
.args(["-c", "user.name=t", "-c", "user.email=t@example.invalid"])
.args(args),
None,
Some(30),
)?,
"git",
)
};
git(&["init", "-q", "-b", "main"])?;
fs::write(root.join("a.txt"), "a\n")?;
git(&["add", "a.txt"])?;
git(&["commit", "-q", "-m", "base"])?;
let tree = temp.path().join("wt");
git(&[
"worktree",
"add",
"-q",
"--detach",
&tree.to_string_lossy(),
"HEAD",
])?;
let repo = Repo {
root: root.clone(),
data: root.join(".git/agent-flow"),
worktrees: temp.path().join("worktrees"),
};
let held = fs::OpenOptions::new()
.read(true)
.share_mode(1)
.open(tree.join("a.txt"))?;
let error = repo
.remove_worktree(&tree)
.expect_err("an open file blocks the removal");
assert!(format!("{error:#}").contains("close programs that use files in it"));
drop(held);
repo.remove_worktree(&tree)?;
assert!(!tree.exists());
assert!(!git(&["worktree", "list"])?.contains("wt"));
Ok(())
}
#[test]
fn agengo_git_commands_ignore_hooks() -> Result<()> {
let temp = tempfile::tempdir()?;
let marker = temp.path().join("hook-ran");
let git = |args: &[&str]| -> Result<String> {
checked(
run(
git_command()
.current_dir(temp.path())
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.env("GIT_CONFIG_NOSYSTEM", "1")
.args(["-c", "user.name=t", "-c", "user.email=t@example.invalid"])
.args(args),
None,
Some(30),
)?,
"git",
)
};
git(&["init", "-q", "-b", "main"])?;
git(&["commit", "-q", "--allow-empty", "-m", "base"])?;
let hook = temp.path().join(".git/hooks/post-checkout");
let target = marker.to_string_lossy().replace('\\', "/");
fs::write(&hook, format!("#!/bin/sh\ntouch '{target}'\n"))?;
#[cfg(unix)]
fs::set_permissions(&hook, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
git(&["worktree", "add", "-q", "--detach", "wt", "HEAD"])?;
assert!(temp.path().join("wt").exists());
assert!(!marker.exists(), "agengo must not run repository hooks");
Ok(())
}
#[test]
fn process_reports_timeout() {
let mut command = shell("sleep 10", "ping -n 10 127.0.0.1");
let started = Instant::now();
let error = run(&mut command, None, Some(1)).expect_err("the command must time out");
assert!(format!("{error:#}").contains("exceeded the timeout"));
assert!(started.elapsed() < Duration::from_secs(5));
}
#[test]
fn timeouts_stop_every_process_the_command_started() -> Result<()> {
let temp = tempfile::tempdir()?;
let record = temp.path().join("pid");
let target = record.to_string_lossy().into_owned();
let mut command = if cfg!(windows) {
let mut command = Command::new("powershell");
command.args([
"-NoProfile",
"-Command",
&format!(
"$p = Start-Process ping -ArgumentList '-n','60','127.0.0.1' -PassThru -WindowStyle Hidden; \
Set-Content -Path '{target}' -Value $p.Id; Start-Sleep 60"
),
]);
command
} else {
shell(&format!("sleep 60 & echo $! > '{target}'; wait"), "")
};
let timeout = if cfg!(windows) { 30 } else { 8 };
let error = run(&mut command, None, Some(timeout)).expect_err("the command must time out");
assert!(format!("{error:#}").contains("exceeded the timeout"));
let pid = fs::read_to_string(&record)?.trim().to_owned();
thread::sleep(Duration::from_millis(500));
let alive = if cfg!(windows) {
let list = Command::new("tasklist")
.args(["/FI", &format!("PID eq {pid}"), "/NH"])
.output()?;
String::from_utf8_lossy(&list.stdout).contains(&pid)
} else {
let state = Command::new("ps")
.args(["-o", "stat=", "-p", &pid])
.output()?;
let state = String::from_utf8_lossy(&state.stdout).trim().to_owned();
!state.is_empty() && !state.starts_with('Z')
};
assert!(!alive, "process {pid} outlived the timed-out command");
Ok(())
}
#[test]
fn executables_are_found_on_path_with_their_extension() -> Result<()> {
let directory = tempfile::tempdir()?;
let name = if cfg!(windows) { "tool.cmd" } else { "tool" };
let path = directory.path().join(name);
fs::write(&path, "")?;
#[cfg(unix)]
fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
let found = resolve(OsStr::new("tool"), directory.path());
let relative = resolve(OsStr::new("./tool"), directory.path());
assert_eq!(found, None, "the directory is not on PATH");
assert_eq!(
relative.map(|path| path.file_name().map(ToOwned::to_owned)),
Some(Some(name.into()))
);
Ok(())
}
#[test]
fn checked_returns_stdout_and_explains_failures() -> Result<()> {
let mut ok = shell("printf hi", "echo hi");
let text = checked(run(&mut ok, None, Some(30))?, "say")?;
assert_eq!(text.trim(), "hi");
let mut bad = shell("echo boom >&2; exit 3", "echo boom 1>&2 & exit 3");
let error = checked(run(&mut bad, None, Some(30))?, "build").unwrap_err();
assert_eq!(error.to_string(), "build: boom");
let mut quiet = shell("echo only; exit 1", "echo only& exit 1");
let error = checked(run(&mut quiet, None, Some(30))?, "build").unwrap_err();
assert_eq!(error.to_string(), "build: only");
Ok(())
}
#[test]
fn argv_splits_program_and_arguments_and_rejects_an_empty_command() -> Result<()> {
let directory = tempfile::tempdir()?;
assert!(argv(&[], directory.path()).is_err());
let command = argv(
&["git".into(), "--version".into(), "x y".into()],
directory.path(),
)?;
assert_eq!(command.get_current_dir(), Some(directory.path()));
let arguments: Vec<_> = command.get_args().collect();
assert_eq!(
arguments,
["--version", "x y"],
"arguments are not re-split"
);
Ok(())
}
#[test]
fn a_command_that_exits_nonzero_is_not_a_timeout() -> Result<()> {
let mut command = shell("exit 7", "exit 7");
let output = run(&mut command, None, Some(30))?;
assert_eq!(output.status.code(), Some(7));
Ok(())
}
}