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

+316
View File
@@ -0,0 +1,316 @@
//! Machine files: TOML state machines that drive one session (see ORCHESTRATOR.md section 3).
// shortcut: nothing calls this yet; the session runner (milestone 2) does. Remove then.
#![allow(dead_code)]
use anyhow::{Context, Result, bail, ensure};
use indexmap::IndexMap;
use serde::Deserialize;
use std::path::{Path, PathBuf};
#[derive(Deserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
Start,
#[default]
Normal,
Gate,
Exit,
Abort,
}
#[derive(Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq, Debug)]
#[serde(rename_all = "lowercase")]
pub enum RunOn {
Computer,
Agent,
Human,
}
#[derive(Deserialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct Step {
pub name: String,
pub run: RunOn,
/// Shell command (`computer`); supports {{session}} {{scope}} {{worktree}} {{branch}}.
pub cmd: Option<String>,
/// Status label shown as `■ <label>`.
pub sets: Option<String>,
/// Prompt kind for `agent` steps.
pub prompt: Option<String>,
/// Test report format the orchestrator parses after the step (`junit`).
pub report: Option<String>,
/// Catch to raise when the step fails; default is the first catch of the state.
pub fail_as: Option<String>,
}
#[derive(Deserialize, Clone, Debug)]
pub struct Retry {
pub max: u32,
pub then: String,
}
#[derive(Deserialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct State {
pub name: String,
#[serde(default)]
pub kind: Kind,
#[serde(default)]
pub steps: Vec<Step>,
/// Catch name -> target state. Order matters: the first key is the default catch.
#[serde(default)]
pub catch: IndexMap<String, String>,
#[serde(default)]
pub retry: IndexMap<String, Retry>,
pub next: Option<String>,
/// Final session status for `exit` and `abort` states.
pub end: Option<String>,
/// Never entered by `next`; only by these catches or events.
#[serde(default)]
pub only_on: Vec<String>,
}
#[derive(Deserialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct Machine {
pub name: String,
pub on_abort: Option<String>,
pub on_budget: Option<String>,
#[serde(rename = "state")]
pub states: Vec<State>,
}
impl Machine {
pub fn parse(text: &str) -> Result<Self> {
let m: Machine = toml::from_str(text)?;
m.validate()?;
Ok(m)
}
pub fn load(path: &Path) -> Result<Self> {
let text = std::fs::read_to_string(path).with_context(|| path.display().to_string())?;
Self::parse(&text).with_context(|| format!("machine {}", path.display()))
}
/// `<name>.toml` in `<repo>/.hx/machines/`, then `~/.hx/machines/`.
pub fn find(name: &str, repo: &Path) -> Result<Self> {
let file = format!("{name}.toml");
let mut dirs = vec![repo.join(".hx/machines")];
if let Some(h) = std::env::var_os("HOME") {
dirs.push(PathBuf::from(h).join(".hx/machines"));
}
for d in &dirs {
if d.join(&file).is_file() {
return Self::load(&d.join(&file));
}
}
bail!("machine {name:?} not found in {dirs:?}")
}
pub fn state(&self, name: &str) -> Option<&State> {
self.states.iter().find(|s| s.name == name)
}
pub fn start(&self) -> &State {
// validate() guarantees exactly one
self.states
.iter()
.find(|s| s.kind == Kind::Start)
.expect("validated machine has a start state")
}
/// States shown in the overview strip: everything except `only_on` states.
pub fn strip(&self) -> impl Iterator<Item = &State> {
self.states.iter().filter(|s| s.only_on.is_empty())
}
pub fn validate(&self) -> Result<()> {
let starts = self.states.iter().filter(|s| s.kind == Kind::Start).count();
ensure!(starts == 1, "need exactly one start state, found {starts}");
let mut seen = std::collections::HashSet::new();
for s in &self.states {
ensure!(seen.insert(&s.name), "duplicate state {:?}", s.name);
}
let target = |from: &str, what: &str, to: &str| -> Result<()> {
ensure!(
self.state(to).is_some(),
"state {from:?}: {what} points at unknown state {to:?}"
);
Ok(())
};
for (what, to) in [("on_abort", &self.on_abort), ("on_budget", &self.on_budget)] {
if let Some(to) = to {
target("<machine>", what, to)?;
}
}
for s in &self.states {
let n = &s.name;
let ends = matches!(s.kind, Kind::Exit | Kind::Abort);
if ends {
ensure!(
s.end.is_some(),
"state {n:?}: {:?} state needs `end`",
s.kind
);
} else {
ensure!(s.next.is_some(), "state {n:?} needs `next`");
}
if let Some(t) = &s.next {
target(n, "next", t)?;
let dest = self.state(t).expect("checked above");
ensure!(
dest.only_on.is_empty(),
"state {n:?}: next points at {t:?}, which has only_on"
);
}
for (c, t) in &s.catch {
target(n, &format!("catch {c}"), t)?;
}
for (c, r) in &s.retry {
target(n, &format!("retry {c}"), &r.then)?;
ensure!(r.max > 0, "state {n:?}: retry {c} needs max > 0");
ensure!(
s.catch.contains_key(c),
"state {n:?}: retry {c} has no matching catch"
);
}
for st in &s.steps {
match st.run {
RunOn::Agent => ensure!(
st.prompt.is_some(),
"state {n:?} step {:?}: agent step needs `prompt`",
st.name
),
RunOn::Computer | RunOn::Human => {}
}
if let Some(f) = &st.fail_as {
ensure!(
s.catch.contains_key(f),
"state {n:?} step {:?}: fail_as {f:?} is not a catch of the state",
st.name
);
}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
const EXAMPLES: &[&str] = &["task", "migration", "docs", "e2e"];
fn example(name: &str) -> Machine {
let p = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("examples/machines")
.join(format!("{name}.toml"));
Machine::load(&p).unwrap()
}
#[test]
fn examples_load_and_validate() {
for n in EXAMPLES {
assert_eq!(example(n).name, *n);
}
}
#[test]
fn strip_matches_the_mockup() {
let names =
|n: &str| -> Vec<String> { example(n).strip().map(|s| s.name.clone()).collect() };
assert_eq!(
names("task"),
["plan", "code", "build", "test", "review", "merge"]
);
assert_eq!(
names("migration"),
["plan", "code", "up", "down", "test", "review", "merge"]
);
assert_eq!(
names("docs"),
["plan", "write", "lint", "links", "review", "merge"]
);
assert_eq!(
names("e2e"),
[
"plan",
"code",
"stack-up",
"e2e",
"stack-down",
"review",
"merge"
]
);
}
#[test]
fn task_machine_details() {
let m = example("task");
assert_eq!(m.start().name, "plan");
let t = m.state("test").unwrap();
assert_eq!(t.catch.keys().next().unwrap(), "TestsFailed");
assert_eq!(t.retry["TestsFailed"].max, 3);
assert_eq!(t.retry["TestsFailed"].then, "escalated");
assert_eq!(t.steps[0].report.as_deref(), Some("junit"));
assert_eq!(m.state("review").unwrap().kind, Kind::Gate);
}
fn err(text: &str) -> String {
format!("{:#}", Machine::parse(text).unwrap_err())
}
const OK: &str = r#"
name = "m"
[[state]]
name = "a"
kind = "start"
next = "b"
[[state]]
name = "b"
kind = "exit"
end = "done"
"#;
#[test]
fn minimal_machine_is_valid() {
Machine::parse(OK).unwrap();
}
#[test]
fn rejects_bad_machines() {
assert!(err(&OK.replace("kind = \"start\"", "")).contains("exactly one start"));
assert!(
err(&OK.replace("kind = \"exit\"", "kind = \"start\"")).contains("exactly one start")
);
assert!(err(&OK.replace("next = \"b\"", "next = \"zzz\"")).contains("unknown state"));
assert!(err(&OK.replace("next = \"b\"", "")).contains("needs `next`"));
assert!(err(&OK.replace("end = \"done\"", "")).contains("needs `end`"));
assert!(err(&format!("{OK}\n[[state]]\nname = \"a\"\nnext = \"b\"")).contains("duplicate"));
assert!(
err(&OK.replace("next = \"b\"", "next = \"b\"\ncatch = { X = \"nope\" }"))
.contains("catch X")
);
assert!(
err(&OK.replace(
"next = \"b\"",
"next = \"b\"\nretry = { X = { max = 2, then = \"b\" } }"
))
.contains("no matching catch")
);
assert!(
err(&OK.replace("end = \"done\"", "end = \"done\"\nonly_on = [\"x\"]"))
.contains("only_on")
);
assert!(
err(&OK.replace(
"next = \"b\"",
"next = \"b\"\nsteps = [{ name = \"s\", run = \"agent\" }]"
))
.contains("needs `prompt`")
);
assert!(err(&format!("{OK}\nbogus = 1")).contains("unknown field"));
}
}