diff --git a/README.md b/README.md index 1f01ea3..3f5ca5c 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,14 @@ Machines are TOML files in `.hx/machines/` or `~/.hx/machines/` (examples in `ex with `report = "junit"` writes its JUnit XML to `$ORCH_REPORT` (also available as `{{report}}` in `cmd`); orch parses it into counts and failing tests. See ORCHESTRATOR.md for the whole design. +The goal lives in the same database: `orch goal "sentence"`, `orch check NAME CMD [--owner sN]` (an acceptance +check: pass = exit 0), `orch checks [--owner sN | --main]`. `g` in the TUI opens the goal view (task graph, critical +path, decisions, checks; `e` edit goal, `+` add check, `R` run all checks on main). `orch session --after s1,s2` makes +a session wait until those have merged. Only one session at a time runs the state that ends in `merged` (first come, +first served); after each merge all checks run again on main in a clean worktree. Machine steps get `ORCH_DB`, +`ORCH_REPO` and `ORCH_SESSION`, and `{{repo}}` in `cmd`; the example machines merge with +`git -C {{repo}} merge --ff-only {{branch}}` in `mark-merged`. + ## More - [docs/cmd-protocol.md](docs/cmd-protocol.md): task sources and result sinks as external commands (+ JSON schema) diff --git a/examples/machines/docs.toml b/examples/machines/docs.toml index 478ef8b..f4a26e0 100644 --- a/examples/machines/docs.toml +++ b/examples/machines/docs.toml @@ -43,7 +43,7 @@ name = "merge" kind = "exit" steps = [ { name = "rebase-main", run = "computer", cmd = "git rebase main" }, - { name = "mark-merged", run = "computer", sets = "merged" }, + { name = "mark-merged", run = "computer", sets = "merged", cmd = "git -C {{repo}} merge --ff-only {{branch}}" }, ] catch = { RebaseConflict = "write" } end = "merged" diff --git a/examples/machines/e2e.toml b/examples/machines/e2e.toml index 168e61a..56026c8 100644 --- a/examples/machines/e2e.toml +++ b/examples/machines/e2e.toml @@ -50,7 +50,7 @@ kind = "exit" steps = [ { name = "rebase-main", run = "computer", cmd = "git rebase main" }, { name = "run-acceptance", run = "computer", cmd = "orch checks --owner {{session}}" }, - { name = "mark-merged", run = "computer", sets = "merged" }, + { name = "mark-merged", run = "computer", sets = "merged", cmd = "git -C {{repo}} merge --ff-only {{branch}}" }, ] catch = { RebaseConflict = "code" } end = "merged" diff --git a/examples/machines/migration.toml b/examples/machines/migration.toml index c51dd51..ad794a6 100644 --- a/examples/machines/migration.toml +++ b/examples/machines/migration.toml @@ -53,7 +53,7 @@ kind = "exit" steps = [ { name = "rebase-main", run = "computer", cmd = "git rebase main" }, { name = "run-acceptance", run = "computer", cmd = "orch checks --owner {{session}}" }, - { name = "mark-merged", run = "computer", sets = "merged" }, + { name = "mark-merged", run = "computer", sets = "merged", cmd = "git -C {{repo}} merge --ff-only {{branch}}" }, ] catch = { RebaseConflict = "code" } end = "merged" diff --git a/examples/machines/task.toml b/examples/machines/task.toml index 17af245..fae300c 100644 --- a/examples/machines/task.toml +++ b/examples/machines/task.toml @@ -48,7 +48,7 @@ kind = "exit" steps = [ { name = "rebase-main", run = "computer", cmd = "git rebase main" }, { name = "run-acceptance", run = "computer", cmd = "orch checks --owner {{session}}" }, - { name = "mark-merged", run = "computer", sets = "merged" }, + { name = "mark-merged", run = "computer", sets = "merged", cmd = "git -C {{repo}} merge --ff-only {{branch}}" }, ] catch = { RebaseConflict = "code" } end = "merged" diff --git a/src/checks.rs b/src/checks.rs new file mode 100644 index 0000000..7d50bad --- /dev/null +++ b/src/checks.rs @@ -0,0 +1,159 @@ +//! Acceptance checks (ORCHESTRATOR.md section 2): shell commands, pass = exit 0. A goal is done when every +//! check is green on main, so results on main are what the goal view shows; a session can also run its own +//! checks on its branch before merging (`run-acceptance` step) without touching the recorded result. + +use crate::db::{CheckRow, Db}; +use crate::run::{git, tail}; +use anyhow::Result; +use serde_json::json; +use std::path::Path; +use std::process::Command; + +/// Pseudo session id for goal-level events (check results on main). +pub const GOAL: &str = "goal"; + +pub struct Outcome { + pub check: CheckRow, + pub pass: bool, + pub exit: Option, + pub output: String, +} + +/// Runs the checks in `dir`. `owner` limits to one session's checks. `record` stores the result as the check's +/// status on main; it is only for runs that really are on main. +pub fn run(db: &Db, dir: &Path, owner: Option<&str>, record: bool) -> Result> { + let mut out = vec![]; + for c in db.checks()? { + if owner.is_some() && c.owner.as_deref() != owner { + continue; + } + let o = Command::new("sh") + .args(["-c", &format!("({}) 2>&1", c.cmd)]) + .current_dir(dir) + .output()?; + let (pass, exit) = (o.status.success(), o.status.code()); + let output = tail(&o.stdout, 2000); + if record { + db.set_check_result(c.id, pass)?; + } + let session = owner.unwrap_or(GOAL); + db.emit( + session, + "check", + json!({ + "name": c.name, "pass": pass, "exit": exit, + "where": if record { "main" } else { "branch" }, + "output": if pass { String::new() } else { output.clone() }, + }), + )?; + out.push(Outcome { + check: c, + pass, + exit, + output, + }); + } + Ok(out) +} + +/// All checks, recorded, in a clean detached worktree of the repo's HEAD (main after a merge). The +/// user's own checkout is never touched. +pub fn run_on_main(db: &Db, repo: &Path) -> Result> { + if db.checks()?.is_empty() { + return Ok(vec![]); + } + let tmp = repo.join(format!(".hx/main-check-{}", crate::state::now_ms())); + let lock_path = repo.join(".git/orch-worktree.lock"); + { + let _l = crate::lock::lock(&lock_path)?; // git races on its own locks + git( + repo, + &[ + "worktree", + "add", + "--detach", + &tmp.to_string_lossy(), + "HEAD", + ], + )?; + } + let res = run(db, &tmp, None, true); + let _l = crate::lock::lock(&lock_path)?; + let _ = git( + repo, + &["worktree", "remove", "--force", &tmp.to_string_lossy()], + ); + res +} + +#[cfg(test)] +mod tests { + use super::*; + + fn repo(tag: &str) -> (std::path::PathBuf, Db) { + let dir = std::env::temp_dir().join(format!("orch-checks-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + git(&dir, &["init", "-q", "-b", "main"]).unwrap(); + std::fs::write(dir.join("present.txt"), "x").unwrap(); + git(&dir, &["add", "-A"]).unwrap(); + git(&dir, &["commit", "-qm", "init"]).unwrap(); + let db = Db::open(&dir.join(".hx/orch.db")).unwrap(); + (dir, db) + } + + #[test] + fn main_run_records_in_a_clean_worktree_and_leaves_the_checkout_alone() { + let (dir, db) = repo("main"); + db.add_check("file present", "test -f present.txt", None) + .unwrap(); + db.add_check("untracked junk absent", "test ! -f junk.txt", Some("s1")) + .unwrap(); + db.add_check("always red", "echo nope; exit 3", None) + .unwrap(); + // junk in the user's checkout must not be visible to the checks: they run in a clean worktree + std::fs::write(dir.join("junk.txt"), "dirty").unwrap(); + let r = run_on_main(&db, &dir).unwrap(); + assert_eq!( + r.iter().map(|o| o.pass).collect::>(), + [true, true, false] + ); + assert_eq!(r[2].exit, Some(3)); + let rows = db.checks().unwrap(); + let st: Vec<_> = rows + .iter() + .map(|c| c.last_status.as_deref().unwrap()) + .collect(); + assert_eq!(st, ["pass", "pass", "fail"]); + assert!(rows[0].last_run_at.is_some()); + assert!(dir.join("junk.txt").exists(), "checkout untouched"); + let leftovers: Vec<_> = std::fs::read_dir(dir.join(".hx")) + .unwrap() + .flatten() + .filter(|e| e.file_name().to_string_lossy().starts_with("main-check")) + .collect(); + assert!(leftovers.is_empty(), "temporary worktree removed"); + let ev = db.events(Some(GOAL), 0).unwrap(); + assert_eq!(ev.len(), 3); + assert_eq!(ev[2].payload["output"], "nope\n"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn branch_run_filters_by_owner_and_does_not_record() { + let (dir, db) = repo("branch"); + db.add_check("mine", "true", Some("s1")).unwrap(); + db.add_check("theirs", "false", Some("s2")).unwrap(); + db.add_check("unowned", "false", None).unwrap(); + let r = run(&db, &dir, Some("s1"), false).unwrap(); + assert_eq!(r.len(), 1); + assert!(r[0].pass); + assert!(db.checks().unwrap().iter().all(|c| c.last_status.is_none())); + assert_eq!( + db.events(Some("s1"), 0).unwrap()[0].payload["where"], + "branch" + ); + assert_eq!(db.events(Some(GOAL), 0).unwrap().len(), 0); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/src/db.rs b/src/db.rs index 0a17ae2..c4b2d2d 100644 --- a/src/db.rs +++ b/src/db.rs @@ -26,10 +26,40 @@ 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); +create table if not exists merge_queue( + ticket integer primary key autoincrement, session_id text not null unique); +create table if not exists needs( + id integer primary key autoincrement, session_id text not null, kind text not null, + payload text not null default '{}', created_at integer not null, answer text, + done integer not null default 0); "; pub struct Db { conn: Connection, + path: std::path::PathBuf, +} + +/// An acceptance check: a shell command, pass = exit 0. `last_status` is the result on main. +#[derive(Clone, Debug, PartialEq)] +pub struct CheckRow { + pub id: i64, + pub name: String, + pub cmd: String, + pub owner: Option, + /// pass | fail, None until the first run + pub last_status: Option, + pub last_run_at: Option, +} + +/// A choice an agent reported with `hx/decision`. +#[derive(Clone, Debug, PartialEq)] +pub struct DecisionRow { + pub id: i64, + pub session: String, + pub text: String, + pub state: String, + pub at: u64, + pub vetoed: bool, } #[derive(Clone, Debug, PartialEq)] @@ -42,6 +72,20 @@ pub struct Event { pub payload: Value, } +/// One item of the Needs-you queue: a `human` step, a permission request or an agent question. The runner +/// writes it and waits; the TUI (or anything else with the database) writes the answer. +#[derive(Clone, Debug, PartialEq)] +pub struct NeedRow { + pub id: i64, + pub session: String, + /// review | permission | input + pub kind: String, + pub payload: Value, + /// Milliseconds since the epoch. + pub at: u64, + pub answer: Option, +} + #[derive(Clone, Debug, PartialEq)] pub struct Task { pub id: String, @@ -72,7 +116,111 @@ impl Db { conn.busy_timeout(std::time::Duration::from_secs(5))?; conn.pragma_update(None, "journal_mode", "WAL")?; conn.execute_batch(SCHEMA)?; - Ok(Self { conn }) + Ok(Self { + conn, + path: path.to_path_buf(), + }) + } + + /// Where this database lives; exported to machine steps as `ORCH_DB`. + pub fn path(&self) -> &Path { + &self.path + } + + pub fn add_check(&self, name: &str, cmd: &str, owner: Option<&str>) -> Result { + self.conn.execute( + "insert into checks(name, cmd, owner_session) values (?1, ?2, ?3)", + params![name, cmd, owner], + )?; + Ok(self.conn.last_insert_rowid()) + } + + pub fn checks(&self) -> Result> { + let mut q = self.conn.prepare( + "select id, name, cmd, owner_session, last_status, last_run_at from checks order by id", + )?; + let rows = q.query_map([], |r| { + Ok(CheckRow { + id: r.get(0)?, + name: r.get(1)?, + cmd: r.get(2)?, + owner: r.get(3)?, + last_status: r.get(4)?, + last_run_at: r.get::<_, Option>(5)?.map(|v| v as u64), + }) + })?; + Ok(rows.collect::>()?) + } + + pub fn set_check_result(&self, id: i64, pass: bool) -> Result<()> { + self.conn.execute( + "update checks set last_status = ?2, last_run_at = ?3 where id = ?1", + params![ + id, + if pass { "pass" } else { "fail" }, + crate::state::now_ms() as i64 + ], + )?; + Ok(()) + } + + pub fn decisions(&self) -> Result> { + let mut q = self.conn.prepare( + "select rowid, session_id, text, state, at, vetoed from decisions order by rowid", + )?; + let rows = q.query_map([], |r| { + Ok(DecisionRow { + id: r.get(0)?, + session: r.get(1)?, + text: r.get(2)?, + state: r.get(3)?, + at: r.get::<_, i64>(4)? as u64, + vetoed: r.get::<_, i64>(5)? != 0, + }) + })?; + Ok(rows.collect::>()?) + } + + /// Joins the merge queue (once) and returns the ticket; lower tickets merge first. + pub fn queue_join(&self, session: &str) -> Result { + self.conn.execute( + "insert or ignore into merge_queue(session_id) values (?1)", + [session], + )?; + Ok(self.conn.query_row( + "select ticket from merge_queue where session_id = ?1", + [session], + |r| r.get(0), + )?) + } + + /// The session at the head of the merge queue. + pub fn queue_head(&self) -> Result> { + Ok(self + .conn + .query_row( + "select session_id from merge_queue order by ticket limit 1", + [], + |r| r.get(0), + ) + .optional()?) + } + + /// 1 = head of the queue. + pub fn queue_position(&self, session: &str) -> Result { + let n: i64 = self.conn.query_row( + "select count(*) from merge_queue where ticket <= + (select ticket from merge_queue where session_id = ?1)", + [session], + |r| r.get(0), + )?; + Ok(n as usize) + } + + pub fn queue_leave(&self, session: &str) -> Result<()> { + self.conn + .execute("delete from merge_queue where session_id = ?1", [session])?; + Ok(()) } pub fn set_goal(&self, text: &str) -> Result<()> { @@ -189,6 +337,70 @@ impl Db { Ok(self.conn.last_insert_rowid()) } + pub fn add_need(&self, session: &str, kind: &str, payload: &Value) -> Result { + self.conn.execute( + "insert into needs(session_id, kind, payload, created_at) values (?1, ?2, ?3, ?4)", + params![ + session, + kind, + payload.to_string(), + crate::state::now_ms() as i64 + ], + )?; + Ok(self.conn.last_insert_rowid()) + } + + const NEED_COLS: &'static str = "id, session_id, kind, payload, created_at, answer"; + + /// Items still waiting for an answer, oldest first. + pub fn pending_needs(&self) -> Result> { + let mut q = self.conn.prepare(&format!( + "select {} from needs where done = 0 and answer is null order by id", + Self::NEED_COLS + ))?; + Ok(q.query_map([], need_row)? + .collect::>()?) + } + + /// An unfinished item of this session with this `payload.key`: after an orchestrator restart the same + /// question must not be asked twice. + pub fn open_need(&self, session: &str, kind: &str, key: &str) -> Result> { + Ok(self + .conn + .query_row( + &format!( + "select {} from needs where session_id = ?1 and kind = ?2 and done = 0 + and json_extract(payload, '$.key') = ?3 order by id desc limit 1", + Self::NEED_COLS + ), + params![session, kind, key], + need_row, + ) + .optional()?) + } + + pub fn need_answer(&self, id: i64) -> Result> { + Ok(self + .conn + .query_row("select answer from needs where id = ?1", [id], |r| r.get(0))?) + } + + /// Answers an item (first answer wins) and returns false if it was already answered. + pub fn answer_need(&self, id: i64, answer: &str) -> Result { + let n = self.conn.execute( + "update needs set answer = ?2 where id = ?1 and answer is null", + params![id, answer], + )?; + Ok(n == 1) + } + + /// The runner took the answer; the item is history now. + pub fn finish_need(&self, id: i64) -> Result<()> { + self.conn + .execute("update needs set done = 1 where id = ?1", [id])?; + Ok(()) + } + /// A choice an agent reported with `hx/decision`; the goal view lists them for veto. pub fn add_decision(&self, session: &str, text: &str, state: &str) -> Result<()> { self.conn.execute( @@ -238,6 +450,18 @@ impl Db { } } +fn need_row(r: &rusqlite::Row) -> rusqlite::Result { + let p: String = r.get(3)?; + Ok(NeedRow { + id: r.get(0)?, + session: r.get(1)?, + kind: r.get(2)?, + payload: serde_json::from_str(&p).unwrap_or(Value::Null), + at: r.get::<_, i64>(4)? as u64, + answer: r.get(5)?, + }) +} + fn session_row(r: &rusqlite::Row) -> rusqlite::Result { Ok(Session { id: r.get(0)?, @@ -289,6 +513,53 @@ mod tests { 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()); + // checks keep their last result; decisions list in insertion order + let c = db.add_check("build", "true", Some("s1")).unwrap(); + assert_eq!(db.checks().unwrap()[0].last_status, None); + db.set_check_result(c, true).unwrap(); + let ch = &db.checks().unwrap()[0]; + assert_eq!( + (ch.last_status.as_deref(), ch.owner.as_deref()), + (Some("pass"), Some("s1")) + ); + db.add_decision("s1", "use a bucket", "plan").unwrap(); + assert_eq!(db.decisions().unwrap()[0].text, "use a bucket"); + // merge queue is first come, first served, and joining twice keeps the place + assert_eq!(db.queue_head().unwrap(), None); + let (t1, t2) = (db.queue_join("s1").unwrap(), db.queue_join("s2").unwrap()); + assert!(t1 < t2); + assert_eq!(db.queue_join("s1").unwrap(), t1); + assert_eq!(db.queue_head().unwrap().as_deref(), Some("s1")); + assert_eq!( + ( + db.queue_position("s1").unwrap(), + db.queue_position("s2").unwrap() + ), + (1, 2) + ); + db.queue_leave("s1").unwrap(); + assert_eq!(db.queue_head().unwrap().as_deref(), Some("s2")); + db.queue_leave("s2").unwrap(); + // needs queue: pending until answered, the first answer wins, finished items disappear + let n = db + .add_need("s1", "review", &json!({"key": "review/ok", "title": "t"})) + .unwrap(); + assert_eq!(db.pending_needs().unwrap().len(), 1); + assert_eq!( + db.open_need("s1", "review", "review/ok") + .unwrap() + .unwrap() + .id, + n + ); + assert!(db.open_need("s1", "review", "other").unwrap().is_none()); + assert_eq!(db.need_answer(n).unwrap(), None); + assert!(db.answer_need(n, "approve").unwrap()); + assert!(!db.answer_need(n, "changes: x").unwrap()); + assert_eq!(db.need_answer(n).unwrap().as_deref(), Some("approve")); + assert!(db.pending_needs().unwrap().is_empty()); + db.finish_need(n).unwrap(); + assert!(db.open_need("s1", "review", "review/ok").unwrap().is_none()); // reopening sees the same data: restart restores views drop(db); let db = Db::open(&dir.join("orch.db")).unwrap(); diff --git a/src/detail.rs b/src/detail.rs index 17c6bd3..ffef640 100644 --- a/src/detail.rs +++ b/src/detail.rs @@ -612,6 +612,9 @@ mod tests { sessions: &sessions, events, machines: &m, + needs: &[], + checks: &[], + decisions: &[], now_ms: 36_000, }, "s2", diff --git a/src/goal.rs b/src/goal.rs new file mode 100644 index 0000000..3c7169f --- /dev/null +++ b/src/goal.rs @@ -0,0 +1,348 @@ +//! View model of the goal screen (ORCHESTRATOR.md 7.3, `Goal.dc.html`): the goal and its definition of done, +//! the task graph in columns by dependency depth, the critical path, the decisions agents made, the checks. + +use crate::view::{Input, Status, hms}; +use std::collections::HashMap; + +#[derive(Clone, PartialEq, Debug)] +pub struct TaskBox { + pub id: String, + pub name: String, + pub status: Status, + /// `merged`, `queued`, or the state the session is in. + pub detail: String, + pub after: Vec, +} + +#[derive(Clone, PartialEq, Debug)] +pub struct Column { + pub label: String, + pub tasks: Vec, +} + +#[derive(Clone, PartialEq, Debug)] +pub struct DecisionView { + pub id: i64, + pub session: String, + pub text: String, + /// `plan · 13:22` + pub whence: String, + pub vetoed: bool, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum CheckState { + Pass, + Fail, + /// Never ran on main. + Unknown, +} + +#[derive(Clone, PartialEq, Debug)] +pub struct CheckView { + pub name: String, + pub owner: String, + pub state: CheckState, +} + +#[derive(Clone, PartialEq, Debug, Default)] +pub struct GoalView { + pub goal: String, + pub done_when: String, + pub columns: Vec, + /// `s2 oauth-provider`, in order; the longest chain of unfinished tasks. + pub critical: Vec, + pub decisions: Vec, + pub checks: Vec, + pub green: usize, +} + +/// Length of the dependency chain below a task (0 = no dependencies). Cycles count as 0 instead of looping. +fn depth(id: &str, deps: &HashMap<&str, &Vec>, seen: &mut Vec) -> usize { + if seen.iter().any(|s| s == id) { + return 0; + } + seen.push(id.to_string()); + let d = deps.get(id).map_or(0, |ds| { + ds.iter() + .map(|d| 1 + depth(d, deps, seen)) + .max() + .unwrap_or(0) + }); + seen.pop(); + d +} + +pub fn build(i: &Input) -> GoalView { + let overview = crate::view::build(i); + let deps: HashMap<&str, &Vec> = i + .tasks + .iter() + .map(|t| (t.id.as_str(), &t.depends_on)) + .collect(); + let mut boxes: Vec<(usize, TaskBox)> = vec![]; + for t in i.tasks { + let row = overview.rows.iter().find(|r| r.id == t.id); + let session = i.sessions.iter().find(|s| s.id == t.id); + let status = row.map_or(Status::Blocked, |r| r.status); + let detail = match (status, session) { + (Status::Done, _) => "merged".to_string(), + (_, Some(s)) if !s.state.is_empty() => match row { + Some(r) if !r.retry.is_empty() => format!("{} {}", s.state, r.retry), + _ => s.state.clone(), + }, + _ => "queued".to_string(), + }; + boxes.push(( + depth(&t.id, &deps, &mut vec![]), + TaskBox { + id: t.id.clone(), + name: t.name.clone(), + status, + detail, + after: t.depends_on.clone(), + }, + )); + } + let levels = boxes.iter().map(|b| b.0).max().map_or(0, |m| m + 1); + let columns = (0..levels) + .map(|l| Column { + label: format!("level {l}"), + tasks: boxes + .iter() + .filter(|b| b.0 == l) + .map(|b| b.1.clone()) + .collect(), + }) + .collect(); + + // critical path: longest chain over unfinished tasks only + let open: Vec<&TaskBox> = boxes + .iter() + .map(|b| &b.1) + .filter(|t| t.status != Status::Done) + .collect(); + let mut best: HashMap<&str, (usize, Option<&str>)> = HashMap::new(); + let mut order: Vec<&TaskBox> = open.clone(); + order.sort_by_key(|t| depth(&t.id, &deps, &mut vec![])); // dependencies first + for t in &order { + let prev = t + .after + .iter() + .filter_map(|d| best.get(d.as_str()).map(|(n, _)| (*n, d.as_str()))) + .max_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(a.1))); // longest, then lowest id + best.insert(&t.id, (prev.map_or(1, |p| p.0 + 1), prev.map(|p| p.1))); + } + let end = open + .iter() + .map(|t| t.id.as_str()) + .max_by(|a, b| best[a].0.cmp(&best[b].0).then(b.cmp(a))); + let mut critical = vec![]; + let mut cur = end; + while let Some(id) = cur { + let name = boxes + .iter() + .find(|b| b.1.id == id) + .map_or("", |b| b.1.name.as_str()); + critical.push(format!("{id} {name}")); + cur = best[id].1; + } + critical.reverse(); + + let decisions = i + .decisions + .iter() + .map(|d| DecisionView { + id: d.id, + session: d.session.clone(), + text: d.text.clone(), + whence: format!("{} · {}", d.state, &hms(d.at)[..5]), + vetoed: d.vetoed, + }) + .collect(); + let checks: Vec = i + .checks + .iter() + .map(|c| CheckView { + name: c.name.clone(), + owner: c.owner.clone().unwrap_or_else(|| "-".into()), + state: match c.last_status.as_deref() { + Some("pass") => CheckState::Pass, + Some(_) => CheckState::Fail, + None => CheckState::Unknown, + }, + }) + .collect(); + let green = checks + .iter() + .filter(|c| c.state == CheckState::Pass) + .count(); + let done_when = if checks.is_empty() { + "Done = all acceptance checks green on main. None defined yet: orch check NAME CMD." + .to_string() + } else { + format!( + "Done = all {} acceptance checks green on main. The orchestrator re-runs them after every merge.", + checks.len() + ) + }; + GoalView { + goal: i.goal.unwrap_or("no goal set: orch goal \"…\"").to_string(), + done_when, + columns, + critical, + decisions, + checks, + green, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::{CheckRow, DecisionRow, Session, Task}; + use crate::machine::Machine; + + fn task(id: &str, name: &str, after: &[&str]) -> Task { + Task { + id: id.into(), + name: name.into(), + subtitle: String::new(), + machine: "task".into(), + depends_on: after.iter().map(|a| a.to_string()).collect(), + } + } + + fn session(id: &str, state: &str, status: &str) -> Session { + Session { + id: id.into(), + task_id: id.into(), + branch: "b".into(), + worktree: "/w".into(), + pid: None, + state: state.into(), + status: status.into(), + } + } + + fn view( + tasks: &[Task], + sessions: &[Session], + checks: &[CheckRow], + decisions: &[DecisionRow], + ) -> GoalView { + let m = HashMap::from([( + "task".to_string(), + Machine::parse(include_str!("../examples/machines/task.toml")).unwrap(), + )]); + build(&Input { + goal: Some("Move login to OAuth2"), + tasks, + sessions, + events: &[], + machines: &m, + needs: &[], + checks, + decisions, + now_ms: 0, + }) + } + + fn check(name: &str, owner: Option<&str>, st: Option<&str>) -> CheckRow { + CheckRow { + id: 1, + name: name.into(), + cmd: "true".into(), + owner: owner.map(Into::into), + last_status: st.map(Into::into), + last_run_at: None, + } + } + + #[test] + fn graph_columns_critical_path_and_checks() { + let tasks = [ + task("s1", "schema-migrate", &[]), + task("s2", "oauth-provider", &["s1"]), + task("s3", "auth-middleware", &["s1"]), + task("s4", "rate-limiter", &["s1"]), + task("s5", "docs-update", &["s2", "s3"]), + task("s6", "e2e-tests", &["s3", "s4"]), + ]; + let sessions = [ + session("s1", "merge", "merged"), + session("s2", "test", "running"), + session("s3", "review", "waiting"), + session("s4", "build", "running"), + session("s5", "", "queued"), + session("s6", "plan", "running"), + ]; + let checks = [ + check("build", None, Some("pass")), + check("unit", Some("s2"), Some("fail")), + check("e2e", Some("s6"), None), + ]; + let decisions = [DecisionRow { + id: 1, + session: "s4".into(), + text: "token bucket".into(), + state: "plan".into(), + at: 0, + vetoed: false, + }]; + let v = view(&tasks, &sessions, &checks, &decisions); + + fn ids(c: &Column) -> Vec<&str> { + c.tasks.iter().map(|t| t.id.as_str()).collect() + } + assert_eq!(v.columns.len(), 3); + assert_eq!(ids(&v.columns[0]), ["s1"]); + assert_eq!(ids(&v.columns[1]), ["s2", "s3", "s4"]); + assert_eq!(ids(&v.columns[2]), ["s5", "s6"]); + assert_eq!(v.columns[0].label, "level 0"); + let s1 = &v.columns[0].tasks[0]; + assert_eq!((s1.status, s1.detail.as_str()), (Status::Done, "merged")); + let s3 = &v.columns[1].tasks[1]; + assert_eq!( + (s3.status, s3.detail.as_str(), s3.after.clone()), + (Status::Wait, "review", vec!["s1".to_string()]) + ); + let s5 = &v.columns[2].tasks[0]; + assert_eq!((s5.status, s5.detail.as_str()), (Status::Blocked, "queued")); + + // longest chain of unfinished tasks; s1 is merged and not part of it + assert_eq!(v.critical, ["s2 oauth-provider", "s5 docs-update"]); + + assert_eq!((v.green, v.checks.len()), (1, 3)); + assert_eq!( + v.checks.iter().map(|c| c.state).collect::>(), + [CheckState::Pass, CheckState::Fail, CheckState::Unknown] + ); + assert_eq!(v.checks[0].owner, "-"); + assert!( + v.done_when + .starts_with("Done = all 3 acceptance checks green on main") + ); + assert_eq!(v.decisions[0].session, "s4"); + assert!(v.decisions[0].whence.starts_with("plan · ")); + } + + #[test] + fn empty_and_cyclic_goals_do_not_break() { + let v = view(&[], &[], &[], &[]); + assert!(v.columns.is_empty() && v.critical.is_empty()); + assert!(v.done_when.contains("None defined yet")); + // a cycle is a user error, not a hang + let tasks = [task("s1", "a", &["s2"]), task("s2", "b", &["s1"])]; + let sessions = [session("s1", "", "queued"), session("s2", "", "queued")]; + let v = view(&tasks, &sessions, &[], &[]); + assert_eq!(v.columns.iter().map(|c| c.tasks.len()).sum::(), 2); + } + + #[test] + fn all_done_has_no_critical_path() { + let tasks = [task("s1", "a", &[])]; + let sessions = [session("s1", "merge", "merged")]; + assert!(view(&tasks, &sessions, &[], &[]).critical.is_empty()); + } +} diff --git a/src/main.rs b/src/main.rs index 7e42634..cd409fb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,9 @@ mod acp; mod adapter; +mod checks; mod db; mod detail; +mod goal; mod junit; mod lock; mod machine; @@ -73,8 +75,42 @@ enum Cmd { #[arg(long)] check: bool, }, - /// Create a state-machine session in REPO and run it to the end (human steps are not supported yet). + /// Show or set the goal sentence; `--export` also prints the acceptance checks (for machine steps). + Goal { + /// New goal text. + text: Option, + #[arg(long)] + export: bool, + /// Repo with the goal (default: ORCH_DB of a machine step, else the current directory). + #[arg(long)] + repo: Option, + }, + /// Add an acceptance check: a shell command, pass = exit 0. + Check { + name: String, + cmd: String, + /// Session that is responsible for it (its `run-acceptance` step runs it before merging). + #[arg(long)] + owner: Option, + #[arg(long)] + repo: Option, + }, + /// Run acceptance checks in the current directory (a worktree), or with --main in a clean copy of main. + Checks { + /// Only the checks this session owns. + #[arg(long)] + owner: Option, + /// All checks on main; the results are recorded for the goal view. + #[arg(long)] + main: bool, + #[arg(long)] + repo: Option, + }, + /// Create a state-machine session in REPO and run it to the end. Waits for `--after` sessions to merge. Session { + /// Sessions that must be merged before this one starts, comma separated. + #[arg(long, value_delimiter = ',')] + after: Vec, #[arg(long)] repo: PathBuf, /// Machine file name, without .toml (looked up in REPO/.hx/machines, then ~/.hx/machines). @@ -120,6 +156,20 @@ pub fn state_dir() -> PathBuf { env_dir("ORCH_STATE_DIR", "XDG_STATE_HOME", ".local/state") } +/// The goal database: `--repo`, else `ORCH_DB` (set by the runner for machine steps), else `./.hx/orch.db`. +fn open_db(repo: Option<&Path>) -> Result { + if repo.is_none() + && let Some(p) = std::env::var_os("ORCH_DB") + { + return db::Db::open(Path::new(&p)); + } + let dir = match repo { + Some(r) => r.to_path_buf(), + None => std::env::current_dir()?, + }; + db::Db::open(&dir.join(".hx/orch.db")) +} + fn code(ok: bool) -> std::process::ExitCode { u8::from(!ok).into() } @@ -130,7 +180,55 @@ fn main() -> Result { return Ok(code(true)); }; match cmd { + Cmd::Goal { text, export, repo } => { + let db = open_db(repo.as_deref())?; + if let Some(t) = text { + db.set_goal(&t)?; + } + println!("{}", db.goal()?.unwrap_or_else(|| "no goal set".into())); + if export { + println!("\nAcceptance checks (all must pass on main):"); + for c in db.checks()? { + let owner = c.owner.map_or(String::new(), |o| format!(" [{o}]")); + println!("- {}{owner}: {}", c.name, c.cmd); + } + } + Ok(code(true)) + } + Cmd::Check { + name, + cmd, + owner, + repo, + } => { + let id = open_db(repo.as_deref())?.add_check(&name, &cmd, owner.as_deref())?; + println!("check {id}: {name}"); + Ok(code(true)) + } + Cmd::Checks { owner, main, repo } => { + let db = open_db(repo.as_deref())?; + let results = if main { + let repo = match (repo, std::env::var_os("ORCH_REPO")) { + (Some(r), _) => r, + (None, Some(r)) => r.into(), + (None, None) => std::env::current_dir()?, + }; + checks::run_on_main(&db, &repo)? + } else { + checks::run(&db, &std::env::current_dir()?, owner.as_deref(), false)? + }; + for r in &results { + if r.pass { + println!("✓ {}", r.check.name); + } else { + println!("✗ {} (exit {})", r.check.name, r.exit.unwrap_or(-1)); + print!("{}", r.output); + } + } + Ok(code(results.iter().all(|r| r.pass))) + } Cmd::Session { + after, repo, machine, name, @@ -144,7 +242,7 @@ fn main() -> Result { // 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 s = runner::create_after(&db, &wts, &name, "", &machine, &after)?; let status = runner::run_session(&db, &m, &s.id, &repo, &scope, &profile)?; println!("{} {} -> {status}", s.id, s.branch); Ok(code(status == "merged")) diff --git a/src/runner.rs b/src/runner.rs index 13b9283..887a262 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -1,6 +1,8 @@ //! Session runner (ORCHESTRATOR.md section 4): walks one session through its machine and writes every step to -//! the event table. `computer` steps run as shell commands, `agent` steps go to hx over ACP. `human` steps -//! and `needs_input` results wait for the Needs-you queue (milestone 6) and fail the session for now. +//! the event table. `computer` steps run as shell commands, `agent` steps go to hx over ACP, `human` steps and +//! agent questions wait in the Needs-you queue. A session waits for its dependencies before it starts and for its +//! turn in the merge queue before it enters the state that ends in `merged`; after the merge all acceptance +//! checks run again on main. use crate::acp::{Acp, Sink, StepResult}; use crate::db::{Db, Session, Task}; @@ -11,7 +13,7 @@ use anyhow::{Context, Result, bail}; use serde_json::{Value, json}; use std::path::Path; use std::process::Command; -use std::time::Instant; +use std::time::{Duration, 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; @@ -19,14 +21,30 @@ const MAX_TRANSITIONS: u32 = 500; const OUTPUT_TAIL: usize = 8000; /// Creates the task and session rows for a new session. The worktree is made by [`run_session`]. +#[cfg(test)] pub fn create( db: &Db, worktrees: &Path, name: &str, subtitle: &str, machine: &str, +) -> Result { + create_after(db, worktrees, name, subtitle, machine, &[]) +} + +/// Like [`create`], for a task that may only start once the sessions in `after` have merged. +pub fn create_after( + db: &Db, + worktrees: &Path, + name: &str, + subtitle: &str, + machine: &str, + after: &[String], ) -> Result { let id = db.next_session_id()?; + for d in after { + anyhow::ensure!(db.session(d)?.is_some(), "no session {d} to wait for"); + } let slug: String = name .chars() .map(|c| { @@ -42,7 +60,7 @@ pub fn create( name: name.into(), subtitle: subtitle.into(), machine: machine.into(), - depends_on: vec![], + depends_on: after.to_vec(), }; let s = Session { branch: format!("hx/{id}-{slug}"), @@ -58,11 +76,12 @@ pub fn create( Ok(s) } -fn render(cmd: &str, s: &Session, scope: &str) -> String { +fn render(cmd: &str, s: &Session, scope: &str, repo: &Path) -> String { cmd.replace("{{session}}", &s.id) .replace("{{scope}}", scope) .replace("{{worktree}}", &s.worktree) .replace("{{branch}}", &s.branch) + .replace("{{repo}}", &repo.to_string_lossy()) } fn ensure_worktree(repo: &Path, s: &Session) -> Result<()> { @@ -87,6 +106,7 @@ struct Ctx<'a> { task: &'a Task, profile: &'a Profile, scope: &'a str, + repo: &'a Path, agent: Option, } @@ -146,13 +166,131 @@ fn run_step(cx: &mut Ctx, st: &State, step: &Step) -> Result { match step.run { RunOn::Computer => run_command(cx, st, step), RunOn::Agent => run_agent(cx, st, step), - RunOn::Human => bail!( - "step {:?}: human steps need the Needs-you queue (milestone 6)", - step.name - ), + RunOn::Human => run_human(cx, st, step), } } +/// Puts an item into the Needs-you queue and blocks until somebody answers it in the database. +/// `reuse`: take over an unfinished item with the same key (orchestrator restarted while it was pending). +fn ask( + db: &Db, + session: &str, + state: &str, + kind: &str, + payload: Value, + reuse: bool, +) -> Result { + let key = payload["key"].as_str().unwrap_or_default().to_string(); + let existing = if reuse { + db.open_need(session, kind, &key)? + } else { + None + }; + // waiting first: an item must never be visible while its session still claims to run + db.set_session(session, state, "waiting")?; + let id = match existing { + Some(n) => n.id, + None => { + let id = db.add_need(session, kind, &payload)?; + db.emit( + session, + "need", + json!({"id": id, "kind": kind, "title": payload["title"]}), + )?; + id + } + }; + let answer = loop { + if let Some(a) = db.need_answer(id)? { + break a; + } + std::thread::sleep(Duration::from_millis(50)); + }; + db.finish_need(id)?; + db.emit( + session, + "answer", + json!({"id": id, "kind": kind, "answer": answer}), + )?; + db.set_session(session, state, "running")?; + Ok(answer) +} + +/// "6 files, +318 −97, 52/52 tests pass": what the reviewer sees in the queue, built from the event stream. +fn review_summary(db: &Db, id: &str) -> Result { + let evs = db.events(Some(id), 0)?; + let (mut files, mut added, mut removed) = (std::collections::BTreeSet::new(), 0, 0); + for e in evs.iter().filter(|e| e.kind == "edit") { + files.insert(e.payload["path"].as_str().unwrap_or_default().to_string()); + added += e.payload["added"].as_u64().unwrap_or(0); + removed += e.payload["removed"].as_u64().unwrap_or(0); + } + let mut parts = vec![]; + if !files.is_empty() { + parts.push(format!("{} files, +{added} −{removed}", files.len())); + } + if let Some(t) = evs.iter().rev().find(|e| e.kind == "test") { + let (p, f) = ( + t.payload["passed"].as_u64().unwrap_or(0), + t.payload["failed"].as_u64().unwrap_or(0), + ); + parts.push(if f == 0 { + format!("{p}/{p} tests pass") + } else { + format!("{p}/{} tests, {f} fail", p + f) + }); + } + Ok(parts.join(", ")) +} + +/// A `human` step: approve, or send it back with a comment (`changes: text`), which raises the step's catch. +fn run_human(cx: &Ctx, st: &State, step: &Step) -> Result { + let title = if st.kind == Kind::Gate { + "review ready".to_string() + } else { + step.name.clone() + }; + let payload = json!({ + "key": format!("{}/{}", st.name, step.name), + "state": st.name, "step": step.name, "title": title, + "detail": review_summary(cx.db, &cx.s.id)?, + }); + let answer = ask(cx.db, &cx.s.id, &st.name, "review", payload, true)?; + if answer == "approve" { + return Ok(StepRes { + ok: true, + exit: Some(0), + out: "approved".into(), + catch: None, + }); + } + let Some(comment) = answer.strip_prefix("changes") else { + bail!("unknown answer {answer:?} to human step {:?}", step.name); + }; + let comment = comment.trim_start_matches(':').trim(); + if !comment.is_empty() { + cx.db.emit(&cx.s.id, "comment", json!({"text": comment}))?; + } + Ok(StepRes { + ok: false, + exit: None, + out: format!("changes requested: {comment}"), + catch: None, + }) +} + +/// A comment from a reviewer that no agent step has seen yet. +fn pending_comment(db: &Db, id: &str) -> Result> { + for e in db.events(Some(id), 0)?.into_iter().rev() { + match e.kind.as_str() { + "comment" => return Ok(e.payload["text"].as_str().map(String::from)), + "step" if e.payload["run"] == "agent" => return Ok(None), + _ => {} + } + } + Ok(None) +} + /// Where a `report = "junit"` step writes its report. Next to the worktree, not in it: it must not dirty git. fn report_path(s: &Session) -> String { format!("{}.junit.xml", s.worktree) @@ -176,10 +314,14 @@ fn run_command(cx: &Ctx, st: &State, step: &Step) -> Result { "-c", &format!( "({}) 2>&1", - render(cmd, cx.s, cx.scope).replace("{{report}}", &report) + render(cmd, cx.s, cx.scope, cx.repo).replace("{{report}}", &report) ), ]) .env("ORCH_REPORT", &report) + // so `orch goal --export` and `orch checks` find the goal from inside a worktree + .env("ORCH_DB", cx.db.path()) + .env("ORCH_REPO", cx.repo) + .env("ORCH_SESSION", &cx.s.id) .current_dir(&cx.s.worktree) .output()?; let mut out = tail(&o.stdout, OUTPUT_TAIL); @@ -246,37 +388,56 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result { cx.agent = Some(Acp::spawn(cx.profile, Path::new(&cx.s.worktree), &cx.s.id)?); } let goal = cx.db.goal()?; - let context = json!({"state": st.name, "last_failure": last_failure(cx.db, &cx.s.id)?}); - let mut sink = DbSink { - db: cx.db, - session: &cx.s.id, - }; - let agent = cx.agent.as_mut().expect("spawned above"); - let r: StepResult = agent.step( - kind, - &instruction(kind, goal.as_deref(), cx.task), - context, - json!({}), - &mut sink, - )?; - match r.status.as_str() { - "done" => Ok(StepRes { - ok: true, - exit: Some(0), - out: r.summary, - catch: None, - }), - "blocked" => Ok(StepRes { - ok: false, - exit: None, - out: r.summary, - catch: r.catch, - }), - "needs_input" => bail!( - "hx asked {:?}; needs_input needs the Needs-you queue (milestone 6)", - r.question.unwrap_or_default() - ), - other => bail!("hx sent unknown step status {other:?}"), + // a reviewer's comment, or the answer to a question hx asked, rides along as the hint + let mut hint = pending_comment(cx.db, &cx.s.id)?; + loop { + let context = json!({ + "state": st.name, "last_failure": last_failure(cx.db, &cx.s.id)?, "hint": hint, + }); + let mut sink = DbSink { + db: cx.db, + session: &cx.s.id, + state: &st.name, + }; + let agent = cx.agent.as_mut().expect("spawned above"); + let r: StepResult = agent.step( + kind, + &instruction(kind, goal.as_deref(), cx.task), + context, + json!({}), + &mut sink, + )?; + return match r.status.as_str() { + "done" => Ok(StepRes { + ok: true, + exit: Some(0), + out: r.summary, + catch: None, + }), + "blocked" => Ok(StepRes { + ok: false, + exit: None, + out: r.summary, + catch: r.catch, + }), + "needs_input" => { + let question = r.question.unwrap_or_default(); + let payload = json!({ + "key": format!("{}/{}/input", st.name, step.name), + "state": st.name, "step": step.name, "title": "question", "detail": question, + }); + let answer = ask(cx.db, &cx.s.id, &st.name, "input", payload, true)?; + hint = Some( + answer + .strip_prefix("reply:") + .unwrap_or(&answer) + .trim() + .to_string(), + ); + continue; // same step again, now with the answer in the context + } + other => bail!("hx sent unknown step status {other:?}"), + }; } } @@ -284,6 +445,28 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result { struct DbSink<'a> { db: &'a Db, session: &'a str, + state: &'a str, +} + +/// The `optionId` of the first option whose kind is one of `kinds`. +fn option_id(options: &Value, kinds: &[&str]) -> Option { + kinds.iter().find_map(|k| { + options + .as_array()? + .iter() + .find_map(|o| (o["kind"] == *k).then(|| o["optionId"].as_str().map(String::from))?) + }) +} + +/// `allow_always` earlier in this session for the same tool: hx is not asked about it again. +fn always_allowed(db: &Db, session: &str, tool: &str) -> bool { + db.events(Some(session), 0).is_ok_and(|evs| { + evs.iter().any(|e| { + e.kind == "permission" + && e.payload["tool"] == tool + && e.payload["decision"] == "allow_always" + }) + }) } impl Sink for DbSink<'_> { @@ -309,19 +492,38 @@ impl Sink for DbSink<'_> { Ok(()) } - /// Until the Needs-you queue exists (milestone 6) every permission request is denied and recorded. + /// Goes to the Needs-you queue and blocks hx (which waits for our reply) until the user decides. + /// An error while waiting cancels the request. fn permission(&mut self, p: &Value) -> Option { - let deny = p["options"].as_array().and_then(|o| { - o.iter() - .find(|o| o["kind"].as_str().is_some_and(|k| k.starts_with("reject"))) - .and_then(|o| o["optionId"].as_str().map(String::from)) - }); + let tool = p["toolCall"]["title"].as_str().unwrap_or("tool call"); + let opts = &p["options"]; + let answer = if always_allowed(self.db, self.session, tool) { + "allow_always".to_string() + } else { + let payload = json!({ + "key": "", "state": self.state, "title": "permission", "tool": tool, + "detail": format!("wants to run {tool}"), "options": opts, + }); + ask( + self.db, + self.session, + self.state, + "permission", + payload, + false, + ) + .ok()? + }; let _ = self.db.emit( self.session, "permission", - json!({"tool": p["toolCall"]["title"], "decision": "denied"}), + json!({"tool": tool, "decision": answer}), ); - deny + match answer.as_str() { + "allow_once" => option_id(opts, &["allow_once", "allow_always"]), + "allow_always" => option_id(opts, &["allow_always", "allow_once"]), + _ => option_id(opts, &["reject_once", "reject_always"]), + } } } @@ -343,6 +545,9 @@ pub fn run_session( .into_iter() .find(|t| t.id == s.task_id) .with_context(|| format!("no task {}", s.task_id))?; + if s.state.is_empty() { + wait_for_dependencies(db, &s, &task)?; + } ensure_worktree(repo, &s)?; let mut cx = Ctx { db, @@ -350,6 +555,7 @@ pub fn run_session( task: &task, profile, scope, + repo, agent: None, }; let mut resumed = !s.state.is_empty(); @@ -370,7 +576,22 @@ pub fn run_session( } resumed = false; db.set_session(id, &cur, "running")?; - let outcome = match run_state(&mut cx, st) { + // the state that ends the session as `merged` is the merge: one session at a time, first come first served + let merging = st.end.as_deref() == Some("merged"); + if merging { + enter_merge_queue(db, id)?; + } + let result = run_state(&mut cx, st); + if merging { + // all acceptance checks again on main, while this session still holds the merge slot + if matches!(result, Ok(Outcome::Ok)) + && let Err(e) = crate::checks::run_on_main(db, repo) + { + db.emit(id, "check_error", json!({"error": format!("{e:#}")}))?; + } + let _ = db.queue_leave(id); + } + let outcome = match result { Ok(o) => o, Err(e) => return finish(db, id, &cur, "failed", Some(format!("{e:#}"))), }; @@ -411,6 +632,63 @@ pub fn run_session( ) } +const POLL: Duration = Duration::from_millis(100); + +/// A task whose dependencies have not merged stays `queued` (BLOCKED on screen) and nothing of it starts. +fn wait_for_dependencies(db: &Db, s: &Session, t: &Task) -> Result<()> { + let mut announced = false; + loop { + let unmet: Vec<&String> = t + .depends_on + .iter() + .filter(|d| { + db.session(d) + .ok() + .flatten() + .is_none_or(|x| x.status != "merged") + }) + .collect(); + if unmet.is_empty() { + return Ok(()); + } + if !announced { + db.emit(&s.id, "blocked", json!({"on": unmet}))?; + announced = true; + } + std::thread::sleep(POLL); + } +} + +/// Is the orchestrator process of this session still alive? A session that crashed inside the merge must not +/// block the queue forever. +fn alive(db: &Db, session: &str) -> bool { + let Some(pid) = db.session(session).ok().flatten().and_then(|s| s.pid) else { + return false; + }; + // SAFETY: signal 0 only checks that the process exists. + let r = unsafe { libc::kill(pid as i32, 0) }; + r == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) +} + +/// Joins the merge queue and blocks until this session is at the head. +fn enter_merge_queue(db: &Db, id: &str) -> Result<()> { + db.queue_join(id)?; + let pos = db.queue_position(id)?; + if pos > 1 { + db.emit(id, "queue", json!({"position": pos}))?; + } + loop { + match db.queue_head()? { + Some(h) if h == id => return Ok(()), + Some(h) if !alive(db, &h) => db.queue_leave(&h)?, + None => { + db.queue_join(id)?; // pruned by somebody else's mistake: stand in line again + } + _ => std::thread::sleep(POLL), + } + } +} + fn finish(db: &Db, id: &str, state: &str, status: &str, reason: Option) -> Result { db.set_session(id, state, status)?; db.set_pid(id, None)?; @@ -627,16 +905,105 @@ next = "done" let _ = std::fs::remove_dir_all(&e.dir); } + /// What the answering thread saw: (kind, payload, session status at that moment). + type Seen = Vec<(String, Value, String)>; + + /// Plays the user: answers the pending queue items one by one with `answers` from another connection. + fn answerer( + db_path: std::path::PathBuf, + answers: &'static [&'static str], + ) -> std::thread::JoinHandle { + std::thread::spawn(move || { + let db = Db::open(&db_path).unwrap(); + let mut seen = vec![]; + let deadline = Instant::now() + Duration::from_secs(20); + while seen.len() < answers.len() && Instant::now() < deadline { + if let Some(n) = db.pending_needs().unwrap().first() { + let status = db.session(&n.session).unwrap().unwrap().status; + db.answer_need(n.id, answers[seen.len()]).unwrap(); + seen.push((n.kind.clone(), n.payload.clone(), status)); + } + std::thread::sleep(Duration::from_millis(20)); + } + seen + }) + } + #[test] - fn human_step_fails_the_session_cleanly() { + fn human_review_waits_in_the_queue_and_changes_requested_loops_back() { let e = env("human"); - let m = one_step(r#"{ name = "ok", run = "human" }"#); + let m = Machine::parse(&format!( + r#"name = "m" +[[state]] +name = "code" +kind = "start" +steps = [{{ name = "edit", run = "computer", cmd = "echo x >> n" }}] +next = "review" +[[state]] +name = "review" +kind = "gate" +steps = [{{ name = "wait-approval", run = "human", sets = "waiting" }}] +catch = {{ ChangesRequested = "code" }} +next = "done" +{TAIL}"# + )) + .unwrap(); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let user = answerer(e.dir.join("orch.db"), &["changes: rename it", "approve"]); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), - "failed" + "merged" ); - assert!(failure_reason(&e).contains("milestone 6")); + let seen = user.join().unwrap(); + assert_eq!( + states(&e.db, "s1"), + ["code", "review", "code", "review", "done"] + ); + assert_eq!(seen.len(), 2); + assert_eq!( + (seen[0].0.as_str(), seen[0].1["title"].as_str()), + ("review", Some("review ready")) + ); + assert_eq!( + seen[0].2, "waiting", + "the session shows as waiting while the item is open" + ); + assert_eq!( + e.db.catch_count("s1", "review", "ChangesRequested") + .unwrap(), + 1 + ); + let ev = e.db.events(Some("s1"), 0).unwrap(); + let comment = ev.iter().find(|v| v.kind == "comment").unwrap(); + assert_eq!(comment.payload["text"], "rename it"); + assert_eq!(ev.iter().filter(|v| v.kind == "need").count(), 2); + assert_eq!(ev.iter().filter(|v| v.kind == "answer").count(), 2); + assert!(e.db.pending_needs().unwrap().is_empty()); + let _ = std::fs::remove_dir_all(&e.dir); + } + + #[test] + fn restart_takes_over_the_pending_item_instead_of_asking_twice() { + let e = env("reuse"); + let m = one_step(r#"{ name = "ok", run = "human" }"#); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + // the first orchestrator died while the item was open; the user answers it afterwards + let n = + e.db.add_need("s1", "review", &json!({"key": "a/ok", "title": "ok"})) + .unwrap(); + e.db.answer_need(n, "approve").unwrap(); + e.db.set_session("s1", "a", "waiting").unwrap(); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), + "merged" + ); + let ev = e.db.events(Some("s1"), 0).unwrap(); + assert_eq!( + ev.iter().filter(|v| v.kind == "need").count(), + 0, + "no second question" + ); + assert_eq!(ev.iter().filter(|v| v.kind == "answer").count(), 1); let _ = std::fs::remove_dir_all(&e.dir); } @@ -732,44 +1099,262 @@ next = "done" } #[test] - fn permission_requests_are_denied_and_recorded() { - let e = env("perm"); + fn permission_request_waits_for_the_user_and_deny_reaches_hx() { + let e = env("deny"); let m = one_step(r#"{ name = "ag", run = "agent", prompt = "implement" }"#); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let user = answerer(e.dir.join("orch.db"), &["deny"]); let p = fake("FAKE_MODE=permission"); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), "merged" ); + let seen = user.join().unwrap(); + assert_eq!(seen[0].0, "permission"); + assert_eq!(seen[0].1["tool"], "docker compose up -d redis"); + assert_eq!(seen[0].2, "waiting"); let answer = std::fs::read_to_string(e.dir.join("wt/s1/permission.txt")).unwrap(); assert!(answer.contains("\"optionId\": \"deny\""), "{answer}"); - let ev = e.db.events(Some("s1"), 0).unwrap(); - let perm = ev.iter().find(|v| v.kind == "permission").unwrap(); - assert_eq!(perm.payload["tool"], "docker compose up -d redis"); let _ = std::fs::remove_dir_all(&e.dir); } #[test] - fn needs_input_and_a_crashing_hx_fail_the_session() { - let e = env("fail"); + fn allow_always_is_remembered_for_the_session() { + let e = env("always"); + let step = r#"{ name = "ag", run = "agent", prompt = "implement" }"#; + let m = one_step(&format!("{step}, {step}")); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let user = answerer(e.dir.join("orch.db"), &["allow_always"]); + let p = fake("FAKE_MODE=permission"); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), + "merged" + ); + user.join().unwrap(); + let ev = e.db.events(Some("s1"), 0).unwrap(); + // hx asked twice, the user was asked once + assert_eq!(ev.iter().filter(|v| v.kind == "permission").count(), 2); + assert_eq!(ev.iter().filter(|v| v.kind == "need").count(), 1); + let answer = std::fs::read_to_string(e.dir.join("wt/s1/permission.txt")).unwrap(); + assert!(answer.contains("\"optionId\": \"allow\""), "{answer}"); + let _ = std::fs::remove_dir_all(&e.dir); + } + + #[test] + fn needs_input_is_asked_in_the_queue_and_the_reply_goes_back_to_hx() { + let e = env("input"); + let log = e.dir.join("fake.log"); let m = one_step(r#"{ name = "ag", run = "agent", prompt = "implement" }"#); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); - let p = fake("FAKE_MODE=needs_input"); + let user = answerer(e.dir.join("orch.db"), &["reply: use claude"]); + let p = fake(&format!("FAKE_MODE=needs_input FAKE_LOG={}", log.display())); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), + "merged" + ); + let seen = user.join().unwrap(); + assert_eq!( + (seen[0].0.as_str(), seen[0].1["detail"].as_str()), + ("input", Some("Which provider?")) + ); + let steps: Vec = std::fs::read_to_string(&log) + .unwrap() + .lines() + .map(|l| serde_json::from_str::(l).unwrap()) + .filter(|m| m["method"] == "hx/step") + .collect(); + assert_eq!(steps.len(), 2, "the same step runs again with the answer"); + assert_eq!(steps[0]["params"]["context"]["hint"], Value::Null); + assert_eq!(steps[1]["params"]["context"]["hint"], "use claude"); + let _ = std::fs::remove_dir_all(&e.dir); + } + + #[test] + fn a_crashing_hx_fails_the_session() { + let e = env("crash"); + let m = one_step(r#"{ name = "ag", run = "agent", prompt = "implement" }"#); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let p = fake("FAKE_MODE=crash"); assert_eq!( run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), "failed" ); - assert!(failure_reason(&e).contains("Which provider?")); + assert!(failure_reason(&e).contains("hx closed its output")); + let _ = std::fs::remove_dir_all(&e.dir); + } - let e2 = env("crash"); - create(&e2.db, &e2.dir.join("wt"), "t", "", "m").unwrap(); - let p = fake("FAKE_MODE=crash"); + /// Runs a session on its own connection in a thread, like another orchestrator process would. + fn spawn_session(e: &Env, m: &Machine, id: &str) -> std::thread::JoinHandle { + let (path, repo, m, id) = ( + e.dir.join("orch.db"), + e.repo.clone(), + m.clone(), + id.to_string(), + ); + std::thread::spawn(move || { + let db = Db::open(&path).unwrap(); + run_session(&db, &m, &id, &repo, "", &plain()).unwrap() + }) + } + + #[test] + fn a_task_waits_for_its_dependencies_to_merge() { + let e = env("deps"); + let m = Machine::parse(&format!( + r#"name = "m" +[[state]] +name = "a" +kind = "start" +steps = [{{ name = "w", run = "computer", cmd = "true" }}] +next = "done" +{TAIL}"# + )) + .unwrap(); + let wt = e.dir.join("wt"); + create(&e.db, &wt, "first", "", "m").unwrap(); + create_after(&e.db, &wt, "second", "", "m", &["s1".to_string()]).unwrap(); + assert!(create_after(&e.db, &wt, "bad", "", "m", &["s9".to_string()]).is_err()); + + let second = spawn_session(&e, &m, "s2"); + std::thread::sleep(Duration::from_millis(500)); + let s2 = e.db.session("s2").unwrap().unwrap(); + assert_eq!(s2.status, "queued", "blocked: not started"); + assert!( + !Path::new(&s2.worktree).exists(), + "nothing of it exists yet" + ); + assert!(kinds(&e.db, "s2").contains(&"blocked".to_string())); + + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), + "merged" + ); + assert_eq!(second.join().unwrap(), "merged"); + let first_end = e.db.events(Some("s1"), 0).unwrap().last().unwrap().id; + let second_start = + e.db.events(Some("s2"), 0) + .unwrap() + .iter() + .find(|v| v.kind == "state") + .unwrap() + .id; + assert!(second_start > first_end, "s2 started only after s1 merged"); + let _ = std::fs::remove_dir_all(&e.dir); + } + + #[test] + fn only_one_session_is_in_merge_at_a_time() { + let e = env("queue"); + let log = e.dir.join("merge.log"); + let m = Machine::parse(&format!( + r#"name = "m" +[[state]] +name = "a" +kind = "start" +steps = [{{ name = "w", run = "computer", cmd = "true" }}] +next = "merge" +[[state]] +name = "merge" +kind = "exit" +steps = [{{ name = "slow", run = "computer", cmd = "echo start >> {0}; sleep 0.3; echo end >> {0}" }}] +end = "merged" +"#, + log.display() + )) + .unwrap(); + let wt = e.dir.join("wt"); + for n in ["a", "b", "c"] { + create(&e.db, &wt, n, "", "m").unwrap(); + } + let runs: Vec<_> = ["s1", "s2", "s3"] + .iter() + .map(|id| spawn_session(&e, &m, id)) + .collect(); + for r in runs { + assert_eq!(r.join().unwrap(), "merged"); + } + let lines: Vec = std::fs::read_to_string(&log) + .unwrap() + .lines() + .map(String::from) + .collect(); + assert_eq!( + lines, + ["start", "end", "start", "end", "start", "end"], + "merges never overlap" + ); + assert_eq!(e.db.queue_head().unwrap(), None, "everybody left the queue"); + let _ = std::fs::remove_dir_all(&e.dir); + } + + #[test] + fn a_dead_session_does_not_block_the_merge_queue() { + let e = env("stale"); + let m = one_step(r#"{ name = "w", run = "computer", cmd = "true" }"#); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + // a crashed orchestrator left its ticket at the head; its pid is gone + e.db.add_session(&Session { + id: "s9".into(), + task_id: "s1".into(), + branch: "b".into(), + worktree: "/nowhere".into(), + pid: Some(2_000_000_000), + state: "merge".into(), + status: "running".into(), + }) + .unwrap(); + e.db.queue_join("s9").unwrap(); + // one_step ends in `done` (merged), which is the merge state + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), + "merged" + ); + assert_eq!(e.db.queue_head().unwrap(), None); + let _ = std::fs::remove_dir_all(&e.dir); + } + + #[test] + fn merge_fast_forwards_main_and_all_checks_run_on_main_afterwards() { + let e = env("main"); + let m = Machine::parse( + r#"name = "m" +[[state]] +name = "code" +kind = "start" +steps = [{ name = "feature", run = "computer", cmd = "echo hi > feature.txt && git add -A && git -c user.name=t -c user.email=t@t commit -qm feature" }] +next = "merge" +[[state]] +name = "merge" +kind = "exit" +steps = [ + { name = "ff", run = "computer", cmd = "git -C {{repo}} merge --ff-only {{branch}}" }, + { name = "mark-merged", run = "computer", sets = "merged" }, +] +end = "merged" +"#, + ) + .unwrap(); + e.db.add_check("feature on main", "test -f feature.txt", None) + .unwrap(); + e.db.add_check("still red", "exit 1", Some("s1")).unwrap(); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), + "merged" + ); + assert!(e.repo.join("feature.txt").exists(), "main moved forward"); + let st: Vec<_> = + e.db.checks() + .unwrap() + .into_iter() + .map(|c| c.last_status.unwrap()) + .collect(); assert_eq!( - run_session(&e2.db, &m, "s1", &e2.repo, "", &p).unwrap(), - "failed" + st, + ["pass", "fail"], + "every check ran on main, owner or not" ); - assert!(failure_reason(&e2).contains("hx closed its output")); + assert_eq!(e.db.events(Some(crate::checks::GOAL), 0).unwrap().len(), 2); let _ = std::fs::remove_dir_all(&e.dir); - let _ = std::fs::remove_dir_all(&e2.dir); } } diff --git a/src/tui/goal.rs b/src/tui/goal.rs new file mode 100644 index 0000000..bbf951e --- /dev/null +++ b/src/tui/goal.rs @@ -0,0 +1,294 @@ +//! Screen 3: goal view (ORCHESTRATOR.md 7.3, `Goal.dc.html`). + +use super::overview::Header; +use super::theme::{self, bold, fg, inverted}; +use crate::goal::{CheckState, GoalView, TaskBox}; +use crate::view::{Status, hms}; +use ratatui::Frame; +use ratatui::layout::{Constraint, Layout, Rect}; +use ratatui::style::{Color, Modifier, Style}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Paragraph}; +use unicode_width::UnicodeWidthStr; + +const BOX_W: u16 = 26; +const GAP_W: u16 = 5; +const BOX_H: u16 = 5; + +pub fn draw(f: &mut Frame, g: &GoalView, h: &Header, checks_running: bool) { + let area = f.area(); + f.render_widget( + Block::new().style(Style::new().bg(theme::BG).fg(theme::TEXT)), + area, + ); + let [head, goal, body, keys] = Layout::vertical([ + Constraint::Length(1), + Constraint::Length(4), + Constraint::Fill(1), + Constraint::Length(1), + ]) + .areas(area); + f.render_widget(header(h, head.width as usize), head); + goal_box(f, goal, g); + let [left, right] = + Layout::horizontal([Constraint::Fill(1), Constraint::Length(56)]).areas(body); + left_box(f, left, g); + acceptance_box(f, right, g, checks_running); + f.render_widget(key_bar(), keys); +} + +fn header(h: &Header, width: usize) -> Line<'static> { + let clock = hms(h.now_ms); + let used = " hx·orch ".width() + " ‹ sessions / goal".width() + clock.width(); + Line::from(vec![ + Span::styled(" hx·orch ", inverted(theme::RUN)), + Span::styled(" ‹ sessions / ", fg(theme::DIM)), + Span::styled("goal", bold(theme::TEXT)), + Span::raw(" ".repeat(width.saturating_sub(used))), + Span::raw(clock), + ]) +} + +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 +} + +fn titled<'a>(title: Vec>, border: Color) -> Block<'a> { + let mut t = vec![Span::raw(" ")]; + t.extend(title); + t.push(Span::raw(" ")); + Block::bordered() + .border_style(fg(border)) + .title(Line::from(t)) +} + +fn goal_box(f: &mut Frame, area: Rect, g: &GoalView) { + let b = Block::bordered().border_style(fg(theme::BORDER)); + let inner = b.inner(area); + f.render_widget(b, area); + let w = inner.width as usize; + f.render_widget( + Paragraph::new(vec![ + Line::from(Span::styled( + format!(" {}", fit(&g.goal, w - 1)), + bold(theme::TEXT), + )), + Line::from(Span::styled( + format!(" {}", fit(&g.done_when, w - 1)), + fg(theme::DIM), + )), + ]), + inner, + ); +} + +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 task_box(f: &mut Frame, area: Rect, t: &TaskBox) { + let border = if t.status == Status::Done { + theme::BORDER + } else { + status_color(t.status) + }; + let b = Block::bordered().border_style(fg(border)); + let inner = b.inner(area); + f.render_widget(b, area); + let w = inner.width as usize; + let after = if t.after.is_empty() { + "after: —".to_string() + } else { + format!("after: {}", t.after.join(", ")) + }; + f.render_widget( + Paragraph::new(vec![ + Line::from(vec![ + Span::styled(format!("{} ", t.id), fg(theme::DIM)), + Span::styled(fit(&t.name, w.saturating_sub(4)), bold(theme::TEXT)), + ]), + Line::from(Span::styled( + fit(&format!("{} · {}", t.status.label(), t.detail), w), + bold(status_color(t.status)), + )), + Line::from(Span::styled(fit(&after, w), fg(theme::DIM))), + ]), + inner, + ); +} + +fn left_box(f: &mut Frame, area: Rect, g: &GoalView) { + let title = vec![ + Span::styled("Task graph", bold(theme::TEXT)), + Span::styled(" left to right = dependency order", fg(theme::DIM)), + ]; + let b = titled(title, theme::BORDER); + let inner = b.inner(area); + f.render_widget(b, area); + let tallest = g.columns.iter().map(|c| c.tasks.len()).max().unwrap_or(0) as u16; + let graph_h = (1 + tallest * (BOX_H + 1)).max(3); + let [graph, crit, decisions] = Layout::vertical([ + Constraint::Length(graph_h.min(inner.height.saturating_sub(8))), + Constraint::Length(3), + Constraint::Fill(1), + ]) + .areas(inner); + + let step = BOX_W + GAP_W; + for (c, col) in g.columns.iter().enumerate() { + let x = graph.x + 1 + c as u16 * step; + if x + BOX_W > graph.right() { + break; // does not fit on this terminal + } + f.render_widget( + Span::styled(col.label.clone(), fg(theme::DIM)), + Rect::new(x, graph.y, BOX_W, 1), + ); + for (i, t) in col.tasks.iter().enumerate() { + let y = graph.y + 1 + i as u16 * (BOX_H + 1); + if y + BOX_H > graph.bottom() { + break; + } + task_box(f, Rect::new(x, y, BOX_W, BOX_H), t); + if c + 1 < g.columns.len() { + f.render_widget( + Span::styled("──▶", fg(theme::SEP)), + Rect::new(x + BOX_W + 1, y + 2, 3, 1), + ); + } + } + } + + let crit_line = if g.critical.is_empty() { + Line::from(Span::styled( + " critical path nothing left to do", + fg(theme::DIM), + )) + } else { + Line::from(vec![ + Span::styled(" critical path ", bold(theme::WAIT)), + Span::raw(g.critical.join(" → ")), + ]) + }; + let sep = Block::new() + .borders(ratatui::widgets::Borders::TOP) + .border_style(fg(theme::BORDER)); + f.render_widget(Paragraph::new(crit_line).block(sep), crit); + + let db = titled( + vec![Span::styled("Decisions agents made", bold(theme::TEXT))], + theme::BORDER, + ); + let di = db.inner(decisions); + f.render_widget(db, decisions); + let w = di.width as usize; + let lines: Vec = g + .decisions + .iter() + .take(di.height as usize) + .map(|d| { + let text_style = if d.vetoed { + fg(theme::DIM).add_modifier(Modifier::CROSSED_OUT) + } else { + Style::new() + }; + Line::from(vec![ + Span::styled(format!(" {:<4}", d.session), fg(theme::RUN)), + Span::styled(fit(&d.text, w.saturating_sub(22)), text_style), + Span::styled(format!(" {:<14}", d.whence), fg(theme::DIM)), + ]) + }) + .collect(); + if lines.is_empty() { + f.render_widget(Span::styled(" none reported yet", fg(theme::DIM)), di); + } else { + f.render_widget(Paragraph::new(lines), di); + } +} + +fn acceptance_box(f: &mut Frame, area: Rect, g: &GoalView, running: bool) { + let mut title = vec![ + Span::styled("Acceptance ", bold(theme::TEXT)), + Span::styled(g.green.to_string(), fg(theme::OK)), + Span::styled(format!("/{}", g.checks.len()), fg(theme::DIM)), + ]; + if running { + title.push(Span::styled(" running…", fg(theme::WAIT))); + } + let b = titled(title, theme::BORDER); + let inner = b.inner(area); + f.render_widget(b, area); + let w = inner.width.saturating_sub(2) as usize; + let total = g.checks.len(); + let on = (g.green * w).checked_div(total).unwrap_or(0); + let mut lines = vec![ + Line::from(vec![ + Span::raw(" "), + Span::styled("█".repeat(on), fg(theme::OK)), + Span::styled("█".repeat(w - on), fg(theme::BORDER)), + ]), + Line::raw(""), + ]; + if g.checks.is_empty() { + lines.push(Line::from(Span::styled( + " no checks yet · press +", + fg(theme::DIM), + ))); + } + for c in &g.checks { + let (mark, style, name_style) = match c.state { + CheckState::Pass => ("✓", fg(theme::OK), Style::new()), + CheckState::Fail => ( + "✗", + fg(theme::ERR), + Style::new().add_modifier(Modifier::BOLD), + ), + CheckState::Unknown => ("·", fg(theme::TODO), fg(theme::DIM)), + }; + let owner_w = 4; // `s12`, `ci`, `-`: right-aligned in a fixed column + let name_w = w.saturating_sub(owner_w + 4); + lines.push(Line::from(vec![ + Span::raw(" "), + Span::styled(mark, style), + Span::raw(" "), + Span::styled(format!("{:owner_w$}", c.owner), fg(theme::DIM)), + ])); + } + f.render_widget(Paragraph::new(lines), inner); +} + +fn key_bar() -> Line<'static> { + let mut v = vec![Span::raw(" ")]; + for (k, what) in [ + ("esc", "back"), + ("e", "edit goal"), + ("+", "add check"), + ("R", "run all checks"), + ] { + 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) +} diff --git a/src/tui/mod.rs b/src/tui/mod.rs index b6e8c7f..8376acf 100644 --- a/src/tui/mod.rs +++ b/src/tui/mod.rs @@ -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)> { + 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, pager: Option, + /// Focused item of the Needs-you box. + need_sel: usize, + input: Option, + goal_view: Option, + /// True while a background `run all checks` is going. + checks_running: std::sync::Arc, } 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, sessions: Vec, + needs: Vec, + checks: Vec, + decisions: Vec, goal: Option, } @@ -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, + machines: &mut HashMap, + now_ms: u64, +) -> Result { + 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::() + .trim_end() + .to_string() + }) + .collect::>() + .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); + } } diff --git a/src/tui/overview.rs b/src/tui/overview.rs index 216a530..5eac0cd 100644 --- a/src/tui/overview.rs +++ b/src/tui/overview.rs @@ -23,7 +23,7 @@ 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) { +pub fn draw(f: &mut Frame, o: &Overview, h: &Header, sel: usize, need_sel: usize) { let area = f.area(); f.render_widget( Block::new().style(Style::new().bg(theme::BG).fg(theme::TEXT)), @@ -44,7 +44,7 @@ pub fn draw(f: &mut Frame, o: &Overview, h: &Header, sel: usize) { 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); + needs_box(f, needs, &o.needs, need_sel); events_box(f, events, &o.events); f.render_widget(key_bar(), keys); } @@ -295,7 +295,7 @@ fn sessions_box(f: &mut Frame, area: Rect, o: &Overview, sel: usize) { f.render_widget(Paragraph::new(lines), inner); } -fn needs_box(f: &mut Frame, area: Rect, needs: &[Need]) { +fn needs_box(f: &mut Frame, area: Rect, needs: &[Need], focus: usize) { let border = if needs.is_empty() { theme::BORDER } else { @@ -305,15 +305,32 @@ fn needs_box(f: &mut Frame, area: Rect, needs: &[Need]) { let inner = block.inner(area); f.render_widget(block, area); let mut lines = vec![]; - for n in needs { + for (i, n) in needs.iter().enumerate() { + // several items: the keys act on the focused one, tab moves the focus + let mark = if i == focus && needs.len() > 1 { + Span::styled("▶", fg(theme::WAIT)) + } else { + Span::raw(" ") + }; + let age = if n.age_secs > 0 { + format!(" · {}", crate::view::ago(n.age_secs)) + } else { + String::new() + }; lines.push(Line::from(vec![ + mark, 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)), + Span::styled(format!(" · {}{age}", n.what), fg(theme::DIM)), ])); + let w = (inner.width as usize).saturating_sub(1); if !n.detail.is_empty() { - lines.push(Line::from(Span::raw(fit(&n.detail, inner.width as usize)))); + lines.push(Line::from(Span::raw(format!(" {}", fit(&n.detail, w))))); + } + let keys = n.keys(); + if !keys.is_empty() { + lines.push(Line::from(Span::styled(format!(" {keys}"), fg(theme::DIM)))); } lines.push(Line::raw("")); } @@ -363,7 +380,13 @@ fn events_box(f: &mut Frame, area: Rect, events: &[EventLine]) { fn key_bar() -> Line<'static> { let mut v = vec![Span::raw(" ")]; - for (k, what) in [("j/k", "move"), ("q", "quit")] { + for (k, what) in [ + ("j/k", "move"), + ("enter", "open"), + ("g", "goal"), + ("tab", "next item"), + ("q", "quit"), + ] { v.push(Span::styled( format!(" {k} "), Style::new().fg(theme::BG).bg(theme::DIM), diff --git a/src/view.rs b/src/view.rs index 88a4d4f..82a0834 100644 --- a/src/view.rs +++ b/src/view.rs @@ -64,12 +64,45 @@ pub struct Row { pub last: String, } +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum NeedKind { + /// A `human` step (review gate): approve or send back with a comment. + Review, + /// hx asks to run a tool: allow once, always, or deny. + Permission, + /// hx asks a question: reply with text. + Input, + /// The session ended in `escalated`. Derived from the session, nothing to answer in the queue. + Escalated, +} + +/// One item of the Needs-you box. #[derive(Clone, PartialEq, Debug)] pub struct Need { + /// Row id in the `needs` table; 0 for derived items. + pub id: i64, + pub kind: NeedKind, pub session: String, pub task: String, + /// `review ready`, `permission`, `question`, `escalated`. pub what: String, pub detail: String, + pub age_secs: u64, +} + +impl Need { + /// The key line under the item, like `[y] allow once [Y] always for s4 [n] deny`. + pub fn keys(&self) -> String { + match self.kind { + NeedKind::Review => "[a] approve [d] open diff [c] comment back".into(), + NeedKind::Permission => format!( + "[y] allow once [Y] always for {} [n] deny", + self.session + ), + NeedKind::Input => "[r] reply".into(), + NeedKind::Escalated => String::new(), + } + } } #[derive(Clone, PartialEq, Debug)] @@ -106,6 +139,11 @@ pub struct Input<'a> { pub events: &'a [Event], /// Loaded machine files by name; a missing one only costs the strip. pub machines: &'a HashMap, + /// Unanswered items of the Needs-you queue, oldest first. + pub needs: &'a [crate::db::NeedRow], + /// Acceptance checks with their last result on main. + pub checks: &'a [crate::db::CheckRow], + pub decisions: &'a [crate::db::DecisionRow], pub now_ms: u64, } @@ -126,6 +164,31 @@ pub fn build(i: &Input) -> Overview { .find(|t| t.id == sid) .map_or_else(String::new, |t| t.name.clone()) }; + let mut escalated = vec![]; + for n in i.needs { + let Some(task) = i + .sessions + .iter() + .find(|s| s.id == n.session) + .and_then(|s| i.tasks.iter().find(|t| t.id == s.task_id)) + else { + continue; + }; + let text = |k: &str| n.payload[k].as_str().unwrap_or_default().to_string(); + o.needs.push(Need { + id: n.id, + kind: match n.kind.as_str() { + "permission" => NeedKind::Permission, + "input" => NeedKind::Input, + _ => NeedKind::Review, + }, + session: n.session.clone(), + task: task.name.clone(), + what: text("title"), + detail: text("detail"), + age_secs: i.now_ms.saturating_sub(n.at) / 1000, + }); + } for s in i.sessions { let Some(task) = i.tasks.iter().find(|t| t.id == s.task_id) else { continue; @@ -155,17 +218,18 @@ pub fn build(i: &Input) -> Overview { } _ => evs.last().map_or_else(String::new, |e| describe(e)), }; - if status == Status::Wait { - o.needs.push(Need { + if s.status == "escalated" { + let end = evs.iter().rev().find(|e| e.kind == "end"); + escalated.push(Need { + id: 0, + kind: NeedKind::Escalated, session: s.id.clone(), task: task.name.clone(), - what: s.status.clone(), - detail: evs - .iter() - .rev() - .find(|e| e.kind == "end") + what: "escalated".into(), + detail: end .and_then(|e| e.payload["reason"].as_str().map(String::from)) .unwrap_or_default(), + age_secs: end.map_or(0, |e| i.now_ms.saturating_sub(e.at) / 1000), }); } match status { @@ -192,6 +256,15 @@ pub fn build(i: &Input) -> Overview { last, }); } + o.needs.extend(escalated); + if !i.checks.is_empty() { + let green = i + .checks + .iter() + .filter(|c| c.last_status.as_deref() == Some("pass")) + .count(); + o.checks = Some((green, i.checks.len())); + } o.events = i .events .iter() @@ -522,6 +595,9 @@ mod tests { sessions: &sessions, events: &events, machines: &m, + needs: &[], + checks: &[], + decisions: &[], now_ms: 20_000, }); let r = &o.rows[0]; @@ -564,6 +640,9 @@ mod tests { sessions: &sessions, events: &events, machines: &m, + needs: &[], + checks: &[], + decisions: &[], now_ms: 0, }); assert_eq!(o.rows[0].retry, ""); @@ -599,6 +678,9 @@ mod tests { sessions: &sessions, events: &events, machines: &m, + needs: &[], + checks: &[], + decisions: &[], now_ms: 61_000, }); let s: Vec<_> = o.rows.iter().map(|r| r.status).collect(); diff --git a/tests/fake_acp_hx.py b/tests/fake_acp_hx.py index afb284e..7f8728c 100644 --- a/tests/fake_acp_hx.py +++ b/tests/fake_acp_hx.py @@ -4,7 +4,7 @@ Behaviour per `hx/step`, chosen with FAKE_MODE (orch passes FAKE_* through the p ok intent, tool call, edit, usage, decision, plan, then step_result done (default) blocked step_result blocked, catch FAKE_CATCH (default PlanInvalid) block_once blocked the first time (marker file .fake_blocked in cwd), done afterwards - needs_input step_result needs_input with a question + needs_input step_result needs_input with a question; finishes when the retried step has a context.hint permission asks session/request_permission first and records the answer in permission.txt crash exits without a step_result Every received message is appended to FAKE_LOG when set. Each step also appends its prompt kind to steps.txt. @@ -59,7 +59,8 @@ def step(params): with open(os.path.join(cwd, "permission.txt"), "w") as f: f.write(json.dumps(m["result"])) break - if mode == "needs_input": + # needs_input asks once; with the user's answer in context.hint the same step finishes + if mode == "needs_input" and not params.get("context", {}).get("hint"): note("hx/step_result", {"status": "needs_input", "question": "Which provider?"}) return blocked = mode == "blocked"