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

+106
View File
@@ -0,0 +1,106 @@
mod profile;
mod run;
mod state;
use anyhow::{Result, bail};
use clap::{Parser, Subcommand};
use std::path::PathBuf;
#[derive(Parser)]
#[command(version, about = "Run hx coding agents on tasks")]
struct Cli {
#[command(subcommand)]
cmd: Cmd,
}
#[derive(Subcommand)]
enum Cmd {
/// Run one task (Markdown file) in a fresh git worktree of REPO.
Run {
task: PathBuf,
#[arg(long)]
repo: PathBuf,
#[arg(long, default_value = "default")]
profile: String,
},
/// List runs, or show one.
Status { id: Option<String> },
/// Print the raw log (hx events, stderr, gate output) of a run.
Logs { id: String },
}
fn env_dir(var: &str, xdg: &str, fallback: &str) -> PathBuf {
if let Some(d) = std::env::var_os(var) {
return d.into();
}
if let Some(d) = std::env::var_os(xdg) {
return PathBuf::from(d).join("orch");
}
PathBuf::from(std::env::var_os("HOME").unwrap_or_default())
.join(fallback)
.join("orch")
}
pub fn config_dir() -> PathBuf {
env_dir("ORCH_CONFIG_DIR", "XDG_CONFIG_HOME", ".config")
}
pub fn state_dir() -> PathBuf {
env_dir("ORCH_STATE_DIR", "XDG_STATE_HOME", ".local/state")
}
fn main() -> Result<std::process::ExitCode> {
match Cli::parse().cmd {
Cmd::Run {
task,
repo,
profile,
} => {
let p = profile::Profile::load(&profile)?;
let mut r = run::new_run(&task, &repo, &profile)?;
run::execute(&mut r, &p, &task)?;
println!(
"{} {}{}",
r.id,
serde_json::to_value(r.status)?.as_str().unwrap(),
r.reason
.as_ref()
.map(|x| format!(" ({x})"))
.unwrap_or_default()
);
Ok(if r.status == state::Status::Done {
0
} else {
1
}
.into())
}
Cmd::Status { id: Some(id) } => {
println!("{}", serde_json::to_string_pretty(&state::Run::load(&id)?)?);
Ok(0.into())
}
Cmd::Status { id: None } => {
for r in state::Run::list()? {
let st = serde_json::to_value(r.status)?;
let end = r.ended.unwrap_or_else(state::now);
println!(
"{:<28} {:<8} {:>5}s {:>8} tok {}{}",
r.id,
st.as_str().unwrap(),
end.saturating_sub(r.started),
r.input_tokens + r.output_tokens,
r.title,
r.reason.map(|x| format!(" [{x}]")).unwrap_or_default()
);
}
Ok(0.into())
}
Cmd::Logs { id } => {
if id.contains('/') || id.starts_with('.') {
bail!("bad run id");
}
print!("{}", std::fs::read_to_string(state::log_path(&id))?);
Ok(0.into())
}
}
}
+99
View File
@@ -0,0 +1,99 @@
//! Profile: `<config>/profiles/NAME.toml`. One profile = one identity (own HOME/auth), budget and gate.
use anyhow::{Context, Result, bail};
use serde::Deserialize;
use std::path::PathBuf;
#[derive(Deserialize, Debug, Default, Clone)]
#[serde(deny_unknown_fields)]
pub struct Budget {
/// Wall clock limit for the hx run (not the gate). Default 30 min.
pub wall_secs: Option<u64>,
/// Max `turn_start` events before hx is killed.
pub max_turns: Option<u64>,
/// Max input+output tokens, summed over `stream/done` events.
pub max_tokens: Option<u64>,
}
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct Profile {
/// hx command, whitespace-split (ponytail: no quoting; wrap in a script if needed).
#[serde(default = "default_hx")]
pub hx: String,
/// HOME for hx, so each profile keeps its own `~/.hx/auth.json`.
pub home: Option<PathBuf>,
pub provider: Option<String>,
#[serde(default)]
pub sandbox: bool,
/// Passes `--yolo`. Only allowed together with `sandbox = true`.
#[serde(default)]
pub yolo: bool,
/// Shell command run in the worktree after hx; exit 0 = pass. None = no gate.
pub gate: Option<String>,
#[serde(default)]
pub budget: Budget,
}
fn default_hx() -> String {
"hx".into()
}
impl Profile {
pub fn parse(s: &str) -> Result<Self> {
let p: Profile = toml::from_str(s)?;
if p.yolo && !p.sandbox {
bail!("yolo = true requires sandbox = true");
}
Ok(p)
}
pub fn load(name: &str) -> Result<Self> {
if name.is_empty() || name.contains(['/', '.']) {
bail!("bad profile name {name:?}");
}
let path = crate::config_dir()
.join("profiles")
.join(format!("{name}.toml"));
let s = std::fs::read_to_string(&path)
.with_context(|| format!("profile {}", path.display()))?;
Self::parse(&s).with_context(|| path.display().to_string())
}
pub fn wall_secs(&self) -> u64 {
self.budget.wall_secs.unwrap_or(1800)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn minimal_and_full() {
let p = Profile::parse("").unwrap();
assert_eq!(
(p.hx.as_str(), p.wall_secs(), p.gate.is_none()),
("hx", 1800, true)
);
let p = Profile::parse(
"hx='x'\nhome='/h'\nsandbox=true\nyolo=true\ngate='true'\n[budget]\nmax_turns=3\nwall_secs=9\n",
)
.unwrap();
assert_eq!(
(p.budget.max_turns, p.wall_secs(), p.home.unwrap().to_str()),
(Some(3), 9, Some("/h"))
);
}
#[test]
fn rejects_yolo_without_sandbox_and_unknown_keys() {
assert!(Profile::parse("yolo=true").is_err());
assert!(Profile::parse("bogus=1").is_err());
}
#[test]
fn rejects_path_like_names() {
assert!(Profile::load("../x").is_err());
}
}
+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);
}
}
+172
View File
@@ -0,0 +1,172 @@
//! Persistent run state: one JSON file per run in `<state>/runs/ID.json`, written atomically.
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
/// queued -> running -> gating -> done | failed. (retry and needs-human arrive with O2.)
#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
#[serde(rename_all = "kebab-case")]
pub enum Status {
Queued,
Running,
Gating,
Done,
Failed,
}
impl Status {
pub fn active(self) -> bool {
matches!(self, Status::Queued | Status::Running | Status::Gating)
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Run {
pub id: String,
pub title: String,
pub profile: String,
pub repo: PathBuf,
pub branch: String,
pub worktree: PathBuf,
pub status: Status,
/// Why a run failed: hx-failed, gate-failed, timeout, budget:<what>, interrupted, setup:<err>.
pub reason: Option<String>,
pub orch_pid: u32,
pub hx_pid: Option<u32>,
pub started: u64,
pub ended: Option<u64>,
pub hx_exit: Option<i32>,
pub gate_exit: Option<i32>,
pub input_tokens: u64,
pub output_tokens: u64,
pub session: Option<String>,
}
pub fn now() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
pub fn runs_dir() -> PathBuf {
crate::state_dir().join("runs")
}
pub fn log_path(id: &str) -> PathBuf {
runs_dir().join(format!("{id}.log"))
}
fn valid_id(id: &str) -> bool {
!id.is_empty() && !id.contains(['/', '\\']) && !id.starts_with('.')
}
impl Run {
pub fn save(&self) -> Result<()> {
let dir = runs_dir();
std::fs::create_dir_all(&dir)?;
let tmp = dir.join(format!("{}.json.tmp", self.id));
std::fs::write(&tmp, serde_json::to_vec_pretty(self)?)?;
std::fs::rename(&tmp, dir.join(format!("{}.json", self.id)))?; // atomic: no half-written state on crash
Ok(())
}
pub fn load(id: &str) -> Result<Self> {
anyhow::ensure!(valid_id(id), "bad run id {id:?}");
let p = runs_dir().join(format!("{id}.json"));
let mut r: Run =
serde_json::from_slice(&std::fs::read(&p).with_context(|| format!("run {id}"))?)?;
r.reconcile()?;
Ok(r)
}
pub fn list() -> Result<Vec<Self>> {
let mut v = vec![];
let Ok(rd) = std::fs::read_dir(runs_dir()) else {
return Ok(v);
};
for e in rd.flatten() {
if let Some(id) = e.file_name().to_str().and_then(|n| n.strip_suffix(".json")) {
v.push(Self::load(id)?);
}
}
v.sort_by(|a, b| (a.started, &a.id).cmp(&(b.started, &b.id)));
Ok(v)
}
/// An active run whose orchestrator died (crash, kill -9, reboot) is marked failed/interrupted and
/// its hx process group is killed, so status never lies and no orphan keeps spending tokens.
/// ponytail: pid reuse can make a dead orch look alive; store a start time (or flock) in O4.
pub fn reconcile(&mut self) -> Result<()> {
if self.status.active() && !alive(self.orch_pid) {
if let Some(p) = self.hx_pid {
kill_group(p);
}
self.status = Status::Failed;
self.reason = Some("interrupted".into());
self.ended = Some(now());
self.save()?;
}
Ok(())
}
}
pub fn alive(pid: u32) -> bool {
// SAFETY: signal 0 only checks existence.
unsafe { libc::kill(pid as i32, 0) == 0 || *libc::__errno_location() == libc::EPERM }
}
pub fn kill_group(pgid: u32) {
// SAFETY: plain syscall; hx is spawned with process_group(0) so pgid == its pid.
unsafe { libc::killpg(pgid as i32, libc::SIGKILL) };
}
#[cfg(test)]
mod tests {
use super::*;
fn sample(id: &str, pid: u32) -> Run {
Run {
id: id.into(),
title: "t".into(),
profile: "p".into(),
repo: "/r".into(),
branch: "b".into(),
worktree: "/w".into(),
status: Status::Running,
reason: None,
orch_pid: pid,
hx_pid: None,
started: 1,
ended: None,
hx_exit: None,
gate_exit: None,
input_tokens: 0,
output_tokens: 0,
session: None,
}
}
#[test]
fn roundtrip_and_stale_detection() {
let d = std::env::temp_dir().join(format!("orch-state-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
// SAFETY: single test touching this var; other tests in this binary do not read it.
unsafe { std::env::set_var("ORCH_STATE_DIR", &d) };
let mut c = std::process::Command::new("true").spawn().unwrap();
let dead = c.id();
c.wait().unwrap();
sample("live", std::process::id()).save().unwrap();
sample("dead", dead).save().unwrap();
let live = Run::load("live").unwrap();
assert_eq!(live.status, Status::Running);
let dead = Run::load("dead").unwrap();
assert_eq!(
(dead.status, dead.reason.as_deref()),
(Status::Failed, Some("interrupted"))
);
assert_eq!(Run::list().unwrap().len(), 2);
assert!(Run::load("../x").is_err());
let _ = std::fs::remove_dir_all(&d);
}
}