Files
orch/src/run.rs
T

326 lines
11 KiB
Rust

//! One run: worktree -> hx (NDJSON, budgets, process group) -> commit -> gate -> final state.
use crate::profile::Profile;
use crate::state::{Run, Status, gate_log_path, kill_group, log_path, now};
use anyhow::{Context, Result, bail};
use serde_json::Value;
use std::io::{BufRead, Write};
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
fn git(dir: &Path, args: &[&str]) -> Result<String> {
let o = Command::new("git")
.args(["-c", "user.name=orch", "-c", "user.email=orch@localhost"])
.args(args)
.current_dir(dir)
.output()?;
if !o.status.success() {
bail!(
"git {}: {}",
args.join(" "),
String::from_utf8_lossy(&o.stderr).trim()
);
}
Ok(String::from_utf8_lossy(&o.stdout).into_owned())
}
/// Task file: first `#` heading = title, the rest = prompt.
pub fn read_task(path: &Path) -> Result<(String, String)> {
let s = std::fs::read_to_string(path).with_context(|| format!("task {}", path.display()))?;
let title = s
.lines()
.find(|l| l.starts_with('#'))
.map(|l| l.trim_start_matches('#').trim().to_string());
let body: String = s
.lines()
.filter(|l| !l.starts_with('#'))
.collect::<Vec<_>>()
.join("\n");
let stem = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("task")
.to_string();
let title = title.unwrap_or(stem);
let body = if body.trim().is_empty() {
title.clone()
} else {
body.trim().to_string()
};
Ok((title, body))
}
pub fn new_run(task: &Path, repo: &Path, profile: &str) -> Result<Run> {
let (title, _) = read_task(task)?;
let stem = task.file_stem().and_then(|s| s.to_str()).unwrap_or("task");
let stem: String = stem
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' {
c
} else {
'-'
}
})
.collect();
let id = format!("{stem}-{}", now());
let repo = repo
.canonicalize()
.with_context(|| format!("repo {}", repo.display()))?;
Ok(Run {
branch: format!("orch/{id}"),
worktree: crate::state_dir().join("worktrees").join(&id),
id,
title,
profile: profile.into(),
repo,
status: Status::Queued,
reason: None,
orch_pid: std::process::id(),
hx_pid: None,
started: now(),
ended: None,
hx_exit: None,
gate_exit: None,
input_tokens: 0,
output_tokens: 0,
session: None,
attempts: 0,
turns: 0,
spent_tokens: 0,
})
}
fn fail(r: &mut Run, reason: impl Into<String>) -> Result<()> {
r.status = Status::Failed;
r.reason = Some(reason.into());
r.ended = Some(now());
r.save()
}
/// Max bytes of gate output fed back to hx (the tail: errors are at the end).
const GATE_LOG_LIMIT: usize = 8000;
fn tail(b: &[u8], limit: usize) -> String {
let s = String::from_utf8_lossy(&b[b.len().saturating_sub(limit)..]).into_owned();
s.trim_start_matches('\u{FFFD}').to_string()
}
fn retry_prompt(gate: &str, code: Option<i32>, out: &[u8], resumed: bool, body: &str) -> String {
let task = if resumed {
String::new()
} else {
format!("Task:\n{body}\n\n")
};
format!(
"{task}The check `{gate}` failed (exit {}). Fix the code so it passes. Output (last {GATE_LOG_LIMIT} bytes):\n{}",
code.map_or("signal".into(), |c| c.to_string()),
tail(out, GATE_LOG_LIMIT)
)
}
/// Runs the whole pipeline. Errors only for orch-internal problems; task failures end as `Failed` or
/// `NeedsHuman` state. After a failed gate hx gets the gate output on the same session, up to `max_retries`.
pub fn execute(r: &mut Run, p: &Profile, task: &Path) -> Result<()> {
let (_, body) = read_task(task)?;
r.save()?;
std::fs::create_dir_all(r.worktree.parent().unwrap())?;
let wt = r.worktree.to_string_lossy().into_owned();
if let Err(e) = git(&r.repo, &["worktree", "add", "-b", &r.branch, &wt, "HEAD"]) {
fail(r, format!("setup: {e}"))?;
return Ok(());
}
let mut log = std::fs::File::create(log_path(&r.id))?;
let mut prompt = body.clone();
let mut session: Option<String> = None;
loop {
r.attempts += 1;
r.status = Status::Running;
r.save()?;
writeln!(log, "\n--- attempt {}", r.attempts)?;
let reason = run_hx(r, p, &prompt, session.as_deref(), &mut log)?;
if !git(&r.worktree, &["status", "--porcelain"])?
.trim()
.is_empty()
{
// keep hx's work on the branch even when it failed: nothing is lost
git(&r.worktree, &["add", "-A"])?;
let msg = format!("orch: {} (attempt {})", r.title, r.attempts);
git(&r.worktree, &["commit", "-qm", &msg])?;
}
if let Some(reason) = reason {
return fail(r, reason);
}
let Some(gate) = &p.gate else { break };
r.status = Status::Gating;
r.save()?;
writeln!(log, "\n--- gate: {gate}")?;
// ponytail: no gate timeout; a hanging gate hangs the run. Add gate_secs when it bites.
let o = Command::new("sh")
.args(["-c", &format!("({gate}) 2>&1")])
.current_dir(&r.worktree)
.output()?;
log.write_all(&o.stdout)?;
r.gate_exit = o.status.code();
if o.status.success() {
break;
}
std::fs::write(gate_log_path(&r.id), &o.stdout)?;
if r.attempts > p.max_retries {
r.status = Status::NeedsHuman;
r.reason = Some("gate-failed".into());
r.ended = Some(now());
return r.save();
}
session = r.session.clone();
prompt = retry_prompt(gate, r.gate_exit, &o.stdout, session.is_some(), &body);
}
r.status = Status::Done;
r.reason = None;
r.ended = Some(now());
r.save()
}
/// Returns the failure reason, or None when hx finished cleanly.
fn run_hx(
r: &mut Run,
p: &Profile,
body: &str,
session: Option<&str>,
log: &mut std::fs::File,
) -> Result<Option<String>> {
let mut parts = p.hx.split_whitespace();
let mut cmd = Command::new(parts.next().context("empty hx command")?);
cmd.args(parts).args(["-p", body, "--mode", "json"]);
if let Some(s) = session {
cmd.args(["--session", s]);
}
if p.sandbox {
cmd.arg("--sandbox");
}
if p.yolo {
cmd.arg("--yolo");
}
if let Some(prov) = &p.provider {
cmd.args(["--provider", prov]);
}
if let Some(h) = &p.home {
cmd.env("HOME", h);
}
cmd.current_dir(&r.worktree)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::from(log.try_clone()?))
.process_group(0); // own group: timeout/crash kills hx and its bash children together
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(e) => return Ok(Some(format!("hx-failed: spawn {}: {e}", p.hx))),
};
r.hx_pid = Some(child.id());
r.save()?;
let (tx, rx) = mpsc::channel::<String>();
let out = child.stdout.take().unwrap();
std::thread::spawn(move || {
for l in std::io::BufReader::new(out).lines().map_while(Result::ok) {
if tx.send(l).is_err() {
break;
}
}
});
let deadline = Instant::now() + Duration::from_secs(p.wall_secs());
let mut done = None::<Value>;
let mut killed = None;
loop {
let left = deadline.saturating_duration_since(Instant::now());
match rx.recv_timeout(left) {
Ok(line) => {
writeln!(log, "{line}")?;
let Ok(ev) = serde_json::from_str::<Value>(&line) else {
continue;
};
match ev["type"].as_str() {
Some("turn_start") => {
r.turns += 1;
if p.budget.max_turns.is_some_and(|m| r.turns > m) {
killed = Some("budget:turns".to_string());
}
}
Some("stream") if ev["event"]["type"] == "done" => {
let u = &ev["event"]["usage"];
r.spent_tokens += u["input_tokens"].as_u64().unwrap_or(0)
+ u["output_tokens"].as_u64().unwrap_or(0);
if p.budget.max_tokens.is_some_and(|m| r.spent_tokens > m) {
killed = Some("budget:tokens".to_string());
}
}
Some("done") => done = Some(ev),
_ => {}
}
if killed.is_some() {
break;
}
}
Err(mpsc::RecvTimeoutError::Timeout) => {
killed = Some("timeout".into());
break;
}
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
}
if killed.is_some() {
kill_group(child.id());
}
let st = child.wait()?;
kill_group(child.id()); // stray bash children that outlived hx
r.hx_exit = st.code();
r.hx_pid = None;
if let Some(d) = &done {
let u = &d["usage"];
r.input_tokens = u["input_tokens"].as_u64().unwrap_or(0);
r.output_tokens = u["output_tokens"].as_u64().unwrap_or(0);
r.session = d["session"].as_str().map(String::from);
}
if let Some(k) = killed {
return Ok(Some(k));
}
Ok(match &done {
None => Some("hx-failed: no done event".into()),
Some(d) if !d["error"].is_null() => Some(format!(
"hx-failed: {}",
d["error"].as_str().unwrap_or("error")
)),
_ if !st.success() => Some(format!("hx-failed: exit {}", st.code().unwrap_or(-1))),
_ => None,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn task_parsing() {
let d = std::env::temp_dir().join(format!("orch-task-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let f = d.join("fix-it.md");
std::fs::write(&f, "# Fix it\n\nDo the thing\nplease\n").unwrap();
assert_eq!(
read_task(&f).unwrap(),
("Fix it".into(), "Do the thing\nplease".into())
);
std::fs::write(&f, "no heading, just text").unwrap();
assert_eq!(
read_task(&f).unwrap(),
("fix-it".into(), "no heading, just text".into())
);
std::fs::write(&f, "# Only title").unwrap();
assert_eq!(read_task(&f).unwrap().1, "Only title");
let _ = std::fs::remove_dir_all(&d);
}
}