Add Needs-you queue and goal view with acceptance checks

- needs table: human steps, permission requests and agent questions wait
  for an answer written to the database; a/c/d, y/Y/n, r keys in the TUI
- goal view (g): task graph, critical path, decisions, acceptance checks;
  e edit goal, + add check, R run all checks on main
- checks.rs: acceptance checks on a branch or on main in a clean worktree
- runner: wait for --after dependencies, one session in merge at a time,
  all checks again on main after each merge
- orch goal / check / checks commands, ORCH_DB and {{repo}} for machine steps
- example machines merge with git merge --ff-only

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
johannesandClaude Sonnet 5.5 committed 2026-11-14 12:38:46 +01:00
1 parent 5b659fa8ba
commit 7bf0986640
16 files changed
+2551 -105

No files matched your search

+586 -12
View File
@@ -1,5 +1,6 @@
//! Terminal UI. Everything on screen comes from the event table and the machine files via `view::build`.
mod goal;
mod overview;
mod session;
mod theme;
@@ -30,6 +31,71 @@ enum Screen {
Overview,
/// Session detail for this session id.
Session(String),
/// Goal, task graph, decisions, acceptance checks.
Goal,
}
/// What a key does to the focused Needs-you item.
#[derive(Debug, PartialEq)]
enum NeedKey {
/// Write this answer to the queue.
Answer(String),
/// Show the session's diff.
Diff,
/// Ask for a line of text first; the answer is `prefix` + text.
Prompt {
label: &'static str,
prefix: &'static str,
},
Nothing,
}
fn need_key(n: &view::Need, c: char) -> NeedKey {
use view::NeedKind::*;
let a = |s: &str| NeedKey::Answer(s.into());
match (n.kind, c) {
(Review, 'a') => a("approve"),
(Review, 'd') => NeedKey::Diff,
(Review, 'c') => NeedKey::Prompt {
label: "comment",
prefix: "changes: ",
},
(Permission, 'y') => a("allow_once"),
(Permission, 'Y') => a("allow_always"),
(Permission, 'n') => a("deny"),
(Input, 'r') => NeedKey::Prompt {
label: "reply",
prefix: "reply: ",
},
_ => NeedKey::Nothing,
}
}
/// What a finished input line is for.
#[derive(Clone, Copy, PartialEq, Debug)]
enum Target {
/// Answer to this Needs-you item.
Need(i64),
/// New goal sentence.
Goal,
/// `name | command | owner` of a new acceptance check; the owner is optional.
Check,
}
/// A one-line text entry shown at the bottom while the user writes a comment, reply, goal or check.
struct InputLine {
label: &'static str,
prefix: &'static str,
target: Target,
text: String,
}
/// `name | command | owner` -> (name, command, owner)
fn parse_check(s: &str) -> Option<(String, String, Option<String>)> {
let mut p = s.split('|').map(str::trim);
let (name, cmd) = (p.next()?, p.next()?);
let owner = p.next().filter(|o| !o.is_empty()).map(String::from);
(!name.is_empty() && !cmd.is_empty()).then(|| (name.into(), cmd.into(), owner))
}
/// A scrollable text overlay: full test output, diff, agent transcript.
@@ -51,9 +117,68 @@ struct App {
screen: Screen,
detail: Option<Detail>,
pager: Option<Pager>,
/// Focused item of the Needs-you box.
need_sel: usize,
input: Option<InputLine>,
goal_view: Option<crate::goal::GoalView>,
/// True while a background `run all checks` is going.
checks_running: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
impl App {
/// Runs every check on main in the background; the goal view shows `running…` meanwhile.
fn run_all_checks(&mut self) {
use std::sync::atomic::Ordering;
if self.checks_running.swap(true, Ordering::SeqCst) {
return; // already running
}
let (repo, flag) = (self.repo.clone(), self.checks_running.clone());
std::thread::spawn(move || {
if let Ok(db) = Db::open(&repo.join(".hx/orch.db")) {
let _ = crate::checks::run_on_main(&db, &repo);
}
flag.store(false, Ordering::SeqCst);
});
}
/// The goal database, created on first use by actions that only make sense with one (edit goal, add check).
fn db_or_create(&mut self) -> Option<&Db> {
if self.db.is_none() {
self.db = Db::open(&self.repo.join(".hx/orch.db")).ok();
}
self.db.as_ref()
}
/// A finished input line: an answer for the queue, a new goal, or a new check.
fn submit(&mut self, i: InputLine) {
let text = i.text.trim().to_string();
match i.target {
Target::Need(id) => return self.answer(id, &format!("{}{text}", i.prefix)),
Target::Goal if !text.is_empty() => {
if let Some(db) = self.db_or_create() {
let _ = db.set_goal(&text);
}
}
Target::Check => {
if let Some((name, cmd, owner)) = parse_check(&text)
&& let Some(db) = self.db_or_create()
{
let _ = db.add_check(&name, &cmd, owner.as_deref());
}
}
Target::Goal => {}
}
self.refresh();
}
/// Writes the user's answer to the queue; the waiting runner picks it up.
fn answer(&mut self, need: i64, answer: &str) {
if let Some(db) = &self.db {
let _ = db.answer_need(need, answer);
}
self.refresh();
}
fn new(repo: PathBuf) -> Self {
let rev = git_rev(&repo);
Self {
@@ -67,6 +192,10 @@ impl App {
screen: Screen::Overview,
detail: None,
pager: None,
need_sel: 0,
input: None,
goal_view: None,
checks_running: Default::default(),
}
}
@@ -91,10 +220,19 @@ impl App {
)
.ok()
.flatten(),
Screen::Overview => None,
_ => None,
};
self.goal_view = match self.screen {
Screen::Goal => {
goal_snapshot(db, &self.repo, &mut self.events, &mut self.machines, now).ok()
}
_ => None,
};
}
self.sel = self.sel.min(self.overview.rows.len().saturating_sub(1));
self.need_sel = self
.need_sel
.min(self.overview.needs.len().saturating_sub(1));
}
fn header(&self) -> Header {
@@ -116,6 +254,9 @@ impl App {
struct Loaded {
tasks: Vec<crate::db::Task>,
sessions: Vec<crate::db::Session>,
needs: Vec<crate::db::NeedRow>,
checks: Vec<crate::db::CheckRow>,
decisions: Vec<crate::db::DecisionRow>,
goal: Option<String>,
}
@@ -139,6 +280,9 @@ fn load(
Ok(Loaded {
tasks,
sessions,
needs: db.pending_needs()?,
checks: db.checks()?,
decisions: db.decisions()?,
goal: db.goal()?,
})
}
@@ -157,6 +301,30 @@ fn snapshot(
sessions: &l.sessions,
events,
machines,
needs: &l.needs,
checks: &l.checks,
decisions: &l.decisions,
now_ms,
}))
}
fn goal_snapshot(
db: &Db,
repo: &Path,
events: &mut Vec<Event>,
machines: &mut HashMap<String, Machine>,
now_ms: u64,
) -> Result<crate::goal::GoalView> {
let l = load(db, repo, events, machines)?;
Ok(crate::goal::build(&view::Input {
goal: l.goal.as_deref(),
tasks: &l.tasks,
sessions: &l.sessions,
events,
machines,
needs: &l.needs,
checks: &l.checks,
decisions: &l.decisions,
now_ms,
}))
}
@@ -177,6 +345,9 @@ fn session_detail(
sessions: &l.sessions,
events,
machines,
needs: &l.needs,
checks: &l.checks,
decisions: &l.decisions,
now_ms,
},
id,
@@ -197,11 +368,56 @@ fn git_rev(repo: &Path) -> String {
fn draw(f: &mut ratatui::Frame, app: &App, header: &Header) {
match (&app.screen, &app.detail) {
(Screen::Session(_), Some(d)) => session::draw(f, d, header),
_ => overview::draw(f, &app.overview, header, app.sel),
(Screen::Goal, _) => {
let empty;
let g = match &app.goal_view {
Some(g) => g,
None => {
empty = crate::goal::GoalView::default();
&empty
}
};
let running = app.checks_running.load(std::sync::atomic::Ordering::SeqCst);
goal::draw(f, g, header, running);
}
_ => overview::draw(f, &app.overview, header, app.sel, app.need_sel),
}
if let Some(p) = &app.pager {
draw_pager(f, p);
}
if let Some(i) = &app.input {
draw_input(f, i);
}
}
/// One bordered line at the bottom: ` comment › text▏`.
fn draw_input(f: &mut ratatui::Frame, i: &InputLine) {
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, Paragraph};
let a = f.area();
let area = ratatui::layout::Rect::new(
a.x + 2,
a.bottom().saturating_sub(4),
a.width.saturating_sub(4),
3,
);
f.render_widget(Clear, area);
let block = Block::bordered()
.border_style(theme::fg(theme::WAIT))
.title(Span::styled(
" enter send · esc cancel ",
theme::fg(theme::DIM),
));
let inner = block.inner(area);
f.render_widget(block, area);
f.render_widget(
Paragraph::new(Line::from(vec![
Span::styled(format!(" {} › ", i.label), theme::fg(theme::WAIT)),
Span::raw(i.text.clone()),
Span::styled("▏", theme::fg(theme::RUN)),
])),
inner,
);
}
fn draw_pager(f: &mut ratatui::Frame, p: &Pager) {
@@ -333,6 +549,22 @@ fn on_key(
if k.code == KeyCode::Char('c') && k.modifiers.contains(KeyModifiers::CONTROL) {
return Ok(true);
}
if let Some(i) = &mut app.input {
match k.code {
KeyCode::Esc => app.input = None,
KeyCode::Backspace => {
i.text.pop();
}
KeyCode::Char(c) => i.text.push(c),
KeyCode::Enter => {
if let Some(done) = app.input.take() {
app.submit(done);
}
}
_ => {}
}
return Ok(false);
}
if let Some(p) = &mut app.pager {
let max = p.lines.len().saturating_sub(1);
match k.code {
@@ -363,9 +595,68 @@ fn on_key(
app.refresh();
}
}
KeyCode::Tab => {
let n = app.overview.needs.len().max(1);
app.need_sel = (app.need_sel + 1) % n;
}
KeyCode::Char('g') => {
app.screen = Screen::Goal;
app.refresh();
}
// every other letter acts on the focused Needs-you item
KeyCode::Char(c) => {
if let Some(n) = app.overview.needs.get(app.need_sel).cloned() {
match need_key(&n, c) {
NeedKey::Answer(a) => app.answer(n.id, &a),
NeedKey::Diff => {
let wt = app
.db
.as_ref()
.and_then(|db| db.session(&n.session).ok().flatten());
if let Some(s) = wt {
app.pager = Some(diff_of(&s.worktree));
}
}
NeedKey::Prompt { label, prefix } => {
app.input = Some(InputLine {
label,
prefix,
target: Target::Need(n.id),
text: String::new(),
});
}
NeedKey::Nothing => {}
}
}
}
_ => {}
}
}
Screen::Goal => match k.code {
KeyCode::Esc | KeyCode::Char('q') => {
app.screen = Screen::Overview;
app.goal_view = None;
}
KeyCode::Char('e') => {
let current = app.db.as_ref().and_then(|d| d.goal().ok().flatten());
app.input = Some(InputLine {
label: "goal",
prefix: "",
target: Target::Goal,
text: current.unwrap_or_default(),
});
}
KeyCode::Char('+') => {
app.input = Some(InputLine {
label: "check: name | command | owner (optional)",
prefix: "",
target: Target::Check,
text: String::new(),
});
}
KeyCode::Char('R') => app.run_all_checks(),
_ => {}
},
Screen::Session(id) => {
let id = id.clone();
match k.code {
@@ -420,7 +711,7 @@ fn event_loop(term: &mut ratatui::DefaultTerminal, app: &mut App) -> Result<()>
#[cfg(test)]
mod tests {
use super::*;
use crate::view::{Chip, EventLine, Mark, Need, Row, Status};
use crate::view::{Chip, EventLine, Mark, Need, NeedKind, Row, Status};
use ratatui::{Terminal, backend::TestBackend};
fn screen(o: &Overview, sel: usize) -> String {
@@ -430,7 +721,7 @@ mod tests {
rev: "main@4f2a91c".into(),
now_ms: 0,
};
t.draw(|f| overview::draw(f, o, &h, sel)).unwrap();
t.draw(|f| overview::draw(f, o, &h, sel, 1)).unwrap();
let b = t.backend().buffer();
let w = b.area.width as usize;
b.content()
@@ -536,12 +827,26 @@ mod tests {
"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(),
}],
needs: vec![
Need {
id: 1,
kind: NeedKind::Review,
session: "s3".into(),
task: "auth-middleware".into(),
what: "review ready".into(),
detail: "6 files, +318 −97, 52/52 tests pass".into(),
age_secs: 240,
},
Need {
id: 2,
kind: NeedKind::Permission,
session: "s4".into(),
task: "rate-limiter".into(),
what: "permission".into(),
detail: "wants to run docker compose up -d redis".into(),
age_secs: 60,
},
],
events: vec![EventLine {
id: 1,
at_ms: 0,
@@ -581,8 +886,13 @@ mod tests {
"▰▰▰▰▰▰▰▱▱▱",
"waits on s2 oauth-provider",
"BLOCKED",
"◆ Needs you 1",
"s3 auth-middleware · review ready",
"◆ Needs you 2",
"s3 auth-middleware · review ready · 4m",
"6 files, +318 −97, 52/52 tests pass",
"[a] approve [d] open diff [c] comment back",
"▶s4 rate-limiter · permission · 1m", // focus is on the second item
"wants to run docker compose up -d redis",
"[y] allow once [Y] always for s4 [n] deny",
"Events all sessions",
] {
assert!(s.contains(want), "missing {want:?} in:\n{s}");
@@ -758,4 +1068,268 @@ end = "escalated"
assert!(diff_of(&d.worktree).lines.iter().any(|l| l == "?? n"));
let _ = std::fs::remove_dir_all(&dir);
}
fn need(kind: NeedKind) -> Need {
Need {
id: 7,
kind,
session: "s4".into(),
task: "t".into(),
what: "w".into(),
detail: String::new(),
age_secs: 0,
}
}
#[test]
fn keys_map_to_answers_per_item_kind() {
let a = |s: &str| NeedKey::Answer(s.into());
let r = need(NeedKind::Review);
assert_eq!(need_key(&r, 'a'), a("approve"));
assert_eq!(need_key(&r, 'd'), NeedKey::Diff);
assert!(matches!(
need_key(&r, 'c'),
NeedKey::Prompt {
prefix: "changes: ",
..
}
));
assert_eq!(
need_key(&r, 'y'),
NeedKey::Nothing,
"permission keys do nothing on a review"
);
let p = need(NeedKind::Permission);
assert_eq!(
[need_key(&p, 'y'), need_key(&p, 'Y'), need_key(&p, 'n')],
[a("allow_once"), a("allow_always"), a("deny")]
);
assert_eq!(need_key(&p, 'a'), NeedKey::Nothing);
assert!(matches!(
need_key(&need(NeedKind::Input), 'r'),
NeedKey::Prompt {
prefix: "reply: ",
..
}
));
assert_eq!(need_key(&need(NeedKind::Escalated), 'a'), NeedKey::Nothing);
}
#[test]
fn answering_in_the_tui_unblocks_the_waiting_runner() {
let dir = std::env::temp_dir().join(format!("orch-tui-needs-{}", 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();
std::fs::write(
repo.join(".hx/machines/m.toml"),
r#"name = "m"
[[state]]
name = "code"
kind = "start"
steps = [{ name = "edit", run = "computer", cmd = "true" }]
next = "review"
[[state]]
name = "review"
kind = "gate"
steps = [{ name = "wait-approval", run = "human" }]
catch = { ChangesRequested = "code" }
next = "merge"
[[state]]
name = "merge"
kind = "exit"
end = "merged"
"#,
)
.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();
let s = crate::runner::create(&db, &dir.join("wt"), "demo", "", "m").unwrap();
// the runner is a separate connection (could be another process): it blocks in the review gate
let (r2, id) = (repo.clone(), s.id.clone());
let runner = std::thread::spawn(move || {
let db = Db::open(&r2.join(".hx/orch.db")).unwrap();
let m = Machine::find("m", &r2).unwrap();
let p = crate::profile::Profile::parse("").unwrap();
crate::runner::run_session(&db, &m, &id, &r2, "", &p).unwrap()
});
let mut app = App::new(repo.clone());
let deadline = std::time::Instant::now() + Duration::from_secs(20);
while app.overview.needs.is_empty() && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(30));
app.refresh();
}
let n = app
.overview
.needs
.first()
.expect("review item appears in the queue")
.clone();
assert_eq!(
(n.kind, n.what.as_str()),
(NeedKind::Review, "review ready")
);
assert_eq!(
app.overview.rows[0].status,
Status::Wait,
"the session waits on the user"
);
let text = screen(&app.overview, 0);
assert!(
text.contains("review ready") && text.contains("[a] approve"),
"{text}"
);
let NeedKey::Answer(a) = need_key(&n, 'a') else {
panic!("a approves")
};
app.answer(n.id, &a);
assert_eq!(runner.join().unwrap(), "merged");
app.refresh();
assert!(app.overview.needs.is_empty());
assert_eq!(app.overview.rows[0].status, Status::Done);
let _ = std::fs::remove_dir_all(&dir);
}
fn goal_text(g: &crate::goal::GoalView, running: bool) -> String {
let mut t = Terminal::new(TestBackend::new(160, 45)).unwrap();
let h = Header {
repo: "~/r".into(),
rev: "main@abc".into(),
now_ms: 0,
};
t.draw(|f| goal::draw(f, g, &h, running)).unwrap();
let b = t.backend().buffer();
b.content()
.chunks(b.area.width as usize)
.map(|r| {
r.iter()
.map(|c| c.symbol())
.collect::<String>()
.trim_end()
.to_string()
})
.collect::<Vec<_>>()
.join("\n")
}
fn add(db: &Db, id: &str, name: &str, after: &[&str], state: &str, status: &str) {
db.add_task(&crate::db::Task {
id: id.into(),
name: name.into(),
subtitle: String::new(),
machine: "task".into(),
depends_on: after.iter().map(|a| a.to_string()).collect(),
})
.unwrap();
db.add_session(&crate::db::Session {
id: id.into(),
task_id: id.into(),
branch: format!("hx/{id}"),
worktree: "/w".into(),
pid: None,
state: state.into(),
status: status.into(),
})
.unwrap();
}
#[test]
fn goal_screen_shows_graph_critical_path_decisions_and_acceptance() {
let dir = std::env::temp_dir().join(format!("orch-tui-goal-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let db = Db::open(&dir.join(".hx/orch.db")).unwrap();
db.set_goal("Move login to OAuth2").unwrap();
add(&db, "s1", "schema-migrate", &[], "merge", "merged");
add(&db, "s2", "oauth-provider", &["s1"], "test", "running");
add(&db, "s3", "auth-middleware", &["s1"], "review", "waiting");
add(&db, "s5", "docs-update", &["s2", "s3"], "", "queued");
let build = db.add_check("cargo build", "true", None).unwrap();
let unit = db
.add_check("unit: auth::token", "false", Some("s2"))
.unwrap();
db.add_check("e2e: login", "true", Some("s6")).unwrap();
db.set_check_result(build, true).unwrap();
db.set_check_result(unit, false).unwrap();
db.add_decision("s2", "refresh tokens stored as argon2 hashes", "code")
.unwrap();
let mut app = App::new(dir.clone());
app.screen = Screen::Goal;
app.refresh();
let g = app.goal_view.as_ref().expect("goal view loads");
let text = goal_text(g, false);
if std::env::var_os("ORCH_DUMP").is_some() {
println!("{text}");
}
for want in [
"‹ sessions / goal",
"Move login to OAuth2",
"Done = all 3 acceptance checks green on main",
"Task graph",
"level 0",
"level 2",
"after: —",
"after: s2, s3",
"DONE · merged",
"WAIT · review",
"BLOCKED · queued",
"critical path",
"s2 oauth-provider → s5 docs-update",
"Decisions agents made",
"refresh tokens stored as argon2 hashes",
"Acceptance 1/3",
"✓ cargo build",
"✗ unit: auth::token",
"· e2e: login",
"esc back",
"R run all checks",
] {
assert!(text.contains(want), "missing {want:?} in:\n{text}");
}
assert!(goal_text(g, true).contains("running…"));
// the overview's acceptance bar reads the same checks
let o = screen(&app.overview, 0);
assert!(o.contains("1/3 checks"), "{o}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn editing_the_goal_and_adding_checks_from_the_tui() {
let dir = std::env::temp_dir().join(format!("orch-tui-edit-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut app = App::new(dir.clone()); // no database yet: the first action creates it
let line = |target, text: &str| InputLine {
label: "x",
prefix: "",
target,
text: text.into(),
};
app.submit(line(Target::Goal, " ship it "));
app.submit(line(Target::Check, "build | cargo build | s1"));
app.submit(line(Target::Check, "no owner|true"));
app.submit(line(Target::Check, "broken, no pipe"));
app.submit(line(Target::Goal, " ")); // empty goal is ignored
let db = Db::open(&dir.join(".hx/orch.db")).unwrap();
assert_eq!(db.goal().unwrap().as_deref(), Some("ship it"));
let c = db.checks().unwrap();
assert_eq!(c.len(), 2);
assert_eq!(
(c[0].name.as_str(), c[0].cmd.as_str(), c[0].owner.as_deref()),
("build", "cargo build", Some("s1"))
);
assert_eq!(c[1].owner, None);
assert_eq!(
parse_check("a | b | "),
Some(("a".into(), "b".into(), None))
);
assert_eq!(parse_check("| b"), None);
let _ = std::fs::remove_dir_all(&dir);
}
}