Add state-machine sessions, event table and TUI overview

- machine.rs: TOML machine parser/validator, four example machines
- db.rs: per-goal SQLite (.hx/orch.db) with append-only events
- runner.rs: session runner for computer steps (catches, retries, resume)
- view.rs + tui/: sessions overview built from events; bare `orch` opens it
- orch session: create and run a session from the CLI
- devenv with git and sqlite

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
johannesandClaude Sonnet 5.5 committed 2026-11-14 11:58:23 +01:00
1 parent 374cf28aed
commit d66a014bc5
19 files changed
+4525 -8

No files matched your search

+394
View File
@@ -0,0 +1,394 @@
//! 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.
use crate::db::{Db, Session, Task};
use crate::machine::{Kind, Machine, RunOn, State, Step};
use crate::run::{git, tail};
use anyhow::{Context, Result, bail};
use serde_json::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;
/// Creates the task and session rows for a new session. The worktree is made by [`run_session`].
pub fn create(
db: &Db,
worktrees: &Path,
name: &str,
subtitle: &str,
machine: &str,
) -> Result<Session> {
let id = db.next_session_id()?;
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: 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) -> String {
cmd.replace("{{session}}", &s.id)
.replace("{{scope}}", scope)
.replace("{{worktree}}", &s.worktree)
.replace("{{branch}}", &s.branch)
}
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(())
}
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> {
for step in &st.steps {
if let Some(label) = &step.sets {
db.emit(
&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,
"step",
json!({
"state": st.name, "step": step.name, "run": step.run, "ok": ok,
"exit": exit, "ms": t0.elapsed().as_millis() as u64, "output": out,
}),
)?;
if !ok {
let catch = 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)
}
/// (success, exit code, output tail)
fn run_step(s: &Session, step: &Step, scope: &str) -> Result<(bool, Option<i32>, String)> {
match step.run {
RunOn::Computer => {}
other => bail!(
"step {:?}: {other:?} steps are not supported yet (milestone 4/6)",
step.name
),
}
let Some(cmd) = &step.cmd else {
return Ok((true, Some(0), String::new())); // marker step (open-diff, mark-merged, ...)
};
let o = Command::new("sh")
.args(["-c", &format!("({}) 2>&1", render(cmd, s, scope))])
.current_dir(&s.worktree)
.output()?;
Ok((
o.status.success(),
o.status.code(),
tail(&o.stdout, OUTPUT_TAIL),
))
}
/// 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> {
let s = db
.session(id)?
.with_context(|| format!("no session {id}"))?;
ensure_worktree(repo, &s)?;
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")?;
let result = run_state(db, &s, st, scope);
let outcome = match result {
Ok(o) => o,
Err(e) => return finish(db, id, &cur, "failed", Some(format!("{e:#}"))),
};
from = cur.clone();
match outcome {
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!("fail_as {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")),
)
}
fn finish(db: &Db, id: &str, state: &str, status: &str, reason: Option<String>) -> Result<String> {
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<String> {
db.events(Some(id), 0)
.unwrap()
.iter()
.filter(|e| e.kind == "state")
.map(|e| e.payload["to"].as_str().unwrap().to_string())
.collect()
}
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, "").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")
);
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, "").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, "").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");
let _ = std::fs::remove_dir_all(&e.dir);
}
#[test]
fn agent_step_fails_the_session_cleanly() {
let e = env("agent");
let m = Machine::parse(&format!(
r#"name = "m"
[[state]]
name = "a"
kind = "start"
steps = [{{ name = "ag", run = "agent", prompt = "plan" }}]
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!(
end.payload["reason"]
.as_str()
.unwrap()
.contains("not supported")
);
let _ = std::fs::remove_dir_all(&e.dir);
}
}