- machine.rs: TOML machine parser/validator, four example machines - db.rs: per-goal SQLite (.hx/orch.db) with append-only events - runner.rs: session runner for computer steps (catches, retries, resume) - view.rs + tui/: sessions overview built from events; bare `orch` opens it - orch session: create and run a session from the CLI - devenv with git and sqlite Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
426 lines
15 KiB
Rust
426 lines
15 KiB
Rust
mod adapter;
|
|
mod db;
|
|
mod lock;
|
|
mod machine;
|
|
mod policy;
|
|
mod profile;
|
|
mod report;
|
|
mod run;
|
|
mod runner;
|
|
mod state;
|
|
mod tui;
|
|
mod view;
|
|
|
|
use anyhow::{Context, Result, bail};
|
|
use clap::{Parser, Subcommand};
|
|
use std::collections::VecDeque;
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::Mutex;
|
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
|
|
|
#[derive(Parser)]
|
|
#[command(
|
|
version,
|
|
about = "Run hx coding agents on tasks; without a subcommand, opens the TUI"
|
|
)]
|
|
struct Cli {
|
|
#[command(subcommand)]
|
|
cmd: Option<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,
|
|
},
|
|
/// Run every task the profile's source lists, one after another (parallel pool: O4).
|
|
Pull {
|
|
#[arg(long, default_value = "default")]
|
|
profile: String,
|
|
/// Stop after N claimed tasks.
|
|
#[arg(long)]
|
|
limit: Option<usize>,
|
|
},
|
|
/// Success rate, tokens, retries and duration per profile and hx version, from the telemetry log.
|
|
Report {
|
|
/// Telemetry file (default: <state>/telemetry.jsonl).
|
|
file: Option<PathBuf>,
|
|
},
|
|
/// Compare two telemetry files per case; exit 1 when B's success rate is below A's.
|
|
Eval { a: PathBuf, b: PathBuf },
|
|
/// Run the eval cases in DIR (task.md, files/, gate.sh each) through a profile; writes telemetry to --out.
|
|
Bench {
|
|
dir: PathBuf,
|
|
#[arg(long, default_value = "default")]
|
|
profile: String,
|
|
#[arg(long)]
|
|
out: Option<PathBuf>,
|
|
/// Runs per case.
|
|
#[arg(long, default_value_t = 1)]
|
|
repeat: u32,
|
|
/// Only this case.
|
|
#[arg(long)]
|
|
case: Option<String>,
|
|
/// No hx: check that every case fails untouched and passes with its solution/ overlay.
|
|
#[arg(long)]
|
|
check: bool,
|
|
},
|
|
/// Create a state-machine session in REPO and run it to the end (computer steps only for now).
|
|
Session {
|
|
#[arg(long)]
|
|
repo: PathBuf,
|
|
/// Machine file name, without .toml (looked up in REPO/.hx/machines, then ~/.hx/machines).
|
|
#[arg(long)]
|
|
machine: String,
|
|
#[arg(long)]
|
|
name: String,
|
|
/// Value for {{scope}} in machine commands.
|
|
#[arg(long, default_value = "")]
|
|
scope: String,
|
|
},
|
|
/// hx extension that enforces a run's tool allowlist (started by hx, not by hand).
|
|
#[command(hide = true)]
|
|
Guard { policy: PathBuf },
|
|
/// Print the audit log, optionally only one run's lines.
|
|
Audit { id: Option<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 code(ok: bool) -> std::process::ExitCode {
|
|
u8::from(!ok).into()
|
|
}
|
|
|
|
fn main() -> Result<std::process::ExitCode> {
|
|
let Some(cmd) = Cli::parse().cmd else {
|
|
tui::run()?;
|
|
return Ok(code(true));
|
|
};
|
|
match cmd {
|
|
Cmd::Session {
|
|
repo,
|
|
machine,
|
|
name,
|
|
scope,
|
|
} => {
|
|
let repo = repo.canonicalize()?;
|
|
let m = machine::Machine::find(&machine, &repo)?;
|
|
let db = db::Db::open(&repo.join(".hx/orch.db"))?;
|
|
// shortcut: worktrees are grouped by repo directory name; two repos with one name would share ids
|
|
let base = repo.file_name().unwrap_or_default();
|
|
let wts = state_dir().join("worktrees").join(base);
|
|
let s = runner::create(&db, &wts, &name, "", &machine)?;
|
|
let status = runner::run_session(&db, &m, &s.id, &repo, &scope)?;
|
|
println!("{} {} -> {status}", s.id, s.branch);
|
|
Ok(code(status == "merged"))
|
|
}
|
|
Cmd::Run {
|
|
task,
|
|
repo,
|
|
profile,
|
|
} => {
|
|
let p = profile::Profile::load(&profile)?;
|
|
let id = task.file_stem().and_then(|s| s.to_str()).unwrap_or("task");
|
|
let t = adapter::parse_task_md(id, &std::fs::read_to_string(&task)?);
|
|
let r = process(&t, &repo, &profile, &p, None, &report::default_path())?;
|
|
Ok(code(r.status == state::Status::Done))
|
|
}
|
|
Cmd::Pull { profile, limit } => {
|
|
let p = profile::Profile::load(&profile)?;
|
|
let src = adapter::source(p.source.as_ref().context("profile has no [source]")?)?;
|
|
let queue = Mutex::new(src.list()?.into_iter().collect::<VecDeque<_>>());
|
|
let (ok, claimed) = (AtomicBool::new(true), AtomicUsize::new(0));
|
|
let account = p.account(&profile).to_string();
|
|
std::thread::scope(|s| {
|
|
for _ in 0..p.workers {
|
|
s.spawn(|| {
|
|
let res = (|| -> Result<()> {
|
|
loop {
|
|
if lock::paused_until(&account) > state::now() {
|
|
eprintln!(
|
|
"account {account} paused (quota); leaving the rest queued"
|
|
);
|
|
return Ok(());
|
|
}
|
|
let Some(t) = queue.lock().unwrap().pop_front() else {
|
|
return Ok(());
|
|
};
|
|
let Some(repo) = t.repo.clone().or_else(|| p.repo.clone()) else {
|
|
eprintln!(
|
|
"{}: no repo (task `repo` or profile `repo`), skipped",
|
|
t.id
|
|
);
|
|
ok.store(false, Ordering::SeqCst);
|
|
continue;
|
|
};
|
|
// task lock first: a second orch on the same queue skips what is already taken
|
|
let Some(_held) = lock::task(&profile, &t.id)? else {
|
|
continue;
|
|
};
|
|
if limit
|
|
.is_some_and(|l| claimed.fetch_add(1, Ordering::SeqCst) >= l)
|
|
{
|
|
return Ok(());
|
|
}
|
|
if !src.claim(&t)? {
|
|
continue;
|
|
}
|
|
let r = process(
|
|
&t,
|
|
&repo,
|
|
&profile,
|
|
&p,
|
|
Some(src.as_ref()),
|
|
&report::default_path(),
|
|
)?;
|
|
if r.status != state::Status::Done
|
|
&& r.status != state::Status::Requeued
|
|
{
|
|
ok.store(false, Ordering::SeqCst);
|
|
}
|
|
}
|
|
})();
|
|
if let Err(e) = res {
|
|
eprintln!("worker: {e:#}");
|
|
ok.store(false, Ordering::SeqCst);
|
|
}
|
|
});
|
|
}
|
|
});
|
|
Ok(code(ok.load(Ordering::SeqCst)))
|
|
}
|
|
Cmd::Report { file } => {
|
|
print!(
|
|
"{}",
|
|
report::report(&report::load(&file.unwrap_or_else(report::default_path))?)
|
|
);
|
|
Ok(0.into())
|
|
}
|
|
Cmd::Eval { a, b } => {
|
|
let (text, regressed) = report::compare(
|
|
&report::load(&a)?,
|
|
&report::load(&b)?,
|
|
&a.to_string_lossy(),
|
|
&b.to_string_lossy(),
|
|
);
|
|
print!("{text}");
|
|
Ok(code(!regressed))
|
|
}
|
|
Cmd::Bench {
|
|
dir,
|
|
profile,
|
|
out,
|
|
repeat,
|
|
case,
|
|
check,
|
|
} => bench(&dir, &profile, out, repeat, case.as_deref(), check),
|
|
Cmd::Guard { policy } => {
|
|
policy::guard(&policy)?;
|
|
Ok(0.into())
|
|
}
|
|
Cmd::Audit { id } => {
|
|
let log = std::fs::read_to_string(policy::audit_path()).unwrap_or_default();
|
|
let pat = id.map(|i| format!("\"run\":{}", serde_json::json!(i)));
|
|
for l in log
|
|
.lines()
|
|
.filter(|l| pat.as_ref().is_none_or(|p| l.contains(p.as_str())))
|
|
{
|
|
println!("{l}");
|
|
}
|
|
Ok(0.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} {:<11} {:>5}s {:>8} tok {}{}",
|
|
r.id,
|
|
st.as_str().unwrap(),
|
|
end.saturating_sub(r.started),
|
|
r.total_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())
|
|
}
|
|
}
|
|
}
|
|
|
|
/// One task through the pipeline: run, publish via the sink when done, report to the source.
|
|
/// A failing adapter never loses the run: the error is printed and kept in `published`.
|
|
fn process(
|
|
t: &adapter::Task,
|
|
repo: &Path,
|
|
profile: &str,
|
|
p: &profile::Profile,
|
|
src: Option<&dyn adapter::Source>,
|
|
telemetry: &Path,
|
|
) -> Result<state::Run> {
|
|
let mut r = run::new_run(t, repo, profile)?;
|
|
if p.allow.is_none() && !p.sandbox {
|
|
eprintln!(
|
|
"warning: profile {profile} has no `allow` list and no sandbox: hx may use every tool"
|
|
);
|
|
}
|
|
let id = r.id.clone();
|
|
let audit = |ev: &str, d: serde_json::Value| policy::audit(&policy::audit_path(), &id, ev, d);
|
|
audit(
|
|
"run_start",
|
|
serde_json::json!({"profile": profile, "repo": repo, "allow": p.allow, "sandbox": p.sandbox, "yolo": p.yolo, "task": t.id}),
|
|
);
|
|
run::execute(&mut r, p, t)?;
|
|
audit(
|
|
"run_end",
|
|
serde_json::json!({"status": r.status, "reason": r.reason, "attempts": r.attempts}),
|
|
);
|
|
// a telemetry failure must not lose the run
|
|
if let Err(e) = report::append(telemetry, &report::rec(&r, &report::hx_version(p))) {
|
|
eprintln!("{}: telemetry: {e:#}", r.id);
|
|
}
|
|
if r.status == state::Status::Done {
|
|
match adapter::sink(p.sink.as_ref()).and_then(|s| s.publish(t, &r)) {
|
|
Ok(note) => r.published = note,
|
|
Err(e) => {
|
|
eprintln!("{}: publish failed: {e:#}", r.id);
|
|
r.published = Some(format!("publish-failed: {e:#}"));
|
|
}
|
|
}
|
|
r.save()?;
|
|
}
|
|
if let Some(src) = src
|
|
&& let Err(e) = src.report(t, &r)
|
|
{
|
|
eprintln!("{}: report failed: {e:#}", r.id);
|
|
}
|
|
println!(
|
|
"{} {}{}{}",
|
|
r.id,
|
|
serde_json::to_value(r.status)?.as_str().unwrap(),
|
|
r.reason
|
|
.as_ref()
|
|
.map(|x| format!(" ({x})"))
|
|
.unwrap_or_default(),
|
|
r.published
|
|
.as_ref()
|
|
.map(|x| format!(" -> {x}"))
|
|
.unwrap_or_default()
|
|
);
|
|
Ok(r)
|
|
}
|
|
|
|
/// `orch bench`: every case gets a fresh git repo of its files and its own gate (`gate.sh`); the profile decides
|
|
/// everything else (hx, allowlist, retries, budget). Sink and source are ignored: nothing is published.
|
|
fn bench(
|
|
dir: &Path,
|
|
profile: &str,
|
|
out: Option<PathBuf>,
|
|
repeat: u32,
|
|
only: Option<&str>,
|
|
check: bool,
|
|
) -> Result<std::process::ExitCode> {
|
|
let mut cases = report::cases(dir)?;
|
|
if let Some(o) = only {
|
|
cases.retain(|c| c.name == o);
|
|
anyhow::ensure!(!cases.is_empty(), "no case named {o:?}");
|
|
}
|
|
if check {
|
|
return bench_check(&cases);
|
|
}
|
|
let mut p = profile::Profile::load(profile)?;
|
|
(p.source, p.sink) = (None, None);
|
|
let out = out.unwrap_or_else(|| state_dir().join("bench.jsonl"));
|
|
let mut ok = true;
|
|
for c in &cases {
|
|
for _ in 0..repeat {
|
|
let repo = report::fixture(c)?;
|
|
let gate = c.dir.join("gate.sh").canonicalize()?;
|
|
p.gate = Some(format!("sh {}", gate.display()));
|
|
let t =
|
|
adapter::parse_task_md(&c.name, &std::fs::read_to_string(c.dir.join("task.md"))?);
|
|
ok &= process(&t, &repo, profile, &p, None, &out)?.status == state::Status::Done;
|
|
}
|
|
}
|
|
println!("telemetry: {}", out.display());
|
|
Ok(code(ok))
|
|
}
|
|
|
|
/// Case-set sanity without an agent: the gate must fail on the untouched files and pass after `solution/`.
|
|
fn bench_check(cases: &[report::Case]) -> Result<std::process::ExitCode> {
|
|
let gate = |dir: &Path, g: &Path| -> Result<bool> {
|
|
Ok(std::process::Command::new("sh")
|
|
.arg(g)
|
|
.current_dir(dir)
|
|
.output()?
|
|
.status
|
|
.success())
|
|
};
|
|
let mut ok = true;
|
|
for c in cases {
|
|
let g = c.dir.join("gate.sh").canonicalize()?;
|
|
let repo = report::fixture(c)?;
|
|
let before = gate(&repo, &g)?;
|
|
let sol = c.dir.join("solution");
|
|
let after = if sol.is_dir() {
|
|
std::process::Command::new("cp")
|
|
.arg("-R")
|
|
.arg(format!("{}/.", sol.display()))
|
|
.arg(&repo)
|
|
.status()?;
|
|
Some(gate(&repo, &g)?)
|
|
} else {
|
|
None
|
|
};
|
|
let good = !before && after != Some(false);
|
|
let solved = match after {
|
|
None => "no solution/",
|
|
Some(true) => "pass",
|
|
Some(false) => "FAIL (bad)",
|
|
};
|
|
let untouched = if before { "PASS (bad)" } else { "fail" };
|
|
let flag = if good { "" } else { " <-- broken case" };
|
|
println!("{:<20} untouched={untouched} solved={solved}{flag}", c.name);
|
|
ok &= good;
|
|
}
|
|
Ok(code(ok))
|
|
}
|