Add loop detector, budgets, and live session control

Milestone 8: the loop detector alerts when test failures repeat, budget
caps limit context/cost/wall-time per session with compaction support,
and live control lets you interrupt, message, or kill a running session
from the TUI. Decisions can now be vetoed, which sends hx/message and
rewinds the session to code. All 82 tests pass.

- src/budget.rs: pure functions for active time, budgets and loop detect
- src/runner.rs: Ctl control object polls for commands ~100ms, handles
  interrupt/message/abort/stop at every blocking point, re-runs on
  hints, and compacts when context is high
- src/db.rs: commands table for TUI→runner control
- src/detail.rs, src/goal.rs, src/tui/: loop detector box, budget caps,
  session keys (i/m/s/k/r), goal keys (v for veto), state forcing
- tests/fake_acp_hx.py: slow mode and hx/message, hx/compact log
- examples/machines/task.toml: [budget] with wall_secs, cost, compact_at

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
johannesandClaude Haiku 4.5 committed 2026-11-14 12:55:44 +01:00
1 parent 7bf0986640
commit bf609c2e0e
16 files changed
+1694 -55

No files matched your search

+739 -24
View File
@@ -4,15 +4,19 @@
//! 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, Sink, StepResult};
use crate::db::{Db, Session, Task};
use crate::machine::{Kind, Machine, RunOn, State, Step};
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;
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).
@@ -99,6 +103,222 @@ fn ensure_worktree(repo: &Path, s: &Session) -> Result<()> {
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<String>,
on_budget: Option<String>,
states: Vec<String>,
start: String,
stop: RefCell<Option<Stop>>,
/// The user pressed interrupt (without asking to go anywhere).
interrupted: Cell<bool>,
/// In the state that handles a budget stop or an abort: budgets no longer apply there.
exempt: Cell<bool>,
last_budget: Cell<Instant>,
last_compact: Cell<Instant>,
compacted: Cell<bool>,
}
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<Stop> {
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<Poll> {
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,
@@ -107,6 +327,7 @@ struct Ctx<'a> {
profile: &'a Profile,
scope: &'a str,
repo: &'a Path,
ctl: Ctl<'a>,
agent: Option<Acp>,
}
@@ -114,6 +335,8 @@ 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 {
@@ -134,6 +357,11 @@ fn run_state(cx: &mut Ctx, st: &State) -> Result<Outcome> {
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(
@@ -144,6 +372,9 @@ fn run_state(cx: &mut Ctx, st: &State) -> Result<Outcome> {
"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
@@ -173,13 +404,14 @@ fn run_step(cx: &mut Ctx, st: &State, step: &Step) -> Result<StepRes> {
/// 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(
db: &Db,
ctl: &Ctl,
session: &str,
state: &str,
kind: &str,
payload: Value,
reuse: bool,
) -> Result<String> {
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)?
@@ -204,6 +436,17 @@ fn ask(
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)?;
@@ -255,7 +498,7 @@ fn run_human(cx: &Ctx, st: &State, step: &Step) -> Result<StepRes> {
"state": st.name, "step": step.name, "title": title,
"detail": review_summary(cx.db, &cx.s.id)?,
});
let answer = ask(cx.db, &cx.s.id, &st.name, "review", payload, true)?;
let answer = ask(&cx.ctl, &cx.s.id, &st.name, "review", payload, true)?;
if answer == "approve" {
return Ok(StepRes {
ok: true,
@@ -279,16 +522,18 @@ fn run_human(cx: &Ctx, st: &State, step: &Step) -> Result<StepRes> {
})
}
/// A comment from a reviewer that no agent step has seen yet.
/// Reviewer comments and user hints (messages, vetoes) that no agent step has seen yet, oldest first.
fn pending_comment(db: &Db, id: &str) -> Result<Option<String>> {
let mut texts = vec![];
for e in db.events(Some(id), 0)?.into_iter().rev() {
match e.kind.as_str() {
"comment" => return Ok(e.payload["text"].as_str().map(String::from)),
"step" if e.payload["run"] == "agent" => return Ok(None),
"comment" | "hint" => texts.extend(e.payload["text"].as_str().map(String::from)),
"step" if e.payload["run"] == "agent" => break,
_ => {}
}
}
Ok(None)
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.
@@ -309,7 +554,7 @@ fn run_command(cx: &Ctx, st: &State, step: &Step) -> Result<StepRes> {
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 o = Command::new("sh")
let mut child = Command::new("sh")
.args([
"-c",
&format!(
@@ -323,8 +568,31 @@ fn run_command(cx: &Ctx, st: &State, step: &Step) -> Result<StepRes> {
.env("ORCH_REPO", cx.repo)
.env("ORCH_SESSION", &cx.s.id)
.current_dir(&cx.s.worktree)
.output()?;
let mut out = tail(&o.stdout, OUTPUT_TAIL);
.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)
{
@@ -343,8 +611,8 @@ fn run_command(cx: &Ctx, st: &State, step: &Step) -> Result<StepRes> {
}
}
Ok(StepRes {
ok: o.status.success(),
exit: o.status.code(),
ok: status.success(),
exit: status.code(),
out,
catch: None,
})
@@ -398,7 +666,9 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result<StepRes> {
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,
@@ -407,6 +677,21 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result<StepRes> {
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,
@@ -426,7 +711,7 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result<StepRes> {
"key": format!("{}/{}/input", st.name, step.name),
"state": st.name, "step": step.name, "title": "question", "detail": question,
});
let answer = ask(cx.db, &cx.s.id, &st.name, "input", payload, true)?;
let answer = ask(&cx.ctl, &cx.s.id, &st.name, "input", payload, true)?;
hint = Some(
answer
.strip_prefix("reply:")
@@ -446,6 +731,7 @@ 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`.
@@ -492,6 +778,12 @@ impl Sink for DbSink<'_> {
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<String> {
@@ -505,7 +797,7 @@ impl Sink for DbSink<'_> {
"detail": format!("wants to run {tool}"), "options": opts,
});
ask(
self.db,
self.ctl,
self.session,
self.state,
"permission",
@@ -545,8 +837,16 @@ pub fn run_session(
.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() {
wait_for_dependencies(db, &s, &task)?;
match wait_for_dependencies(&ctl, &s, &task) {
Ok(()) => {}
Err(e) if e.is::<Stopped>() => {
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 {
@@ -556,6 +856,7 @@ pub fn run_session(
profile,
scope,
repo,
ctl,
agent: None,
};
let mut resumed = !s.state.is_empty();
@@ -576,12 +877,15 @@ pub fn run_session(
}
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");
if merging {
enter_merge_queue(db, id)?;
}
let result = run_state(&mut cx, st);
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))
@@ -593,10 +897,25 @@ pub fn run_session(
}
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::<Stopped>() => 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());
@@ -635,9 +954,14 @@ pub fn run_session(
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(db: &Db, s: &Session, t: &Task) -> Result<()> {
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()
@@ -671,13 +995,19 @@ fn alive(db: &Db, session: &str) -> bool {
}
/// Joins the merge queue and blocks until this session is at the head.
fn enter_merge_queue(db: &Db, id: &str) -> Result<()> {
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)?,
@@ -1357,4 +1687,389 @@ end = "merged"
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<Value> = std::fs::read_to_string(&log)
.unwrap()
.lines()
.map(|l| serde_json::from_str::<Value>(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);
}
}