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

+309 -3
View File
@@ -72,7 +72,7 @@ fn need_key(n: &view::Need, c: char) -> NeedKey {
}
/// What a finished input line is for.
#[derive(Clone, Copy, PartialEq, Debug)]
#[derive(Clone, PartialEq, Debug)]
enum Target {
/// Answer to this Needs-you item.
Need(i64),
@@ -80,6 +80,12 @@ enum Target {
Goal,
/// `name | command | owner` of a new acceptance check; the owner is optional.
Check,
/// A hint for the agent of this session.
Message(String),
/// Force this session into the state named in the text.
Goto(String),
/// Kill this session, but only when the text is `yes`.
Abort(String),
}
/// A one-line text entry shown at the bottom while the user writes a comment, reply, goal or check.
@@ -121,6 +127,8 @@ struct App {
need_sel: usize,
input: Option<InputLine>,
goal_view: Option<crate::goal::GoalView>,
/// Selected decision on the goal screen.
dec_sel: usize,
/// True while a background `run all checks` is going.
checks_running: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
@@ -149,11 +157,79 @@ impl App {
self.db.as_ref()
}
/// Sends a command to a running session; its runner (maybe another process) picks it up within a moment.
fn command(&mut self, session: &str, kind: &str, payload: serde_json::Value) {
if let Some(db) = &self.db {
let _ = db.add_command(session, kind, &payload);
}
}
/// Vetoes the selected decision: the agent is told, and the session goes back to `code`.
fn veto_selected(&mut self) {
let Some(d) = self
.goal_view
.as_ref()
.and_then(|g| g.decisions.get(self.dec_sel))
.filter(|d| !d.vetoed)
.cloned()
else {
return;
};
if self
.db
.as_ref()
.is_some_and(|db| db.veto_decision(d.id).unwrap_or(false))
{
self.command(
&d.session,
"veto",
serde_json::json!({"text": d.text, "state": d.state}),
);
}
self.refresh();
}
/// A finished input line: an answer for the queue, a new goal, or a new check.
fn submit(&mut self, i: InputLine) {
let text = i.text.trim().to_string();
match i.target {
Target::Need(id) => return self.answer(id, &format!("{}{text}", i.prefix)),
Target::Message(sid) => {
if !text.is_empty() {
self.command(&sid, "message", serde_json::json!({"text": text}));
}
return;
}
Target::Goto(sid) => {
let states = self
.detail
.as_ref()
.map(|d| d.states.clone())
.unwrap_or_default();
if states.contains(&text) {
self.command(
&sid,
"goto",
serde_json::json!({"state": text, "why": "forced"}),
);
} else {
self.pager = Some(Pager {
title: "force state".into(),
lines: vec![
format!("no state {text:?}"),
format!("states: {}", states.join(", ")),
],
scroll: 0,
});
}
return;
}
Target::Abort(sid) => {
if text == "yes" {
self.command(&sid, "abort", serde_json::json!({}));
}
return;
}
Target::Goal if !text.is_empty() => {
if let Some(db) = self.db_or_create() {
let _ = db.set_goal(&text);
@@ -195,6 +271,7 @@ impl App {
need_sel: 0,
input: None,
goal_view: None,
dec_sel: 0,
checks_running: Default::default(),
}
}
@@ -378,7 +455,7 @@ fn draw(f: &mut ratatui::Frame, app: &App, header: &Header) {
}
};
let running = app.checks_running.load(std::sync::atomic::Ordering::SeqCst);
goal::draw(f, g, header, running);
goal::draw(f, g, header, running, app.dec_sel);
}
_ => overview::draw(f, &app.overview, header, app.sel, app.need_sel),
}
@@ -655,6 +732,15 @@ fn on_key(
});
}
KeyCode::Char('R') => app.run_all_checks(),
KeyCode::Char('j') | KeyCode::Down => {
let last = app
.goal_view
.as_ref()
.map_or(0, |g| g.decisions.len().saturating_sub(1));
app.dec_sel = (app.dec_sel + 1).min(last);
}
KeyCode::Char('k') | KeyCode::Up => app.dec_sel = app.dec_sel.saturating_sub(1),
KeyCode::Char('v') => app.veto_selected(),
_ => {}
},
Screen::Session(id) => {
@@ -664,6 +750,44 @@ fn on_key(
app.screen = Screen::Overview;
app.detail = None;
}
KeyCode::Char('i') => app.command(&id, "interrupt", serde_json::json!({})),
KeyCode::Char('m') => {
app.input = Some(InputLine {
label: "message to the agent",
prefix: "",
target: Target::Message(id),
text: String::new(),
});
}
KeyCode::Char('s') => {
app.input = Some(InputLine {
label: "force state",
prefix: "",
target: Target::Goto(id),
text: String::new(),
});
}
KeyCode::Char('k') => {
app.input = Some(InputLine {
label: "type yes to kill this session (hx stops, it goes to on abort)",
prefix: "",
target: Target::Abort(id),
text: String::new(),
});
}
// re-plan from the start state; only offered while the loop detector shows
KeyCode::Char('r') if app.detail.as_ref().is_some_and(|d| d.looping.is_some()) => {
let start = app
.detail
.as_ref()
.map(|d| d.start.clone())
.unwrap_or_default();
app.command(
&id,
"goto",
serde_json::json!({"state": start, "why": "replan"}),
);
}
KeyCode::Char('t') => app.pager = Some(test_output(app, &id)),
KeyCode::Char('l') => app.pager = Some(transcript(app, &id)),
KeyCode::Char('d') => {
@@ -713,6 +837,7 @@ mod tests {
use super::*;
use crate::view::{Chip, EventLine, Mark, Need, NeedKind, Row, Status};
use ratatui::{Terminal, backend::TestBackend};
use serde_json::json;
fn screen(o: &Overview, sel: usize) -> String {
let mut t = Terminal::new(TestBackend::new(160, 45)).unwrap();
@@ -772,6 +897,7 @@ mod tests {
machine: "task.toml".into(),
chips: chips(spec),
retry: retry.into(),
looping: false,
tests: tests.into(),
tests_ok: ok,
added: 164,
@@ -1202,7 +1328,7 @@ end = "merged"
rev: "main@abc".into(),
now_ms: 0,
};
t.draw(|f| goal::draw(f, g, &h, running)).unwrap();
t.draw(|f| goal::draw(f, g, &h, running, 0)).unwrap();
let b = t.backend().buffer();
b.content()
.chunks(b.area.width as usize)
@@ -1332,4 +1458,184 @@ end = "merged"
assert_eq!(parse_check("| b"), None);
let _ = std::fs::remove_dir_all(&dir);
}
/// A repo with `task.toml` and a running session s2 whose last two test runs failed on the same two tests.
fn looping_repo(tag: &str) -> (PathBuf, Db) {
let dir = std::env::temp_dir().join(format!("orch-tui-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join(".hx/machines")).unwrap();
std::fs::write(
dir.join(".hx/machines/task.toml"),
include_str!("../../examples/machines/task.toml"),
)
.unwrap();
let db = Db::open(&dir.join(".hx/orch.db")).unwrap();
add(&db, "s2", "oauth-provider", &[], "code", "running");
let run = |names: &[&str]| {
let f: Vec<_> = names
.iter()
.map(|n| json!({"name": n, "message": "left != right", "location": "src/token.rs:142"}))
.collect();
db.emit("s2", "test", json!({"state": "test", "step": "cargo test", "passed": 39, "failed": names.len(), "skipped": 0, "secs": 6.2, "failures": f})).unwrap();
};
let go = |from: &str, to: &str| {
db.emit("s2", "state", json!({"from": from, "to": to}))
.unwrap();
};
go("", "plan");
go("plan", "code");
go("code", "build");
go("build", "test");
run(&["auth::token::refresh", "auth::token::expired"]);
db.emit(
"s2",
"catch",
json!({"state": "test", "catch": "TestsFailed"}),
)
.unwrap();
go("test", "code");
db.emit(
"s2",
"edit",
json!({"path": "src/token.rs", "added": 6, "removed": 2}),
)
.unwrap();
go("code", "build");
go("build", "test");
run(&["auth::token::expired", "auth::token::refresh"]);
db.emit(
"s2",
"catch",
json!({"state": "test", "catch": "TestsFailed"}),
)
.unwrap();
go("test", "code");
db.emit(
"s2",
"usage",
json!({"ctx_used": 142_000, "ctx_limit": 200_000, "cost": 1.12}),
)
.unwrap();
(dir, db)
}
#[test]
fn the_session_screen_shows_the_loop_detector_and_budget_caps() {
let (dir, db) = looping_repo("loop");
let mut app = App::new(dir.clone());
app.screen = Screen::Session("s2".into());
app.refresh();
let d = app.detail.as_ref().expect("detail").clone();
assert_eq!(d.looping.as_ref().map(|l| (l.runs, l.tests)), Some((2, 2)));
let mut t = Terminal::new(TestBackend::new(160, 45)).unwrap();
let h = Header {
repo: "~/r".into(),
rev: "main@abc".into(),
now_ms: 0,
};
t.draw(|f| session::draw(f, &d, &h)).unwrap();
let b = t.backend().buffer();
let text = b
.content()
.chunks(b.area.width as usize)
.map(|r| {
r.iter()
.map(|c| c.symbol())
.collect::<String>()
.trim_end()
.to_string()
})
.collect::<Vec<_>>()
.join("\n");
if std::env::var_os("ORCH_DUMP").is_some() {
println!("{text}");
}
for want in [
"◆ Loop detector",
"The last 2 test runs failed on the same 2 tests.",
"editing src/token.rs.",
"[r] re-plan from PLAN [m] send hint to agent",
"[k] kill and hand over",
"142k / 200k compact at 85%",
"$1.12 / $5.00",
"/ 1h cap",
" r re-plan",
" i interrupt",
" k kill",
] {
assert!(text.contains(want), "missing {want:?} in:\n{text}");
}
// the overview marks the row too
let o = screen(&app.overview, 0);
assert!(o.contains("· looping"), "{o}");
drop(db);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn session_keys_become_commands_and_bad_input_is_refused() {
let (dir, _db) = looping_repo("cmds");
let mut app = App::new(dir.clone());
app.screen = Screen::Session("s2".into());
app.refresh();
let line = |target, text: &str| InputLine {
label: "x",
prefix: "",
target,
text: text.into(),
};
app.submit(line(Target::Message("s2".into()), " use a bucket "));
app.submit(line(Target::Message("s2".into()), " ")); // empty: nothing sent
app.submit(line(Target::Goto("s2".into()), "review"));
app.submit(line(Target::Goto("s2".into()), "nowhere"));
assert!(app.pager.as_ref().unwrap().lines[1].contains("states: plan, code"));
app.submit(line(Target::Abort("s2".into()), "no"));
app.submit(line(Target::Abort("s2".into()), "yes"));
app.command("s2", "interrupt", json!({}));
let db = Db::open(&dir.join(".hx/orch.db")).unwrap();
let cmds = db.take_commands("s2").unwrap();
let kinds: Vec<_> = cmds.iter().map(|c| c.0.as_str()).collect();
assert_eq!(kinds, ["message", "goto", "abort", "interrupt"]);
assert_eq!(cmds[0].1["text"], "use a bucket");
assert_eq!(
(cmds[1].1["state"].as_str(), cmds[1].1["why"].as_str()),
(Some("review"), Some("forced"))
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn vetoing_a_decision_marks_it_and_tells_the_session() {
let (dir, db) = looping_repo("veto");
db.add_decision("s2", "token bucket in Redis", "plan")
.unwrap();
db.add_decision("s2", "limit keyed by user id", "code")
.unwrap();
let mut app = App::new(dir.clone());
app.screen = Screen::Goal;
app.refresh();
app.dec_sel = 1;
app.veto_selected();
app.veto_selected(); // already vetoed: no second command
let ds = db.decisions().unwrap();
assert_eq!(
ds.iter().map(|d| d.vetoed).collect::<Vec<_>>(),
[false, true]
);
let cmds = db.take_commands("s2").unwrap();
assert_eq!(cmds.len(), 1);
assert_eq!(cmds[0].0, "veto");
assert_eq!(
(cmds[0].1["text"].as_str(), cmds[0].1["state"].as_str()),
(Some("limit keyed by user id"), Some("code"))
);
// the goal screen shows it struck out and tagged
let text = goal_text(app.goal_view.as_ref().unwrap(), false);
assert!(
text.contains("limit keyed by user id") && text.contains("vetoed"),
"{text}"
);
assert!(text.contains("v veto decision"));
let _ = std::fs::remove_dir_all(&dir);
}
}