From 52de3e16e8b641afa2bf2192bd9e75f49c587572 Mon Sep 17 00:00:00 2001 From: hermes Date: Thu, 12 Nov 2026 23:19:00 +0000 Subject: [PATCH] O1: Rust crate, profiles, persistent run state (closes #2) --- .gitignore | 3 + Cargo.lock | 345 +++++++++++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 13 ++ src/main.rs | 106 +++++++++++++++ src/profile.rs | 99 ++++++++++++++ src/run.rs | 279 +++++++++++++++++++++++++++++++++++++++ src/state.rs | 172 ++++++++++++++++++++++++ tests/all.sh | 10 ++ tests/e2e.py | 101 +++++++++++++++ 9 files changed, 1128 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 src/main.rs create mode 100644 src/profile.rs create mode 100644 src/run.rs create mode 100644 src/state.rs create mode 100644 tests/all.sh create mode 100644 tests/e2e.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..264a04e --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +target/ +__pycache__/ +*.jsonl diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..a715295 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,345 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "orch" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "libc", + "serde", + "serde_json", + "toml", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..429c41b --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "orch" +version = "0.1.0" +edition = "2024" +description = "Orchestrator that runs many hx coding agents" + +[dependencies] +anyhow = "1" +clap = { version = "4", features = ["derive"] } +libc = "0.2" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "0.8" diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..c2ddfc4 --- /dev/null +++ b/src/main.rs @@ -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 }, + /// 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 { + 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()) + } + } +} diff --git a/src/profile.rs b/src/profile.rs new file mode 100644 index 0000000..d15390d --- /dev/null +++ b/src/profile.rs @@ -0,0 +1,99 @@ +//! Profile: `/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, + /// Max `turn_start` events before hx is killed. + pub max_turns: Option, + /// Max input+output tokens, summed over `stream/done` events. + pub max_tokens: Option, +} + +#[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, + pub provider: Option, + #[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, + #[serde(default)] + pub budget: Budget, +} + +fn default_hx() -> String { + "hx".into() +} + +impl Profile { + pub fn parse(s: &str) -> Result { + 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 { + 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()); + } +} diff --git a/src/run.rs b/src/run.rs new file mode 100644 index 0000000..2f96a55 --- /dev/null +++ b/src/run.rs @@ -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 { + 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::>() + .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 { + 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) -> 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> { + 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::(); + 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::); + 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::(&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); + } +} diff --git a/src/state.rs b/src/state.rs new file mode 100644 index 0000000..b97542e --- /dev/null +++ b/src/state.rs @@ -0,0 +1,172 @@ +//! Persistent run state: one JSON file per run in `/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:, interrupted, setup:. + pub reason: Option, + pub orch_pid: u32, + pub hx_pid: Option, + pub started: u64, + pub ended: Option, + pub hx_exit: Option, + pub gate_exit: Option, + pub input_tokens: u64, + pub output_tokens: u64, + pub session: Option, +} + +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 { + 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> { + 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); + } +} diff --git a/tests/all.sh b/tests/all.sh new file mode 100644 index 0000000..1bee427 --- /dev/null +++ b/tests/all.sh @@ -0,0 +1,10 @@ +#!/bin/sh +# Full local gate: fmt, clippy, unit tests, e2e with fake hx, O0 spike check. +cd "$(dirname "$0")/.." +set -e +cargo fmt --all --check +cargo clippy -q --all-targets -- -D warnings +cargo test -q +cargo build -q +python3 tests/e2e.py +python3 spike/check.py diff --git a/tests/e2e.py b/tests/e2e.py new file mode 100644 index 0000000..3df43e8 --- /dev/null +++ b/tests/e2e.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""End-to-end test for the orch binary with a fake hx. Run: python3 tests/e2e.py [path/to/orch]""" +import json, os, pathlib, signal, subprocess, sys, tempfile, time + +root = pathlib.Path(__file__).resolve().parent.parent +orch = sys.argv[1] if len(sys.argv) > 1 else str(root / "target/debug/orch") +tmp = pathlib.Path(tempfile.mkdtemp()) +env = {**os.environ, "ORCH_CONFIG_DIR": str(tmp / "cfg"), "ORCH_STATE_DIR": str(tmp / "state")} +repo = tmp / "repo" +repo.mkdir() +subprocess.run(["git", "init", "-q", "-b", "main"], cwd=repo, check=True) +subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "i"], cwd=repo, check=True) +(tmp / "cfg/profiles").mkdir(parents=True) +fake = tmp / "fake_hx.py" +fake.write_text(''' +import json, sys, time, os +body = sys.argv[sys.argv.index("-p") + 1] +e = lambda o: print(json.dumps(o), flush=True) +e({"type": "session_start"}) +if "NOJSON" in body: sys.exit(1) +if "HANG" in body: + open(os.environ.get("PIDFILE", "/dev/null"), "w").write(str(os.getpid())) + time.sleep(300) +for i in range(int(body.split("TURNS=")[1].split()[0]) if "TURNS=" in body else 1): + e({"type": "turn_start"}) + e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50}}}) +if "WRITE" in body: open("out.txt", "w").write("x") +e({"type": "done", "error": "boom" if "FAIL" in body else None, "usage": {"input_tokens": 100, "output_tokens": 50}, "session": "/s.jsonl"}) +''') + + +def profile(name, extra=""): + (tmp / f"cfg/profiles/{name}.toml").write_text(f'hx = "{sys.executable} {fake}"\n{extra}') + + +def task(name, body): + f = tmp / f"{name}.md" + f.write_text(f"# Title {name}\n{body}\n") + return f + + +def run(name, profile_name="p", **kw): + return subprocess.run([orch, "run", str(task(name, kw.pop("body"))), "--repo", str(repo), "--profile", profile_name], + env={**env, **kw.pop("env", {})}, capture_output=True, text=True, timeout=60) + + +def status(id): + return json.loads(subprocess.run([orch, "status", id], env=env, capture_output=True, text=True).stdout) + + +def check(p, st, reason=None): + id = p.stdout.split()[0] + s = status(id) + assert s["status"] == st and (reason is None or (s["reason"] or "").startswith(reason)), (p.stdout, p.stderr, s) + return s + + +profile("p", 'gate = "test -f out.txt"\n') +s = check(run("ok", body="WRITE"), "done") +assert s["gate_exit"] == 0 and s["input_tokens"] == 100 and s["session"] == "/s.jsonl", s +assert "out.txt" in subprocess.run(["git", "ls-tree", "--name-only", s["branch"]], cwd=repo, capture_output=True, text=True).stdout +check(run("nowrite", body="x"), "failed", "gate-failed") +check(run("hxerr", body="FAIL WRITE"), "failed", "hx-failed: boom") +check(run("nojson", body="NOJSON"), "failed", "hx-failed") + +profile("t", "[budget]\nwall_secs = 1\n") +check(run("slow", "t", body="HANG"), "failed", "timeout") +profile("m", "[budget]\nmax_turns = 2\n") +check(run("turns", "m", body="TURNS=5"), "failed", "budget:turns") +profile("k", "[budget]\nmax_tokens = 200\n") +check(run("tokens", "k", body="TURNS=5"), "failed", "budget:tokens") + +# yolo without sandbox is refused at load time +profile("y", "yolo = true\n") +assert run("yolo", "y", body="x").returncode != 0 + +# kill orch mid-run: status must say interrupted and hx must be dead after the next orch call +pidfile = tmp / "hx.pid" +p = subprocess.Popen([orch, "run", str(task("killed", "HANG")), "--repo", str(repo), "--profile", "p"], + env={**env, "PIDFILE": str(pidfile)}, stdout=subprocess.PIPE, text=True) +for _ in range(100): + if pidfile.exists() and pidfile.read_text(): + break + time.sleep(0.1) +hx_pid = int(pidfile.read_text()) +p.send_signal(signal.SIGKILL) +p.wait() +time.sleep(0.2) +out = subprocess.run([orch, "status"], env=env, capture_output=True, text=True).stdout +line = next(l for l in out.splitlines() if l.startswith("killed-")) +assert "failed" in line and "[interrupted]" in line, out +time.sleep(0.5) +try: + os.kill(hx_pid, 0) + raise AssertionError("orphan hx still alive") +except ProcessLookupError: + pass + +logs = subprocess.run([orch, "logs", s["id"]], env=env, capture_output=True, text=True).stdout +assert '"type": "done"' in logs or '"type":"done"' in logs, logs +print("e2e ok")