//! 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); "; pub struct Db { conn: Connection, } #[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, } #[derive(Clone, Debug, PartialEq)] pub struct Task { pub id: String, pub name: String, pub subtitle: String, pub machine: String, pub depends_on: Vec, } #[derive(Clone, Debug, PartialEq)] pub struct Session { pub id: String, pub task_id: String, pub branch: String, pub worktree: String, pub pid: Option, 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 { 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 }) } 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> { 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 { 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> { 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::>()?) } 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(()) } pub fn session(&self, id: &str) -> Result> { 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> { 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::>()?) } 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(()) } pub fn set_pid(&self, id: &str, pid: Option) -> 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 { 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()) } /// Events oldest first, optionally one session, only those after `after` (event id). pub fn events(&self, session: Option<&str>, after: i64) -> Result> { 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::>()?) } /// How often `catch` fired in `state` of this session (rebuilt from events, so it survives restarts). pub fn catch_count(&self, session: &str, state: &str, catch: &str) -> Result { 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", params![session, state, catch], |r| r.get(0), )?; Ok(n as u32) } } fn session_row(r: &rusqlite::Row) -> rusqlite::Result { 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); assert!(db.events(Some("s9"), 0).unwrap().is_empty()); // 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); } }