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:
1 parent
374cf28aed
commit
d66a014bc5
19 files changed
+4525
-8
No files matched your search
@@ -0,0 +1,280 @@
|
||||
//! Per-goal SQLite file (`.hx/orch.db`, ORCHESTRATOR.md section 6). The `events` table is append-only; every
|
||||
//! view is rebuilt from it plus the machine files. Each thread opens its own connection (WAL + busy timeout).
|
||||
// shortcut: checks/decisions tables exist but have no accessors yet; milestones 7 and 8 add them.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use serde_json::Value;
|
||||
use std::path::Path;
|
||||
|
||||
const SCHEMA: &str = "
|
||||
create table if not exists goal(text text not null, created_at integer not null);
|
||||
create table if not exists checks(
|
||||
id integer primary key, name text not null, cmd text not null, owner_session text,
|
||||
last_status text, last_run_at integer);
|
||||
create table if not exists tasks(
|
||||
id text primary key, name text not null, subtitle text not null default '',
|
||||
machine text not null, depends_on text not null default '[]');
|
||||
create table if not exists sessions(
|
||||
id text primary key, task_id text not null, branch text not null, worktree text not null,
|
||||
pid integer, current_state text not null default '', status text not null default 'queued');
|
||||
create table if not exists events(
|
||||
id integer primary key autoincrement, session_id text not null, at integer not null,
|
||||
kind text not null, payload text not null default '{}');
|
||||
create index if not exists events_session on events(session_id, id);
|
||||
create table if not exists decisions(
|
||||
session_id text not null, text text not null, state text not null, at integer not null,
|
||||
vetoed integer not null default 0);
|
||||
";
|
||||
|
||||
pub struct Db {
|
||||
conn: Connection,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Event {
|
||||
pub id: i64,
|
||||
pub session: String,
|
||||
/// Milliseconds since the epoch.
|
||||
pub at: u64,
|
||||
pub kind: String,
|
||||
pub payload: Value,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Task {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub subtitle: String,
|
||||
pub machine: String,
|
||||
pub depends_on: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Session {
|
||||
pub id: String,
|
||||
pub task_id: String,
|
||||
pub branch: String,
|
||||
pub worktree: String,
|
||||
pub pid: Option<u32>,
|
||||
pub state: String,
|
||||
/// queued, running, or the machine's `end` value (merged, escalated, aborted) or `failed`.
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
impl Db {
|
||||
pub fn open(path: &Path) -> Result<Self> {
|
||||
if let Some(d) = path.parent() {
|
||||
std::fs::create_dir_all(d)?;
|
||||
}
|
||||
let conn = Connection::open(path).with_context(|| path.display().to_string())?;
|
||||
conn.busy_timeout(std::time::Duration::from_secs(5))?;
|
||||
conn.pragma_update(None, "journal_mode", "WAL")?;
|
||||
conn.execute_batch(SCHEMA)?;
|
||||
Ok(Self { conn })
|
||||
}
|
||||
|
||||
pub fn set_goal(&self, text: &str) -> Result<()> {
|
||||
self.conn.execute("delete from goal", [])?;
|
||||
self.conn.execute(
|
||||
"insert into goal(text, created_at) values (?1, ?2)",
|
||||
params![text, crate::state::now() as i64],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn goal(&self) -> Result<Option<String>> {
|
||||
Ok(self
|
||||
.conn
|
||||
.query_row("select text from goal limit 1", [], |r| r.get(0))
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
/// Next free session id: s1, s2, ...
|
||||
pub fn next_session_id(&self) -> Result<String> {
|
||||
let n: i64 = self.conn.query_row(
|
||||
"select coalesce(max(cast(substr(id, 2) as integer)), 0) from sessions",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
Ok(format!("s{}", n + 1))
|
||||
}
|
||||
|
||||
pub fn add_task(&self, t: &Task) -> Result<()> {
|
||||
self.conn.execute(
|
||||
"insert into tasks(id, name, subtitle, machine, depends_on) values (?1, ?2, ?3, ?4, ?5)",
|
||||
params![
|
||||
t.id,
|
||||
t.name,
|
||||
t.subtitle,
|
||||
t.machine,
|
||||
serde_json::to_string(&t.depends_on)?
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn tasks(&self) -> Result<Vec<Task>> {
|
||||
let mut q = self.conn.prepare(
|
||||
"select id, name, subtitle, machine, depends_on from tasks order by cast(substr(id, 2) as integer), id",
|
||||
)?;
|
||||
let rows = q.query_map([], |r| {
|
||||
let deps: String = r.get(4)?;
|
||||
Ok(Task {
|
||||
id: r.get(0)?,
|
||||
name: r.get(1)?,
|
||||
subtitle: r.get(2)?,
|
||||
machine: r.get(3)?,
|
||||
depends_on: serde_json::from_str(&deps).unwrap_or_default(),
|
||||
})
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn add_session(&self, s: &Session) -> Result<()> {
|
||||
self.conn.execute(
|
||||
"insert into sessions(id, task_id, branch, worktree, pid, current_state, status) values (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
|
||||
params![s.id, s.task_id, s.branch, s.worktree, s.pid, s.state, s.status],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn session(&self, id: &str) -> Result<Option<Session>> {
|
||||
Ok(self
|
||||
.conn
|
||||
.query_row(
|
||||
"select id, task_id, branch, worktree, pid, current_state, status from sessions where id = ?1",
|
||||
[id],
|
||||
session_row,
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn sessions(&self) -> Result<Vec<Session>> {
|
||||
let mut q = self.conn.prepare(
|
||||
"select id, task_id, branch, worktree, pid, current_state, status from sessions order by cast(substr(id, 2) as integer), id",
|
||||
)?;
|
||||
Ok(q.query_map([], session_row)?
|
||||
.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn set_session(&self, id: &str, state: &str, status: &str) -> Result<()> {
|
||||
self.conn.execute(
|
||||
"update sessions set current_state = ?2, status = ?3 where id = ?1",
|
||||
params![id, state, status],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_pid(&self, id: &str, pid: Option<u32>) -> Result<()> {
|
||||
self.conn.execute(
|
||||
"update sessions set pid = ?2 where id = ?1",
|
||||
params![id, pid],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Append one event; returns its id.
|
||||
pub fn emit(&self, session: &str, kind: &str, payload: Value) -> Result<i64> {
|
||||
self.conn.execute(
|
||||
"insert into events(session_id, at, kind, payload) values (?1, ?2, ?3, ?4)",
|
||||
params![
|
||||
session,
|
||||
crate::state::now_ms() as i64,
|
||||
kind,
|
||||
payload.to_string()
|
||||
],
|
||||
)?;
|
||||
Ok(self.conn.last_insert_rowid())
|
||||
}
|
||||
|
||||
/// Events oldest first, optionally one session, only those after `after` (event id).
|
||||
pub fn events(&self, session: Option<&str>, after: i64) -> Result<Vec<Event>> {
|
||||
let mut q = self.conn.prepare(
|
||||
"select id, session_id, at, kind, payload from events
|
||||
where id > ?1 and (?2 is null or session_id = ?2) order by id",
|
||||
)?;
|
||||
let rows = q.query_map(params![after, session], |r| {
|
||||
let p: String = r.get(4)?;
|
||||
Ok(Event {
|
||||
id: r.get(0)?,
|
||||
session: r.get(1)?,
|
||||
at: r.get::<_, i64>(2)? as u64,
|
||||
kind: r.get(3)?,
|
||||
payload: serde_json::from_str(&p).unwrap_or(Value::Null),
|
||||
})
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
/// How often `catch` fired in `state` of this session (rebuilt from events, so it survives restarts).
|
||||
pub fn catch_count(&self, session: &str, state: &str, catch: &str) -> Result<u32> {
|
||||
let n: i64 = self.conn.query_row(
|
||||
"select count(*) from events where session_id = ?1 and kind = 'catch'
|
||||
and json_extract(payload, '$.state') = ?2 and json_extract(payload, '$.catch') = ?3",
|
||||
params![session, state, catch],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
Ok(n as u32)
|
||||
}
|
||||
}
|
||||
|
||||
fn session_row(r: &rusqlite::Row) -> rusqlite::Result<Session> {
|
||||
Ok(Session {
|
||||
id: r.get(0)?,
|
||||
task_id: r.get(1)?,
|
||||
branch: r.get(2)?,
|
||||
worktree: r.get(3)?,
|
||||
pid: r.get(4)?,
|
||||
state: r.get(5)?,
|
||||
status: r.get(6)?,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
pub fn temp_db(tag: &str) -> (Db, std::path::PathBuf) {
|
||||
let d = std::env::temp_dir().join(format!("orch-db-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
(Db::open(&d.join("orch.db")).unwrap(), d)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
let (db, dir) = temp_db("rt");
|
||||
assert_eq!(db.goal().unwrap(), None);
|
||||
db.set_goal("ship it").unwrap();
|
||||
assert_eq!(db.goal().unwrap().as_deref(), Some("ship it"));
|
||||
assert_eq!(db.next_session_id().unwrap(), "s1");
|
||||
let s = Session {
|
||||
id: "s1".into(),
|
||||
task_id: "s1".into(),
|
||||
branch: "hx/s1-x".into(),
|
||||
worktree: "/w".into(),
|
||||
pid: None,
|
||||
state: String::new(),
|
||||
status: "queued".into(),
|
||||
};
|
||||
db.add_session(&s).unwrap();
|
||||
assert_eq!(db.next_session_id().unwrap(), "s2");
|
||||
db.set_session("s1", "plan", "running").unwrap();
|
||||
assert_eq!(db.session("s1").unwrap().unwrap().state, "plan");
|
||||
db.emit("s1", "catch", json!({"state": "test", "catch": "T"}))
|
||||
.unwrap();
|
||||
let last = db.emit("s1", "state", json!({"to": "code"})).unwrap();
|
||||
assert_eq!(db.catch_count("s1", "test", "T").unwrap(), 1);
|
||||
assert_eq!(db.catch_count("s1", "test", "U").unwrap(), 0);
|
||||
assert_eq!(db.events(Some("s1"), 0).unwrap().len(), 2);
|
||||
assert_eq!(db.events(None, last - 1).unwrap().len(), 1);
|
||||
assert!(db.events(Some("s9"), 0).unwrap().is_empty());
|
||||
// reopening sees the same data: restart restores views
|
||||
drop(db);
|
||||
let db = Db::open(&dir.join("orch.db")).unwrap();
|
||||
assert_eq!(db.sessions().unwrap().len(), 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
+316
@@ -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"));
|
||||
}
|
||||
}
|
||||
+45
-3
@@ -1,10 +1,15 @@
|
||||
mod adapter;
|
||||
mod db;
|
||||
mod lock;
|
||||
mod machine;
|
||||
mod policy;
|
||||
mod profile;
|
||||
mod report;
|
||||
mod run;
|
||||
mod runner;
|
||||
mod state;
|
||||
mod tui;
|
||||
mod view;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::{Parser, Subcommand};
|
||||
@@ -14,10 +19,13 @@ use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(version, about = "Run hx coding agents on tasks")]
|
||||
#[command(
|
||||
version,
|
||||
about = "Run hx coding agents on tasks; without a subcommand, opens the TUI"
|
||||
)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
cmd: Cmd,
|
||||
cmd: Option<Cmd>,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
@@ -62,6 +70,19 @@ enum Cmd {
|
||||
#[arg(long)]
|
||||
check: bool,
|
||||
},
|
||||
/// Create a state-machine session in REPO and run it to the end (computer steps only for now).
|
||||
Session {
|
||||
#[arg(long)]
|
||||
repo: PathBuf,
|
||||
/// Machine file name, without .toml (looked up in REPO/.hx/machines, then ~/.hx/machines).
|
||||
#[arg(long)]
|
||||
machine: String,
|
||||
#[arg(long)]
|
||||
name: String,
|
||||
/// Value for {{scope}} in machine commands.
|
||||
#[arg(long, default_value = "")]
|
||||
scope: String,
|
||||
},
|
||||
/// hx extension that enforces a run's tool allowlist (started by hx, not by hand).
|
||||
#[command(hide = true)]
|
||||
Guard { policy: PathBuf },
|
||||
@@ -98,7 +119,28 @@ fn code(ok: bool) -> std::process::ExitCode {
|
||||
}
|
||||
|
||||
fn main() -> Result<std::process::ExitCode> {
|
||||
match Cli::parse().cmd {
|
||||
let Some(cmd) = Cli::parse().cmd else {
|
||||
tui::run()?;
|
||||
return Ok(code(true));
|
||||
};
|
||||
match cmd {
|
||||
Cmd::Session {
|
||||
repo,
|
||||
machine,
|
||||
name,
|
||||
scope,
|
||||
} => {
|
||||
let repo = repo.canonicalize()?;
|
||||
let m = machine::Machine::find(&machine, &repo)?;
|
||||
let db = db::Db::open(&repo.join(".hx/orch.db"))?;
|
||||
// shortcut: worktrees are grouped by repo directory name; two repos with one name would share ids
|
||||
let base = repo.file_name().unwrap_or_default();
|
||||
let wts = state_dir().join("worktrees").join(base);
|
||||
let s = runner::create(&db, &wts, &name, "", &machine)?;
|
||||
let status = runner::run_session(&db, &m, &s.id, &repo, &scope)?;
|
||||
println!("{} {} -> {status}", s.id, s.branch);
|
||||
Ok(code(status == "merged"))
|
||||
}
|
||||
Cmd::Run {
|
||||
task,
|
||||
repo,
|
||||
|
||||
+2
-2
@@ -14,7 +14,7 @@ use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) -> Result<String> {
|
||||
pub(crate) fn git(dir: &Path, args: &[&str]) -> Result<String> {
|
||||
let o = Command::new("git")
|
||||
.args(["-c", "user.name=orch", "-c", "user.email=orch@localhost"])
|
||||
.args(args)
|
||||
@@ -124,7 +124,7 @@ fn is_rate_limit(reason: &str) -> bool {
|
||||
/// Max bytes of gate output fed back to hx (the tail: errors are at the end).
|
||||
const GATE_LOG_LIMIT: usize = 8000;
|
||||
|
||||
fn tail(b: &[u8], limit: usize) -> String {
|
||||
pub(crate) fn tail(b: &[u8], limit: usize) -> String {
|
||||
let s = String::from_utf8_lossy(&b[b.len().saturating_sub(limit)..]).into_owned();
|
||||
s.trim_start_matches('\u{FFFD}').to_string()
|
||||
}
|
||||
|
||||
+394
@@ -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);
|
||||
}
|
||||
}
|
||||
+386
@@ -0,0 +1,386 @@
|
||||
//! Terminal UI. Everything on screen comes from the event table and the machine files via `view::build`.
|
||||
|
||||
mod overview;
|
||||
mod theme;
|
||||
|
||||
use crate::db::{Db, Event};
|
||||
use crate::machine::Machine;
|
||||
use crate::view::{self, Overview};
|
||||
use anyhow::{Result, bail};
|
||||
use overview::Header;
|
||||
use std::collections::HashMap;
|
||||
use std::io::IsTerminal;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
pub fn run() -> Result<()> {
|
||||
if !std::io::stdout().is_terminal() {
|
||||
bail!("orch needs a terminal; use a subcommand (orch --help) in scripts");
|
||||
}
|
||||
let mut app = App::new(std::env::current_dir()?);
|
||||
let mut term = ratatui::init();
|
||||
let res = event_loop(&mut term, &mut app);
|
||||
ratatui::restore();
|
||||
res
|
||||
}
|
||||
|
||||
struct App {
|
||||
repo: PathBuf,
|
||||
/// Opened lazily: launching `orch` in a directory without a goal must not create `.hx/orch.db`.
|
||||
db: Option<Db>,
|
||||
events: Vec<Event>,
|
||||
machines: HashMap<String, Machine>,
|
||||
overview: Overview,
|
||||
rev: String,
|
||||
sel: usize,
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn new(repo: PathBuf) -> Self {
|
||||
let rev = git_rev(&repo);
|
||||
Self {
|
||||
repo,
|
||||
db: None,
|
||||
events: vec![],
|
||||
machines: HashMap::new(),
|
||||
overview: Overview::default(),
|
||||
rev,
|
||||
sel: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh(&mut self) {
|
||||
let path = self.repo.join(".hx/orch.db");
|
||||
if self.db.is_none() && path.exists() {
|
||||
self.db = Db::open(&path).ok();
|
||||
}
|
||||
if let Some(db) = &self.db
|
||||
&& let Ok(o) = snapshot(
|
||||
db,
|
||||
&self.repo,
|
||||
&mut self.events,
|
||||
&mut self.machines,
|
||||
crate::state::now_ms(),
|
||||
)
|
||||
{
|
||||
self.overview = o;
|
||||
}
|
||||
self.sel = self.sel.min(self.overview.rows.len().saturating_sub(1));
|
||||
}
|
||||
|
||||
fn header(&self) -> Header {
|
||||
let home = std::env::var("HOME").unwrap_or_default();
|
||||
let repo = self.repo.to_string_lossy().into_owned();
|
||||
let repo = match repo.strip_prefix(&home) {
|
||||
Some(rest) if !home.is_empty() => format!("~{rest}"),
|
||||
_ => repo,
|
||||
};
|
||||
Header {
|
||||
repo,
|
||||
rev: self.rev.clone(),
|
||||
now_ms: crate::state::now_ms(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads what is new in the database since the last call and builds the overview.
|
||||
fn snapshot(
|
||||
db: &Db,
|
||||
repo: &Path,
|
||||
events: &mut Vec<Event>,
|
||||
machines: &mut HashMap<String, Machine>,
|
||||
now_ms: u64,
|
||||
) -> Result<Overview> {
|
||||
let last = events.last().map_or(0, |e| e.id);
|
||||
events.extend(db.events(None, last)?);
|
||||
let (tasks, sessions) = (db.tasks()?, db.sessions()?);
|
||||
for t in &tasks {
|
||||
if !machines.contains_key(&t.machine)
|
||||
&& let Ok(m) = Machine::find(&t.machine, repo)
|
||||
{
|
||||
machines.insert(t.machine.clone(), m);
|
||||
}
|
||||
}
|
||||
let goal = db.goal()?;
|
||||
Ok(view::build(&view::Input {
|
||||
goal: goal.as_deref(),
|
||||
tasks: &tasks,
|
||||
sessions: &sessions,
|
||||
events,
|
||||
machines,
|
||||
now_ms,
|
||||
}))
|
||||
}
|
||||
|
||||
fn git_rev(repo: &Path) -> String {
|
||||
let git = |a: &[&str]| crate::run::git(repo, a).map(|s| s.trim().to_string());
|
||||
match (
|
||||
git(&["rev-parse", "--abbrev-ref", "HEAD"]),
|
||||
git(&["rev-parse", "--short", "HEAD"]),
|
||||
) {
|
||||
(Ok(b), Ok(s)) => format!("{b}@{s}"),
|
||||
_ => "no git".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn event_loop(term: &mut ratatui::DefaultTerminal, app: &mut App) -> Result<()> {
|
||||
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
|
||||
app.refresh();
|
||||
loop {
|
||||
let header = app.header();
|
||||
term.draw(|f| overview::draw(f, &app.overview, &header, app.sel))?;
|
||||
if !event::poll(Duration::from_millis(250))? {
|
||||
app.refresh();
|
||||
continue;
|
||||
}
|
||||
let Event::Key(k) = event::read()? else {
|
||||
continue;
|
||||
};
|
||||
if k.kind != KeyEventKind::Press {
|
||||
continue;
|
||||
}
|
||||
let last = app.overview.rows.len().saturating_sub(1);
|
||||
match k.code {
|
||||
KeyCode::Char('q') => return Ok(()),
|
||||
KeyCode::Char('c') if k.modifiers.contains(KeyModifiers::CONTROL) => return Ok(()),
|
||||
KeyCode::Char('j') | KeyCode::Down => app.sel = (app.sel + 1).min(last),
|
||||
KeyCode::Char('k') | KeyCode::Up => app.sel = app.sel.saturating_sub(1),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::view::{Chip, EventLine, Mark, Need, Row, Status};
|
||||
use ratatui::{Terminal, backend::TestBackend};
|
||||
|
||||
fn screen(o: &Overview, sel: usize) -> String {
|
||||
let mut t = Terminal::new(TestBackend::new(160, 45)).unwrap();
|
||||
let h = Header {
|
||||
repo: "~/code/api".into(),
|
||||
rev: "main@4f2a91c".into(),
|
||||
now_ms: 0,
|
||||
};
|
||||
t.draw(|f| overview::draw(f, o, &h, sel)).unwrap();
|
||||
let b = t.backend().buffer();
|
||||
let w = b.area.width as usize;
|
||||
b.content()
|
||||
.chunks(w)
|
||||
.map(|r| {
|
||||
r.iter()
|
||||
.map(|c| c.symbol())
|
||||
.collect::<String>()
|
||||
.trim_end()
|
||||
.to_string()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn chips(spec: &str) -> Vec<Chip> {
|
||||
let names = ["plan", "code", "build", "test", "review", "merge"];
|
||||
spec.chars()
|
||||
.zip(names)
|
||||
.map(|(c, n)| Chip {
|
||||
name: n.into(),
|
||||
mark: match c {
|
||||
'd' => Mark::Done,
|
||||
'a' => Mark::Active,
|
||||
'f' => Mark::Failed,
|
||||
'w' => Mark::Waiting,
|
||||
_ => Mark::Todo,
|
||||
},
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Sample data of `Main.dc.html`.
|
||||
fn mockup() -> Overview {
|
||||
let row = |id: &str,
|
||||
status,
|
||||
task: &str,
|
||||
sub: &str,
|
||||
spec: &str,
|
||||
retry: &str,
|
||||
tests: &str,
|
||||
ok,
|
||||
last: &str| Row {
|
||||
id: id.into(),
|
||||
status,
|
||||
task: task.into(),
|
||||
sub: sub.into(),
|
||||
machine: "task.toml".into(),
|
||||
chips: chips(spec),
|
||||
retry: retry.into(),
|
||||
tests: tests.into(),
|
||||
tests_ok: ok,
|
||||
added: 164,
|
||||
removed: 51,
|
||||
ctx: Some(71),
|
||||
last: last.into(),
|
||||
};
|
||||
Overview {
|
||||
goal: "Move login to OAuth2 and add per-user rate limiting".into(),
|
||||
rows: vec![
|
||||
row(
|
||||
"s1",
|
||||
Status::Done,
|
||||
"schema-migrate",
|
||||
"users → oauth_identities",
|
||||
"dddddd",
|
||||
"",
|
||||
"18/18 ✓",
|
||||
Some(true),
|
||||
"merged to main · 12m ago",
|
||||
),
|
||||
row(
|
||||
"s2",
|
||||
Status::Fix,
|
||||
"oauth-provider",
|
||||
"GitHub + Google login",
|
||||
"dadftt",
|
||||
"↻ fix 2/3",
|
||||
"39/41 ✗2",
|
||||
Some(false),
|
||||
"editing src/auth/token.rs",
|
||||
),
|
||||
row(
|
||||
"s3",
|
||||
Status::Wait,
|
||||
"auth-middleware",
|
||||
"session → bearer tokens",
|
||||
"ddddwt",
|
||||
"",
|
||||
"52/52 ✓",
|
||||
Some(true),
|
||||
"review ready · 4m",
|
||||
),
|
||||
row(
|
||||
"s5",
|
||||
Status::Blocked,
|
||||
"docs-update",
|
||||
"AUTH.md, migration notes",
|
||||
"tttttt",
|
||||
"",
|
||||
"—",
|
||||
None,
|
||||
"waits on s2 oauth-provider",
|
||||
),
|
||||
],
|
||||
needs: vec![Need {
|
||||
session: "s3".into(),
|
||||
task: "auth-middleware".into(),
|
||||
what: "review ready".into(),
|
||||
detail: "6 files, 52/52 tests pass".into(),
|
||||
}],
|
||||
events: vec![EventLine {
|
||||
id: 1,
|
||||
at_ms: 0,
|
||||
session: "s2".into(),
|
||||
kind: "test".into(),
|
||||
text: "cargo test auth:: → 39 passed, 2 failed".into(),
|
||||
}],
|
||||
merged: 1,
|
||||
total: 6,
|
||||
checks: Some((9, 14)),
|
||||
running: 4,
|
||||
waiting: 1,
|
||||
blocked: 1,
|
||||
cost: 3.41,
|
||||
elapsed_secs: 42 * 60,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overview_matches_the_mockup_at_160x45() {
|
||||
let s = screen(&mockup(), 1);
|
||||
for want in [
|
||||
"hx·orch",
|
||||
"Move login to OAuth2 and add per-user rate limiting",
|
||||
"main@4f2a91c",
|
||||
"1/6 merged",
|
||||
"9/14 checks",
|
||||
"4 running · 1 waiting on you · 1 blocked",
|
||||
"spent $3.41 · 42m elapsed",
|
||||
"Sessions 4",
|
||||
"▶ s2",
|
||||
"oauth-provider",
|
||||
"✓plan › ●code › ✓build › ✗test › ·review › ·merge",
|
||||
"↻ fix 2/3",
|
||||
"39/41 ✗2",
|
||||
"+164 −51",
|
||||
"▰▰▰▰▰▰▰▱▱▱",
|
||||
"waits on s2 oauth-provider",
|
||||
"BLOCKED",
|
||||
"◆ Needs you 1",
|
||||
"s3 auth-middleware · review ready",
|
||||
"Events all sessions",
|
||||
] {
|
||||
assert!(s.contains(want), "missing {want:?} in:\n{s}");
|
||||
}
|
||||
// chips of s2 use the spec's glyphs; the cursor row has the selected background
|
||||
assert!(!s.contains("✗build"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_overview_explains_how_to_start() {
|
||||
let s = screen(&Overview::default(), 0);
|
||||
assert!(s.contains("no sessions yet"), "{s}");
|
||||
assert!(s.contains("Sessions 0"));
|
||||
assert!(s.contains("nothing waits on you"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_session_flows_from_runner_through_events_to_screen() {
|
||||
let dir = std::env::temp_dir().join(format!("orch-tui-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let repo = dir.join("repo");
|
||||
std::fs::create_dir_all(repo.join(".hx/machines")).unwrap();
|
||||
crate::run::git(&repo, &["init", "-q", "-b", "main"]).unwrap();
|
||||
// a small machine of local steps is enough to drive the screen
|
||||
std::fs::write(
|
||||
repo.join(".hx/machines/m.toml"),
|
||||
"name = \"m\"\n[[state]]\nname = \"plan\"\nkind = \"start\"\nnext = \"build\"\n\
|
||||
[[state]]\nname = \"build\"\nsteps = [{ name = \"b\", run = \"computer\", cmd = \"true\" }]\nnext = \"merge\"\n\
|
||||
[[state]]\nname = \"merge\"\nkind = \"exit\"\nend = \"merged\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
crate::run::git(&repo, &["add", "-A"]).unwrap();
|
||||
crate::run::git(&repo, &["commit", "-qm", "init"]).unwrap();
|
||||
let db = Db::open(&repo.join(".hx/orch.db")).unwrap();
|
||||
db.set_goal("ship the thing").unwrap();
|
||||
let s = crate::runner::create(&db, &dir.join("wt"), "demo", "", "m").unwrap();
|
||||
let m = Machine::find("m", &repo).unwrap();
|
||||
crate::runner::run_session(&db, &m, &s.id, &repo, "").unwrap();
|
||||
|
||||
let (mut events, mut machines) = (vec![], HashMap::new());
|
||||
let o = snapshot(
|
||||
&db,
|
||||
&repo,
|
||||
&mut events,
|
||||
&mut machines,
|
||||
crate::state::now_ms(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(o.rows.len(), 1);
|
||||
assert_eq!(o.rows[0].status, Status::Done);
|
||||
let text = screen(&o, 0);
|
||||
for want in [
|
||||
"ship the thing",
|
||||
"demo",
|
||||
"✓plan › ✓build › ✓merge",
|
||||
"1/1 merged",
|
||||
"ended: merged",
|
||||
"m.toml",
|
||||
] {
|
||||
assert!(text.contains(want), "missing {want:?} in:\n{text}");
|
||||
}
|
||||
// incremental: a second snapshot adds no events twice
|
||||
let n = events.len();
|
||||
snapshot(&db, &repo, &mut events, &mut machines, 0).unwrap();
|
||||
assert_eq!(events.len(), n);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
//! Screen 1: sessions overview (ORCHESTRATOR.md 7.1, `Main.dc.html`).
|
||||
|
||||
use super::theme::{self, bold, fg, inverted};
|
||||
use crate::view::{Chip, EventLine, Mark, Need, Overview, Row, Status, hms};
|
||||
use ratatui::Frame;
|
||||
use ratatui::layout::{Constraint, Layout, Rect};
|
||||
use ratatui::style::{Color, Style};
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Block, Paragraph};
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
/// What the header shows that is not derived from events.
|
||||
pub struct Header {
|
||||
pub repo: String,
|
||||
pub rev: String,
|
||||
pub now_ms: u64,
|
||||
}
|
||||
|
||||
const W_ID: usize = 5;
|
||||
const W_STATUS: usize = 7;
|
||||
const W_TASK: usize = 24;
|
||||
const W_TESTS: usize = 10;
|
||||
const W_DIFF: usize = 10;
|
||||
const W_CTX: usize = 10;
|
||||
|
||||
pub fn draw(f: &mut Frame, o: &Overview, h: &Header, sel: usize) {
|
||||
let area = f.area();
|
||||
f.render_widget(
|
||||
Block::new().style(Style::new().bg(theme::BG).fg(theme::TEXT)),
|
||||
area,
|
||||
);
|
||||
let rows_h = (o.rows.len().max(1) * 2 + 3) as u16;
|
||||
let sessions_h = rows_h.clamp(5, area.height.saturating_sub(14).max(5));
|
||||
let [head, stats, sessions, lower, keys] = Layout::vertical([
|
||||
Constraint::Length(1),
|
||||
Constraint::Length(1),
|
||||
Constraint::Length(sessions_h),
|
||||
Constraint::Fill(1),
|
||||
Constraint::Length(1),
|
||||
])
|
||||
.areas(area);
|
||||
let [needs, events] =
|
||||
Layout::horizontal([Constraint::Length(62), Constraint::Fill(1)]).areas(lower);
|
||||
f.render_widget(header_line(o, h, head.width as usize), head);
|
||||
f.render_widget(stats_line(o), stats);
|
||||
sessions_box(f, sessions, o, sel);
|
||||
needs_box(f, needs, &o.needs);
|
||||
events_box(f, events, &o.events);
|
||||
f.render_widget(key_bar(), keys);
|
||||
}
|
||||
|
||||
/// Cuts `s` to `w` display columns, ending in `…` when it was too long.
|
||||
fn fit(s: &str, w: usize) -> String {
|
||||
if s.width() <= w {
|
||||
return s.to_string();
|
||||
}
|
||||
let mut out = String::new();
|
||||
for c in s.chars() {
|
||||
if out.width() + 1 >= w {
|
||||
break;
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out.push('…');
|
||||
out
|
||||
}
|
||||
|
||||
/// Appends `parts` and pads the cell to `w` columns plus one gap column.
|
||||
fn cell<'a>(line: &mut Vec<Span<'a>>, parts: Vec<Span<'a>>, w: usize) {
|
||||
let used: usize = parts.iter().map(|s| s.width()).sum();
|
||||
line.extend(parts);
|
||||
line.push(Span::raw(" ".repeat((w + 1).saturating_sub(used))));
|
||||
}
|
||||
|
||||
fn bar(done: usize, total: usize) -> Vec<Span<'static>> {
|
||||
let n = total.min(24);
|
||||
let d = (done * n).checked_div(total).unwrap_or(0);
|
||||
vec![
|
||||
Span::styled("█".repeat(d), fg(theme::OK)),
|
||||
Span::styled("█".repeat(n - d), fg(theme::BORDER)),
|
||||
]
|
||||
}
|
||||
|
||||
fn header_line(o: &Overview, h: &Header, width: usize) -> Line<'static> {
|
||||
let goal = if o.goal.is_empty() {
|
||||
"no goal set"
|
||||
} else {
|
||||
&o.goal
|
||||
};
|
||||
let right = format!("{} · {} {}", h.repo, h.rev, hms(h.now_ms));
|
||||
let left_fixed = " hx·orch ".width() + " goal ".width();
|
||||
let goal_w = width.saturating_sub(left_fixed + right.width() + 2);
|
||||
let goal = fit(goal, goal_w);
|
||||
let gap = goal_w.saturating_sub(goal.width()) + 2;
|
||||
Line::from(vec![
|
||||
Span::styled(" hx·orch ", inverted(theme::RUN)),
|
||||
Span::styled(" goal ", fg(theme::DIM)),
|
||||
Span::styled(
|
||||
goal,
|
||||
Style::new().add_modifier(ratatui::style::Modifier::BOLD),
|
||||
),
|
||||
Span::raw(" ".repeat(gap)),
|
||||
Span::styled(right, fg(theme::DIM)),
|
||||
])
|
||||
}
|
||||
|
||||
fn stats_line(o: &Overview) -> Line<'static> {
|
||||
let mut v = vec![Span::styled(" tasks ", fg(theme::DIM))];
|
||||
if o.total == 0 {
|
||||
v.push(Span::raw("—"));
|
||||
} else {
|
||||
v.extend(bar(o.merged, o.total));
|
||||
v.push(Span::raw(format!(" {}/{} merged", o.merged, o.total)));
|
||||
}
|
||||
v.push(Span::styled(" acceptance ", fg(theme::DIM)));
|
||||
match o.checks {
|
||||
Some((ok, total)) => {
|
||||
v.extend(bar(ok, total));
|
||||
v.push(Span::raw(format!(" {ok}/{total} checks")));
|
||||
}
|
||||
None => v.push(Span::raw("—")),
|
||||
}
|
||||
v.push(Span::raw(" "));
|
||||
v.push(Span::styled(
|
||||
format!("{} running", o.running),
|
||||
fg(theme::RUN),
|
||||
));
|
||||
v.push(Span::raw(" · "));
|
||||
v.push(Span::styled(
|
||||
format!("{} waiting on you", o.waiting),
|
||||
fg(theme::WAIT),
|
||||
));
|
||||
v.push(Span::raw(" · "));
|
||||
v.push(Span::styled(
|
||||
format!("{} blocked", o.blocked),
|
||||
fg(theme::AGENT),
|
||||
));
|
||||
v.push(Span::styled(
|
||||
format!(
|
||||
" spent ${:.2} · {} elapsed",
|
||||
o.cost,
|
||||
crate::view::ago(o.elapsed_secs)
|
||||
),
|
||||
fg(theme::DIM),
|
||||
));
|
||||
Line::from(v)
|
||||
}
|
||||
|
||||
/// A box with its title set into the top border, like `┌ Sessions 6 ──`.
|
||||
fn boxed<'a>(title: &str, count: Option<usize>, color: Color, border: Color) -> Block<'a> {
|
||||
let mut t = vec![Span::styled(format!(" {title}"), bold(color))];
|
||||
if let Some(n) = count {
|
||||
t.push(Span::styled(format!(" {n}"), fg(theme::DIM)));
|
||||
}
|
||||
t.push(Span::raw(" "));
|
||||
Block::bordered()
|
||||
.border_style(fg(border))
|
||||
.title(Line::from(t))
|
||||
}
|
||||
|
||||
fn status_color(s: Status) -> Color {
|
||||
match s {
|
||||
Status::Done => theme::OK,
|
||||
Status::Fix | Status::Fail => theme::ERR,
|
||||
Status::Wait => theme::WAIT,
|
||||
Status::Run => theme::RUN,
|
||||
Status::Blocked => theme::AGENT,
|
||||
}
|
||||
}
|
||||
|
||||
fn chip_span(c: &Chip) -> Span<'static> {
|
||||
match c.mark {
|
||||
Mark::Done => Span::styled(format!("✓{}", c.name), fg(theme::OK)),
|
||||
Mark::Active => Span::styled(format!("●{}", c.name), inverted(theme::RUN)),
|
||||
Mark::Failed => Span::styled(format!("✗{}", c.name), fg(theme::ERR)),
|
||||
Mark::Waiting => Span::styled(format!("◆{}", c.name), inverted(theme::WAIT)),
|
||||
Mark::Todo => Span::styled(format!("·{}", c.name), fg(theme::TODO)),
|
||||
}
|
||||
}
|
||||
|
||||
fn machine_spans(r: &Row) -> Vec<Span<'static>> {
|
||||
let mut v = vec![];
|
||||
for (i, c) in r.chips.iter().enumerate() {
|
||||
if i > 0 {
|
||||
v.push(Span::styled(" › ", fg(theme::SEP)));
|
||||
}
|
||||
v.push(chip_span(c));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn ctx_bar(pct: u8) -> Span<'static> {
|
||||
let n = (pct as usize + 5) / 10;
|
||||
let color = if pct > 65 { theme::WAIT } else { theme::DIM };
|
||||
Span::styled(
|
||||
format!("{}{}", "▰".repeat(n), "▱".repeat(10 - n)),
|
||||
fg(color),
|
||||
)
|
||||
}
|
||||
|
||||
fn sessions_box(f: &mut Frame, area: Rect, o: &Overview, sel: usize) {
|
||||
let block = boxed("Sessions", Some(o.rows.len()), theme::TEXT, theme::BORDER);
|
||||
let inner = block.inner(area);
|
||||
f.render_widget(block, area);
|
||||
if o.rows.is_empty() {
|
||||
let hint = " no sessions yet · orch session --repo . --machine task --name NAME";
|
||||
f.render_widget(Paragraph::new(Span::styled(hint, fg(theme::DIM))), inner);
|
||||
return;
|
||||
}
|
||||
let w_machine = o
|
||||
.rows
|
||||
.iter()
|
||||
.map(|r| machine_spans(r).iter().map(|s| s.width()).sum::<usize>())
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
.clamp(12, 72);
|
||||
let mut head = vec![];
|
||||
cell(&mut head, vec![Span::raw(" id")], W_ID);
|
||||
cell(&mut head, vec![Span::raw("status")], W_STATUS);
|
||||
cell(&mut head, vec![Span::raw("task")], W_TASK);
|
||||
cell(&mut head, vec![Span::raw("machine")], w_machine);
|
||||
cell(&mut head, vec![Span::raw("tests")], W_TESTS);
|
||||
cell(&mut head, vec![Span::raw("diff")], W_DIFF);
|
||||
cell(&mut head, vec![Span::raw("context")], W_CTX);
|
||||
head.push(Span::raw("last activity"));
|
||||
let mut lines = vec![Line::from(head).style(fg(theme::DIM))];
|
||||
for (i, r) in o.rows.iter().enumerate() {
|
||||
let on = i == sel;
|
||||
let cursor = if on {
|
||||
Span::styled("▶ ", fg(theme::RUN))
|
||||
} else {
|
||||
Span::raw(" ")
|
||||
};
|
||||
let mut l1 = vec![];
|
||||
cell(&mut l1, vec![cursor, Span::raw(r.id.clone())], W_ID);
|
||||
cell(
|
||||
&mut l1,
|
||||
vec![Span::styled(r.status.label(), bold(status_color(r.status)))],
|
||||
W_STATUS,
|
||||
);
|
||||
cell(
|
||||
&mut l1,
|
||||
vec![Span::styled(fit(&r.task, W_TASK), bold(theme::TEXT))],
|
||||
W_TASK,
|
||||
);
|
||||
cell(&mut l1, machine_spans(r), w_machine);
|
||||
let tests_color = match r.tests_ok {
|
||||
Some(true) => theme::OK,
|
||||
Some(false) => theme::ERR,
|
||||
None => theme::TODO,
|
||||
};
|
||||
cell(
|
||||
&mut l1,
|
||||
vec![Span::styled(r.tests.clone(), fg(tests_color))],
|
||||
W_TESTS,
|
||||
);
|
||||
let diff = if r.added + r.removed == 0 {
|
||||
vec![]
|
||||
} else {
|
||||
vec![
|
||||
Span::styled(format!("+{}", r.added), fg(theme::OK)),
|
||||
Span::raw(" "),
|
||||
Span::styled(format!("−{}", r.removed), fg(theme::ERR)),
|
||||
]
|
||||
};
|
||||
cell(&mut l1, diff, W_DIFF);
|
||||
let ctx = r
|
||||
.ctx
|
||||
.map_or_else(|| Span::styled("—", fg(theme::TODO)), ctx_bar);
|
||||
cell(&mut l1, vec![ctx], W_CTX);
|
||||
let rest = (inner.width as usize)
|
||||
.saturating_sub(W_ID + W_STATUS + W_TASK + w_machine + W_TESTS + W_DIFF + W_CTX + 8);
|
||||
l1.push(Span::styled(fit(&r.last, rest), fg(theme::DIM)));
|
||||
let mut l2 = vec![];
|
||||
cell(&mut l2, vec![], W_ID + W_STATUS + 1);
|
||||
cell(
|
||||
&mut l2,
|
||||
vec![Span::styled(fit(&r.sub, W_TASK), fg(theme::DIM))],
|
||||
W_TASK,
|
||||
);
|
||||
// the retry counter sits next to the machine file name: on the chip line it would push every column right
|
||||
let mut m2 = vec![Span::styled(r.machine.clone(), fg(theme::DIM))];
|
||||
if !r.retry.is_empty() {
|
||||
m2.push(Span::styled(format!(" {}", r.retry), fg(theme::ERR)));
|
||||
}
|
||||
cell(&mut l2, m2, w_machine);
|
||||
let bg = if on {
|
||||
Style::new().bg(theme::SEL)
|
||||
} else {
|
||||
Style::new()
|
||||
};
|
||||
lines.push(Line::from(l1).style(bg));
|
||||
lines.push(Line::from(l2).style(bg));
|
||||
}
|
||||
f.render_widget(Paragraph::new(lines), inner);
|
||||
}
|
||||
|
||||
fn needs_box(f: &mut Frame, area: Rect, needs: &[Need]) {
|
||||
let border = if needs.is_empty() {
|
||||
theme::BORDER
|
||||
} else {
|
||||
theme::WAIT
|
||||
};
|
||||
let block = boxed("◆ Needs you", Some(needs.len()), theme::WAIT, border);
|
||||
let inner = block.inner(area);
|
||||
f.render_widget(block, area);
|
||||
let mut lines = vec![];
|
||||
for n in needs {
|
||||
lines.push(Line::from(vec![
|
||||
Span::styled(n.session.clone(), fg(theme::WAIT)),
|
||||
Span::raw(" "),
|
||||
Span::styled(n.task.clone(), bold(theme::TEXT)),
|
||||
Span::styled(format!(" · {}", n.what), fg(theme::DIM)),
|
||||
]));
|
||||
if !n.detail.is_empty() {
|
||||
lines.push(Line::from(Span::raw(fit(&n.detail, inner.width as usize))));
|
||||
}
|
||||
lines.push(Line::raw(""));
|
||||
}
|
||||
if needs.is_empty() {
|
||||
lines.push(Line::from(Span::styled(
|
||||
" nothing waits on you",
|
||||
fg(theme::DIM),
|
||||
)));
|
||||
}
|
||||
f.render_widget(Paragraph::new(lines), inner);
|
||||
}
|
||||
|
||||
fn kind_color(kind: &str) -> Color {
|
||||
match kind {
|
||||
"test" | "catch" => theme::ERR,
|
||||
"state" | "resume" => theme::RUN,
|
||||
"tool" => theme::AGENT,
|
||||
"edit" => theme::OK,
|
||||
"notify" | "end" => theme::WAIT,
|
||||
_ => theme::DIM,
|
||||
}
|
||||
}
|
||||
|
||||
fn events_box(f: &mut Frame, area: Rect, events: &[EventLine]) {
|
||||
let mut title = vec![Span::styled(" Events", bold(theme::TEXT))];
|
||||
title.push(Span::styled(" all sessions · f filter ", fg(theme::DIM)));
|
||||
let block = Block::bordered()
|
||||
.border_style(fg(theme::BORDER))
|
||||
.title(Line::from(title));
|
||||
let inner = block.inner(area);
|
||||
f.render_widget(block, area);
|
||||
let take = inner.height as usize;
|
||||
let skip = events.len().saturating_sub(take);
|
||||
let lines: Vec<Line> = events[skip..]
|
||||
.iter()
|
||||
.map(|e| {
|
||||
Line::from(vec![
|
||||
Span::styled(format!("{} ", hms(e.at_ms)), fg(theme::DIM)),
|
||||
Span::styled(format!("{:<4}", e.session), fg(theme::RUN)),
|
||||
Span::styled(format!("{:<7}", fit(&e.kind, 7)), fg(kind_color(&e.kind))),
|
||||
Span::raw(fit(&e.text, (inner.width as usize).saturating_sub(21))),
|
||||
])
|
||||
})
|
||||
.collect();
|
||||
f.render_widget(Paragraph::new(lines), inner);
|
||||
}
|
||||
|
||||
fn key_bar() -> Line<'static> {
|
||||
let mut v = vec![Span::raw(" ")];
|
||||
for (k, what) in [("j/k", "move"), ("q", "quit")] {
|
||||
v.push(Span::styled(
|
||||
format!(" {k} "),
|
||||
Style::new().fg(theme::BG).bg(theme::DIM),
|
||||
));
|
||||
v.push(Span::styled(format!(" {what} "), fg(theme::DIM)));
|
||||
}
|
||||
Line::from(v)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Colors from ORCHESTRATOR.md section 8. Truecolor; ratatui maps to the nearest color on 256-color terminals
|
||||
//! only through the terminal itself, so `COLORTERM` without truecolor looks approximate.
|
||||
// shortcut: no explicit 256-color table; add one if a target terminal needs it.
|
||||
|
||||
use ratatui::style::{Color, Modifier, Style};
|
||||
|
||||
const fn rgb(hex: u32) -> Color {
|
||||
Color::Rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8)
|
||||
}
|
||||
|
||||
pub const BG: Color = rgb(0x0b0e14);
|
||||
pub const TEXT: Color = rgb(0xc9d1d9);
|
||||
pub const DIM: Color = rgb(0x8b949e);
|
||||
pub const TODO: Color = rgb(0x7d8590);
|
||||
pub const BORDER: Color = rgb(0x30363d);
|
||||
pub const SEL: Color = rgb(0x161b22);
|
||||
pub const SEP: Color = rgb(0x484f58);
|
||||
pub const RUN: Color = rgb(0x79c0ff);
|
||||
pub const OK: Color = rgb(0x7ee787);
|
||||
pub const ERR: Color = rgb(0xff7b72);
|
||||
pub const WAIT: Color = rgb(0xe3b341);
|
||||
pub const AGENT: Color = rgb(0xd2a8ff);
|
||||
|
||||
pub fn fg(c: Color) -> Style {
|
||||
Style::new().fg(c)
|
||||
}
|
||||
|
||||
pub fn bold(c: Color) -> Style {
|
||||
Style::new().fg(c).add_modifier(Modifier::BOLD)
|
||||
}
|
||||
|
||||
/// Inverted block: dark text on a colored ground (active and waiting marks, key caps).
|
||||
pub fn inverted(c: Color) -> Style {
|
||||
Style::new().fg(BG).bg(c).add_modifier(Modifier::BOLD)
|
||||
}
|
||||
+611
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user