Add Needs-you queue and goal view with acceptance checks

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

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

No files matched your search

+272 -1
View File
@@ -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<String>,
/// pass | fail, None until the first run
pub last_status: Option<String>,
pub last_run_at: Option<u64>,
}
/// 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<String>,
}
#[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<i64> {
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<Vec<CheckRow>> {
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<i64>>(5)?.map(|v| v as u64),
})
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
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<Vec<DecisionRow>> {
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::<rusqlite::Result<_>>()?)
}
/// Joins the merge queue (once) and returns the ticket; lower tickets merge first.
pub fn queue_join(&self, session: &str) -> Result<i64> {
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<Option<String>> {
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<usize> {
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<i64> {
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<Vec<NeedRow>> {
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::<rusqlite::Result<_>>()?)
}
/// 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<Option<NeedRow>> {
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<Option<String>> {
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<bool> {
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<NeedRow> {
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<Session> {
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();