From c59924fc0fda1212f1660766b7e8e84aa4985cc3 Mon Sep 17 00:00:00 2001 From: Johannes Kresner Date: Tue, 17 Nov 2026 16:41:01 +0100 Subject: [PATCH] feat: orch down stops an issue's sessions, --forget deletes them Live sessions get the abort `k` sends; unfinished ones whose process is gone are marked aborted so `orch up` leaves them alone. --forget waits for the aborted ones to exit, then deletes their rows and logs. Worktrees stay. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++- src/db.rs | 11 ++++ src/issue.rs | 161 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 13 +++++ 4 files changed, 191 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index dd9a98c..3c759a7 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ git host: tasks come from a folder or any JSON command, results go to a local br 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 down MANIFEST [--forget] stop those sessions; --forget also deletes them orch issues TUI on the sessions `orch up` started, grouped by issue ## How a run goes @@ -129,8 +130,11 @@ when one is broken, then starts one detached session per worktree and returns. L `/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`): +`u` and `R` start sessions detached again. `orch down ABC-123` stops the issue's sessions: running ones get the +same abort as `k`, unfinished ones whose process is gone are marked aborted, so `orch up` leaves them alone. +`--forget` then deletes the sessions and their logs (it waits up to a minute for aborted ones to exit), so `orch +issues` no longer lists them and the next `orch up` starts fresh. Worktrees and branches stay. `manifest_dir` +defaults to `/manifests` and is set in `/config.toml` (`~/.config/orch/config.toml`): ```toml manifest_dir = "~/notes/manifests" diff --git a/src/db.rs b/src/db.rs index 0895b0f..636847d 100644 --- a/src/db.rs +++ b/src/db.rs @@ -399,6 +399,17 @@ impl Db { Ok(()) } + /// Deletes a session and everything recorded for it. + pub fn forget(&self, id: &str) -> Result<()> { + let tx = self.conn.unchecked_transaction()?; + for t in ["events", "decisions", "commands", "merge_queue", "needs"] { + tx.execute(&format!("delete from {t} where session_id = ?1"), [id])?; + } + tx.execute("delete from sessions where id = ?1", [id])?; + tx.commit()?; + Ok(()) + } + pub fn set_pid(&self, id: &str, pid: Option) -> Result<()> { self.conn.execute( "update sessions set pid = ?2 where id = ?1", diff --git a/src/issue.rs b/src/issue.rs index 1053ec6..ffe1c87 100644 --- a/src/issue.rs +++ b/src/issue.rs @@ -245,6 +245,7 @@ pub fn up(arg: &str) -> Result> { 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) @@ -285,6 +286,104 @@ pub fn up(arg: &str) -> Result> { 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())?; @@ -328,6 +427,68 @@ profile = "p" ); } + #[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(); diff --git a/src/main.rs b/src/main.rs index 83cfe90..1f15932 100644 --- a/src/main.rs +++ b/src/main.rs @@ -146,6 +146,13 @@ enum Cmd { }, /// Start one detached session per worktree of an issue manifest (a file, or NAME in `manifest_dir`). Up { manifest: String }, + /// Stop the sessions of an issue manifest: live ones are aborted, the rest marked aborted. Worktrees stay. + Down { + manifest: String, + /// Then delete the sessions and their logs, so `orch issues` no longer shows them and `orch up` starts fresh. + #[arg(long)] + forget: bool, + }, /// 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). @@ -217,6 +224,12 @@ fn main() -> Result { println!("watch them with: orch issues"); Ok(code(true)) } + Cmd::Down { manifest, forget } => { + for o in issue::down(&manifest, forget)? { + println!("{} {}: {}", o.session, o.name, o.what); + } + Ok(code(true)) + } Cmd::Launch { id } => match issue::launch(&id) { Ok(status) => { println!("{id} -> {status}");