O1: Rust crate, profiles, persistent run state (#9)

This commit was merged in pull request #9.
This commit is contained in:
hermes committed 2026-11-12 23:19:05 +00:00
1 parent 29c08130c2
commit fb434c670c
9 files changed
+1128

No files matched your search

+279
View File
@@ -0,0 +1,279 @@
//! One run: worktree -> hx (NDJSON, budgets, process group) -> commit -> gate -> final state.
use crate::profile::Profile;
use crate::state::{Run, Status, 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,
})
}
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()
}
/// Runs the whole pipeline. Errors only for orch-internal problems; task failures end as `Failed` state.
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(());
}
r.status = Status::Running;
r.save()?;
let mut log = std::fs::File::create(log_path(&r.id))?;
let reason = run_hx(r, p, &body, &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"])?;
git(
&r.worktree,
&["commit", "-qm", &format!("orch: {}", r.title)],
)?;
}
if let Some(reason) = reason {
return fail(r, reason);
}
if let Some(gate) = &p.gate {
r.status = Status::Gating;
r.save()?;
writeln!(log, "\n--- gate: {gate}")?;
let st = Command::new("sh")
.args(["-c", gate])
.current_dir(&r.worktree)
.stdout(log.try_clone()?)
.stderr(log.try_clone()?)
.status()?;
r.gate_exit = st.code();
if !st.success() {
return fail(r, "gate-failed");
}
}
r.status = Status::Done;
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, 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 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 turns, mut tokens, mut done) = (0u64, 0u64, 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") => {
turns += 1;
if p.budget.max_turns.is_some_and(|m| turns > m) {
killed = Some("budget:turns".to_string());
}
}
Some("stream") if ev["event"]["type"] == "done" => {
let u = &ev["event"]["usage"];
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| 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);
}
}