Files
orch/src/db.rs
T
johannesandClaude Sonnet 5.5 e50f90d299
build / version (push) Successful in 10s
build / build (aarch64-apple-darwin) (push) Successful in 4m5s
build / build (x86_64-unknown-linux-musl) (push) Successful in 3m34s
build / release (push) Successful in 16s
feat: restart a failed or escalated session at the state where it stopped
Adds orch session --restart sN and R in the TUI. A restart event gives the
session fresh budgets and retry counts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 22:36:10 +01:00

673 lines
25 KiB
Rust

//! Per-goal SQLite file (`.hx/orch.db`, ORCHESTRATOR.md section 6). The `events` table is append-only; every
//! view is rebuilt from it plus the machine files. Each thread opens its own connection (WAL + busy timeout).
// shortcut: checks/decisions tables exist but have no accessors yet; milestones 7 and 8 add them.
#![allow(dead_code)]
use anyhow::{Context, Result};
use rusqlite::{Connection, OptionalExtension, params};
use serde_json::Value;
use std::path::Path;
const SCHEMA: &str = "
create table if not exists goal(text text not null, created_at integer not null);
create table if not exists checks(
id integer primary key, name text not null, cmd text not null, owner_session text,
last_status text, last_run_at integer);
create table if not exists tasks(
id text primary key, name text not null, subtitle text not null default '',
machine text not null, depends_on text not null default '[]');
create table if not exists sessions(
id text primary key, task_id text not null, branch text not null, worktree text not null,
pid integer, current_state text not null default '', status text not null default 'queued');
create table if not exists events(
id integer primary key autoincrement, session_id text not null, at integer not null,
kind text not null, payload text not null default '{}');
create index if not exists events_session on events(session_id, id);
create table if not exists decisions(
session_id text not null, text text not null, state text not null, at integer not null,
vetoed integer not null default 0);
create table if not exists commands(
id integer primary key autoincrement, session_id text not null, kind text not null,
payload text not null default '{}', at integer not null, done 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)]
pub struct Event {
pub id: i64,
pub session: String,
/// Milliseconds since the epoch.
pub at: u64,
pub kind: String,
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,
pub name: String,
pub subtitle: String,
pub machine: String,
pub depends_on: Vec<String>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Session {
pub id: String,
pub task_id: String,
pub branch: String,
pub worktree: String,
pub pid: Option<u32>,
pub state: String,
/// queued, running, or the machine's `end` value (merged, escalated, aborted) or `failed`.
pub status: String,
}
impl Db {
pub fn open(path: &Path) -> Result<Self> {
if let Some(d) = path.parent() {
std::fs::create_dir_all(d)?;
}
let conn = Connection::open(path).with_context(|| path.display().to_string())?;
conn.busy_timeout(std::time::Duration::from_secs(5))?;
conn.pragma_update(None, "journal_mode", "WAL")?;
conn.execute_batch(SCHEMA)?;
Ok(Self {
conn,
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(())
}
/// A command for a running session (`message`, `interrupt`, `goto`, `abort`, `veto`). The runner, which may be
/// another process, picks it up the next time it polls.
pub fn add_command(&self, session: &str, kind: &str, payload: &Value) -> Result<i64> {
self.conn.execute(
"insert into commands(session_id, kind, payload, at) values (?1, ?2, ?3, ?4)",
params![
session,
kind,
payload.to_string(),
crate::state::now_ms() as i64
],
)?;
Ok(self.conn.last_insert_rowid())
}
/// Takes the session's unprocessed commands, oldest first, and marks them processed.
pub fn take_commands(&self, session: &str) -> Result<Vec<(String, Value)>> {
let mut q = self.conn.prepare(
"select id, kind, payload from commands where session_id = ?1 and done = 0 order by id",
)?;
let rows: Vec<(i64, String, String)> = q
.query_map([session], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?
.collect::<rusqlite::Result<_>>()?;
for (id, ..) in &rows {
self.conn
.execute("update commands set done = 1 where id = ?1", [id])?;
}
Ok(rows
.into_iter()
.map(|(_, k, p)| (k, serde_json::from_str(&p).unwrap_or(Value::Null)))
.collect())
}
/// Marks a decision as vetoed; false if it does not exist or was already vetoed.
pub fn veto_decision(&self, id: i64) -> Result<bool> {
let n = self.conn.execute(
"update decisions set vetoed = 1 where rowid = ?1 and vetoed = 0",
[id],
)?;
Ok(n == 1)
}
pub fn set_goal(&self, text: &str) -> Result<()> {
self.conn.execute("delete from goal", [])?;
self.conn.execute(
"insert into goal(text, created_at) values (?1, ?2)",
params![text, crate::state::now() as i64],
)?;
Ok(())
}
pub fn goal(&self) -> Result<Option<String>> {
Ok(self
.conn
.query_row("select text from goal limit 1", [], |r| r.get(0))
.optional()?)
}
/// Next free session id: s1, s2, ...
pub fn next_session_id(&self) -> Result<String> {
let n: i64 = self.conn.query_row(
"select coalesce(max(cast(substr(id, 2) as integer)), 0) from sessions",
[],
|r| r.get(0),
)?;
Ok(format!("s{}", n + 1))
}
pub fn add_task(&self, t: &Task) -> Result<()> {
self.conn.execute(
"insert into tasks(id, name, subtitle, machine, depends_on) values (?1, ?2, ?3, ?4, ?5)",
params![
t.id,
t.name,
t.subtitle,
t.machine,
serde_json::to_string(&t.depends_on)?
],
)?;
Ok(())
}
pub fn tasks(&self) -> Result<Vec<Task>> {
let mut q = self.conn.prepare(
"select id, name, subtitle, machine, depends_on from tasks order by cast(substr(id, 2) as integer), id",
)?;
let rows = q.query_map([], |r| {
let deps: String = r.get(4)?;
Ok(Task {
id: r.get(0)?,
name: r.get(1)?,
subtitle: r.get(2)?,
machine: r.get(3)?,
depends_on: serde_json::from_str(&deps).unwrap_or_default(),
})
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn add_session(&self, s: &Session) -> Result<()> {
self.conn.execute(
"insert into sessions(id, task_id, branch, worktree, pid, current_state, status) values (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![s.id, s.task_id, s.branch, s.worktree, s.pid, s.state, s.status],
)?;
Ok(())
}
/// Points a session at a branch and worktree chosen by the user instead of the generated ones.
pub fn set_location(&self, id: &str, branch: &str, worktree: &str) -> Result<()> {
self.conn.execute(
"update sessions set branch = ?2, worktree = ?3 where id = ?1",
params![id, branch, worktree],
)?;
Ok(())
}
pub fn session(&self, id: &str) -> Result<Option<Session>> {
Ok(self
.conn
.query_row(
"select id, task_id, branch, worktree, pid, current_state, status from sessions where id = ?1",
[id],
session_row,
)
.optional()?)
}
pub fn sessions(&self) -> Result<Vec<Session>> {
let mut q = self.conn.prepare(
"select id, task_id, branch, worktree, pid, current_state, status from sessions order by cast(substr(id, 2) as integer), id",
)?;
Ok(q.query_map([], session_row)?
.collect::<rusqlite::Result<_>>()?)
}
pub fn set_session(&self, id: &str, state: &str, status: &str) -> Result<()> {
self.conn.execute(
"update sessions set current_state = ?2, status = ?3 where id = ?1",
params![id, state, status],
)?;
Ok(())
}
/// Turns a failed or escalated session back into a suspended one at the state where it stopped, so the
/// resume path continues it. Budgets and catch counts start again from the `restart` event.
pub fn reopen(&self, id: &str) -> Result<()> {
let s = self
.session(id)?
.with_context(|| format!("no session {id}"))?;
anyhow::ensure!(
matches!(s.status.as_str(), "failed" | "escalated"),
"session {id} is {}; only a failed or escalated session can be restarted",
s.status
);
self.set_session(id, &s.state, "suspended")?;
self.set_pid(id, None)?;
self.emit(id, "restart", serde_json::json!({"from": s.status, "state": s.state}))?;
Ok(())
}
pub fn set_pid(&self, id: &str, pid: Option<u32>) -> Result<()> {
self.conn.execute(
"update sessions set pid = ?2 where id = ?1",
params![id, pid],
)?;
Ok(())
}
/// Append one event; returns its id.
pub fn emit(&self, session: &str, kind: &str, payload: Value) -> Result<i64> {
self.conn.execute(
"insert into events(session_id, at, kind, payload) values (?1, ?2, ?3, ?4)",
params![
session,
crate::state::now_ms() as i64,
kind,
payload.to_string()
],
)?;
Ok(self.conn.last_insert_rowid())
}
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(
"insert into decisions(session_id, text, state, at) values (?1, ?2, ?3, ?4)",
params![session, text, state, crate::state::now_ms() as i64],
)?;
Ok(())
}
pub fn decision_count(&self, session: &str) -> Result<usize> {
let n: i64 = self.conn.query_row(
"select count(*) from decisions where session_id = ?1",
[session],
|r| r.get(0),
)?;
Ok(n as usize)
}
/// Events oldest first, optionally one session, only those after `after` (event id).
pub fn events(&self, session: Option<&str>, after: i64) -> Result<Vec<Event>> {
let mut q = self.conn.prepare(
"select id, session_id, at, kind, payload from events
where id > ?1 and (?2 is null or session_id = ?2) order by id",
)?;
let rows = q.query_map(params![after, session], |r| {
let p: String = r.get(4)?;
Ok(Event {
id: r.get(0)?,
session: r.get(1)?,
at: r.get::<_, i64>(2)? as u64,
kind: r.get(3)?,
payload: serde_json::from_str(&p).unwrap_or(Value::Null),
})
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// How often `catch` fired in `state` of this session (rebuilt from events, so it survives restarts).
/// Catches before the last `restart` do not count: a restarted session gets its retries back.
pub fn catch_count(&self, session: &str, state: &str, catch: &str) -> Result<u32> {
let n: i64 = self.conn.query_row(
"select count(*) from events where session_id = ?1 and kind = 'catch'
and json_extract(payload, '$.state') = ?2 and json_extract(payload, '$.catch') = ?3
and id > coalesce((select max(id) from events where session_id = ?1 and kind = 'restart'), 0)",
params![session, state, catch],
|r| r.get(0),
)?;
Ok(n as u32)
}
}
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)?,
task_id: r.get(1)?,
branch: r.get(2)?,
worktree: r.get(3)?,
pid: r.get(4)?,
state: r.get(5)?,
status: r.get(6)?,
})
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
pub fn temp_db(tag: &str) -> (Db, std::path::PathBuf) {
let d = std::env::temp_dir().join(format!("orch-db-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
(Db::open(&d.join("orch.db")).unwrap(), d)
}
#[test]
fn roundtrip() {
let (db, dir) = temp_db("rt");
assert_eq!(db.goal().unwrap(), None);
db.set_goal("ship it").unwrap();
assert_eq!(db.goal().unwrap().as_deref(), Some("ship it"));
assert_eq!(db.next_session_id().unwrap(), "s1");
let s = Session {
id: "s1".into(),
task_id: "s1".into(),
branch: "hx/s1-x".into(),
worktree: "/w".into(),
pid: None,
state: String::new(),
status: "queued".into(),
};
db.add_session(&s).unwrap();
assert_eq!(db.next_session_id().unwrap(), "s2");
db.set_session("s1", "plan", "running").unwrap();
assert_eq!(db.session("s1").unwrap().unwrap().state, "plan");
db.emit("s1", "catch", json!({"state": "test", "catch": "T"}))
.unwrap();
let last = db.emit("s1", "state", json!({"to": "code"})).unwrap();
assert_eq!(db.catch_count("s1", "test", "T").unwrap(), 1);
assert_eq!(db.catch_count("s1", "test", "U").unwrap(), 0);
assert_eq!(db.events(Some("s1"), 0).unwrap().len(), 2);
assert_eq!(db.events(None, last - 1).unwrap().len(), 1);
// only a failed or escalated session reopens; it keeps its state and gets its retries back
assert!(db.reopen("s1").is_err(), "running");
db.set_session("s1", "test", "failed").unwrap();
db.reopen("s1").unwrap();
let s = db.session("s1").unwrap().unwrap();
assert_eq!((s.status.as_str(), s.state.as_str()), ("suspended", "test"));
assert_eq!(db.catch_count("s1", "test", "T").unwrap(), 0);
db.emit("s1", "catch", json!({"state": "test", "catch": "T"}))
.unwrap();
assert_eq!(db.catch_count("s1", "test", "T").unwrap(), 1);
assert!(db.reopen("s1").is_err(), "suspended");
db.set_session("s1", "plan", "running").unwrap();
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();
// commands: taken once, in order, per session
db.add_command("s1", "message", &json!({"text": "hi"}))
.unwrap();
db.add_command("s1", "interrupt", &json!({})).unwrap();
db.add_command("s2", "abort", &json!({})).unwrap();
let cmds = db.take_commands("s1").unwrap();
assert_eq!(
cmds.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(),
["message", "interrupt"]
);
assert_eq!(cmds[0].1["text"], "hi");
assert!(db.take_commands("s1").unwrap().is_empty());
assert_eq!(db.take_commands("s2").unwrap().len(), 1);
// a decision can be vetoed once
let d = db.decisions().unwrap()[0].id;
assert!(db.veto_decision(d).unwrap());
assert!(!db.veto_decision(d).unwrap());
assert!(db.decisions().unwrap()[0].vetoed);
// 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();
assert_eq!(db.sessions().unwrap().len(), 1);
let _ = std::fs::remove_dir_all(&dir);
}
}