Adds orch session --restart sN and R in the TUI. A restart event gives the session fresh budgets and retry counts. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
600 lines
22 KiB
Rust
600 lines
22 KiB
Rust
mod acp;
|
|
mod adapter;
|
|
mod budget;
|
|
mod checks;
|
|
mod db;
|
|
mod detail;
|
|
mod goal;
|
|
mod init;
|
|
mod junit;
|
|
mod lock;
|
|
mod machine;
|
|
mod place;
|
|
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(
|
|
// CI sets ORCH_VERSION to the release version; local builds use Cargo's
|
|
version = option_env!("ORCH_VERSION").unwrap_or(env!("CARGO_PKG_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 {
|
|
/// Write example machines to REPO/.hx/machines and an example profile to the config dir.
|
|
Init {
|
|
#[arg(long, default_value = ".")]
|
|
repo: PathBuf,
|
|
/// Overwrite files that already exist.
|
|
#[arg(long)]
|
|
force: bool,
|
|
},
|
|
/// 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,
|
|
},
|
|
/// Show or set the goal sentence; `--export` also prints the acceptance checks (for machine steps).
|
|
Goal {
|
|
/// New goal text.
|
|
text: Option<String>,
|
|
#[arg(long)]
|
|
export: bool,
|
|
/// Repo with the goal (default: ORCH_DB of a machine step, else the current directory).
|
|
#[arg(long)]
|
|
repo: Option<PathBuf>,
|
|
},
|
|
/// Add an acceptance check: a shell command, pass = exit 0.
|
|
Check {
|
|
name: String,
|
|
cmd: String,
|
|
/// Session that is responsible for it (its `run-acceptance` step runs it before merging).
|
|
#[arg(long)]
|
|
owner: Option<String>,
|
|
#[arg(long)]
|
|
repo: Option<PathBuf>,
|
|
},
|
|
/// Run acceptance checks in the current directory (a worktree), or with --main in a clean copy of main.
|
|
Checks {
|
|
/// Only the checks this session owns.
|
|
#[arg(long)]
|
|
owner: Option<String>,
|
|
/// All checks on main; the results are recorded for the goal view.
|
|
#[arg(long)]
|
|
main: bool,
|
|
#[arg(long)]
|
|
repo: Option<PathBuf>,
|
|
},
|
|
/// Create a state-machine session in REPO and run it to the end. Waits for `--after` sessions to merge.
|
|
Session {
|
|
/// Sessions that must be merged before this one starts, comma separated.
|
|
#[arg(long, value_delimiter = ',')]
|
|
after: Vec<String>,
|
|
#[arg(long)]
|
|
repo: PathBuf,
|
|
/// Machine file name, without .toml (looked up in REPO/.hx/machines, then ~/.hx/machines).
|
|
#[arg(long, required_unless_present_any = ["resume", "restart"])]
|
|
machine: Option<String>,
|
|
#[arg(long, required_unless_present_any = ["resume", "restart"])]
|
|
name: Option<String>,
|
|
/// Continue this unfinished session (e.g. s1) from its saved state instead of creating one.
|
|
#[arg(long, conflicts_with_all = ["machine", "name", "after", "restart"])]
|
|
resume: Option<String>,
|
|
/// Continue this failed or escalated session at the state where it stopped, with fresh budgets and retries.
|
|
#[arg(long, conflicts_with_all = ["machine", "name", "after"])]
|
|
restart: Option<String>,
|
|
/// Value for {{scope}} in machine commands.
|
|
#[arg(long, default_value = "")]
|
|
scope: String,
|
|
/// Profile that says how to start hx for agent steps.
|
|
#[arg(long, default_value = "default")]
|
|
profile: 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")
|
|
}
|
|
|
|
/// The goal database: `--repo`, else `ORCH_DB` (set by the runner for machine steps), else `./.hx/orch.db`.
|
|
fn open_db(repo: Option<&Path>) -> Result<db::Db> {
|
|
if repo.is_none()
|
|
&& let Some(p) = std::env::var_os("ORCH_DB")
|
|
{
|
|
return db::Db::open(Path::new(&p));
|
|
}
|
|
let dir = match repo {
|
|
Some(r) => r.to_path_buf(),
|
|
None => std::env::current_dir()?,
|
|
};
|
|
db::Db::open(&dir.join(".hx/orch.db"))
|
|
}
|
|
|
|
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::Init { repo, force } => {
|
|
let written = init::run(&repo, &config_dir(), force)?;
|
|
for p in &written {
|
|
println!("wrote {}", p.display());
|
|
}
|
|
if written.is_empty() {
|
|
println!("nothing to do (use --force to overwrite)");
|
|
}
|
|
Ok(code(true))
|
|
}
|
|
Cmd::Goal { text, export, repo } => {
|
|
let db = open_db(repo.as_deref())?;
|
|
if let Some(t) = text {
|
|
db.set_goal(&t)?;
|
|
}
|
|
println!("{}", db.goal()?.unwrap_or_else(|| "no goal set".into()));
|
|
if export {
|
|
println!("\nAcceptance checks (all must pass on main):");
|
|
for c in db.checks()? {
|
|
let owner = c.owner.map_or(String::new(), |o| format!(" [{o}]"));
|
|
println!("- {}{owner}: {}", c.name, c.cmd);
|
|
}
|
|
}
|
|
Ok(code(true))
|
|
}
|
|
Cmd::Check {
|
|
name,
|
|
cmd,
|
|
owner,
|
|
repo,
|
|
} => {
|
|
let id = open_db(repo.as_deref())?.add_check(&name, &cmd, owner.as_deref())?;
|
|
println!("check {id}: {name}");
|
|
Ok(code(true))
|
|
}
|
|
Cmd::Checks { owner, main, repo } => {
|
|
let db = open_db(repo.as_deref())?;
|
|
let results = if main {
|
|
let repo = match (repo, std::env::var_os("ORCH_REPO")) {
|
|
(Some(r), _) => r,
|
|
(None, Some(r)) => r.into(),
|
|
(None, None) => std::env::current_dir()?,
|
|
};
|
|
checks::run_on_main(&db, &repo)?
|
|
} else {
|
|
checks::run(&db, &std::env::current_dir()?, owner.as_deref(), false)?
|
|
};
|
|
for r in &results {
|
|
if r.pass {
|
|
println!("✓ {}", r.check.name);
|
|
} else {
|
|
println!("✗ {} (exit {})", r.check.name, r.exit.unwrap_or(-1));
|
|
print!("{}", r.output);
|
|
}
|
|
}
|
|
Ok(code(results.iter().all(|r| r.pass)))
|
|
}
|
|
Cmd::Session {
|
|
after,
|
|
repo,
|
|
machine,
|
|
name,
|
|
resume,
|
|
restart,
|
|
scope,
|
|
profile,
|
|
} => {
|
|
let profile = profile::Profile::load(&profile)?;
|
|
let repo = repo.canonicalize()?;
|
|
let db = db::Db::open(&repo.join(".hx/orch.db"))?;
|
|
if let Some(id) = &restart {
|
|
db.reopen(id)?;
|
|
}
|
|
let s = if let Some(id) = resume.or(restart) {
|
|
let s = db
|
|
.session(&id)?
|
|
.with_context(|| format!("no session {id}"))?;
|
|
anyhow::ensure!(
|
|
!db.events(Some(&id), 0)?
|
|
.iter()
|
|
.rfind(|e| matches!(e.kind.as_str(), "end" | "restart"))
|
|
.is_some_and(|e| e.kind == "end"),
|
|
"session {id} already ended; --restart continues a failed or escalated one, else start a new one"
|
|
);
|
|
anyhow::ensure!(
|
|
s.pid
|
|
.is_none_or(|p| !Path::new(&format!("/proc/{p}")).exists()
|
|
|| p == std::process::id()),
|
|
"session {id} is still running (pid {})",
|
|
s.pid.unwrap_or(0)
|
|
);
|
|
s
|
|
} else {
|
|
// 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 (machine, name) = (machine.unwrap_or_default(), name.unwrap_or_default());
|
|
machine::Machine::find(&machine, &repo)?;
|
|
runner::create_after(&db, &wts, &name, "", &machine, &after)?
|
|
};
|
|
let task = db
|
|
.tasks()?
|
|
.into_iter()
|
|
.find(|t| t.id == s.task_id)
|
|
.with_context(|| format!("no task {}", s.task_id))?;
|
|
let m = machine::Machine::find(&task.machine, &repo)?;
|
|
let status = runner::run_session(&db, &m, &s.id, &repo, &scope, &profile)?;
|
|
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.sandboxed() {
|
|
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.sandboxed(), "yolo": p.yolo_on(), "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),
|
|
&report::provider_mode(p, &r.worktree),
|
|
),
|
|
) {
|
|
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))
|
|
}
|