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

+611
View File
@@ -0,0 +1,611 @@
//! Pure view models: sessions, tasks, events and machine files in, what a screen shows out (ORCHESTRATOR.md
//! principle 3: no panel computes state on its own). No terminal and no database in here, so it is easy to test.
use crate::db::{Event, Session, Task};
use crate::machine::Machine;
use std::collections::HashMap;
/// Overview status column. `Fail` is not in the spec's list; a failed or aborted session needs some label.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Status {
Run,
Fix,
Wait,
Blocked,
Done,
Fail,
}
impl Status {
pub fn label(self) -> &'static str {
match self {
Status::Run => "RUN",
Status::Fix => "FIX",
Status::Wait => "WAIT",
Status::Blocked => "BLOCKED",
Status::Done => "DONE",
Status::Fail => "FAIL",
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mark {
Done,
Active,
Failed,
Waiting,
Todo,
}
#[derive(Clone, PartialEq, Debug)]
pub struct Chip {
pub name: String,
pub mark: Mark,
}
#[derive(Clone, PartialEq, Debug)]
pub struct Row {
pub id: String,
pub status: Status,
pub task: String,
pub sub: String,
pub machine: String,
pub chips: Vec<Chip>,
/// `↻ fix 2/3` while the session recovers from a catch, else empty.
pub retry: String,
/// `39/41 ✗2`, `18/18 ✓` or `—`.
pub tests: String,
pub tests_ok: Option<bool>,
pub added: u32,
pub removed: u32,
/// Context used, percent.
pub ctx: Option<u8>,
pub last: String,
}
#[derive(Clone, PartialEq, Debug)]
pub struct Need {
pub session: String,
pub task: String,
pub what: String,
pub detail: String,
}
#[derive(Clone, PartialEq, Debug)]
pub struct EventLine {
pub id: i64,
pub at_ms: u64,
pub session: String,
pub kind: String,
pub text: String,
}
#[derive(Clone, Default, PartialEq, Debug)]
pub struct Overview {
pub goal: String,
pub rows: Vec<Row>,
pub needs: Vec<Need>,
pub events: Vec<EventLine>,
pub merged: usize,
pub total: usize,
/// (passing, total) acceptance checks; None until checks exist (milestone 7).
pub checks: Option<(usize, usize)>,
pub running: usize,
pub waiting: usize,
pub blocked: usize,
pub cost: f64,
pub elapsed_secs: u64,
}
pub struct Input<'a> {
pub goal: Option<&'a str>,
pub tasks: &'a [Task],
pub sessions: &'a [Session],
/// All events, oldest first.
pub events: &'a [Event],
/// Loaded machine files by name; a missing one only costs the strip.
pub machines: &'a HashMap<String, Machine>,
pub now_ms: u64,
}
pub fn build(i: &Input) -> Overview {
let mut by_session: HashMap<&str, Vec<&Event>> = HashMap::new();
for e in i.events {
by_session.entry(e.session.as_str()).or_default().push(e);
}
let none = vec![];
let mut o = Overview {
goal: i.goal.unwrap_or_default().to_string(),
total: i.tasks.len(),
..Default::default()
};
let name_of = |sid: &str| {
i.tasks
.iter()
.find(|t| t.id == sid)
.map_or_else(String::new, |t| t.name.clone())
};
for s in i.sessions {
let Some(task) = i.tasks.iter().find(|t| t.id == s.task_id) else {
continue;
};
let evs = by_session.get(s.id.as_str()).unwrap_or(&none);
let machine = i.machines.get(&task.machine);
let scan = scan(evs, s, machine);
let unmet = task.depends_on.iter().find(|d| {
i.sessions
.iter()
.find(|x| &x.id == *d)
.is_none_or(|x| x.status != "merged")
});
let status = match s.status.as_str() {
"merged" => Status::Done,
"failed" | "aborted" => Status::Fail,
"waiting" | "escalated" => Status::Wait,
"queued" if unmet.is_some() => Status::Blocked,
_ if !scan.retry.is_empty() => Status::Fix,
_ => Status::Run,
};
let last = match (status, unmet) {
(Status::Blocked, Some(d)) => format!("waits on {d} {}", name_of(d)),
(Status::Done, _) => {
let at = evs.last().map_or(0, |e| e.at);
format!("merged · {} ago", ago(i.now_ms.saturating_sub(at) / 1000))
}
_ => evs.last().map_or_else(String::new, |e| describe(e)),
};
if status == Status::Wait {
o.needs.push(Need {
session: s.id.clone(),
task: task.name.clone(),
what: s.status.clone(),
detail: evs
.iter()
.rev()
.find(|e| e.kind == "end")
.and_then(|e| e.payload["reason"].as_str().map(String::from))
.unwrap_or_default(),
});
}
match status {
Status::Run | Status::Fix => o.running += 1,
Status::Wait => o.waiting += 1,
Status::Blocked => o.blocked += 1,
Status::Done => o.merged += 1,
Status::Fail => {}
}
o.cost += scan.cost;
o.rows.push(Row {
id: s.id.clone(),
status,
task: task.name.clone(),
sub: task.subtitle.clone(),
machine: machine.map_or_else(|| task.machine.clone(), |m| format!("{}.toml", m.name)),
chips: scan.chips,
retry: scan.retry,
tests: scan.tests.0,
tests_ok: scan.tests.1,
added: scan.added,
removed: scan.removed,
ctx: scan.ctx,
last,
});
}
o.events = i
.events
.iter()
.map(|e| EventLine {
id: e.id,
at_ms: e.at,
session: e.session.clone(),
kind: e.kind.clone(),
text: line_text(e),
})
.collect();
o.elapsed_secs = i
.events
.first()
.map_or(0, |e| i.now_ms.saturating_sub(e.at) / 1000);
o
}
struct Scan {
chips: Vec<Chip>,
retry: String,
tests: (String, Option<bool>),
added: u32,
removed: u32,
ctx: Option<u8>,
cost: f64,
}
/// One pass over a session's events. Strip marks: a state that was left through a catch is failed, one left
/// normally is done, the state the session is in is active.
fn scan(evs: &[&Event], s: &Session, machine: Option<&Machine>) -> Scan {
let mut marks: HashMap<String, Mark> = HashMap::new();
let mut cur = String::new();
let mut pending_fail: Option<String> = None;
// (state, catch) the session is recovering from; cleared once that state passes again
let mut recovering: Option<(String, String)> = None;
let mut sc = Scan {
chips: vec![],
retry: String::new(),
tests: ("—".into(), None),
added: 0,
removed: 0,
ctx: None,
cost: 0.0,
};
for e in evs {
let p = &e.payload;
match e.kind.as_str() {
"catch" => {
let (st, c) = (str_of(p, "state"), str_of(p, "catch"));
pending_fail = Some(st.clone());
recovering = Some((st, c));
}
"state" => {
let (from, to) = (str_of(p, "from"), str_of(p, "to"));
if !from.is_empty() {
let failed = pending_fail.as_deref() == Some(from.as_str());
marks.insert(from.clone(), if failed { Mark::Failed } else { Mark::Done });
if !failed && recovering.as_ref().is_some_and(|(r, _)| *r == from) {
recovering = None;
}
}
pending_fail = None;
marks.insert(to.clone(), Mark::Active);
cur = to;
}
"end" => {
let ok = p["status"].as_str().is_some_and(|x| x != "failed");
marks.insert(cur.clone(), if ok { Mark::Done } else { Mark::Failed });
}
"test" => {
let (pass, fail) = (
p["passed"].as_u64().unwrap_or(0),
p["failed"].as_u64().unwrap_or(0),
);
let total = pass + fail;
sc.tests = if fail > 0 {
(format!("{pass}/{total} ✗{fail}"), Some(false))
} else {
(format!("{pass}/{total} ✓"), Some(true))
};
}
"edit" => {
sc.added += p["added"].as_u64().unwrap_or(0) as u32;
sc.removed += p["removed"].as_u64().unwrap_or(0) as u32;
}
"usage" => {
let (used, limit) = (
p["ctx_used"].as_u64().unwrap_or(0),
p["ctx_limit"].as_u64().unwrap_or(0),
);
if let Some(pct) = (used * 100).checked_div(limit) {
sc.ctx = Some(pct.min(100) as u8);
}
sc.cost = p["cost"].as_f64().unwrap_or(sc.cost);
}
_ => {}
}
}
if s.status == "waiting"
&& let Some(m) = marks.get_mut(&cur)
{
*m = Mark::Waiting;
}
if let Some(m) = machine {
sc.chips = m
.strip()
.map(|st| Chip {
name: st.name.clone(),
mark: marks.get(&st.name).copied().unwrap_or(Mark::Todo),
})
.collect();
if s.status == "running"
&& let Some((st, c)) = &recovering
{
let n = evs
.iter()
.filter(|e| {
e.kind == "catch"
&& str_of(&e.payload, "state") == *st
&& str_of(&e.payload, "catch") == *c
})
.count();
sc.retry = match m.state(st).and_then(|x| x.retry.get(c)) {
Some(r) => format!("↻ fix {n}/{}", r.max),
None => format!("↻ fix {n}"),
};
}
}
sc
}
fn str_of(p: &serde_json::Value, k: &str) -> String {
p[k].as_str().unwrap_or_default().to_string()
}
/// Short text for the "last activity" column.
fn describe(e: &Event) -> String {
let p = &e.payload;
match e.kind.as_str() {
"state" => format!("entered {}", str_of(p, "to")),
"step" if p["ok"] == true => format!(
"{} · {}",
str_of(p, "step"),
secs(p["ms"].as_u64().unwrap_or(0))
),
"step" => format!("{} failed", str_of(p, "step")),
"catch" => format!("{} ✗ {}", str_of(p, "state"), str_of(p, "catch")),
"end" => format!("ended: {}", str_of(p, "status")),
"resume" => "resumed".into(),
"status" => str_of(p, "label"),
"intent" => str_of(p, "text"),
k => k.to_string(),
}
}
/// Text of one line in the events box.
fn line_text(e: &Event) -> String {
let p = &e.payload;
match e.kind.as_str() {
"state" if str_of(p, "from").is_empty() => format!("start {}", str_of(p, "to")),
"state" => format!("{} → {}", str_of(p, "from"), str_of(p, "to")),
"step" => {
let res = if p["ok"] == true {
"ok".to_string()
} else {
format!("exit {}", p["exit"])
};
format!(
"{}/{} → {res} ({})",
str_of(p, "state"),
str_of(p, "step"),
secs(p["ms"].as_u64().unwrap_or(0))
)
}
"catch" => format!("{} ✗ {}", str_of(p, "state"), str_of(p, "catch")),
"end" => match p["reason"].as_str() {
Some(r) => format!("ended: {} ({r})", str_of(p, "status")),
None => format!("ended: {}", str_of(p, "status")),
},
"status" => format!("■ {}", str_of(p, "label")),
"resume" => format!("resumed in {}", str_of(p, "state")),
"edit" => format!("{} +{} −{}", str_of(p, "path"), p["added"], p["removed"]),
_ => p["text"]
.as_str()
.map_or_else(|| e.kind.clone(), String::from),
}
}
fn secs(ms: u64) -> String {
if ms < 10_000 {
format!("{:.1}s", ms as f64 / 1000.0)
} else {
format!("{}s", ms / 1000)
}
}
pub fn ago(secs: u64) -> String {
match secs {
0..60 => format!("{secs}s"),
60..3600 => format!("{}m", secs / 60),
_ => format!("{}h", secs / 3600),
}
}
/// Local wall-clock time `HH:MM:SS` of a millisecond timestamp.
pub fn hms(ms: u64) -> String {
let t = (ms / 1000) as libc::time_t;
// SAFETY: localtime_r writes into our zeroed tm and reads t; no shared state.
let tm = unsafe {
let mut tm: libc::tm = std::mem::zeroed();
libc::localtime_r(&t, &mut tm);
tm
};
format!("{:02}:{:02}:{:02}", tm.tm_hour, tm.tm_min, tm.tm_sec)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn session(id: &str, task: &str, state: &str, status: &str) -> Session {
Session {
id: id.into(),
task_id: task.into(),
branch: "b".into(),
worktree: "/w".into(),
pid: None,
state: state.into(),
status: status.into(),
}
}
fn task(id: &str, name: &str, deps: &[&str]) -> Task {
Task {
id: id.into(),
name: name.into(),
subtitle: "sub".into(),
machine: "task".into(),
depends_on: deps.iter().map(|d| d.to_string()).collect(),
}
}
fn ev(id: i64, s: &str, kind: &str, payload: serde_json::Value) -> Event {
Event {
id,
session: s.into(),
at: 1_000 * id as u64,
kind: kind.into(),
payload,
}
}
fn machines() -> HashMap<String, Machine> {
let text = include_str!("../examples/machines/task.toml");
HashMap::from([("task".into(), Machine::parse(text).unwrap())])
}
fn marks(r: &Row) -> String {
r.chips
.iter()
.map(|c| match c.mark {
Mark::Done => 'd',
Mark::Active => 'a',
Mark::Failed => 'f',
Mark::Waiting => 'w',
Mark::Todo => 't',
})
.collect()
}
fn st(id: i64, from: &str, to: &str) -> Event {
ev(id, "s2", "state", json!({"from": from, "to": to}))
}
#[test]
fn fix_loop_marks_and_label() {
// plan -> code -> build -> test fails -> code (fix 1 of 3)
let events = vec![
st(1, "", "plan"),
st(2, "plan", "code"),
st(3, "code", "build"),
st(4, "build", "test"),
ev(5, "s2", "test", json!({"passed": 39, "failed": 2})),
ev(
6,
"s2",
"catch",
json!({"state": "test", "catch": "TestsFailed"}),
),
st(7, "test", "code"),
ev(
8,
"s2",
"edit",
json!({"path": "a.rs", "added": 6, "removed": 2}),
),
ev(
9,
"s2",
"usage",
json!({"ctx_used": 71, "ctx_limit": 100, "cost": 1.5}),
),
];
let m = machines();
let (tasks, sessions) = (
[task("s2", "oauth", &[])],
[session("s2", "s2", "code", "running")],
);
let o = build(&Input {
goal: Some("g"),
tasks: &tasks,
sessions: &sessions,
events: &events,
machines: &m,
now_ms: 20_000,
});
let r = &o.rows[0];
// plan done, code active again, build done, test failed, review and merge not reached
assert_eq!(marks(r), "dadftt");
assert_eq!(r.status, Status::Fix);
assert_eq!(r.retry, "↻ fix 1/3");
assert_eq!((r.tests.as_str(), r.tests_ok), ("39/41 ✗2", Some(false)));
assert_eq!((r.added, r.removed, r.ctx), (6, 2, Some(71)));
assert_eq!(o.running, 1);
assert!((o.cost - 1.5).abs() < 1e-9);
assert_eq!(o.elapsed_secs, 19);
assert_eq!(o.events.len(), 9);
assert_eq!(o.events[5].text, "test ✗ TestsFailed");
}
#[test]
fn retry_label_clears_when_the_state_passes() {
let events = vec![
st(1, "", "test"),
ev(
2,
"s2",
"catch",
json!({"state": "test", "catch": "TestsFailed"}),
),
st(3, "test", "code"),
st(4, "code", "build"),
st(5, "build", "test"),
st(6, "test", "review"),
];
let m = machines();
let (tasks, sessions) = (
[task("s2", "t", &[])],
[session("s2", "s2", "review", "running")],
);
let o = build(&Input {
goal: None,
tasks: &tasks,
sessions: &sessions,
events: &events,
machines: &m,
now_ms: 0,
});
assert_eq!(o.rows[0].retry, "");
assert_eq!(o.rows[0].status, Status::Run);
assert_eq!(marks(&o.rows[0]), "tdddat");
}
#[test]
fn blocked_done_and_wait() {
let events = vec![
ev(1, "s1", "end", json!({"status": "merged", "reason": null})),
ev(
2,
"s3",
"end",
json!({"status": "escalated", "reason": "budget"}),
),
];
let m = machines();
let tasks = [
task("s1", "one", &[]),
task("s2", "two", &["s1", "s3"]),
task("s3", "three", &[]),
];
let sessions = [
session("s1", "s1", "merge", "merged"),
session("s2", "s2", "", "queued"),
session("s3", "s3", "escalated", "escalated"),
];
let o = build(&Input {
goal: None,
tasks: &tasks,
sessions: &sessions,
events: &events,
machines: &m,
now_ms: 61_000,
});
let s: Vec<_> = o.rows.iter().map(|r| r.status).collect();
assert_eq!(s, [Status::Done, Status::Blocked, Status::Wait]);
assert_eq!(o.rows[1].last, "waits on s3 three");
assert_eq!(o.rows[0].last, "merged · 1m ago");
assert_eq!((o.merged, o.total, o.blocked, o.waiting), (1, 3, 1, 1));
assert_eq!(o.needs.len(), 1);
assert_eq!(
(o.needs[0].session.as_str(), o.needs[0].detail.as_str()),
("s3", "budget")
);
}
#[test]
fn helpers() {
assert_eq!(ago(5), "5s");
assert_eq!(ago(130), "2m");
assert_eq!(ago(7300), "2h");
assert_eq!(secs(1500), "1.5s");
assert_eq!(secs(38_000), "38s");
assert_eq!(hms(0).len(), 8);
}
}