//! 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 -> (retry: running) -> done | failed | needs-human | requeued. #[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)] #[serde(rename_all = "kebab-case")] pub enum Status { Queued, Running, Gating, Done, Failed, /// Provider quota used up: account paused, the task runs again later as a new run. Requeued, /// Gate still red after all retries: branch holds the best attempt, gate output in `ID.gate.log`. NeedsHuman, } impl Run { /// Everything the model processed: fresh + cached input + output. pub fn total_tokens(&self) -> u64 { self.input_tokens + self.cache_read_tokens + self.cache_write_tokens + self.output_tokens } } 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, /// Task id from the source (eval: case name). #[serde(default)] pub task: 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, /// Fresh (uncached) input only; with the cache fields below this is everything hx sent. pub input_tokens: u64, pub output_tokens: u64, #[serde(default)] pub cache_read_tokens: u64, #[serde(default)] pub cache_write_tokens: u64, pub session: Option, /// hx runs so far (1 + retries). #[serde(default)] pub attempts: u32, /// Budget counters, summed over all attempts. #[serde(default)] pub turns: u64, #[serde(default)] pub spent_tokens: u64, /// Tool calls the policy denied (soft denies that the agent got to answer, plus the one that stopped the run). #[serde(default)] pub denies: u32, /// Sink result (PR URL, branch note) once published. #[serde(default)] pub published: Option, /// Unix time a full quota window resets (seen in this run's hx events). #[serde(default)] pub quota_until: Option, } pub fn now() -> u64 { now_ms() / 1000 } pub fn now_ms() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_millis() as u64) } pub fn runs_dir() -> PathBuf { crate::state_dir().join("runs") } pub fn gate_log_path(id: &str) -> PathBuf { runs_dir().join(format!("{id}.gate.log")) } 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. /// Liveness = the run's flock (held by the executing orch for the whole run, released by the kernel on /// death), so pid reuse cannot fake a live run. pub fn reconcile(&mut self) -> Result<()> { if self.status.active() && crate::lock::run(&self.id)?.is_some() { 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 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(), task: "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, cache_read_tokens: 0, cache_write_tokens: 0, session: None, attempts: 0, turns: 0, spent_tokens: 0, denies: 0, published: None, quota_until: 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) }; sample("live", 1).save().unwrap(); sample("dead", 1).save().unwrap(); let _held = crate::lock::run("live").unwrap().unwrap(); // the live run's orch holds its lock 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); } }