Add ACP agent steps, JUnit reports and session detail screen

- acp.rs: ACP client for hx serve --acp, hx/* events into the event table
- tests/fake_acp_hx.py: Python fake hx for the runner tests
- runner.rs: agent steps, blocked catches, failure context, junit test events
- junit.rs: JUnit XML parser (counts, failing tests, locations)
- detail.rs + tui/session.rs: session detail screen with machine view
- tui: enter/esc navigation, pagers for test output, diff and transcript

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
johannesandClaude Sonnet 5.5 committed 2026-11-14 12:14:25 +01:00
1 parent d66a014bc5
commit 5b659fa8ba
14 files changed
+2676 -91

No files matched your search

+439 -58
View File
@@ -1,18 +1,22 @@
//! Session runner (ORCHESTRATOR.md section 4): walks one session through its machine, writes every step to the
//! event table. Milestone 2 handles `computer` steps only; `agent` and `human` steps fail the session for now.
//! 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 `needs_input` results wait for the Needs-you queue (milestone 6) and fail the session for now.
use crate::acp::{Acp, Sink, StepResult};
use crate::db::{Db, Session, Task};
use crate::machine::{Kind, Machine, RunOn, State, Step};
use crate::profile::Profile;
use crate::run::{git, tail};
use anyhow::{Context, Result, bail};
use serde_json::json;
use serde_json::{Value, json};
use std::path::Path;
use std::process::Command;
use std::time::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;
const OUTPUT_TAIL: usize = 2000;
/// 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`].
pub fn create(
@@ -76,35 +80,54 @@ fn ensure_worktree(repo: &Path, s: &Session) -> Result<()> {
Ok(())
}
/// 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,
agent: Option<Acp>,
}
enum Outcome {
Ok,
/// A step failed with this catch name.
Caught(String),
}
fn run_state(db: &Db, s: &Session, st: &State, scope: &str) -> Result<Outcome> {
struct StepRes {
ok: bool,
exit: Option<i32>,
/// 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<String>,
}
fn run_state(cx: &mut Ctx, st: &State) -> Result<Outcome> {
for step in &st.steps {
if let Some(label) = &step.sets {
db.emit(
&s.id,
cx.db.emit(
&cx.s.id,
"status",
json!({"state": st.name, "step": step.name, "label": label}),
)?;
}
let t0 = Instant::now();
let (ok, exit, out) = run_step(s, step, scope)?;
db.emit(
&s.id,
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": ok,
"exit": exit, "ms": t0.elapsed().as_millis() as u64, "output": out,
"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 !ok {
let catch = step
.fail_as
.clone()
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!(
@@ -119,36 +142,216 @@ fn run_state(db: &Db, s: &Session, st: &State, scope: &str) -> Result<Outcome> {
Ok(Outcome::Ok)
}
/// (success, exit code, output tail)
fn run_step(s: &Session, step: &Step, scope: &str) -> Result<(bool, Option<i32>, String)> {
fn run_step(cx: &mut Ctx, st: &State, step: &Step) -> Result<StepRes> {
match step.run {
RunOn::Computer => {}
other => bail!(
"step {:?}: {other:?} steps are not supported yet (milestone 4/6)",
RunOn::Computer => run_command(cx, st, step),
RunOn::Agent => run_agent(cx, st, step),
RunOn::Human => bail!(
"step {:?}: human steps need the Needs-you queue (milestone 6)",
step.name
),
}
}
/// 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<StepRes> {
let Some(cmd) = &step.cmd else {
return Ok((true, Some(0), String::new())); // marker step (open-diff, mark-merged, ...)
// 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 o = Command::new("sh")
.args(["-c", &format!("({}) 2>&1", render(cmd, s, scope))])
.current_dir(&s.worktree)
.args([
"-c",
&format!(
"({}) 2>&1",
render(cmd, cx.s, cx.scope).replace("{{report}}", &report)
),
])
.env("ORCH_REPORT", &report)
.current_dir(&cx.s.worktree)
.output()?;
Ok((
o.status.success(),
o.status.code(),
tail(&o.stdout, OUTPUT_TAIL),
))
let mut out = tail(&o.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: o.status.success(),
exit: o.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<Value> {
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<StepRes> {
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()?;
let context = json!({"state": st.name, "last_failure": last_failure(cx.db, &cx.s.id)?});
let mut sink = DbSink {
db: cx.db,
session: &cx.s.id,
};
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,
)?;
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" => bail!(
"hx asked {:?}; needs_input needs the Needs-you queue (milestone 6)",
r.question.unwrap_or_default()
),
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,
}
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(())
}
/// Until the Needs-you queue exists (milestone 6) every permission request is denied and recorded.
fn permission(&mut self, p: &Value) -> Option<String> {
let deny = p["options"].as_array().and_then(|o| {
o.iter()
.find(|o| o["kind"].as_str().is_some_and(|k| k.starts_with("reject")))
.and_then(|o| o["optionId"].as_str().map(String::from))
});
let _ = self.db.emit(
self.session,
"permission",
json!({"tool": p["toolCall"]["title"], "decision": "denied"}),
);
deny
}
}
/// 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) -> Result<String> {
pub fn run_session(
db: &Db,
m: &Machine,
id: &str,
repo: &Path,
scope: &str,
profile: &Profile,
) -> Result<String> {
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))?;
ensure_worktree(repo, &s)?;
let mut cx = Ctx {
db,
s: &s,
task: &task,
profile,
scope,
agent: None,
};
let mut resumed = !s.state.is_empty();
let (mut cur, mut from) = if resumed {
db.emit(id, "resume", json!({"state": s.state}))?;
@@ -167,8 +370,7 @@ pub fn run_session(db: &Db, m: &Machine, id: &str, repo: &Path, scope: &str) ->
}
resumed = false;
db.set_session(id, &cur, "running")?;
let result = run_state(db, &s, st, scope);
let outcome = match result {
let outcome = match run_state(&mut cx, st) {
Ok(o) => o,
Err(e) => return finish(db, id, &cur, "failed", Some(format!("{e:#}"))),
};
@@ -192,8 +394,7 @@ pub fn run_session(db: &Db, m: &Machine, id: &str, repo: &Path, scope: &str) ->
_ => match st.catch.get(&c) {
Some(t) => t.clone(),
None => {
let why =
format!("fail_as {c:?} is not a catch of state {:?}", st.name);
let why = format!("{c:?} is not a catch of state {:?}", st.name);
return finish(db, id, &cur, "failed", Some(why));
}
},
@@ -252,6 +453,24 @@ mod tests {
.collect()
}
fn kinds(db: &Db, id: &str) -> Vec<String> {
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"
@@ -283,19 +502,14 @@ next = "done"
.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, "").unwrap();
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!(
e.db.events(Some("s1"), 0)
.unwrap()
.iter()
.any(|v| v.kind == "status")
);
assert!(kinds(&e.db, "s1").contains(&"status".to_string()));
let _ = std::fs::remove_dir_all(&e.dir);
}
@@ -320,7 +534,7 @@ next = "done"
.unwrap();
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "").unwrap(),
run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(),
"escalated"
);
assert_eq!(
@@ -351,44 +565,211 @@ next = "done"
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, "").unwrap(), "merged");
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());
let kinds: Vec<_> =
e.db.events(Some("s1"), 0)
.unwrap()
.into_iter()
.map(|v| v.kind)
.collect();
assert_eq!(kinds[0], "resume");
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 agent_step_fails_the_session_cleanly() {
let e = env("agent");
fn junit_report_becomes_a_test_event() {
let e = env("junit");
let m = Machine::parse(&format!(
r#"name = "m"
[[state]]
name = "a"
name = "test"
kind = "start"
steps = [{{ name = "ag", run = "agent", prompt = "plan" }}]
steps = [{{ name = "t", run = "computer", report = "junit", cmd = "printf '<testsuite><testcase name=\"a::ok\"/><testcase name=\"a::bad\"><failure message=\"nope\">at src/x.rs:9:1</failure></testcase></testsuite>' > {{{{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, "").unwrap(), "failed");
let end = e.db.events(Some("s1"), 0).unwrap().pop().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!(
end.payload["reason"]
step.payload["output"]
.as_str()
.unwrap()
.contains("not supported")
.contains("to-stdout")
);
let _ = std::fs::remove_dir_all(&e.dir);
}
#[test]
fn human_step_fails_the_session_cleanly() {
let e = env("human");
let m = one_step(r#"{ name = "ok", run = "human" }"#);
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(),
"failed"
);
assert!(failure_reason(&e).contains("milestone 6"));
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<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(), 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_requests_are_denied_and_recorded() {
let e = env("perm");
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=permission");
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(),
"merged"
);
let answer = std::fs::read_to_string(e.dir.join("wt/s1/permission.txt")).unwrap();
assert!(answer.contains("\"optionId\": \"deny\""), "{answer}");
let ev = e.db.events(Some("s1"), 0).unwrap();
let perm = ev.iter().find(|v| v.kind == "permission").unwrap();
assert_eq!(perm.payload["tool"], "docker compose up -d redis");
let _ = std::fs::remove_dir_all(&e.dir);
}
#[test]
fn needs_input_and_a_crashing_hx_fail_the_session() {
let e = env("fail");
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=needs_input");
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(),
"failed"
);
assert!(failure_reason(&e).contains("Which provider?"));
let e2 = env("crash");
create(&e2.db, &e2.dir.join("wt"), "t", "", "m").unwrap();
let p = fake("FAKE_MODE=crash");
assert_eq!(
run_session(&e2.db, &m, "s1", &e2.repo, "", &p).unwrap(),
"failed"
);
assert!(failure_reason(&e2).contains("hx closed its output"));
let _ = std::fs::remove_dir_all(&e.dir);
let _ = std::fs::remove_dir_all(&e2.dir);
}
}