//! One run: worktree -> hx (NDJSON, budgets, process group) -> commit -> gate -> final state. use crate::adapter::Task; use crate::lock; use crate::policy::{self, Decision, Policy}; use crate::profile::{OnDeny, Profile}; use crate::state::{Run, Status, gate_log_path, 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}; pub(crate) 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()) } pub fn new_run(task: &Task, repo: &Path, profile: &str) -> Result { let stem = task.id.as_str(); let stem: String = stem .chars() .map(|c| { if c.is_ascii_alphanumeric() || c == '-' { c } else { '-' } }) .collect(); // ms, not s: a requeued task can start again within the same second and must not reuse the branch name let id = format!("{stem}-{}", crate::state::now_ms()); 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: task.title.clone(), task: task.id.clone(), 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, cache_read_tokens: 0, cache_write_tokens: 0, session: None, attempts: 0, turns: 0, spent_tokens: 0, denies: 0, published: None, quota_until: 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() } /// Environment hx gets: a fixed base plus the profile's `env` patterns. `HX_HOME` only when the profile has no /// own `home` (otherwise it would point back at another identity). pub fn hx_env(vars: impl Iterator, p: &Profile) -> Vec<(String, String)> { const BASE: &[&str] = &[ "PATH", "HOME", "USER", "LOGNAME", "SHELL", "TERM", "LANG", "LC_*", "TMPDIR", "CARGO_*", "RUST*", "NIX_*", ]; vars.filter(|(k, _)| { BASE.iter().any(|b| policy::glob(b, k)) || p.env.iter().any(|b| policy::glob(b, k)) || (k == "HX_HOME" && p.home.is_none()) }) .collect() } /// All tokens of one hx usage object. hx reports `input_tokens` as the uncached part only, so cached input /// (`cache_read_tokens`, `cache_write_tokens`) has to be added or the count is off by orders of magnitude. const USAGE_KEYS: [&str; 4] = [ "input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", ]; fn usage_total(u: &Value) -> u64 { USAGE_KEYS.iter().map(|k| u[*k].as_u64().unwrap_or(0)).sum() } /// The line hx' claude_cli provider writes into the text stream for every tool claude runs: `\n[claude Bash: ls]\n`. fn is_claude_tool_line(t: &str) -> bool { t.starts_with("\n[claude ") && t.ends_with("]\n") && t.len() > 12 } /// hx surfaces provider rejections as `api 429: ...`; also match the usual wording. fn is_rate_limit(reason: &str) -> bool { let r = reason.to_lowercase(); r.contains("api 429") || r.contains("rate limit") || r.contains("rate_limit") || r.contains("usage limit") } /// Max bytes of gate output fed back to hx (the tail: errors are at the end). const GATE_LOG_LIMIT: usize = 8000; pub(crate) fn tail(b: &[u8], limit: usize) -> String { let s = String::from_utf8_lossy(&b[b.len().saturating_sub(limit)..]).into_owned(); s.trim_start_matches('\u{FFFD}').to_string() } fn retry_prompt(gate: &str, code: Option, out: &[u8], resumed: bool, body: &str) -> String { let task = if resumed { String::new() } else { format!("Task:\n{body}\n\n") }; format!( "{task}The check `{gate}` failed (exit {}). Fix the code so it passes. Output (last {GATE_LOG_LIMIT} bytes):\n{}", code.map_or("signal".into(), |c| c.to_string()), tail(out, GATE_LOG_LIMIT) ) } /// Runs the whole pipeline. Errors only for orch-internal problems; task failures end as `Failed` or /// `NeedsHuman` state. After a failed gate hx gets the gate output on the same session, up to `max_retries`. pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> { let body = task.body.clone(); // held until return: proves the run is alive to `Run::reconcile` in any other orch process let _alive = lock::run(&r.id)?; r.save()?; let account = p.account(&r.profile).to_string(); let _slot = lock::slot(&account, p.max_concurrent.unwrap_or(p.workers))?; let until = lock::paused_until(&account); if until > now() { r.status = Status::Requeued; r.reason = Some(format!("quota-paused until {until}")); r.ended = Some(now()); return r.save(); } std::fs::create_dir_all(r.worktree.parent().unwrap())?; let wt = r.worktree.to_string_lossy().into_owned(); let added = { let _repo = lock::repo(&r.repo)?; // git races on its own locks when worktrees are added in parallel git(&r.repo, &["worktree", "add", "-b", &r.branch, &wt, "HEAD"]) }; if let Err(e) = added { fail(r, format!("setup: {e}"))?; return Ok(()); } let mut log = std::fs::File::create(log_path(&r.id))?; let mut prompt = body.clone(); let mut session: Option = None; loop { r.attempts += 1; r.quota_until = None; // per attempt: only a window seen in THIS attempt can excuse its failure r.status = Status::Running; r.save()?; writeln!(log, "\n--- attempt {}", r.attempts)?; // rewritten before every attempt: an agent that tampered with it is healed let pol = match p.allow.as_ref().map(|a| { policy::install( &r.id, &r.worktree, a, &p.read_roots, p.on_deny == OnDeny::Continue, ) }) { Some(Err(e)) => return fail(r, format!("setup: {e:#}")), Some(Ok(pol)) => Some(pol), None => None, }; let reason = run_hx(r, p, &prompt, session.as_deref(), pol.as_ref(), &mut log)?; if pol.is_some() { policy::uninstall(&r.worktree); } 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"])?; let msg = format!("orch: {} (attempt {})", r.title, r.attempts); git(&r.worktree, &["commit", "-qm", &msg])?; } if let Some(until) = r.quota_until { lock::pause(&account, until)?; // every full window pauses the account, even after a clean run } if let Some(reason) = reason { if reason.starts_with("policy:") { // the agent wanted something the profile does not allow: a human decides r.status = Status::NeedsHuman; r.reason = Some(reason); r.ended = Some(now()); return r.save(); } if r.quota_until.is_some() || is_rate_limit(&reason) { // provider said no: not the task's fault. Pause the account and hand the task back. lock::pause(&account, r.quota_until.unwrap_or(now() + 900))?; r.status = Status::Requeued; r.reason = Some(format!("quota: {reason}")); r.ended = Some(now()); return r.save(); } return fail(r, reason); } let Some(gate) = &p.gate else { break }; r.status = Status::Gating; r.save()?; writeln!(log, "\n--- gate: {gate}")?; // ponytail: no gate timeout; a hanging gate hangs the run. Add gate_secs when it bites. let o = Command::new("sh") .args(["-c", &format!("({gate}) 2>&1")]) .current_dir(&r.worktree) .output()?; log.write_all(&o.stdout)?; r.gate_exit = o.status.code(); if o.status.success() { break; } std::fs::write(gate_log_path(&r.id), &o.stdout)?; if r.attempts > p.max_retries { r.status = Status::NeedsHuman; r.reason = Some("gate-failed".into()); r.ended = Some(now()); return r.save(); } session = r.session.clone(); prompt = retry_prompt(gate, r.gate_exit, &o.stdout, session.is_some(), &body); } r.status = Status::Done; r.reason = None; 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, session: Option<&str>, pol: Option<&Policy>, 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 let Some(s) = session { cmd.args(["--session", s]); } if p.sandbox { cmd.arg("--sandbox"); } if p.yolo { cmd.arg("--yolo"); } if let Some(prov) = &p.provider { cmd.args(["--provider", prov]); } // cleared environment: orch's own secrets and another profile's HX_HOME never reach the agent cmd.env_clear().envs(hx_env(std::env::vars(), p)); 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 done = None::; // usage per component from the stream `done` events of THIS attempt: the final `done` line never comes when // the run is stopped (guard, budget, timeout), and those runs would otherwise report 0 tokens let mut seen = [0u64; 4]; // claude_cli: claude runs the tools; hx prints a `[claude TOOL: ...]` line per tool use and (hx#182) reports // each one as a tool_call event so the guard can decide. Fewer events than lines = something ran unseen. let (mut claude_lines, mut calls) = (0u32, 0u32); let mut seen_ids = std::collections::HashSet::::new(); 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") => { r.turns += 1; if p.budget.max_turns.is_some_and(|m| r.turns > m) { killed = Some("budget:turns".to_string()); } } Some("stream") if pol.is_some() && ev["event"]["type"] == "text_delta" && is_claude_tool_line( ev["event"]["text"].as_str().unwrap_or_default(), ) => { claude_lines += 1; } Some("tool_call") if pol.is_some() => { calls += 1; seen_ids.insert(ev["id"].as_str().unwrap_or_default().to_string()); // second line of defence: hx treats a dead or slow guard as "continue" let name = ev["name"].as_str().unwrap_or_default(); let d = pol.unwrap().decide(name, &ev["args"]); // soft denies under on_deny=continue are answered by the guard (the tool never runs); // everything else is a reason to stop the run let stop = match &d { Decision::Hard(_) => true, Decision::Deny(_) => p.on_deny == OnDeny::Stop, Decision::Allow(_) => false, }; if let Some(why) = d.deny_reason() { r.denies += 1; if stop { // the guard may not have logged yet (we read the event first): log it here too policy::audit( &policy::audit_path(), &r.id, "tool", serde_json::json!({"tool": name, "decision": "deny", "why": why, "args": ev["args"], "by": "orch"}), ); killed = Some(format!("policy: {why}")); } } } Some("tool_result") if pol.is_some() && ev["is_error"] == true && (ev["content"].to_string().contains(policy::PREFIX) || ev["content"].to_string().contains(policy::SOFT_PREFIX)) => { let c = ev["content"].as_str().unwrap_or_default(); if c.contains(policy::SOFT_PREFIX) { // soft deny answered to the agent (on_deny = continue): the guard saw the call even // though no tool_call line reached this stream; count it, keep the run going if !seen_ids.contains(ev["id"].as_str().unwrap_or_default()) { calls += 1; r.denies += 1; } } else { // hard (or `stop`-mode) deny: counted unless the tool_call event of the same id was // already evaluated by the stream check above if !seen_ids.contains(ev["id"].as_str().unwrap_or_default()) { r.denies += 1; } let why = c.split_once(policy::PREFIX).map_or(c, |(_, w)| w.trim()); killed = Some(format!("policy: {why}")); } } Some("stream") if ev["event"]["type"] == "quota" => { let full: Vec<&Value> = ev["event"]["windows"] .as_array() .map(|w| { w.iter() .filter(|w| w["used_pct"].as_f64().unwrap_or(0.0) >= 99.5) .collect() }) .unwrap_or_default(); if !full.is_empty() { let reset = full.iter().filter_map(|w| w["resets_at"].as_u64()).max(); r.quota_until = Some(reset.unwrap_or(now() + 3600)); } } Some("stream") if ev["event"]["type"] == "done" => { let u = &ev["event"]["usage"]; for (s, k) in seen.iter_mut().zip(USAGE_KEYS) { *s += u[k].as_u64().unwrap_or(0); } r.spent_tokens += usage_total(u); if p.budget.max_tokens.is_some_and(|m| r.spent_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"]; let f = |k: &str| u[k].as_u64().unwrap_or(0); r.input_tokens = f("input_tokens"); r.output_tokens = f("output_tokens"); r.cache_read_tokens = f("cache_read_tokens"); r.cache_write_tokens = f("cache_write_tokens"); r.session = d["session"].as_str().map(String::from); } else { // killed before the final `done`: keep what the stream reported (a lower bound, never less than before) r.input_tokens = r.input_tokens.max(seen[0]); r.output_tokens = r.output_tokens.max(seen[1]); r.cache_read_tokens = r.cache_read_tokens.max(seen[2]); r.cache_write_tokens = r.cache_write_tokens.max(seen[3]); } if let Some(k) = killed { return Ok(Some(k)); } if pol.is_some() && calls < claude_lines { // fail closed: never call a run guarded when claude used tools hx did not report to the guard return Ok(Some(format!( "policy: claude used {claude_lines} tool(s) but hx reported {calls} tool_call event(s); the allowlist \ could not be enforced for this run (hx without claude_cli tool events, see johannes/hx#182)" ))); } 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 env_tests { use super::*; fn vars(names: &[&str]) -> Vec<(String, String)> { names.iter().map(|n| (n.to_string(), "v".into())).collect() } fn keys(p: &str, names: &[&str]) -> Vec { let p = Profile::parse(p).unwrap(); hx_env(vars(names).into_iter(), &p) .into_iter() .map(|(k, _)| k) .collect() } #[test] fn env_is_filtered() { let all = [ "PATH", "LC_ALL", "CARGO_HOME", "AWS_SECRET_ACCESS_KEY", "GITEA_TOKEN", "HX_HOME", "HX_BASE_URL", "ORCH_STATE_DIR", ]; assert_eq!( keys("", &all), ["PATH", "LC_ALL", "CARGO_HOME", "HX_HOME"], "HX_HOME passes without own home" ); assert_eq!( keys("home = \"/h\"", &all), ["PATH", "LC_ALL", "CARGO_HOME"], "own home drops HX_HOME" ); assert_eq!( keys("env = [\"HX_BASE_URL\", \"GITEA_*\"]\nhome = \"/h\"", &all), ["PATH", "LC_ALL", "CARGO_HOME", "GITEA_TOKEN", "HX_BASE_URL"] ); } }