//! 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() } "aborted" => "aborted: orch down --forget, then orch up starts it fresh".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 down MANIFEST [--forget]`: stops every session of the manifest's worktrees. A live one gets the same /// abort as `k` in the TUI (hx stops, the machine runs its `on abort` state); one whose process is gone is marked /// aborted, so `orch up` does not start it again. With `forget`, sessions are deleted with their logs once their /// process has exited, and a later `orch up` starts fresh. The worktrees and branches stay. pub fn down(arg: &str, forget: bool) -> Result> { let file = manifest_path(arg)?; let m: Manifest = toml::from_str(&std::fs::read_to_string(&file)?) .with_context(|| file.display().to_string())?; // no `plan`: a worktree that is gone by now must not keep its sessions from being stopped let entries = m .sessions .iter() .map(|e| { let p = expand(&e.worktree); (e.name.clone(), p.canonicalize().unwrap_or(p)) }) .collect::>(); let db = Db::open(&db_path())?; let out = down_in(&db, &entries, forget, std::time::Duration::from_secs(60))?; for o in out.iter().filter(|o| o.what == "forgotten") { let log = format!("issue-{}.log", o.session); let _ = std::fs::remove_file(crate::state_dir().join("logs").join(log)); } Ok(out) } fn down_in( db: &Db, entries: &[(String, PathBuf)], forget: bool, wait: std::time::Duration, ) -> Result> { let live = |s: &crate::db::Session| s.pid.is_some_and(crate::state::pid_alive); let mut out = vec![]; let mut aborted = vec![]; for (name, wt) in entries { let wt = wt.to_string_lossy(); let sessions: Vec<_> = db .sessions()? .into_iter() .filter(|s| s.worktree == wt) .collect(); if sessions.is_empty() { out.push(Outcome { session: "-".into(), name: name.clone(), what: "no session".into(), }); } for s in sessions { let what = match s.status.as_str() { "done" | "merged" | "failed" | "escalated" | "aborted" if !live(&s) => { format!("{} already", s.status) } _ if live(&s) => { db.add_command(&s.id, "abort", &json!({}))?; aborted.push(s.id.clone()); "aborting".into() } _ => { db.set_session(&s.id, &s.state, "aborted")?; db.set_pid(&s.id, None)?; "aborted (its process was gone)".into() } }; out.push(Outcome { session: s.id, name: name.clone(), what, }); } } if !forget { return Ok(out); } let until = std::time::Instant::now() + wait; while std::time::Instant::now() < until && aborted .iter() .any(|id| db.session(id).ok().flatten().is_some_and(|s| live(&s))) { std::thread::sleep(std::time::Duration::from_millis(250)); } for o in out.iter_mut().filter(|o| o.session != "-") { match db.session(&o.session)? { Some(s) if live(&s) => { o.what = "still running after the abort; run orch down --forget again".into(); } Some(_) => { db.forget(&o.session)?; o.what = "forgotten".into(); } None => {} } } 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 down_stops_then_forgets() { let d = std::env::temp_dir().join(format!("orch-down-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); let db = Db::open(&d.join("issues.db")).unwrap(); let add = |id: &str, wt: &str, status: &str| { db.add_session(&crate::db::Session { id: id.into(), task_id: id.into(), branch: "b".into(), worktree: wt.into(), pid: None, state: "work".into(), status: status.into(), }) .unwrap(); db.emit(id, "options", json!({"issue": "X"})).unwrap(); }; add("s1", "/wt/a", "suspended"); add("s2", "/wt/b", "done"); add("s3", "/wt/other", "suspended"); let entries = [ ("a".to_string(), PathBuf::from("/wt/a")), ("b".to_string(), PathBuf::from("/wt/b")), ("c".to_string(), PathBuf::from("/wt/c")), ]; let zero = std::time::Duration::ZERO; let what = |out: Vec| out.into_iter().map(|o| o.what).collect::>(); let out = down_in(&db, &entries, false, zero).unwrap(); assert_eq!( what(out), ["aborted (its process was gone)", "done already", "no session"] ); assert_eq!(db.session("s1").unwrap().unwrap().status, "aborted"); let out = down_in(&db, &entries, true, zero).unwrap(); assert_eq!(what(out), ["forgotten", "forgotten", "no session"]); assert!(db.session("s1").unwrap().is_none()); assert!(db.events(Some("s2"), 0).unwrap().is_empty()); assert_eq!( db.session("s3").unwrap().unwrap().status, "suspended", "another issue's session is untouched" ); // a live process gets the abort command and is kept until it exits let mut child = Command::new("sleep").arg("30").spawn().unwrap(); add("s4", "/wt/a", "running"); db.set_pid("s4", Some(child.id())).unwrap(); let ms = std::time::Duration::from_millis(300); let out = down_in(&db, &entries[..1], true, ms).unwrap(); child.kill().unwrap(); child.wait().unwrap(); assert_eq!( what(out), ["still running after the abort; run orch down --forget again"] ); let cmds = db.take_commands("s4").unwrap(); assert_eq!(cmds[0].0, "abort"); } #[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")); } }