use anyhow::{anyhow, bail, Context, Result};
use serde_json::Value;
use std::{
collections::BTreeSet,
fs,
io::{self, Read, Write},
os::fd::{AsRawFd, RawFd},
os::unix::process::CommandExt,
path::{Path, PathBuf},
process::{Command, Output, Stdio},
sync::atomic::{AtomicBool, Ordering},
time::Instant,
};
pub static INTERRUPTED: AtomicBool = AtomicBool::new(false);
pub static CANCEL_ASSIGNMENTS: AtomicBool = AtomicBool::new(false);
const OUTPUT_LIMIT: usize = 16 * 1024 * 1024;
pub fn run(command: &mut Command, input: Option<&[u8]>, timeout: Option<u64>) -> Result<Output> {
run_with_limit(command, input, timeout, OUTPUT_LIMIT)
}
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())
.process_group(0);
let program = command.get_program().to_owned();
let mut child = command
.spawn()
.with_context(|| format!("cannot launch {program:?}"))?;
let mut stdin = child.stdin.take();
let mut stdout = child.stdout.take();
let mut stderr = child.stderr.take();
let result = (|| -> Result<Output> {
for fd in [descriptor(&stdin), descriptor(&stdout), descriptor(&stderr)] {
if fd >= 0 {
nonblocking(fd)?;
}
}
let mut input = input.unwrap_or_default();
let mut out = Vec::new();
let mut err = Vec::new();
let start = Instant::now();
let mut status = None;
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() {
stdin = None;
}
write_input(&mut stdin, &mut input)?;
read_output(&mut stdout, &mut out, limit)
.with_context(|| format!("{program:?} stdout"))?;
read_output(&mut stderr, &mut err, limit)
.with_context(|| format!("{program:?} stderr"))?;
if let Some(status) = status {
if stdout.is_none() && stderr.is_none() {
return Ok(Output {
status,
stdout: out,
stderr: err,
});
}
}
let mut fds = [
libc::pollfd {
fd: descriptor(&stdin),
events: libc::POLLOUT,
revents: 0,
},
libc::pollfd {
fd: descriptor(&stdout),
events: libc::POLLIN,
revents: 0,
},
libc::pollfd {
fd: descriptor(&stderr),
events: libc::POLLIN,
revents: 0,
},
];
let wait_ms = if fds.iter().all(|pipe| pipe.fd < 0) {
2
} else {
10
};
if unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, wait_ms) } < 0 {
let error = io::Error::last_os_error();
if error.kind() != io::ErrorKind::Interrupted {
return Err(error.into());
}
}
}
})();
if result.is_err() {
drop((stdin, stdout, stderr));
unsafe {
libc::kill(-(child.id() as i32), libc::SIGKILL);
}
let _ = child.wait();
}
result
}
fn descriptor<T: AsRawFd>(pipe: &Option<T>) -> RawFd {
pipe.as_ref().map_or(-1, AsRawFd::as_raw_fd)
}
fn nonblocking(fd: RawFd) -> io::Result<()> {
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
fn write_input(pipe: &mut Option<impl Write>, input: &mut &[u8]) -> io::Result<()> {
if input.is_empty() {
*pipe = None;
} else if let Some(writer) = pipe {
match writer.write(input) {
Ok(count) => {
*input = &input[count..];
if input.is_empty() {
*pipe = None;
}
}
Err(error) if error.kind() == io::ErrorKind::BrokenPipe => *pipe = None,
Err(error)
if matches!(
error.kind(),
io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
) => {}
Err(error) => return Err(error),
}
}
Ok(())
}
fn read_output(pipe: &mut Option<impl Read>, output: &mut Vec<u8>, limit: usize) -> Result<()> {
if let Some(reader) = pipe {
let mut chunk = [0; 16 * 1024];
match reader.read(&mut chunk) {
Ok(0) => *pipe = None,
Ok(count) => {
if count > limit - output.len() {
bail!("output exceeded the {limit}-byte limit");
}
output.extend_from_slice(&chunk[..count]);
}
Err(error)
if matches!(
error.kind(),
io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
) => {}
Err(error) => return Err(error.into()),
}
}
Ok(())
}
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,
}
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"));
}
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(Command::new("git").current_dir(cwd).args(args), None, None)?,
"git",
)
};
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(Command::new("git").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() {
let path = path
.to_str()
.ok_or_else(|| anyhow!("invalid worktree path"))?;
self.git(&["worktree", "remove", "--force", "--force", path])?;
}
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))
{
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> {
let untracked_mode = if setup_artifacts.is_empty() {
"--untracked-files=all"
} else {
"--untracked-files=no"
};
if !self
.git_at(&["status", "--porcelain", untracked_mode], path)?
.is_empty()
|| (!setup_artifacts.is_empty()
&& !self.untracked(path, true)?.is_subset(setup_artifacts))
{
bail!("worktree has uncommitted changes");
}
self.sha_at("HEAD", path)
}
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: &Value, cwd: &Path) -> Result<Command> {
let values = crate::contract::array_or_empty(command);
let executable = values
.first()
.and_then(Value::as_str)
.ok_or_else(|| anyhow!("empty command"))?;
let mut result = Command::new(executable);
result
.current_dir(cwd)
.args(values.iter().skip(1).map(crate::contract::string_or_empty));
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
use std::{thread, time::Duration};
#[test]
fn output_read_yields_when_a_pipe_still_has_a_writer() -> Result<()> {
let (reader, mut writer) = io::pipe()?;
nonblocking(reader.as_raw_fd())?;
writer.write_all(b"ready")?;
let mut pipe = Some(reader);
let mut output = Vec::new();
read_output(&mut pipe, &mut output, 1024)?;
read_output(&mut pipe, &mut output, 1024)?;
assert_eq!(output, b"ready");
assert!(pipe.is_some());
drop(writer);
let deadline = Instant::now() + Duration::from_secs(2);
while pipe.is_some() && Instant::now() < deadline {
read_output(&mut pipe, &mut output, 1024)?;
if pipe.is_some() {
thread::sleep(Duration::from_millis(2));
}
}
assert!(pipe.is_none());
Ok(())
}
#[test]
fn process_reports_output_limit_instead_of_truncating() -> Result<()> {
let mut command = Command::new("sh");
command.args(["-c", "printf '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 process_reports_timeout() {
let mut command = Command::new("sleep");
command.arg("10");
let error = run(&mut command, None, Some(1)).expect_err("the command must time out");
assert!(format!("{error:#}").contains("exceeded the timeout"));
}
}