diff --git a/GLOSSARY.md b/GLOSSARY.md index 22e08e7..a1e3fce 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -17,7 +17,7 @@ A point where a session waits on the human: a permission request, a review, a qu _Avoid_: Prompt, interrupt (an interrupt is something the human sends) **Named worktree**: -A worktree or branch the human picks for a session, such as a ticket branch, instead of the default `hx/sN-slug`. orch never deletes one it did not create. +A worktree or branch the human picks for a session, such as an issue branch, instead of the default `hx/sN-slug`. orch never deletes one it did not create. _Avoid_: Custom branch, existing worktree **Host**: diff --git a/README.md b/README.md index 7e82c79..dd9a98c 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,8 @@ git host: tasks come from a folder or any JSON command, results go to a local br orch goal [TEXT] [--export] show or set the goal (--export adds the checks) orch check NAME CMD [--owner sN] add an acceptance check (pass = exit 0) orch checks [--owner sN | --main] run acceptance checks here, or on a clean copy of main + orch up MANIFEST one detached session per worktree of an issue (any repos) + orch issues TUI on the sessions `orch up` started, grouped by issue ## How a run goes @@ -104,6 +106,36 @@ first served); after each merge all checks run again on main in a clean worktree `ORCH_REPO` and `ORCH_SESSION`, and `{{repo}}` in `cmd`; the example machines merge with `git -C {{repo}} merge --ff-only {{branch}}` in `mark-merged`. +## Issues: `orch up` + +For work on an issue that spans worktrees you made yourself, in one repo or several. Each worktree has its own +machine, profile and task text in its `.hx/` (`.hx` should be git-ignored). A manifest lists them: + +```toml +# /ABC-123.toml +issue = "ABC-123" + +[[session]] +worktree = "~/Repos/api/.worktrees/abc-123" # an existing linked worktree; its repo follows from it +name = "api endpoint" +machine = "abc-123" # /.hx/machines/, then the repo's .hx/machines/, then ~/.hx/machines/ +profile = "abc-123" # /.hx/profiles/, then /profiles/ +# task = ".hx/task.md" # default, relative to the worktree; given to the agent with every prompt +# merge = false # default: the session ends at `done` and the branch stays for a pull request +``` + +`orch up ABC-123` reads `/ABC-123.toml` (or takes a path), checks every entry first and starts nothing +when one is broken, then starts one detached session per worktree and returns. Logs go to +`/logs/issue-sN.log`. Running it again is safe: sessions that run or are done are left alone, and ones that +stopped unfinished start again. The sessions of every repo live in one database, `/issues.db`; `orch +issues` shows them grouped by issue, with the repo under each name. Steering and kill work as in the normal TUI; +`u` and `R` start sessions detached again. `manifest_dir` defaults to `/manifests` and is set in +`/config.toml` (`~/.config/orch/config.toml`): + +```toml +manifest_dir = "~/notes/manifests" +``` + ## More - [docs/cmd-protocol.md](docs/cmd-protocol.md): task sources and result sinks as external commands (+ JSON schema) diff --git a/src/db.rs b/src/db.rs index 1176ad7..0895b0f 100644 --- a/src/db.rs +++ b/src/db.rs @@ -30,7 +30,7 @@ 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); + issue 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, @@ -119,6 +119,15 @@ impl Db { conn.busy_timeout(std::time::Duration::from_secs(5))?; conn.pragma_update(None, "journal_mode", "WAL")?; conn.execute_batch(SCHEMA)?; + // databases from before the rename call the merge queue's number `ticket` + let old: bool = conn.query_row( + "select count(*) > 0 from pragma_table_info('merge_queue') where name = 'ticket'", + [], + |r| r.get(0), + )?; + if old { + conn.execute_batch("alter table merge_queue rename column ticket to issue")?; + } Ok(Self { conn, path: path.to_path_buf(), @@ -184,14 +193,14 @@ impl Db { Ok(rows.collect::>()?) } - /// Joins the merge queue (once) and returns the ticket; lower tickets merge first. + /// Joins the merge queue (once) and returns the issue; lower issues 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", + "select issue from merge_queue where session_id = ?1", [session], |r| r.get(0), )?) @@ -202,7 +211,7 @@ impl Db { Ok(self .conn .query_row( - "select session_id from merge_queue order by ticket limit 1", + "select session_id from merge_queue order by issue limit 1", [], |r| r.get(0), ) @@ -212,8 +221,8 @@ impl Db { /// 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)", + "select count(*) from merge_queue where issue <= + (select issue from merge_queue where session_id = ?1)", [session], |r| r.get(0), )?; @@ -382,7 +391,11 @@ impl Db { ); 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}))?; + self.emit( + id, + "restart", + serde_json::json!({"from": s.status, "state": s.state}), + )?; Ok(()) } @@ -394,6 +407,20 @@ impl Db { Ok(()) } + /// Every `options` event of a session merged into one object, later keys win (`no_merge`, and for an issue + /// session `issue`, `repo`, `profile` and `task`). + pub fn options(&self, session: &str) -> Result> { + let mut m = serde_json::Map::new(); + for e in self.events(Some(session), 0)? { + if e.kind == "options" + && let Value::Object(o) = e.payload + { + m.extend(o); + } + } + Ok(m) + } + /// Append one event; returns its id. pub fn emit(&self, session: &str, kind: &str, payload: Value) -> Result { self.conn.execute( @@ -558,6 +585,28 @@ mod tests { (Db::open(&d.join("orch.db")).unwrap(), d) } + #[test] + fn old_merge_queue_column_is_renamed() { + let d = std::env::temp_dir().join(format!("orch-db-mq-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let path = d.join("orch.db"); + Connection::open(&path) + .unwrap() + .execute_batch( + "create table merge_queue(ticket integer primary key autoincrement, session_id text not null unique); + insert into merge_queue(session_id) values ('s1');", + ) + .unwrap(); + let db = Db::open(&path).unwrap(); + assert_eq!(db.queue_head().unwrap().as_deref(), Some("s1")); + db.queue_join("s2").unwrap(); + assert_eq!(db.queue_position("s2").unwrap(), 2); + drop(db); + Db::open(&path).unwrap(); // a second open finds nothing to rename + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn roundtrip() { let (db, dir) = temp_db("rt"); diff --git a/src/issue.rs b/src/issue.rs new file mode 100644 index 0000000..1053ec6 --- /dev/null +++ b/src/issue.rs @@ -0,0 +1,337 @@ +//! Issues: `orch up MANIFEST` starts one detached session per worktree an issue manifest lists. The worktrees may +//! belong to different repos, so these sessions live in one database of their own, `/issues.db`, which +//! `orch issues` shows. Each session keeps its repo, profile file and task text in an `options` event. + +use crate::db::Db; +use crate::machine::Machine; +use crate::place::Place; +use crate::profile::Profile; +use crate::run::git; +use anyhow::{Context, Result, bail, ensure}; +use serde::Deserialize; +use serde_json::json; +use std::os::unix::process::CommandExt; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +/// `/config.toml`. Every key is optional. +#[derive(Deserialize, Default)] +#[serde(deny_unknown_fields)] +struct Config { + /// Where `orch up NAME` looks for `NAME.toml` (default `/manifests`). + manifest_dir: Option, +} + +#[derive(Deserialize, Debug)] +#[serde(deny_unknown_fields)] +struct Manifest { + issue: String, + #[serde(default, rename = "session")] + sessions: Vec, +} + +#[derive(Deserialize, Debug)] +#[serde(deny_unknown_fields)] +struct Entry { + /// Path of an existing linked worktree (`~` allowed). + worktree: String, + name: String, + /// `/.hx/machines/NAME.toml`, then the repo's `.hx/machines/`, then `~/.hx/machines/`. + machine: String, + /// `/.hx/profiles/NAME.toml`, then `/profiles/NAME.toml`. + profile: String, + /// Task text for the agent, relative to the worktree. + #[serde(default = "default_task")] + task: String, + /// Run the machine's merge state; by default the session stops at `done` and the branch stays for a PR. + #[serde(default)] + merge: bool, +} + +fn default_task() -> String { + ".hx/task.md".into() +} + +/// A checked manifest entry: everything it names exists and parses. +struct Planned { + name: String, + worktree: PathBuf, + branch: String, + repo: PathBuf, + machine: PathBuf, + profile: PathBuf, + task: String, + merge: bool, +} + +pub fn db_path() -> PathBuf { + crate::state_dir().join("issues.db") +} + +fn expand(p: &str) -> PathBuf { + match p.strip_prefix("~/") { + Some(rest) => PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(rest), + None => PathBuf::from(p), + } +} + +fn manifest_dir() -> Result { + let file = crate::config_dir().join("config.toml"); + let cfg: Config = match std::fs::read_to_string(&file) { + Ok(s) => toml::from_str(&s).with_context(|| file.display().to_string())?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Config::default(), + Err(e) => return Err(e).with_context(|| file.display().to_string()), + }; + Ok(cfg + .manifest_dir + .map_or_else(|| crate::config_dir().join("manifests"), |d| expand(&d))) +} + +/// A manifest file as given, else `/ARG.toml`. +fn manifest_path(arg: &str) -> Result { + let p = expand(arg); + if p.is_file() { + return Ok(p); + } + let dir = manifest_dir()?; + let file = if arg.ends_with(".toml") { + dir.join(arg) + } else { + dir.join(format!("{arg}.toml")) + }; + ensure!( + file.is_file(), + "no manifest {arg:?}: neither a file nor {}", + file.display() + ); + Ok(file) +} + +fn first_file(candidates: &[PathBuf], what: &str) -> Result { + candidates + .iter() + .find(|p| p.is_file()) + .cloned() + .with_context(|| format!("{what} not found in {candidates:?}")) +} + +fn plan(e: &Entry) -> Result { + let wt = expand(&e.worktree) + .canonicalize() + .with_context(|| format!("worktree {}", e.worktree))?; + let common = git( + &wt, + &["rev-parse", "--path-format=absolute", "--git-common-dir"], + ) + .with_context(|| format!("{} is not in a git repo", wt.display()))?; + let common = PathBuf::from(common.trim()).canonicalize()?; + let repo = common + .parent() + .context("git common dir has no parent")? + .to_path_buf(); + let Place::Worktree { path, branch } = crate::place::resolve(&repo, &wt.to_string_lossy())? + else { + bail!( + "{} is not a linked worktree of {}", + wt.display(), + repo.display() + ); + }; + let home = PathBuf::from(std::env::var_os("HOME").unwrap_or_default()); + let mfile = format!("{}.toml", e.machine); + let machine = first_file( + &[ + wt.join(".hx/machines").join(&mfile), + repo.join(".hx/machines").join(&mfile), + home.join(".hx/machines").join(&mfile), + ], + &format!("machine {:?}", e.machine), + )?; + Machine::load(&machine)?; + let pfile = format!("{}.toml", e.profile); + let profile = first_file( + &[ + wt.join(".hx/profiles").join(&pfile), + crate::config_dir().join("profiles").join(&pfile), + ], + &format!("profile {:?}", e.profile), + )?; + Profile::load_path(&profile)?; + let task_file = wt.join(&e.task); + let task = std::fs::read_to_string(&task_file) + .with_context(|| format!("task file {}", task_file.display()))?; + Ok(Planned { + name: e.name.clone(), + worktree: path, + branch, + repo, + machine, + profile, + task, + merge: e.merge, + }) +} + +/// Starts `orch launch ID` in its own process session: it outlives the terminal and logs to `/logs/`. +pub fn spawn(db: &Db, id: &str) -> Result<()> { + let logs = crate::state_dir().join("logs"); + std::fs::create_dir_all(&logs)?; + let log = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(logs.join(format!("issue-{id}.log")))?; + let mut cmd = Command::new(std::env::current_exe()?); + cmd.args(["launch", id]) + .stdin(Stdio::null()) + .stdout(log.try_clone()?) + .stderr(log); + // SAFETY: setsid is async-signal-safe; it detaches the child from this terminal's session. + unsafe { + cmd.pre_exec(|| { + libc::setsid(); + Ok(()) + }); + } + let child = cmd.spawn()?; + // the child runs the session with this very pid: a second `orch up` sees it as live right away + db.set_pid(id, Some(child.id()))?; + Ok(()) +} + +/// What `orch up` did with one manifest entry. +pub struct Outcome { + pub session: String, + pub name: String, + pub what: String, +} + +/// Checks every entry of the manifest first and starts nothing when one is broken. Then, per worktree: a new +/// session is created and started; one that is still running or done is left alone; one that stopped unfinished +/// (suspended, or its process died) is started again. A failed one is left for `R` in `orch issues`. +pub fn up(arg: &str) -> Result> { + let file = manifest_path(arg)?; + let m: Manifest = toml::from_str(&std::fs::read_to_string(&file)?) + .with_context(|| file.display().to_string())?; + ensure!( + !m.issue.trim().is_empty(), + "{}: issue is empty", + file.display() + ); + ensure!(!m.sessions.is_empty(), "{}: no [[session]]", file.display()); + let planned = m + .sessions + .iter() + .map(|e| plan(e).with_context(|| format!("session {:?}", e.name))) + .collect::>>()?; + for (i, p) in planned.iter().enumerate() { + ensure!( + planned[..i].iter().all(|q| q.worktree != p.worktree), + "{} is listed twice", + p.worktree.display() + ); + } + let db = Db::open(&db_path())?; + let mut out = vec![]; + for p in planned { + let wt = p.worktree.to_string_lossy().into_owned(); + let last = db.sessions()?.into_iter().rev().find(|s| s.worktree == wt); + let (session, what) = match last { + Some(s) => { + let live = s.pid.is_some_and(crate::state::pid_alive); + let what = match s.status.as_str() { + "done" | "merged" => "done already".to_string(), + _ if live => "running already".into(), + "suspended" | "running" | "waiting" | "queued" => { + spawn(&db, &s.id)?; + "started again".into() + } + other => format!("{other}: restart it with R in orch issues"), + }; + (s.id, what) + } + None => { + let place = Place::Worktree { + path: p.worktree.clone(), + branch: p.branch.clone(), + }; + let repo_name = p.repo.file_name().unwrap_or_default().to_string_lossy(); + let s = crate::runner::create_in( + &db, + &crate::state_dir().join("worktrees"), + &p.name, + &repo_name, + &p.machine.to_string_lossy(), + &[], + &place, + !p.merge, + )?; + db.emit( + &s.id, + "options", + json!({ + "issue": m.issue, "repo": p.repo, "profile": p.profile, "task": p.task, + }), + )?; + spawn(&db, &s.id)?; + (s.id, "started".into()) + } + }; + out.push(Outcome { + session, + name: p.name, + what, + }); + } + Ok(out) +} + +/// `orch launch ID`: runs one session of the issues database to its end (started by [`spawn`]). +pub fn launch(id: &str) -> Result { + let db = Db::open(&db_path())?; + let s = db + .session(id)? + .with_context(|| format!("no session {id}"))?; + ensure!( + !matches!( + s.status.as_str(), + "done" | "merged" | "failed" | "escalated" | "aborted" + ), + "session {id} already ended ({})", + s.status + ); + let fallback = Profile::load("default")?; + let (m, repo, profile) = crate::runner::launch(&db, id, Path::new("."), &fallback)?; + crate::runner::run_session(&db, &m, id, &repo, "", &profile) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn manifest_defaults_and_unknown_keys() { + let m: Manifest = toml::from_str( + r#"issue = "ABC-1" +[[session]] +worktree = "~/wt" +name = "api" +machine = "m" +profile = "p" +"#, + ) + .unwrap(); + assert_eq!(m.sessions[0].task, ".hx/task.md"); + assert!(!m.sessions[0].merge); + assert!( + toml::from_str::("issue = \"x\"\nworkers = 2").is_err(), + "a typo must not pass silently" + ); + } + + #[test] + fn tilde_expands_to_home() { + let home = std::env::var("HOME").unwrap(); + assert_eq!(expand("~/a/b"), PathBuf::from(home).join("a/b")); + assert_eq!(expand("/x"), PathBuf::from("/x")); + } +} diff --git a/src/machine.rs b/src/machine.rs index d35e19a..6dfd1c7 100644 --- a/src/machine.rs +++ b/src/machine.rs @@ -134,8 +134,12 @@ impl Machine { v } - /// `.toml` in `/.hx/machines/`, then `~/.hx/machines/`. + /// `.toml` in `/.hx/machines/`, then `~/.hx/machines/`. An absolute path to a `.toml` file (what + /// `orch up` stores for an issue session) is loaded as it is. pub fn find(name: &str, repo: &Path) -> Result { + if Path::new(name).is_absolute() && name.ends_with(".toml") { + return Self::load(Path::new(name)); + } let file = format!("{name}.toml"); let dirs = Self::dirs(repo); for d in &dirs { diff --git a/src/main.rs b/src/main.rs index 5e26166..83cfe90 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,7 @@ mod db; mod detail; mod goal; mod init; +mod issue; mod junit; mod lock; mod machine; @@ -143,6 +144,13 @@ enum Cmd { #[arg(long, default_value = "default")] profile: String, }, + /// Start one detached session per worktree of an issue manifest (a file, or NAME in `manifest_dir`). + Up { manifest: String }, + /// The TUI on the sessions `orch up` started, grouped by issue. + Issues, + /// Run one session of the issues database (started by `orch up`, not by hand). + #[command(hide = true)] + Launch { id: String }, /// hx extension that enforces a run's tool allowlist (started by hx, not by hand). #[command(hide = true)] Guard { policy: PathBuf }, @@ -194,10 +202,47 @@ fn code(ok: bool) -> std::process::ExitCode { fn main() -> Result { let Some(cmd) = Cli::parse().cmd else { - tui::run()?; + tui::run(false)?; return Ok(code(true)); }; match cmd { + Cmd::Issues => { + tui::run(true)?; + Ok(code(true)) + } + Cmd::Up { manifest } => { + for o in issue::up(&manifest)? { + println!("{} {}: {}", o.session, o.name, o.what); + } + println!("watch them with: orch issues"); + Ok(code(true)) + } + Cmd::Launch { id } => match issue::launch(&id) { + Ok(status) => { + println!("{id} -> {status}"); + Ok(code(status == "merged" || status == "done")) + } + Err(e) => { + // the TUI shows why; without this the session would sit there as queued + if let Ok(db) = db::Db::open(&issue::db_path()) + && db.session(&id).ok().flatten().is_some_and(|s| { + !matches!( + s.status.as_str(), + "done" | "merged" | "failed" | "escalated" | "aborted" + ) + }) + { + let _ = db.set_session(&id, "", "failed"); + let _ = db.set_pid(&id, None); + let _ = db.emit( + &id, + "end", + serde_json::json!({"status": "failed", "reason": format!("{e:#}")}), + ); + } + Err(e) + } + }, Cmd::Init { repo, force } => { let written = init::run(&repo, &config_dir(), force)?; for p in &written { @@ -284,8 +329,7 @@ fn main() -> Result { ); anyhow::ensure!( s.pid - .is_none_or(|p| !Path::new(&format!("/proc/{p}")).exists() - || p == std::process::id()), + .is_none_or(|p| !state::pid_alive(p) || p == std::process::id()), "session {id} is still running (pid {})", s.pid.unwrap_or(0) ); diff --git a/src/place.rs b/src/place.rs index 8675b37..51fd5fa 100644 --- a/src/place.rs +++ b/src/place.rs @@ -1,4 +1,4 @@ -//! Where a new session works: a fresh branch and worktree (the default), or one the user names, such as a ticket +//! Where a new session works: a fresh branch and worktree (the default), or one the user names, such as an issue //! branch. orch never removes a worktree it did not create, so nothing here has a cleanup side. use crate::db::Db; @@ -90,12 +90,12 @@ pub fn ensure_free(db: &Db, place: &Place) -> Result<()> { let (branch, path) = match place { Place::Fresh => return Ok(()), Place::Branch(b) => (Some(b.as_str()), None), - Place::Worktree { path, branch } => (Some(branch.as_str()), Some(path)), + // the path alone: the same branch name in another repo (one issue, two repos) is another place + Place::Worktree { path, .. } => (None, Some(path)), }; for s in db.sessions()? { let live = matches!(s.status.as_str(), "queued" | "running" | "waiting") - && s.pid - .is_none_or(|p| Path::new(&format!("/proc/{p}")).exists()); + && s.pid.is_none_or(crate::state::pid_alive); let same = Some(s.branch.as_str()) == branch || path.is_some_and(|p| Path::new(&s.worktree) == p.as_path()); ensure!(!(live && same), "session {} already works there", s.id); @@ -158,7 +158,7 @@ end = "merged" ); assert!(resolve(&repo, "bad name").is_err()); assert!(resolve(&repo, "/nowhere/else").is_err()); - let wt = dir.join("ticket"); + let wt = dir.join("issue"); git( &repo, &["worktree", "add", "-b", "PROJ-9", &wt.to_string_lossy()], @@ -173,7 +173,7 @@ end = "merged" branch: "PROJ-9".into(), }; assert_eq!(resolve(&repo, "PROJ-9").unwrap(), want, "by branch"); - assert_eq!(resolve(&repo, "ticket").unwrap(), want, "by directory name"); + assert_eq!(resolve(&repo, "issue").unwrap(), want, "by directory name"); assert_eq!( resolve(&repo, &listed[0].path.to_string_lossy()).unwrap(), want, @@ -185,18 +185,20 @@ end = "merged" #[test] fn named_worktree_is_used_kept_and_not_merged_on_request() { let (dir, repo, db) = setup("named"); - let wt = dir.join("ticket"); + let wt = dir.join("issue"); git( &repo, &["worktree", "add", "-b", "PROJ-9", &wt.to_string_lossy()], ) .unwrap(); let place = resolve(&repo, "PROJ-9").unwrap(); - let s = runner::create_in(&db, &dir.join("wts"), "t", "m", &[], &place, true).unwrap(); + let s = runner::create_in(&db, &dir.join("wts"), "t", "", "m", &[], &place, true).unwrap(); assert_eq!(s.branch, "PROJ-9"); assert_eq!(db.session(&s.id).unwrap().unwrap().worktree, s.worktree); // a second session may not take the same worktree while the first is live - assert!(runner::create_in(&db, &dir.join("wts"), "u", "m", &[], &place, false).is_err()); + assert!( + runner::create_in(&db, &dir.join("wts"), "u", "", "m", &[], &place, false).is_err() + ); let m = Machine::parse(M).unwrap(); let status = runner::run_session(&db, &m, &s.id, &repo, "", &Profile::parse("").unwrap()).unwrap(); @@ -219,6 +221,7 @@ end = "merged" &db, &dir.join("wts"), b, + "", "m", &[], &Place::Branch(b.into()), diff --git a/src/profile.rs b/src/profile.rs index 0acb1e7..80007ef 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -178,6 +178,13 @@ impl Profile { f } + /// A profile file named by its path (an issue session's profile in its worktree). + pub fn load_path(path: &std::path::Path) -> Result { + let s = + std::fs::read_to_string(path).with_context(|| format!("profile {}", path.display()))?; + Self::parse(&s).with_context(|| path.display().to_string()) + } + pub fn load(name: &str) -> Result { if name.is_empty() || name.contains(['/', '.']) { bail!("bad profile name {name:?}"); diff --git a/src/runner.rs b/src/runner.rs index 067c354..015269f 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -15,7 +15,7 @@ use serde_json::{Value, json}; use std::cell::{Cell, RefCell}; use std::io::Read; use std::os::unix::process::CommandExt; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::time::{Duration, Instant}; @@ -82,10 +82,12 @@ pub fn create_after( /// Like [`create_after`], working in a branch or worktree the user named. With `no_merge` the session stops at /// `done` where its machine would run the state that ends as `merged`, and leaves the branch for a pull request. +#[allow(clippy::too_many_arguments)] // shortcut: one caller each in the TUI form and `orch up` pub fn create_in( db: &Db, worktrees: &Path, name: &str, + subtitle: &str, machine: &str, after: &[String], place: &crate::place::Place, @@ -93,7 +95,7 @@ pub fn create_in( ) -> Result { use crate::place::Place; crate::place::ensure_free(db, place)?; - let mut s = create_after(db, worktrees, name, "", machine, after)?; + let mut s = create_after(db, worktrees, name, subtitle, machine, after)?; match place { Place::Fresh => {} Place::Branch(b) => s.branch = b.clone(), @@ -127,7 +129,7 @@ fn ensure_worktree(repo: &Path, s: &Session) -> Result<()> { std::fs::create_dir_all(wt.parent().context("worktree has no parent")?)?; // git races on its own locks when worktrees are added in parallel let _l = crate::lock::lock(&repo.join(".git/orch-worktree.lock"))?; - // a branch the user named may exist already (a ticket branch): check it out instead of creating it + // a branch the user named may exist already (an issue branch): check it out instead of creating it let exists = git( repo, &[ @@ -386,6 +388,8 @@ struct Ctx<'a> { repo: &'a Path, ctl: Ctl<'a>, agent: Option, + /// The task text (`orch up` reads it from the worktree's task file); empty for other sessions. + body: String, } enum Outcome { @@ -676,7 +680,7 @@ fn run_command(cx: &Ctx, st: &State, step: &Step) -> Result { } /// Instruction text for a prompt kind. The kind itself is sent too, so hx can use its own prompts. -fn instruction(kind: &str, goal: Option<&str>, t: &Task) -> String { +fn instruction(kind: &str, goal: Option<&str>, t: &Task, body: &str) -> String { let lead = match kind { "plan" => "Plan the work for this task. Report the plan with hx/plan.", "implement" => "Implement this task, following the plan.", @@ -689,6 +693,9 @@ fn instruction(kind: &str, goal: Option<&str>, t: &Task) -> String { if let Some(g) = goal { s.push_str(&format!("\nGoal: {g}")); } + if !body.trim().is_empty() { + s.push_str(&format!("\n\n{}", body.trim())); + } s } @@ -730,7 +737,7 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result { let agent = cx.agent.as_mut().expect("spawned above"); let r: StepResult = agent.step( kind, - &instruction(kind, goal.as_deref(), cx.task), + &instruction(kind, goal.as_deref(), cx.task, &cx.body), context, json!({}), &mut sink, @@ -887,6 +894,34 @@ impl Sink for DbSink<'_> { } } +/// What session `id` runs with: its machine, repo and profile. A issue session (`orch up`) carries its own repo +/// and profile file in its options; any other session uses `repo` and `profile`. +pub fn launch( + db: &Db, + id: &str, + repo: &Path, + profile: &Profile, +) -> Result<(Machine, PathBuf, Profile)> { + let s = db + .session(id)? + .with_context(|| format!("no session {id}"))?; + let task = db + .tasks()? + .into_iter() + .find(|t| t.id == s.task_id) + .with_context(|| format!("no task {}", s.task_id))?; + let o = db.options(id)?; + let repo = o + .get("repo") + .and_then(Value::as_str) + .map_or_else(|| repo.to_path_buf(), PathBuf::from); + let profile = match o.get("profile").and_then(Value::as_str) { + Some(p) => Profile::load_path(Path::new(p))?, + None => profile.clone(), + }; + Ok((Machine::find(&task.machine, &repo)?, repo, profile)) +} + /// Runs the session to the end of its machine and returns the final status (`merged`, `escalated`, `failed`, ...). /// Resumes at `current_state` when the session was started before (orchestrator restart). pub fn run_session( @@ -929,6 +964,12 @@ pub fn run_session( repo, ctl, agent: None, + body: db + .options(id)? + .get("task") + .and_then(Value::as_str) + .unwrap_or_default() + .into(), }; let mut resumed = !s.state.is_empty(); let (mut cur, mut from) = if resumed { @@ -938,10 +979,7 @@ pub fn run_session( (m.start().name.clone(), String::new()) }; db.set_pid(id, Some(std::process::id()))?; - let no_merge = db - .events(Some(id), 0)? - .iter() - .any(|e| e.kind == "options" && e.payload["no_merge"] == true); + let no_merge = db.options(id)?.get("no_merge") == Some(&json!(true)); for _ in 0..MAX_TRANSITIONS { let st = m .state(&cur) @@ -1074,9 +1112,7 @@ 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) + crate::state::pid_alive(pid) } /// Joins the merge queue and blocks until this session is at the head. @@ -1795,7 +1831,7 @@ end = "merged" 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 + // a crashed orchestrator left its issue at the head; its pid is gone e.db.add_session(&Session { id: "s9".into(), task_id: "s1".into(), diff --git a/src/state.rs b/src/state.rs index c7a07b7..e04288a 100644 --- a/src/state.rs +++ b/src/state.rs @@ -156,6 +156,13 @@ impl Run { } } +/// Does a process with this pid exist? Works on Linux and macOS (no `/proc` there). +pub fn pid_alive(pid: u32) -> bool { + // 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) +} + pub fn kill_group(pgid: u32) { // SAFETY: plain syscall; hx is spawned with process_group(0) so pgid == its pid. unsafe { libc::killpg(pgid as i32, libc::SIGKILL) }; diff --git a/src/tui/host.rs b/src/tui/host.rs index 46ad818..b51723c 100644 --- a/src/tui/host.rs +++ b/src/tui/host.rs @@ -2,16 +2,17 @@ //! suspends them (state kept), and `orch session --resume` or the TUI's resume key continues them. use crate::db::Db; -use crate::machine::Machine; use crate::profile::Profile; use crate::runner; -use anyhow::{Context, Result}; +use anyhow::Result; use std::collections::VecDeque; use std::path::PathBuf; use std::thread::JoinHandle; use std::time::{Duration, Instant}; pub struct Host { + /// The database the sessions live in: the repo's `.hx/orch.db`, or the issues database. + db_path: PathBuf, repo: PathBuf, profile: Profile, /// Sessions that wait for a free slot, oldest first. @@ -20,8 +21,9 @@ pub struct Host { } impl Host { - pub fn new(repo: PathBuf, profile: Profile) -> Self { + pub fn new(db_path: PathBuf, repo: PathBuf, profile: Profile) -> Self { Self { + db_path, repo, profile, pending: VecDeque::new(), @@ -75,18 +77,10 @@ impl Host { } fn start(&self, id: &str) -> Result> { - let (repo, profile, id) = (self.repo.clone(), self.profile.clone(), id.to_string()); + let id = id.to_string(); // fail here, on the caller's thread, when the session or its machine is missing - let db = Db::open(&repo.join(".hx/orch.db"))?; - let s = db - .session(&id)? - .with_context(|| format!("no session {id}"))?; - let task = db - .tasks()? - .into_iter() - .find(|t| t.id == s.task_id) - .with_context(|| format!("no task {}", s.task_id))?; - let m = Machine::find(&task.machine, &repo)?; + let db = Db::open(&self.db_path)?; + let (m, repo, profile) = runner::launch(&db, &id, &self.repo, &self.profile)?; Ok(std::thread::spawn(move || { if let Err(e) = runner::run_session(&db, &m, &id, &repo, "", &profile) { let _ = db.set_session(&id, "", "failed"); @@ -126,9 +120,7 @@ pub fn resumable(db: &Db) -> Vec { .into_iter() .filter(|s| match s.status.as_str() { "suspended" => true, - "running" | "waiting" => s - .pid - .is_none_or(|p| !std::path::Path::new(&format!("/proc/{p}")).exists()), + "running" | "waiting" => s.pid.is_none_or(|p| !crate::state::pid_alive(p)), _ => false, }) .map(|s| s.id) @@ -210,7 +202,11 @@ end = "merged" for n in ["one", "two"] { runner::create_after(&db, &dir.join("wt"), n, "", "sleeper", &[]).unwrap(); } - let mut host = Host::new(repo.clone(), Profile::parse("workers = 1").unwrap()); + let mut host = Host::new( + repo.join(".hx/orch.db"), + repo.clone(), + Profile::parse("workers = 1").unwrap(), + ); host.submit("s1"); host.submit("s2"); host.submit("s2"); // twice is once diff --git a/src/tui/mod.rs b/src/tui/mod.rs index 67ca8ea..83c5205 100644 --- a/src/tui/mod.rs +++ b/src/tui/mod.rs @@ -18,11 +18,17 @@ use std::io::IsTerminal; use std::path::{Path, PathBuf}; use std::time::Duration; -pub fn run() -> Result<()> { +/// The TUI on the current directory's `.hx/orch.db`, or with `issues` on the database of `orch up`. +pub fn run(issues: bool) -> Result<()> { if !std::io::stdout().is_terminal() { bail!("orch needs a terminal; use a subcommand (orch --help) in scripts"); } let mut app = App::new(std::env::current_dir()?); + if issues { + app.db_path = crate::issue::db_path(); + app.issues = true; + app.rev = "all repos".into(); + } let mut term = ratatui::init(); let res = event_loop(&mut term, &mut app); ratatui::restore(); @@ -155,6 +161,10 @@ struct Pager { struct App { repo: PathBuf, + /// `/.hx/orch.db`, or the issues database. + db_path: PathBuf, + /// Showing the sessions of `orch up` (many repos): no new-session form and no checks on main. + issues: bool, /// Opened lazily: launching `orch` in a directory without a goal must not create `.hx/orch.db`. db: Option, events: Vec, @@ -185,7 +195,11 @@ impl App { fn ensure_host(&mut self) -> Result<&mut host::Host> { if self.host.is_none() { let profile = crate::profile::Profile::load(PROFILE)?; - self.host = Some(host::Host::new(self.repo.clone(), profile)); + self.host = Some(host::Host::new( + self.db_path.clone(), + self.repo.clone(), + profile, + )); } Ok(self.host.as_mut().expect("just created")) } @@ -194,6 +208,14 @@ impl App { fn resume_all(&mut self) -> Result { let Some(db) = &self.db else { return Ok(0) }; let ids = host::resumable(db); + if self.issues { + // issue sessions run detached, like `orch up` starts them: they outlive this TUI + for id in &ids { + crate::issue::spawn(db, id)?; + } + self.refresh(); + return Ok(ids.len()); + } let host = self.ensure_host()?; let ids: Vec = ids.into_iter().filter(|id| !host.hosts(id)).collect(); for id in &ids { @@ -209,7 +231,11 @@ impl App { bail!("no database") }; db.reopen(id)?; - self.ensure_host()?.submit(id); + if self.issues { + crate::issue::spawn(db, id)?; + } else { + self.ensure_host()?.submit(id); + } self.refresh(); Ok(()) } @@ -247,7 +273,7 @@ impl App { let db = self.db.as_ref().expect("db_or_create opened it"); let base = self.repo.file_name().unwrap_or_default(); let wts = crate::state_dir().join("worktrees").join(base); - let s = crate::runner::create_in(db, &wts, name, machine, &after, &place, f.no_merge)?; + let s = crate::runner::create_in(db, &wts, name, "", machine, &after, &place, f.no_merge)?; if let Some(h) = &mut self.host { h.submit(&s.id); } @@ -272,7 +298,7 @@ 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) { + if self.issues || self.checks_running.swap(true, Ordering::SeqCst) { return; // already running } let (repo, flag) = (self.repo.clone(), self.checks_running.clone()); @@ -287,7 +313,7 @@ impl App { /// 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 = Db::open(&self.db_path).ok(); } self.db.as_ref() } @@ -429,6 +455,8 @@ impl App { fn new(repo: PathBuf) -> Self { let rev = git_rev(&repo); Self { + db_path: repo.join(".hx/orch.db"), + issues: false, repo, db: None, events: vec![], @@ -451,9 +479,8 @@ impl App { } fn refresh(&mut self) { - let path = self.repo.join(".hx/orch.db"); - if self.db.is_none() && path.exists() { - self.db = Db::open(&path).ok(); + if self.db.is_none() && self.db_path.exists() { + self.db = Db::open(&self.db_path).ok(); } if let (Some(h), Some(db)) = (&mut self.host, &self.db) { h.tick(db); @@ -496,7 +523,11 @@ impl App { fn header(&self) -> Header { let home = std::env::var("HOME").unwrap_or_default(); - let repo = self.repo.to_string_lossy().into_owned(); + let repo = if self.issues { + "issues".to_string() + } else { + self.repo.to_string_lossy().into_owned() + }; let repo = match repo.strip_prefix(&home) { Some(rest) if !home.is_empty() => format!("~{rest}"), _ => repo, @@ -907,7 +938,9 @@ fn on_key( app.screen = Screen::Goal; app.refresh(); } - KeyCode::Char('N') => app.form = Some(newform::Form::new(&app.repo)), + KeyCode::Char('N') if !app.issues => { + app.form = Some(newform::Form::new(&app.repo)); + } KeyCode::Char('u') if app.overview.resumable > 0 => { if let Err(e) = app.resume_all() { app.pager = Some(Pager { @@ -1147,6 +1180,7 @@ mod tests { ok, last: &str| Row { id: id.into(), + group: String::new(), status, task: task.into(), sub: sub.into(), @@ -1921,7 +1955,7 @@ end = "merged" } let err = app.start_session(&form).unwrap_err().to_string(); assert!(err.contains("name"), "{err}"); - form.name = "ticket work".into(); + form.name = "issue work".into(); form.after = "s1, s9".into(); let err = app.start_session(&form).unwrap_err().to_string(); assert!(err.contains("no session s9"), "{err}"); diff --git a/src/tui/overview.rs b/src/tui/overview.rs index edb448c..b2a436f 100644 --- a/src/tui/overview.rs +++ b/src/tui/overview.rs @@ -34,7 +34,7 @@ pub fn draw(f: &mut Frame, o: &Overview, h: &Header, sel: usize, need_sel: usize keys.push(("R", "restart")); } let key_lines = theme::key_lines(&keys, area.width); - let rows_h = (o.rows.len().max(1) * 2 + 3) as u16; + let rows_h = (o.rows.len().max(1) * 2 + groups(o) + 3) as u16; let sessions_h = rows_h.clamp(5, area.height.saturating_sub(14).max(5)); let [head, stats, sessions, lower, keys] = Layout::vertical([ Constraint::Length(1), @@ -206,6 +206,15 @@ fn ctx_bar(pct: u8) -> Span<'static> { ) } +/// Group heading lines: one per run of rows with the same non-empty issue. +fn groups(o: &Overview) -> usize { + o.rows + .iter() + .enumerate() + .filter(|(i, r)| !r.group.is_empty() && (*i == 0 || o.rows[i - 1].group != r.group)) + .count() +} + fn sessions_box(f: &mut Frame, area: Rect, o: &Overview, sel: usize) { let block = boxed("Sessions", Some(o.rows.len()), theme::TEXT, theme::BORDER); let inner = block.inner(area); @@ -233,6 +242,12 @@ fn sessions_box(f: &mut Frame, area: Rect, o: &Overview, sel: usize) { head.push(Span::raw("last activity")); let mut lines = vec![Line::from(head).style(fg(theme::DIM))]; for (i, r) in o.rows.iter().enumerate() { + if !r.group.is_empty() && (i == 0 || o.rows[i - 1].group != r.group) { + lines.push(Line::from(Span::styled( + format!(" ── {}", r.group), + bold(theme::TEXT), + ))); + } let on = i == sel; let cursor = if on { Span::styled("▶ ", fg(theme::RUN)) diff --git a/src/view.rs b/src/view.rs index 1718e14..10d9d24 100644 --- a/src/view.rs +++ b/src/view.rs @@ -47,6 +47,8 @@ pub struct Chip { #[derive(Clone, PartialEq, Debug)] pub struct Row { pub id: String, + /// The issue of an `orch up` session; rows are sorted by it and the overview heads each group. + pub group: String, pub status: Status, pub task: String, pub sub: String, @@ -248,8 +250,19 @@ pub fn build(i: &Input) -> Overview { Status::Fail => {} } o.cost += scan.cost; + let group = evs + .iter() + .rev() + .find_map(|e| { + (e.kind == "options") + .then(|| e.payload["issue"].as_str()) + .flatten() + }) + .unwrap_or_default() + .to_string(); o.rows.push(Row { id: s.id.clone(), + group, status, task: task.name.clone(), sub: task.subtitle.clone(), @@ -265,6 +278,7 @@ pub fn build(i: &Input) -> Overview { last, }); } + o.rows.sort_by(|a, b| a.group.cmp(&b.group)); // stable: within a group, session order stays o.needs.extend(escalated); if !i.checks.is_empty() { let green = i @@ -713,6 +727,40 @@ mod tests { ); } + #[test] + fn rows_group_by_issue_in_session_order() { + let events = vec![ + ev(1, "s1", "options", json!({"issue": "B-2"})), + ev(2, "s2", "options", json!({"issue": "A-1"})), + ev(3, "s3", "options", json!({"no_merge": true})), + ev(4, "s4", "options", json!({"issue": "B-2"})), + ]; + let tasks: Vec<_> = ["s1", "s2", "s3", "s4"].map(|i| task(i, i, &[])).into(); + let sessions: Vec<_> = ["s1", "s2", "s3", "s4"] + .map(|i| session(i, i, "", "queued")) + .into(); + let o = build(&Input { + goal: None, + tasks: &tasks, + sessions: &sessions, + events: &events, + machines: &machines(), + needs: &[], + checks: &[], + decisions: &[], + now_ms: 0, + }); + let got: Vec<_> = o + .rows + .iter() + .map(|r| (r.id.as_str(), r.group.as_str())) + .collect(); + assert_eq!( + got, + [("s3", ""), ("s2", "A-1"), ("s1", "B-2"), ("s4", "B-2")] + ); + } + #[test] fn helpers() { assert_eq!(ago(5), "5s"); diff --git a/tests/all.sh b/tests/all.sh index 79098d6..1b1252a 100644 --- a/tests/all.sh +++ b/tests/all.sh @@ -7,6 +7,7 @@ cargo clippy -q --all-targets -- -D warnings cargo test -q cargo build -q python3 tests/e2e.py +python3 tests/issues.py python3 spike/check.py ./target/debug/orch bench eval --check diff --git a/tests/issues.py b/tests/issues.py new file mode 100644 index 0000000..9db43a3 --- /dev/null +++ b/tests/issues.py @@ -0,0 +1,113 @@ +"""orch up: one manifest, worktrees in two repos, detached sessions in the issues database, rerun, kill.""" +import json, os, pathlib, sqlite3, subprocess, sys, tempfile, time + +root = pathlib.Path(__file__).resolve().parent.parent +orch = sys.argv[1] if len(sys.argv) > 1 else str(root / "target/debug/orch") +tmp = pathlib.Path(tempfile.mkdtemp()) +cfg, state = tmp / "cfg", tmp / "state" +env = {**os.environ, "ORCH_CONFIG_DIR": str(cfg), "ORCH_STATE_DIR": str(state)} + +QUICK = """name = "quick" +[[state]] +name = "work" +kind = "start" +steps = [{ name = "w", run = "computer", cmd = "cp .hx/task.md seen.txt" }] +next = "merge" +[[state]] +name = "merge" +kind = "exit" +steps = [{ name = "never", run = "computer", cmd = "touch merged-it" }] +end = "merged" +""" +SLOW = QUICK.replace('"quick"', '"slow"').replace("cp .hx/task.md seen.txt", "sleep 60") + + +def git(cwd, *a): + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *a], cwd=cwd, check=True, capture_output=True) + + +def worktree(repo_name, machine): + repo = tmp / repo_name + repo.mkdir() + git(repo, "init", "-q", "-b", "main") + (repo / "f").write_text("x") + git(repo, "add", "-A") + git(repo, "commit", "-qm", "init") + wt = tmp / f"{repo_name}-abc" + git(repo, "worktree", "add", "-q", "-b", "abc-1", str(wt)) + (wt / ".hx/machines").mkdir(parents=True) + (wt / ".hx/profiles").mkdir(parents=True) + (wt / ".hx/machines/abc.toml").write_text(machine) + (wt / ".hx/profiles/abc.toml").write_text("max_retries = 0\n") + (wt / ".hx/task.md").write_text(f"do the {repo_name} part\n") + return repo, wt + + +api, api_wt = worktree("api", QUICK) +web, web_wt = worktree("web", SLOW) + +# the manifest lives where config.toml says, not in the default place +issues = tmp / "my-manifests" +issues.mkdir() +cfg.mkdir() +(cfg / "config.toml").write_text(f'manifest_dir = "{issues}"\n') +entry = lambda wt, name: f'[[session]]\nworktree = "{wt}"\nname = "{name}"\nmachine = "abc"\nprofile = "abc"\n' +(issues / "ABC-1.toml").write_text('issue = "ABC-1"\n' + entry(api_wt, "api part") + entry(web_wt, "web part")) + + +def up(name="ABC-1"): + return subprocess.run([orch, "up", name], env=env, capture_output=True, text=True, timeout=30) + + + + +def sessions(): + c = sqlite3.connect(state / "issues.db") + rows = c.execute("select id, worktree, status, pid from sessions order by id").fetchall() + c.close() + return {r[0]: {"worktree": r[1], "status": r[2], "pid": r[3]} for r in rows} + + +def wait(sid, statuses, secs=20): + end = time.time() + secs + while time.time() < end: + s = sessions().get(sid) + if s and s["status"] in statuses: + return s + time.sleep(0.1) + raise AssertionError(f"{sid} never reached {statuses}: {sessions()} {(state / 'logs' / f'issue-{sid}.log').read_text()}") + + +# a broken entry starts nothing +(issues / "BAD.toml").write_text('issue = "BAD"\n' + entry(api_wt, "ok") + entry(tmp / "nope", "missing")) +p = up("BAD") +assert p.returncode != 0 and "missing" in p.stderr, p.stderr +assert not (state / "issues.db").exists() or not sessions(), "nothing may start when one entry is broken" + +p = up() +assert p.returncode == 0, p.stderr +assert "s1 api part: started" in p.stdout and "s2 web part: started" in p.stdout, p.stdout +wait("s1", {"done"}) +assert (api_wt / "seen.txt").read_text() == "do the api part\n", "the step ran in the user's worktree" +assert not (api_wt / "merged-it").exists(), "stops at done, no merge" +wait("s2", {"running"}) + +c = sqlite3.connect(state / "issues.db") +opts = [json.loads(r[0]) for r in c.execute("select payload from events where session_id = 's1' and kind = 'options'")] +merged = {k: v for o in opts for k, v in o.items()} +assert merged["issue"] == "ABC-1" and merged["task"] == "do the api part\n" and merged["no_merge"] is True, merged +assert merged["repo"] == str(api.resolve()), merged +sub = c.execute("select subtitle from tasks where id = 's2'").fetchone()[0] +assert sub == "web", sub + +# running it again starts nothing twice +p = up() +assert "s1 api part: done already" in p.stdout and "s2 web part: running already" in p.stdout, p.stdout +assert len(sessions()) == 2 + +# kill, as the TUI's k does: an abort command through the database reaches the detached process +c.execute("insert into commands(session_id, kind, payload, at) values ('s2', 'abort', '{}', 0)") +c.commit() +s = wait("s2", {"aborted", "failed"}) +c.close() +print("issues ok", s["status"])