- Use the terminal's own colors and background; the key bar and the Needs-you panel wrap, fixed-width panels shrink on narrow terminals. - Sessions run on threads of the TUI (tui/host.rs), capped by the profile's `workers`; quitting asks for `yes` and suspends them. New `suspend` command keeps the state so a session can be resumed. - `N` opens a new-session form: machine, name, --after, a named branch or worktree (place.rs; never deleted by orch), and a "keep for a PR" option. - `u` resumes suspended sessions and ones whose process died. - `A` allows identical permission requests across sessions, `P` saves an allow rule to the profile with toml_edit (comments kept). - Fix clippy lint in report.rs so tests/all.sh passes; add GLOSSARY.md. Includes the already staged `orch init` work (init.rs, example profile). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
391 lines
12 KiB
Rust
391 lines
12 KiB
Rust
//! 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>,
|
|
}
|
|
|
|
/// Per-session limits. Exceeding `wall_secs` (time spent working, not waiting for the user) or `cost` emits a
|
|
/// `budget` event and sends the session to `on_budget`. Past `compact_at` percent of the context window hx is
|
|
/// told to compact. The retry limit is the `retry` table of the state that loops.
|
|
#[derive(Deserialize, Clone, Debug, Default, PartialEq)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct BudgetCfg {
|
|
pub wall_secs: Option<u64>,
|
|
/// US dollars.
|
|
pub cost: Option<f64>,
|
|
pub compact_at: Option<u8>,
|
|
}
|
|
|
|
#[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(default)]
|
|
pub budget: BudgetCfg,
|
|
#[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()))
|
|
}
|
|
|
|
fn dirs(repo: &Path) -> Vec<PathBuf> {
|
|
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"));
|
|
}
|
|
dirs
|
|
}
|
|
|
|
/// Names of the machine files in `<repo>/.hx/machines/` and `~/.hx/machines/`, sorted, without duplicates.
|
|
pub fn names(repo: &Path) -> Vec<String> {
|
|
let mut v: Vec<String> = Self::dirs(repo)
|
|
.iter()
|
|
.filter_map(|d| std::fs::read_dir(d).ok())
|
|
.flatten()
|
|
.flatten()
|
|
.filter_map(|e| {
|
|
let p = e.path();
|
|
if p.extension()? != "toml" {
|
|
return None;
|
|
}
|
|
p.file_stem()?.to_str().map(String::from)
|
|
})
|
|
.collect();
|
|
v.sort();
|
|
v.dedup();
|
|
v
|
|
}
|
|
|
|
/// `<name>.toml` in `<repo>/.hx/machines/`, then `~/.hx/machines/`.
|
|
pub fn find(name: &str, repo: &Path) -> Result<Self> {
|
|
let file = format!("{name}.toml");
|
|
let dirs = Self::dirs(repo);
|
|
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(())
|
|
};
|
|
if let Some(c) = self.budget.compact_at {
|
|
ensure!(
|
|
(1..=100).contains(&c),
|
|
"budget.compact_at is a percent, 1 to 100"
|
|
);
|
|
}
|
|
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(r) = &st.report {
|
|
ensure!(
|
|
r == "junit",
|
|
"state {n:?} step {:?}: unknown report format {r:?} (only junit)",
|
|
st.name
|
|
);
|
|
ensure!(
|
|
st.run == RunOn::Computer,
|
|
"state {n:?} step {:?}: only computer steps can have a report",
|
|
st.name
|
|
);
|
|
}
|
|
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");
|
|
assert_eq!(
|
|
m.budget,
|
|
BudgetCfg {
|
|
wall_secs: Some(5400),
|
|
cost: Some(5.0),
|
|
compact_at: Some(85)
|
|
}
|
|
);
|
|
assert_eq!(example("docs").budget, BudgetCfg::default());
|
|
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("name = \"m\"", "name = \"m\"\n[budget]\ncompact_at = 0"))
|
|
.contains("percent")
|
|
);
|
|
assert!(
|
|
err(&OK.replace("name = \"m\"", "name = \"m\"\n[budget]\nbogus = 1"))
|
|
.contains("unknown field")
|
|
);
|
|
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"));
|
|
}
|
|
}
|