//! Session runner (ORCHESTRATOR.md section 4): walks one session through its machine and writes every step to //! the event table. `computer` steps run as shell commands, `agent` steps go to hx over ACP, `human` steps and //! agent questions wait in the Needs-you queue. A session waits for its dependencies before it starts and for its //! turn in the merge queue before it enters the state that ends in `merged`; after the merge all acceptance //! checks run again on main. use crate::acp::{Acp, Poll, Sink, StepResult}; use crate::budget; use crate::db::{Db, Event, Session, Task}; use crate::machine::{BudgetCfg, Kind, Machine, RunOn, State, Step}; use crate::profile::Profile; use crate::run::{git, tail}; use anyhow::{Context, Result, bail}; use serde_json::{Value, json}; use std::cell::{Cell, RefCell}; use std::io::Read; use std::os::unix::process::CommandExt; use std::path::Path; use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; /// Safety cap against catch loops that have no `retry` limit (e.g. build -> code -> build with a no-op code). const MAX_TRANSITIONS: u32 = 500; /// Bytes of step output kept in the event (the `t` key shows it as the full test output). const OUTPUT_TAIL: usize = 8000; /// Creates the task and session rows for a new session. The worktree is made by [`run_session`]. #[cfg(test)] pub fn create( db: &Db, worktrees: &Path, name: &str, subtitle: &str, machine: &str, ) -> Result { create_after(db, worktrees, name, subtitle, machine, &[]) } /// Like [`create`], for a task that may only start once the sessions in `after` have merged. pub fn create_after( db: &Db, worktrees: &Path, name: &str, subtitle: &str, machine: &str, after: &[String], ) -> Result { let id = db.next_session_id()?; for d in after { anyhow::ensure!(db.session(d)?.is_some(), "no session {d} to wait for"); } let slug: String = name .chars() .map(|c| { if c.is_ascii_alphanumeric() || c == '-' { c } else { '-' } }) .collect(); let task = Task { id: id.clone(), name: name.into(), subtitle: subtitle.into(), machine: machine.into(), depends_on: after.to_vec(), }; let s = Session { branch: format!("hx/{id}-{slug}"), worktree: worktrees.join(&id).to_string_lossy().into_owned(), id, task_id: task.id.clone(), pid: None, state: String::new(), status: "queued".into(), }; db.add_task(&task)?; db.add_session(&s)?; Ok(s) } fn render(cmd: &str, s: &Session, scope: &str, repo: &Path) -> String { cmd.replace("{{session}}", &s.id) .replace("{{scope}}", scope) .replace("{{worktree}}", &s.worktree) .replace("{{branch}}", &s.branch) .replace("{{repo}}", &repo.to_string_lossy()) } fn ensure_worktree(repo: &Path, s: &Session) -> Result<()> { let wt = Path::new(&s.worktree); if wt.exists() { return Ok(()); } std::fs::create_dir_all(wt.parent().context("worktree has no parent")?)?; // git races on its own locks when worktrees are added in parallel let _l = crate::lock::lock(&repo.join(".git/orch-worktree.lock"))?; git( repo, &["worktree", "add", "-b", &s.branch, &s.worktree, "HEAD"], )?; Ok(()) } /// Why the runner leaves what it is doing (a command from the user, or a budget). #[derive(Clone, Debug, PartialEq)] enum Stop { /// Abandon the current step and continue in this state. Goto { state: String, why: String }, /// End the session. End { status: &'static str, reason: String, }, } /// Error that unwinds a blocked wait (command, agent step, Needs-you item, queue) because a [`Stop`] is pending. #[derive(Debug)] struct Stopped; impl std::fmt::Display for Stopped { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str("stopped") } } impl std::error::Error for Stopped {} /// Live control of a running session. Everything that blocks calls [`Ctl::poll`] while it waits, so a command /// written to the database by the TUI (another process) takes effect within a fraction of a second. struct Ctl<'a> { db: &'a Db, id: String, cfg: BudgetCfg, on_abort: Option, on_budget: Option, states: Vec, start: String, stop: RefCell>, /// The user pressed interrupt (without asking to go anywhere). interrupted: Cell, /// In the state that handles a budget stop or an abort: budgets no longer apply there. exempt: Cell, last_budget: Cell, last_compact: Cell, compacted: Cell, } impl<'a> Ctl<'a> { fn new(db: &'a Db, id: &str, m: &Machine) -> Self { let long_ago = Instant::now() - Duration::from_secs(60); Self { db, id: id.to_string(), cfg: m.budget.clone(), on_abort: m.on_abort.clone(), on_budget: m.on_budget.clone(), states: m.states.iter().map(|s| s.name.clone()).collect(), start: m.start().name.clone(), stop: RefCell::new(None), interrupted: Cell::new(false), exempt: Cell::new(false), last_budget: Cell::new(long_ago), last_compact: Cell::new(long_ago), compacted: Cell::new(false), } } fn enter_state(&self, name: &str) { let n = Some(name); self.exempt .set(n == self.on_abort.as_deref() || n == self.on_budget.as_deref()); } fn has_state(&self, s: &str) -> bool { self.states.iter().any(|x| x == s) } fn set_stop(&self, s: Stop) { let mut st = self.stop.borrow_mut(); if st.is_none() { *st = Some(s); // the first one wins } } fn stopped(&self) -> bool { self.stop.borrow().is_some() } fn take_stop(&self) -> Option { self.stop.borrow_mut().take() } fn take_interrupt(&self) -> bool { self.interrupted.replace(false) } /// Reads new commands and checks the budgets. Messages become `hint` events (the next agent step gets them /// as context) and are returned so a running step can be told right away. fn poll(&self) -> Result { let mut p = Poll::default(); for (kind, pl) in self.db.take_commands(&self.id)? { let text = pl["text"].as_str().unwrap_or_default().to_string(); let target = pl["state"].as_str().unwrap_or_default(); let fail = |what: String| { self.db.emit( &self.id, "command_failed", json!({"kind": kind, "error": what}), ) }; match kind.as_str() { "message" => { self.db.emit(&self.id, "hint", json!({"text": text}))?; p.messages.push(text); } "interrupt" => { self.interrupted.set(true); p.interrupt = true; } "goto" if self.has_state(target) => { let why = pl["why"].as_str().unwrap_or("forced").to_string(); self.set_stop(Stop::Goto { state: target.into(), why, }); p.interrupt = true; } "goto" => { fail(format!("no state {target:?}"))?; } "abort" => { self.set_stop(match &self.on_abort { Some(s) => Stop::Goto { state: s.clone(), why: "abort".into(), }, None => Stop::End { status: "aborted", reason: "aborted by the user".into(), }, }); p.interrupt = true; } "veto" => { // the agent hears why, and the session goes back to `code` (spec 7.3) let msg = format!( "The user vetoed this decision: {text}. Choose a different approach." ); self.db.emit(&self.id, "hint", json!({"text": msg}))?; p.messages.push(msg); let back = ["code", target].into_iter().find(|s| self.has_state(s)); self.set_stop(Stop::Goto { state: back.unwrap_or(&self.start).to_string(), why: "veto".into(), }); p.interrupt = true; } other => { fail(format!("unknown command {other:?}"))?; } } } if !self.exempt.get() && !self.stopped() && self.last_budget.get().elapsed() >= Duration::from_secs(1) { self.last_budget.set(Instant::now()); let evs = self.db.events(Some(&self.id), 0)?; let refs: Vec<&Event> = evs.iter().collect(); if let Some(x) = budget::exceeded(&refs, &self.cfg, crate::state::now_ms()) { self.db.emit( &self.id, "budget", json!({"what": x.what, "used": x.used, "limit": x.limit}), )?; self.set_stop(match &self.on_budget { Some(s) => Stop::Goto { state: s.clone(), why: "budget".into(), }, None => Stop::End { status: "failed", reason: format!("budget: {} {} > {}", x.what, x.used, x.limit), }, }); p.interrupt = true; } } Ok(p) } /// True once when the context window passes `compact_at` percent; hx is told to compact. fn compaction_due(&self) -> bool { let Some(limit) = self.cfg.compact_at else { return false; }; if self.last_compact.get().elapsed() < Duration::from_secs(1) { return false; } self.last_compact.set(Instant::now()); let Ok(evs) = self.db.events(Some(&self.id), 0) else { return false; }; let refs: Vec<&Event> = evs.iter().collect(); match budget::ctx_pct(&refs) { Some(p) if p >= limit && !self.compacted.get() => { self.compacted.set(true); let _ = self.db.emit(&self.id, "compact", json!({"pct": p})); true } Some(p) if p < limit => { self.compacted.set(false); // it worked: arm again for the next time false } _ => false, } } } /// Everything a running session needs; the hx process lives here for the whole session. struct Ctx<'a> { db: &'a Db, s: &'a Session, task: &'a Task, profile: &'a Profile, scope: &'a str, repo: &'a Path, ctl: Ctl<'a>, agent: Option, } enum Outcome { Ok, /// A step failed with this catch name. Caught(String), /// A command or a budget ended the state early. Stop(Stop), } struct StepRes { ok: bool, exit: Option, /// Command output tail, or the agent's summary. out: String, /// Catch named by the step itself (hx `blocked` result); otherwise `fail_as` or the state's first catch. catch: Option, } fn run_state(cx: &mut Ctx, st: &State) -> Result { for step in &st.steps { if let Some(label) = &step.sets { cx.db.emit( &cx.s.id, "status", json!({"state": st.name, "step": step.name, "label": label}), )?; } // a command or budget stop is pending: do not start the next step cx.ctl.poll()?; if cx.ctl.stopped() { return Err(Stopped.into()); } let t0 = Instant::now(); let r = run_step(cx, st, step)?; cx.db.emit( &cx.s.id, "step", json!({ "state": st.name, "step": step.name, "run": step.run, "ok": r.ok, "exit": r.exit, "ms": t0.elapsed().as_millis() as u64, "output": r.out, }), )?; if cx.ctl.stopped() { return Err(Stopped.into()); // it arrived while the step ran (the step was cut short) } if !r.ok { let catch = r .catch .or_else(|| step.fail_as.clone()) .or_else(|| st.catch.keys().next().cloned()); let Some(catch) = catch else { bail!( "state {:?} step {:?} failed and the state has no catch", st.name, step.name ); }; return Ok(Outcome::Caught(catch)); } } Ok(Outcome::Ok) } fn run_step(cx: &mut Ctx, st: &State, step: &Step) -> Result { match step.run { RunOn::Computer => run_command(cx, st, step), RunOn::Agent => run_agent(cx, st, step), RunOn::Human => run_human(cx, st, step), } } /// Puts an item into the Needs-you queue and blocks until somebody answers it in the database. /// `reuse`: take over an unfinished item with the same key (orchestrator restarted while it was pending). fn ask( ctl: &Ctl, session: &str, state: &str, kind: &str, payload: Value, reuse: bool, ) -> Result { let db = ctl.db; let key = payload["key"].as_str().unwrap_or_default().to_string(); let existing = if reuse { db.open_need(session, kind, &key)? } else { None }; // waiting first: an item must never be visible while its session still claims to run db.set_session(session, state, "waiting")?; let id = match existing { Some(n) => n.id, None => { let id = db.add_need(session, kind, &payload)?; db.emit( session, "need", json!({"id": id, "kind": kind, "title": payload["title"]}), )?; id } }; let answer = loop { if let Some(a) = db.need_answer(id)? { break a; } ctl.poll()?; if ctl.stopped() { // abort, force state or budget while the item is open: it is moot now db.finish_need(id)?; db.emit( session, "answer", json!({"id": id, "kind": kind, "answer": "(cancelled)"}), )?; return Err(Stopped.into()); } std::thread::sleep(Duration::from_millis(50)); }; db.finish_need(id)?; db.emit( session, "answer", json!({"id": id, "kind": kind, "answer": answer}), )?; db.set_session(session, state, "running")?; Ok(answer) } /// "6 files, +318 −97, 52/52 tests pass": what the reviewer sees in the queue, built from the event stream. fn review_summary(db: &Db, id: &str) -> Result { let evs = db.events(Some(id), 0)?; let (mut files, mut added, mut removed) = (std::collections::BTreeSet::new(), 0, 0); for e in evs.iter().filter(|e| e.kind == "edit") { files.insert(e.payload["path"].as_str().unwrap_or_default().to_string()); added += e.payload["added"].as_u64().unwrap_or(0); removed += e.payload["removed"].as_u64().unwrap_or(0); } let mut parts = vec![]; if !files.is_empty() { parts.push(format!("{} files, +{added} −{removed}", files.len())); } if let Some(t) = evs.iter().rev().find(|e| e.kind == "test") { let (p, f) = ( t.payload["passed"].as_u64().unwrap_or(0), t.payload["failed"].as_u64().unwrap_or(0), ); parts.push(if f == 0 { format!("{p}/{p} tests pass") } else { format!("{p}/{} tests, {f} fail", p + f) }); } Ok(parts.join(", ")) } /// A `human` step: approve, or send it back with a comment (`changes: text`), which raises the step's catch. fn run_human(cx: &Ctx, st: &State, step: &Step) -> Result { let title = if st.kind == Kind::Gate { "review ready".to_string() } else { step.name.clone() }; let payload = json!({ "key": format!("{}/{}", st.name, step.name), "state": st.name, "step": step.name, "title": title, "detail": review_summary(cx.db, &cx.s.id)?, }); let answer = ask(&cx.ctl, &cx.s.id, &st.name, "review", payload, true)?; if answer == "approve" { return Ok(StepRes { ok: true, exit: Some(0), out: "approved".into(), catch: None, }); } let Some(comment) = answer.strip_prefix("changes") else { bail!("unknown answer {answer:?} to human step {:?}", step.name); }; let comment = comment.trim_start_matches(':').trim(); if !comment.is_empty() { cx.db.emit(&cx.s.id, "comment", json!({"text": comment}))?; } Ok(StepRes { ok: false, exit: None, out: format!("changes requested: {comment}"), catch: None, }) } /// Reviewer comments and user hints (messages, vetoes) that no agent step has seen yet, oldest first. fn pending_comment(db: &Db, id: &str) -> Result> { let mut texts = vec![]; for e in db.events(Some(id), 0)?.into_iter().rev() { match e.kind.as_str() { "comment" | "hint" => texts.extend(e.payload["text"].as_str().map(String::from)), "step" if e.payload["run"] == "agent" => break, _ => {} } } texts.reverse(); Ok((!texts.is_empty()).then(|| texts.join("\n"))) } /// Where a `report = "junit"` step writes its report. Next to the worktree, not in it: it must not dirty git. fn report_path(s: &Session) -> String { format!("{}.junit.xml", s.worktree) } fn run_command(cx: &Ctx, st: &State, step: &Step) -> Result { let Some(cmd) = &step.cmd else { // marker step (open-diff, mark-merged, ...) return Ok(StepRes { ok: true, exit: Some(0), out: String::new(), catch: None, }); }; let report = report_path(cx.s); // a stale report from an earlier run must not be read as this run's result let _ = std::fs::remove_file(&report); let mut child = Command::new("sh") .args([ "-c", &format!( "({}) 2>&1", render(cmd, cx.s, cx.scope, cx.repo).replace("{{report}}", &report) ), ]) .env("ORCH_REPORT", &report) // so `orch goal --export` and `orch checks` find the goal from inside a worktree .env("ORCH_DB", cx.db.path()) .env("ORCH_REPO", cx.repo) .env("ORCH_SESSION", &cx.s.id) .current_dir(&cx.s.worktree) .stdin(Stdio::null()) .stdout(Stdio::piped()) .process_group(0) // own group: an abort kills the command and what it started .spawn()?; let mut pipe = child.stdout.take().expect("piped"); let reader = std::thread::spawn(move || { let mut buf = Vec::new(); let _ = pipe.read_to_end(&mut buf); buf }); // wait in small steps so an abort, a forced state or a budget stop can cut the command short let status = loop { if let Some(s) = child.try_wait()? { break s; } cx.ctl.poll()?; if cx.ctl.stopped() { crate::state::kill_group(child.id()); let _ = child.wait(); return Err(Stopped.into()); } std::thread::sleep(Duration::from_millis(30)); }; let stdout = reader.join().unwrap_or_default(); let mut out = tail(&stdout, OUTPUT_TAIL); if step.report.as_deref() == Some("junit") && let Ok(xml) = std::fs::read_to_string(&report) { match crate::junit::parse(&xml) { Ok(r) => { cx.db.emit( &cx.s.id, "test", json!({ "state": st.name, "step": step.name, "passed": r.passed, "failed": r.failed, "skipped": r.skipped, "secs": r.secs, "failures": r.failures, }), )?; } Err(e) => out.push_str(&format!("\n[orch] junit report unreadable: {e:#}")), } } Ok(StepRes { ok: status.success(), exit: status.code(), out, catch: None, }) } /// Instruction text for a prompt kind. The kind itself is sent too, so hx can use its own prompts. fn instruction(kind: &str, goal: Option<&str>, t: &Task) -> String { let lead = match kind { "plan" => "Plan the work for this task. Report the plan with hx/plan.", "implement" => "Implement this task, following the plan.", _ => "Do this step of the task.", }; let mut s = format!("{lead}\n\nTask: {}", t.name); if !t.subtitle.is_empty() { s.push_str(&format!(" ({})", t.subtitle)); } if let Some(g) = goal { s.push_str(&format!("\nGoal: {g}")); } s } /// The last failed step of this session: what a re-entered `code` state needs to know to fix it. fn last_failure(db: &Db, id: &str) -> Result { Ok(db .events(Some(id), 0)? .into_iter() .rev() .find(|e| e.kind == "step" && e.payload["ok"] == false) .map_or(Value::Null, |e| { json!({ "state": e.payload["state"], "step": e.payload["step"], "exit": e.payload["exit"], "output": e.payload["output"], }) })) } fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result { let kind = step.prompt.as_deref().unwrap_or("implement"); if cx.agent.is_none() { cx.agent = Some(Acp::spawn(cx.profile, Path::new(&cx.s.worktree), &cx.s.id)?); } let goal = cx.db.goal()?; // a reviewer's comment, or the answer to a question hx asked, rides along as the hint let mut hint = pending_comment(cx.db, &cx.s.id)?; loop { let context = json!({ "state": st.name, "last_failure": last_failure(cx.db, &cx.s.id)?, "hint": hint, }); let mut sink = DbSink { db: cx.db, session: &cx.s.id, state: &st.name, ctl: &cx.ctl, }; cx.ctl.take_interrupt(); // an interrupt pressed during an earlier computer step is stale let agent = cx.agent.as_mut().expect("spawned above"); let r: StepResult = agent.step( kind, &instruction(kind, goal.as_deref(), cx.task), context, json!({}), &mut sink, )?; if cx.ctl.stopped() { return Err(Stopped.into()); // abort, forced state, veto or budget: hx was interrupted } if cx.ctl.take_interrupt() { // the user interrupted: hx stopped after its tool call. Ask what it should do now. let payload = json!({ "key": format!("{}/{}/interrupted", st.name, step.name), "state": st.name, "step": step.name, "title": "interrupted", "detail": "the agent stopped; reply with a hint to go on (empty = go on as before)", }); let answer = ask(&cx.ctl, &cx.s.id, &st.name, "input", payload, true)?; let reply = answer.strip_prefix("reply:").unwrap_or(&answer).trim(); hint = (!reply.is_empty()).then(|| reply.to_string()); continue; } return match r.status.as_str() { "done" => Ok(StepRes { ok: true, exit: Some(0), out: r.summary, catch: None, }), "blocked" => Ok(StepRes { ok: false, exit: None, out: r.summary, catch: r.catch, }), "needs_input" => { let question = r.question.unwrap_or_default(); let payload = json!({ "key": format!("{}/{}/input", st.name, step.name), "state": st.name, "step": step.name, "title": "question", "detail": question, }); let answer = ask(&cx.ctl, &cx.s.id, &st.name, "input", payload, true)?; hint = Some( answer .strip_prefix("reply:") .unwrap_or(&answer) .trim() .to_string(), ); continue; // same step again, now with the answer in the context } other => bail!("hx sent unknown step status {other:?}"), }; } } /// Turns what hx reports into events (and decisions) of one session. struct DbSink<'a> { db: &'a Db, session: &'a str, state: &'a str, ctl: &'a Ctl<'a>, } /// The `optionId` of the first option whose kind is one of `kinds`. fn option_id(options: &Value, kinds: &[&str]) -> Option { kinds.iter().find_map(|k| { options .as_array()? .iter() .find_map(|o| (o["kind"] == *k).then(|| o["optionId"].as_str().map(String::from))?) }) } /// `allow_always` earlier in this session for the same tool: hx is not asked about it again. fn always_allowed(db: &Db, session: &str, tool: &str) -> bool { db.events(Some(session), 0).is_ok_and(|evs| { evs.iter().any(|e| { e.kind == "permission" && e.payload["tool"] == tool && e.payload["decision"] == "allow_always" }) }) } impl Sink for DbSink<'_> { fn notify(&mut self, method: &str, p: &Value) -> Result<()> { let (kind, payload) = match method { "hx/intent" => ("intent", p.clone()), "hx/edit" => ("edit", p.clone()), "hx/usage" => ("usage", p.clone()), "hx/plan" => ("plan", p.clone()), "hx/decision" => { let text = p["text"].as_str().unwrap_or_default(); let state = p["state"].as_str().unwrap_or_default(); self.db.add_decision(self.session, text, state)?; ("decision", p.clone()) } "session/update" if p["update"]["sessionUpdate"] == "tool_call" => ( "tool", json!({"title": p["update"]["title"], "kind": p["update"]["kind"]}), ), _ => return Ok(()), // message chunks and the like: not worth a row }; self.db.emit(self.session, kind, payload)?; Ok(()) } fn poll(&mut self) -> Poll { let mut p = self.ctl.poll().unwrap_or_default(); p.compact = self.ctl.compaction_due(); p } /// Goes to the Needs-you queue and blocks hx (which waits for our reply) until the user decides. /// An error while waiting cancels the request. fn permission(&mut self, p: &Value) -> Option { let tool = p["toolCall"]["title"].as_str().unwrap_or("tool call"); let opts = &p["options"]; let answer = if always_allowed(self.db, self.session, tool) { "allow_always".to_string() } else { let payload = json!({ "key": "", "state": self.state, "title": "permission", "tool": tool, "detail": format!("wants to run {tool}"), "options": opts, }); ask( self.ctl, self.session, self.state, "permission", payload, false, ) .ok()? }; let _ = self.db.emit( self.session, "permission", json!({"tool": tool, "decision": answer}), ); match answer.as_str() { "allow_once" => option_id(opts, &["allow_once", "allow_always"]), "allow_always" => option_id(opts, &["allow_always", "allow_once"]), _ => option_id(opts, &["reject_once", "reject_always"]), } } } /// Runs the session to the end of its machine and returns the final status (`merged`, `escalated`, `failed`, ...). /// Resumes at `current_state` when the session was started before (orchestrator restart). pub fn run_session( db: &Db, m: &Machine, id: &str, repo: &Path, scope: &str, profile: &Profile, ) -> Result { let s = db .session(id)? .with_context(|| format!("no session {id}"))?; let task = db .tasks()? .into_iter() .find(|t| t.id == s.task_id) .with_context(|| format!("no task {}", s.task_id))?; let ctl = Ctl::new(db, id, m); if s.state.is_empty() { match wait_for_dependencies(&ctl, &s, &task) { Ok(()) => {} Err(e) if e.is::() => { let why = "stopped while blocked on its dependencies".to_string(); return finish(db, id, "", "aborted", Some(why)); } Err(e) => return Err(e), } } ensure_worktree(repo, &s)?; let mut cx = Ctx { db, s: &s, task: &task, profile, scope, repo, ctl, agent: None, }; let mut resumed = !s.state.is_empty(); let (mut cur, mut from) = if resumed { db.emit(id, "resume", json!({"state": s.state}))?; (s.state.clone(), s.state.clone()) } else { (m.start().name.clone(), String::new()) }; db.set_pid(id, Some(std::process::id()))?; for _ in 0..MAX_TRANSITIONS { let st = m .state(&cur) .with_context(|| format!("machine has no state {cur:?}"))?; if !resumed { // also for a catch that points back at its own state (PlanInvalid -> plan) db.emit(id, "state", json!({"from": from, "to": cur}))?; } resumed = false; db.set_session(id, &cur, "running")?; cx.ctl.enter_state(&cur); // the state that ends the session as `merged` is the merge: one session at a time, first come first served let merging = st.end.as_deref() == Some("merged"); let result = (|| { if merging { enter_merge_queue(&cx.ctl, id)?; } run_state(&mut cx, st) })(); if merging { // all acceptance checks again on main, while this session still holds the merge slot if matches!(result, Ok(Outcome::Ok)) && let Err(e) = crate::checks::run_on_main(db, repo) { db.emit(id, "check_error", json!({"error": format!("{e:#}")}))?; } let _ = db.queue_leave(id); } let outcome = match result { Ok(o) => o, // a wait was cut short by a command or a budget: what was asked decides where we go Err(e) if e.is::() => Outcome::Stop(cx.ctl.take_stop().unwrap_or(Stop::End { status: "failed", reason: "stopped".into(), })), Err(e) => return finish(db, id, &cur, "failed", Some(format!("{e:#}"))), }; from = cur.clone(); match outcome { Outcome::Stop(Stop::End { status, reason }) => { return finish(db, id, &cur, status, Some(reason)); } Outcome::Stop(Stop::Goto { state, why }) => { db.emit(id, "goto", json!({"from": cur, "to": state, "why": why}))?; if matches!(why.as_str(), "abort" | "budget") { cx.agent = None; // stop hx for good; a forced state or a veto keeps its conversation } cur = state; } Outcome::Ok => { if matches!(st.kind, Kind::Exit | Kind::Abort) || st.next.is_none() { let end = st.end.clone().unwrap_or_else(|| "done".into()); return finish(db, id, &cur, &end, None); } cur = st .next .clone() .expect("validated: non-exit states have next"); } Outcome::Caught(c) => { db.emit(id, "catch", json!({"state": cur, "catch": c}))?; let n = db.catch_count(id, &cur, &c)?; cur = match st.retry.get(&c) { Some(r) if n >= r.max => r.then.clone(), _ => match st.catch.get(&c) { Some(t) => t.clone(), None => { let why = format!("{c:?} is not a catch of state {:?}", st.name); return finish(db, id, &cur, "failed", Some(why)); } }, }; } } } finish( db, id, &cur, "failed", Some(format!("more than {MAX_TRANSITIONS} transitions")), ) } const POLL: Duration = Duration::from_millis(100); /// A task whose dependencies have not merged stays `queued` (BLOCKED on screen) and nothing of it starts. fn wait_for_dependencies(ctl: &Ctl, s: &Session, t: &Task) -> Result<()> { let db = ctl.db; let mut announced = false; loop { ctl.poll()?; if ctl.stopped() { return Err(Stopped.into()); } let unmet: Vec<&String> = t .depends_on .iter() .filter(|d| { db.session(d) .ok() .flatten() .is_none_or(|x| x.status != "merged") }) .collect(); if unmet.is_empty() { return Ok(()); } if !announced { db.emit(&s.id, "blocked", json!({"on": unmet}))?; announced = true; } std::thread::sleep(POLL); } } /// Is the orchestrator process of this session still alive? A session that crashed inside the merge must not /// block the queue forever. fn alive(db: &Db, session: &str) -> bool { let Some(pid) = db.session(session).ok().flatten().and_then(|s| s.pid) else { return false; }; // SAFETY: signal 0 only checks that the process exists. let r = unsafe { libc::kill(pid as i32, 0) }; r == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) } /// Joins the merge queue and blocks until this session is at the head. fn enter_merge_queue(ctl: &Ctl, id: &str) -> Result<()> { let db = ctl.db; db.queue_join(id)?; let pos = db.queue_position(id)?; if pos > 1 { db.emit(id, "queue", json!({"position": pos}))?; } loop { ctl.poll()?; if ctl.stopped() { db.queue_leave(id)?; // an aborted session must not keep its place return Err(Stopped.into()); } match db.queue_head()? { Some(h) if h == id => return Ok(()), Some(h) if !alive(db, &h) => db.queue_leave(&h)?, None => { db.queue_join(id)?; // pruned by somebody else's mistake: stand in line again } _ => std::thread::sleep(POLL), } } } fn finish(db: &Db, id: &str, state: &str, status: &str, reason: Option) -> Result { db.set_session(id, state, status)?; db.set_pid(id, None)?; db.emit(id, "end", json!({"status": status, "reason": reason}))?; Ok(status.to_string()) } #[cfg(test)] mod tests { use super::*; struct Env { db: Db, dir: std::path::PathBuf, repo: std::path::PathBuf, } fn env(tag: &str) -> Env { let dir = std::env::temp_dir().join(format!("orch-runner-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); let repo = dir.join("repo"); std::fs::create_dir_all(&repo).unwrap(); git(&repo, &["init", "-q", "-b", "main"]).unwrap(); std::fs::write(repo.join("f"), "x").unwrap(); git(&repo, &["add", "-A"]).unwrap(); git(&repo, &["commit", "-qm", "init"]).unwrap(); Env { db: Db::open(&dir.join("orch.db")).unwrap(), dir, repo, } } fn states(db: &Db, id: &str) -> Vec { db.events(Some(id), 0) .unwrap() .iter() .filter(|e| e.kind == "state") .map(|e| e.payload["to"].as_str().unwrap().to_string()) .collect() } fn kinds(db: &Db, id: &str) -> Vec { db.events(Some(id), 0) .unwrap() .into_iter() .map(|e| e.kind) .collect() } fn plain() -> Profile { Profile::parse("").unwrap() } /// Profile whose hx is the Python fake; `vars` are set through `env` (the runner clears its environment). fn fake(vars: &str) -> Profile { let script = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fake_acp_hx.py"); Profile::parse(&format!("hx = \"env {vars} python3 {script}\"")).unwrap() } const TAIL: &str = r#" [[state]] name = "done" kind = "exit" end = "merged" [[state]] name = "stuck" kind = "exit" only_on = ["x"] end = "escalated" "#; #[test] fn happy_path_and_templates() { let e = env("ok"); let m = Machine::parse(&format!( r#"name = "m" [[state]] name = "a" kind = "start" steps = [{{ name = "w", run = "computer", sets = "writing", cmd = "echo {{{{session}}}} {{{{branch}}}} > out.txt" }}] next = "b" [[state]] name = "b" steps = [{{ name = "r", run = "computer", cmd = "test -f out.txt" }}, {{ name = "mark", run = "computer" }}] next = "done" {TAIL}"# )) .unwrap(); let s = create(&e.db, &e.dir.join("wt"), "my task", "", "m").unwrap(); assert_eq!((s.id.as_str(), s.branch.as_str()), ("s1", "hx/s1-my-task")); let status = run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(); assert_eq!(status, "merged"); assert_eq!(states(&e.db, "s1"), ["a", "b", "done"]); let out = std::fs::read_to_string(e.dir.join("wt/s1/out.txt")).unwrap(); assert_eq!(out.trim(), "s1 hx/s1-my-task"); let row = e.db.session("s1").unwrap().unwrap(); assert_eq!((row.status.as_str(), row.pid), ("merged", None)); assert!(kinds(&e.db, "s1").contains(&"status".to_string())); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn catch_retry_then_escalates() { let e = env("retry"); let m = Machine::parse(&format!( r#"name = "m" [[state]] name = "code" kind = "start" steps = [{{ name = "edit", run = "computer", cmd = "echo x >> n" }}] next = "test" [[state]] name = "test" steps = [{{ name = "t", run = "computer", cmd = "false" }}] catch = {{ TestsFailed = "code" }} retry = {{ TestsFailed = {{ max = 3, then = "stuck" }} }} next = "done" {TAIL}"# )) .unwrap(); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), "escalated" ); assert_eq!( states(&e.db, "s1"), ["code", "test", "code", "test", "code", "test", "stuck"] ); assert_eq!(e.db.catch_count("s1", "test", "TestsFailed").unwrap(), 3); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn resume_continues_at_current_state_and_keeps_counts() { let e = env("resume"); let m = Machine::parse(&format!( r#"name = "m" [[state]] name = "a" kind = "start" steps = [{{ name = "once", run = "computer", cmd = "echo ran >> a.log" }}] next = "b" [[state]] name = "b" steps = [{{ name = "s", run = "computer", cmd = "echo b >> b.log" }}] next = "done" {TAIL}"# )) .unwrap(); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); // the orchestrator died while the session was in state b e.db.set_session("s1", "b", "running").unwrap(); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), "merged" ); assert!( !e.dir.join("wt/s1/a.log").exists(), "state a must not run again" ); assert!(e.dir.join("wt/s1/b.log").exists()); assert_eq!(kinds(&e.db, "s1")[0], "resume"); let _ = std::fs::remove_dir_all(&e.dir); } fn one_step(step: &str) -> Machine { Machine::parse(&format!( "name = \"m\"\n[[state]]\nname = \"a\"\nkind = \"start\"\nsteps = [{step}]\nnext = \"done\"\n{TAIL}" )) .unwrap() } fn failure_reason(e: &Env) -> String { let end = e.db.events(Some("s1"), 0).unwrap().pop().unwrap(); end.payload["reason"].as_str().unwrap().to_string() } #[test] fn junit_report_becomes_a_test_event() { let e = env("junit"); let m = Machine::parse(&format!( r#"name = "m" [[state]] name = "test" kind = "start" steps = [{{ name = "t", run = "computer", report = "junit", cmd = "printf 'at src/x.rs:9:1' > {{{{report}}}}; echo to-stdout; exit 1" }}] catch = {{ TestsFailed = "stuck" }} next = "done" {TAIL}"# )) .unwrap(); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), "escalated" ); let ev = e.db.events(Some("s1"), 0).unwrap(); let t = ev.iter().find(|v| v.kind == "test").expect("test event"); assert_eq!( (t.payload["passed"].as_u64(), t.payload["failed"].as_u64()), (Some(1), Some(1)) ); assert_eq!(t.payload["failures"][0]["name"], "a::bad"); assert_eq!(t.payload["failures"][0]["location"], "src/x.rs:9"); let step = ev.iter().find(|v| v.kind == "step").unwrap(); assert!( step.payload["output"] .as_str() .unwrap() .contains("to-stdout") ); let _ = std::fs::remove_dir_all(&e.dir); } /// What the answering thread saw: (kind, payload, session status at that moment). type Seen = Vec<(String, Value, String)>; /// Plays the user: answers the pending queue items one by one with `answers` from another connection. fn answerer( db_path: std::path::PathBuf, answers: &'static [&'static str], ) -> std::thread::JoinHandle { std::thread::spawn(move || { let db = Db::open(&db_path).unwrap(); let mut seen = vec![]; let deadline = Instant::now() + Duration::from_secs(20); while seen.len() < answers.len() && Instant::now() < deadline { if let Some(n) = db.pending_needs().unwrap().first() { let status = db.session(&n.session).unwrap().unwrap().status; db.answer_need(n.id, answers[seen.len()]).unwrap(); seen.push((n.kind.clone(), n.payload.clone(), status)); } std::thread::sleep(Duration::from_millis(20)); } seen }) } #[test] fn human_review_waits_in_the_queue_and_changes_requested_loops_back() { let e = env("human"); let m = Machine::parse(&format!( r#"name = "m" [[state]] name = "code" kind = "start" steps = [{{ name = "edit", run = "computer", cmd = "echo x >> n" }}] next = "review" [[state]] name = "review" kind = "gate" steps = [{{ name = "wait-approval", run = "human", sets = "waiting" }}] catch = {{ ChangesRequested = "code" }} next = "done" {TAIL}"# )) .unwrap(); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); let user = answerer(e.dir.join("orch.db"), &["changes: rename it", "approve"]); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), "merged" ); let seen = user.join().unwrap(); assert_eq!( states(&e.db, "s1"), ["code", "review", "code", "review", "done"] ); assert_eq!(seen.len(), 2); assert_eq!( (seen[0].0.as_str(), seen[0].1["title"].as_str()), ("review", Some("review ready")) ); assert_eq!( seen[0].2, "waiting", "the session shows as waiting while the item is open" ); assert_eq!( e.db.catch_count("s1", "review", "ChangesRequested") .unwrap(), 1 ); let ev = e.db.events(Some("s1"), 0).unwrap(); let comment = ev.iter().find(|v| v.kind == "comment").unwrap(); assert_eq!(comment.payload["text"], "rename it"); assert_eq!(ev.iter().filter(|v| v.kind == "need").count(), 2); assert_eq!(ev.iter().filter(|v| v.kind == "answer").count(), 2); assert!(e.db.pending_needs().unwrap().is_empty()); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn restart_takes_over_the_pending_item_instead_of_asking_twice() { let e = env("reuse"); let m = one_step(r#"{ name = "ok", run = "human" }"#); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); // the first orchestrator died while the item was open; the user answers it afterwards let n = e.db.add_need("s1", "review", &json!({"key": "a/ok", "title": "ok"})) .unwrap(); e.db.answer_need(n, "approve").unwrap(); e.db.set_session("s1", "a", "waiting").unwrap(); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), "merged" ); let ev = e.db.events(Some("s1"), 0).unwrap(); assert_eq!( ev.iter().filter(|v| v.kind == "need").count(), 0, "no second question" ); assert_eq!(ev.iter().filter(|v| v.kind == "answer").count(), 1); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn agent_steps_report_through_events() { let e = env("agent"); let m = Machine::parse(&format!( r#"name = "m" [[state]] name = "plan" kind = "start" steps = [{{ name = "draft", run = "agent", sets = "planning", prompt = "plan" }}] next = "code" [[state]] name = "code" steps = [{{ name = "edit", run = "agent", sets = "coding", prompt = "implement" }}] next = "done" {TAIL}"# )) .unwrap(); e.db.set_goal("rate limit it").unwrap(); create(&e.db, &e.dir.join("wt"), "limiter", "token bucket", "m").unwrap(); let status = run_session(&e.db, &m, "s1", &e.repo, "", &fake("FAKE_MODE=ok")).unwrap(); assert_eq!(status, "merged"); let k = kinds(&e.db, "s1"); for want in [ "intent", "tool", "edit", "usage", "decision", "plan", "step", ] { assert!(k.contains(&want.to_string()), "no {want} event in {k:?}"); } let wt = e.dir.join("wt/s1"); assert_eq!( std::fs::read_to_string(wt.join("steps.txt")).unwrap(), "plan\nimplement\n" ); assert!(wt.join("agent_implement.txt").exists()); let usage = e.db.events(Some("s1"), 0) .unwrap() .into_iter() .find(|v| v.kind == "usage") .unwrap(); assert_eq!(usage.payload["ctx_used"], 40000); // one decision per agent step, stored for the goal view's veto list assert_eq!(e.db.decision_count("s1").unwrap(), 2); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn blocked_result_takes_the_named_catch_and_context_carries_the_failure() { let e = env("blocked"); let log = e.dir.join("fake.log"); let m = Machine::parse(&format!( r#"name = "m" [[state]] name = "code" kind = "start" steps = [{{ name = "edit", run = "agent", prompt = "implement" }}] catch = {{ PlanInvalid = "code" }} next = "build" [[state]] name = "build" steps = [{{ name = "b", run = "computer", cmd = "echo boom-output; test $(wc -l < steps.txt) -ge 3" }}] catch = {{ BuildFailed = "code" }} next = "done" {TAIL}"# )) .unwrap(); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); let p = fake(&format!("FAKE_MODE=block_once FAKE_LOG={}", log.display())); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), "merged" ); // code (blocked) -> code (done) -> build (fails: 2 steps) -> code (done, 3 steps) -> build ok assert_eq!( states(&e.db, "s1"), ["code", "code", "build", "code", "build", "done"] ); assert_eq!(e.db.catch_count("s1", "code", "PlanInvalid").unwrap(), 1); // the third hx/step (re-entering code after the failed build) carries the build output let steps: Vec = std::fs::read_to_string(&log) .unwrap() .lines() .map(|l| serde_json::from_str::(l).unwrap()) .filter(|m| m["method"] == "hx/step") .collect(); assert_eq!(steps.len(), 3); let ctx = &steps[2]["params"]["context"]["last_failure"]; assert_eq!(ctx["state"], "build"); assert!(ctx["output"].as_str().unwrap().contains("boom-output")); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn permission_request_waits_for_the_user_and_deny_reaches_hx() { let e = env("deny"); let m = one_step(r#"{ name = "ag", run = "agent", prompt = "implement" }"#); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); let user = answerer(e.dir.join("orch.db"), &["deny"]); let p = fake("FAKE_MODE=permission"); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), "merged" ); let seen = user.join().unwrap(); assert_eq!(seen[0].0, "permission"); assert_eq!(seen[0].1["tool"], "docker compose up -d redis"); assert_eq!(seen[0].2, "waiting"); let answer = std::fs::read_to_string(e.dir.join("wt/s1/permission.txt")).unwrap(); assert!(answer.contains("\"optionId\": \"deny\""), "{answer}"); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn allow_always_is_remembered_for_the_session() { let e = env("always"); let step = r#"{ name = "ag", run = "agent", prompt = "implement" }"#; let m = one_step(&format!("{step}, {step}")); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); let user = answerer(e.dir.join("orch.db"), &["allow_always"]); let p = fake("FAKE_MODE=permission"); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), "merged" ); user.join().unwrap(); let ev = e.db.events(Some("s1"), 0).unwrap(); // hx asked twice, the user was asked once assert_eq!(ev.iter().filter(|v| v.kind == "permission").count(), 2); assert_eq!(ev.iter().filter(|v| v.kind == "need").count(), 1); let answer = std::fs::read_to_string(e.dir.join("wt/s1/permission.txt")).unwrap(); assert!(answer.contains("\"optionId\": \"allow\""), "{answer}"); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn needs_input_is_asked_in_the_queue_and_the_reply_goes_back_to_hx() { let e = env("input"); let log = e.dir.join("fake.log"); let m = one_step(r#"{ name = "ag", run = "agent", prompt = "implement" }"#); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); let user = answerer(e.dir.join("orch.db"), &["reply: use claude"]); let p = fake(&format!("FAKE_MODE=needs_input FAKE_LOG={}", log.display())); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), "merged" ); let seen = user.join().unwrap(); assert_eq!( (seen[0].0.as_str(), seen[0].1["detail"].as_str()), ("input", Some("Which provider?")) ); let steps: Vec = std::fs::read_to_string(&log) .unwrap() .lines() .map(|l| serde_json::from_str::(l).unwrap()) .filter(|m| m["method"] == "hx/step") .collect(); assert_eq!(steps.len(), 2, "the same step runs again with the answer"); assert_eq!(steps[0]["params"]["context"]["hint"], Value::Null); assert_eq!(steps[1]["params"]["context"]["hint"], "use claude"); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn a_crashing_hx_fails_the_session() { let e = env("crash"); let m = one_step(r#"{ name = "ag", run = "agent", prompt = "implement" }"#); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); let p = fake("FAKE_MODE=crash"); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), "failed" ); assert!(failure_reason(&e).contains("hx closed its output")); let _ = std::fs::remove_dir_all(&e.dir); } /// Runs a session on its own connection in a thread, like another orchestrator process would. fn spawn_session(e: &Env, m: &Machine, id: &str) -> std::thread::JoinHandle { let (path, repo, m, id) = ( e.dir.join("orch.db"), e.repo.clone(), m.clone(), id.to_string(), ); std::thread::spawn(move || { let db = Db::open(&path).unwrap(); run_session(&db, &m, &id, &repo, "", &plain()).unwrap() }) } #[test] fn a_task_waits_for_its_dependencies_to_merge() { let e = env("deps"); let m = Machine::parse(&format!( r#"name = "m" [[state]] name = "a" kind = "start" steps = [{{ name = "w", run = "computer", cmd = "true" }}] next = "done" {TAIL}"# )) .unwrap(); let wt = e.dir.join("wt"); create(&e.db, &wt, "first", "", "m").unwrap(); create_after(&e.db, &wt, "second", "", "m", &["s1".to_string()]).unwrap(); assert!(create_after(&e.db, &wt, "bad", "", "m", &["s9".to_string()]).is_err()); let second = spawn_session(&e, &m, "s2"); std::thread::sleep(Duration::from_millis(500)); let s2 = e.db.session("s2").unwrap().unwrap(); assert_eq!(s2.status, "queued", "blocked: not started"); assert!( !Path::new(&s2.worktree).exists(), "nothing of it exists yet" ); assert!(kinds(&e.db, "s2").contains(&"blocked".to_string())); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), "merged" ); assert_eq!(second.join().unwrap(), "merged"); let first_end = e.db.events(Some("s1"), 0).unwrap().last().unwrap().id; let second_start = e.db.events(Some("s2"), 0) .unwrap() .iter() .find(|v| v.kind == "state") .unwrap() .id; assert!(second_start > first_end, "s2 started only after s1 merged"); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn only_one_session_is_in_merge_at_a_time() { let e = env("queue"); let log = e.dir.join("merge.log"); let m = Machine::parse(&format!( r#"name = "m" [[state]] name = "a" kind = "start" steps = [{{ name = "w", run = "computer", cmd = "true" }}] next = "merge" [[state]] name = "merge" kind = "exit" steps = [{{ name = "slow", run = "computer", cmd = "echo start >> {0}; sleep 0.3; echo end >> {0}" }}] end = "merged" "#, log.display() )) .unwrap(); let wt = e.dir.join("wt"); for n in ["a", "b", "c"] { create(&e.db, &wt, n, "", "m").unwrap(); } let runs: Vec<_> = ["s1", "s2", "s3"] .iter() .map(|id| spawn_session(&e, &m, id)) .collect(); for r in runs { assert_eq!(r.join().unwrap(), "merged"); } let lines: Vec = std::fs::read_to_string(&log) .unwrap() .lines() .map(String::from) .collect(); assert_eq!( lines, ["start", "end", "start", "end", "start", "end"], "merges never overlap" ); assert_eq!(e.db.queue_head().unwrap(), None, "everybody left the queue"); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn a_dead_session_does_not_block_the_merge_queue() { let e = env("stale"); let m = one_step(r#"{ name = "w", run = "computer", cmd = "true" }"#); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); // a crashed orchestrator left its ticket at the head; its pid is gone e.db.add_session(&Session { id: "s9".into(), task_id: "s1".into(), branch: "b".into(), worktree: "/nowhere".into(), pid: Some(2_000_000_000), state: "merge".into(), status: "running".into(), }) .unwrap(); e.db.queue_join("s9").unwrap(); // one_step ends in `done` (merged), which is the merge state assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), "merged" ); assert_eq!(e.db.queue_head().unwrap(), None); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn merge_fast_forwards_main_and_all_checks_run_on_main_afterwards() { let e = env("main"); let m = Machine::parse( r#"name = "m" [[state]] name = "code" kind = "start" steps = [{ name = "feature", run = "computer", cmd = "echo hi > feature.txt && git add -A && git -c user.name=t -c user.email=t@t commit -qm feature" }] next = "merge" [[state]] name = "merge" kind = "exit" steps = [ { name = "ff", run = "computer", cmd = "git -C {{repo}} merge --ff-only {{branch}}" }, { name = "mark-merged", run = "computer", sets = "merged" }, ] end = "merged" "#, ) .unwrap(); e.db.add_check("feature on main", "test -f feature.txt", None) .unwrap(); e.db.add_check("still red", "exit 1", Some("s1")).unwrap(); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), "merged" ); assert!(e.repo.join("feature.txt").exists(), "main moved forward"); let st: Vec<_> = e.db.checks() .unwrap() .into_iter() .map(|c| c.last_status.unwrap()) .collect(); assert_eq!( st, ["pass", "fail"], "every check ran on main, owner or not" ); assert_eq!(e.db.events(Some(crate::checks::GOAL), 0).unwrap().len(), 2); let _ = std::fs::remove_dir_all(&e.dir); } // ---- live control: commands from another connection, budgets ---- const CTL_TAIL: &str = r#" [[state]] name = "done" kind = "exit" end = "merged" [[state]] name = "stuck" kind = "exit" only_on = ["budget"] end = "escalated" [[state]] name = "aborted" kind = "abort" only_on = ["abort"] end = "aborted" "#; fn ctl_machine(top_and_states: &str) -> Machine { Machine::parse(&[top_and_states, CTL_TAIL].concat()).unwrap() } /// Polls `f` until it is true or `secs` passed. fn wait_until(secs: u64, mut f: impl FnMut() -> bool) -> bool { let end = Instant::now() + Duration::from_secs(secs); while Instant::now() < end { if f() { return true; } std::thread::sleep(Duration::from_millis(20)); } false } /// The user in another process: waits until `ready` holds on the session's events, then runs `act`. fn user( e: &Env, ready: impl Fn(&[crate::db::Event]) -> bool + Send + 'static, act: impl FnOnce(&Db) + Send + 'static, ) -> std::thread::JoinHandle<()> { let path = e.dir.join("orch.db"); std::thread::spawn(move || { let db = Db::open(&path).unwrap(); assert!( wait_until(20, || ready(&db.events(Some("s1"), 0).unwrap())), "the session never got there" ); act(&db); }) } fn has(evs: &[crate::db::Event], kind: &str) -> bool { evs.iter().any(|e| e.kind == kind) } const ABORTABLE: &str = r#"name = "m" on_abort = "aborted" on_budget = "stuck" [[state]] name = "a" kind = "start" steps = [{ name = "long", run = "computer", cmd = "sleep 30" }] next = "done" "#; #[test] fn abort_kills_a_running_command_and_goes_to_on_abort() { let e = env("abort"); let m = ctl_machine(ABORTABLE); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); let u = user( &e, |ev| has(ev, "state"), |db| { db.add_command("s1", "abort", &json!({})).unwrap(); }, ); let t0 = Instant::now(); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), "aborted" ); u.join().unwrap(); assert!( t0.elapsed() < Duration::from_secs(10), "the sleep 30 was killed, not waited for" ); let ev = e.db.events(Some("s1"), 0).unwrap(); let g = ev.iter().find(|v| v.kind == "goto").unwrap(); assert_eq!( (g.payload["to"].as_str(), g.payload["why"].as_str()), (Some("aborted"), Some("abort")) ); assert_eq!(states(&e.db, "s1"), ["a", "aborted"]); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn force_state_jumps_and_an_unknown_state_is_refused() { let e = env("force"); let m = ctl_machine(ABORTABLE); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); let u = user( &e, |ev| has(ev, "state"), |db| { db.add_command("s1", "goto", &json!({"state": "nowhere"})) .unwrap(); std::thread::sleep(Duration::from_millis(400)); // the bad one is taken and refused first db.add_command("s1", "goto", &json!({"state": "done", "why": "forced"})) .unwrap(); }, ); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), "merged" ); u.join().unwrap(); let ev = e.db.events(Some("s1"), 0).unwrap(); let bad = ev .iter() .find(|v| v.kind == "command_failed") .expect("refused"); assert!(bad.payload["error"].as_str().unwrap().contains("nowhere")); assert_eq!(states(&e.db, "s1"), ["a", "done"]); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn abort_cancels_an_open_needs_you_item() { let e = env("abort-need"); let m = ctl_machine( r#"name = "m" on_abort = "aborted" [[state]] name = "review" kind = "start" steps = [{ name = "wait", run = "human" }] next = "done" "#, ); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); let u = user( &e, |ev| has(ev, "need"), |db| { db.add_command("s1", "abort", &json!({})).unwrap(); }, ); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), "aborted" ); u.join().unwrap(); assert!( e.db.pending_needs().unwrap().is_empty(), "the moot item left the queue" ); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn budget_stop_interrupts_hx_and_goes_to_on_budget() { let e = env("budget"); let m = ctl_machine( r#"name = "m" on_abort = "aborted" on_budget = "stuck" [budget] cost = 1.0 [[state]] name = "a" kind = "start" steps = [{ name = "ag", run = "agent", prompt = "implement" }] next = "done" "#, ); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); // hx reports $2.50 spent and keeps working until it is interrupted let p = fake("FAKE_MODE=slow FAKE_USAGE=1000,100000,2.5"); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), "escalated" ); let ev = e.db.events(Some("s1"), 0).unwrap(); let b = ev .iter() .find(|v| v.kind == "budget") .expect("budget event"); assert_eq!(b.payload["what"], "cost"); assert_eq!( (b.payload["used"].as_str(), b.payload["limit"].as_str()), (Some("$2.50"), Some("$1.00")) ); let g = ev.iter().find(|v| v.kind == "goto").unwrap(); assert_eq!( (g.payload["to"].as_str(), g.payload["why"].as_str()), (Some("stuck"), Some("budget")) ); assert_eq!( ev.iter().filter(|v| v.kind == "budget").count(), 1, "stops once, not on every poll" ); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn a_budget_without_on_budget_fails_the_session() { let e = env("budget-fail"); let m = ctl_machine( r#"name = "m" [budget] cost = 1.0 [[state]] name = "a" kind = "start" steps = [{ name = "ag", run = "agent", prompt = "implement" }] next = "done" "#, ); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); let p = fake("FAKE_MODE=slow FAKE_USAGE=1000,100000,2.5"); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), "failed" ); assert!( failure_reason(&e).contains("budget: cost $2.50 > $1.00"), "{}", failure_reason(&e) ); let _ = std::fs::remove_dir_all(&e.dir); } const SLOW_AGENT: &str = r#"name = "m" on_abort = "aborted" [[state]] name = "a" kind = "start" steps = [{ name = "ag", run = "agent", prompt = "implement" }] next = "done" "#; #[test] fn interrupt_asks_what_now_and_the_reply_goes_to_hx() { let e = env("interrupt"); let log = e.dir.join("fake.log"); let m = ctl_machine(SLOW_AGENT); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); let u = user( &e, |ev| has(ev, "intent"), |db| { db.add_command("s1", "interrupt", &json!({})).unwrap(); }, ); let answerer = answerer(e.dir.join("orch.db"), &["reply: try tokens"]); let p = fake(&format!("FAKE_MODE=slow FAKE_LOG={}", log.display())); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), "merged" ); u.join().unwrap(); let seen = answerer.join().unwrap(); assert_eq!( (seen[0].0.as_str(), seen[0].1["title"].as_str()), ("input", Some("interrupted")) ); let steps: Vec = std::fs::read_to_string(&log) .unwrap() .lines() .map(|l| serde_json::from_str::(l).unwrap()) .filter(|m| m["method"] == "hx/step") .collect(); assert_eq!(steps.len(), 2, "the step ran again after the reply"); assert_eq!(steps[1]["params"]["context"]["hint"], "try tokens"); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn messages_reach_a_running_step_and_veto_goes_back_to_code() { let e = env("veto"); let m = ctl_machine( r#"name = "m" on_abort = "aborted" [[state]] name = "plan" kind = "start" steps = [{ name = "draft", run = "agent", prompt = "plan" }] next = "code" [[state]] name = "code" steps = [{ name = "edit", run = "computer", cmd = "true" }] next = "done" "#, ); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); let wt = e.dir.join("wt/s1"); let messages = wt.join("messages.txt"); let u = user( &e, |ev| has(ev, "intent"), move |db| { db.add_command("s1", "message", &json!({"text": "prefer a bucket"})) .unwrap(); // let the message arrive before the veto interrupts hx assert!(wait_until(10, || std::fs::read_to_string(&messages) .is_ok_and(|m| m.contains("prefer a bucket")))); db.add_command( "s1", "veto", &json!({"text": "sliding window", "state": "plan"}), ) .unwrap(); }, ); let p = fake("FAKE_MODE=slow"); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), "merged" ); u.join().unwrap(); let said = std::fs::read_to_string(wt.join("messages.txt")).unwrap(); assert!(said.contains("prefer a bucket")); assert!( said.contains("vetoed this decision: sliding window"), "{said}" ); assert_eq!( states(&e.db, "s1"), ["plan", "code", "done"], "veto goes back to code" ); let g = e.db.events(Some("s1"), 0) .unwrap() .into_iter() .find(|v| v.kind == "goto") .unwrap(); assert_eq!(g.payload["why"], "veto"); let _ = std::fs::remove_dir_all(&e.dir); } #[test] fn hx_is_told_to_compact_once_the_context_passes_the_threshold() { let e = env("compact"); let m = ctl_machine( r#"name = "m" on_abort = "aborted" [budget] compact_at = 85 [[state]] name = "a" kind = "start" steps = [{ name = "ag", run = "agent", prompt = "implement" }] next = "done" "#, ); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); let marker = e.dir.join("wt/s1/compact.txt"); let u = user( &e, |ev| has(ev, "intent"), move |db| { assert!(wait_until(15, || marker.exists()), "hx got hx/compact"); db.add_command("s1", "abort", &json!({})).unwrap(); }, ); let p = fake("FAKE_MODE=slow FAKE_USAGE=90000,100000,0.1"); // 90% of the window assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), "aborted" ); u.join().unwrap(); let ev = e.db.events(Some("s1"), 0).unwrap(); assert_eq!( ev.iter().filter(|v| v.kind == "compact").count(), 1, "asked once, not every second" ); let _ = std::fs::remove_dir_all(&e.dir); } }