diff --git a/README.md b/README.md index 4e43b33..7e82c79 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ git host: tasks come from a folder or any JSON command, results go to a local br orch session --repo DIR --machine M --name N create a state-machine session and run it [--profile P] [--after s1,s2] [--scope S] orch session --repo DIR --resume sN continue an unfinished session from its saved state + orch session --repo DIR --restart sN continue a failed or escalated session where it stopped 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 @@ -71,6 +72,8 @@ the branch stays for a pull request. Sessions started this way run on threads of `default` profile at a time (the rest wait as `queued`; sessions waiting for `--after` take no slot). `q` while they run asks for `yes` and suspends them; `u` on the overview resumes every suspended session and every one whose process died (it shows in the key bar with a count); `orch session --resume sN` does the same for one session from a shell. +A session that ended `failed` or `escalated` is continued at the state where it stopped with `R` on its row (or the +session screen) or `orch session --repo . --restart sN`. Budgets and retry counts start again from that point. On a permission request in the Needs-you box: `y` allow once, `Y` always for that session, `n` deny, `A` allow once every pending request that asks for the same thing (any session), and `P` save an allow rule to the profile diff --git a/src/budget.rs b/src/budget.rs index bed76ee..a815e90 100644 --- a/src/budget.rs +++ b/src/budget.rs @@ -62,7 +62,10 @@ pub struct Exceeded { pub limit: String, } -pub fn exceeded(evs: &[&Event], cfg: &BudgetCfg, now_ms: u64) -> Option { +/// A restarted session gets a fresh budget: only the events from its last `restart` count. +pub fn exceeded(all: &[&Event], cfg: &BudgetCfg, now_ms: u64) -> Option { + let restarted = all.iter().rposition(|e| e.kind == "restart"); + let evs = &all[restarted.unwrap_or(0)..]; if let Some(limit) = cfg.wall_secs { let used = active_secs(evs, now_ms); if used > limit { @@ -74,7 +77,12 @@ pub fn exceeded(evs: &[&Event], cfg: &BudgetCfg, now_ms: u64) -> Option limit { return Some(Exceeded { what: "cost", diff --git a/src/db.rs b/src/db.rs index 1c7fad3..1176ad7 100644 --- a/src/db.rs +++ b/src/db.rs @@ -369,6 +369,23 @@ impl Db { 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) -> Result<()> { self.conn.execute( "update sessions set pid = ?2 where id = ?1", @@ -493,10 +510,12 @@ impl Db { } /// 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 { 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 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), )?; @@ -566,6 +585,18 @@ mod tests { 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(); diff --git a/src/main.rs b/src/main.rs index d00384d..5e26166 100644 --- a/src/main.rs +++ b/src/main.rs @@ -126,13 +126,16 @@ enum Cmd { #[arg(long)] repo: PathBuf, /// Machine file name, without .toml (looked up in REPO/.hx/machines, then ~/.hx/machines). - #[arg(long, required_unless_present = "resume")] + #[arg(long, required_unless_present_any = ["resume", "restart"])] machine: Option, - #[arg(long, required_unless_present = "resume")] + #[arg(long, required_unless_present_any = ["resume", "restart"])] name: Option, /// Continue this unfinished session (e.g. s1) from its saved state instead of creating one. - #[arg(long, conflicts_with_all = ["machine", "name", "after"])] + #[arg(long, conflicts_with_all = ["machine", "name", "after", "restart"])] resume: Option, + /// Continue this failed or escalated session at the state where it stopped, with fresh budgets and retries. + #[arg(long, conflicts_with_all = ["machine", "name", "after"])] + restart: Option, /// Value for {{scope}} in machine commands. #[arg(long, default_value = "")] scope: String, @@ -258,19 +261,26 @@ fn main() -> Result { machine, name, resume, + restart, scope, profile, } => { let profile = profile::Profile::load(&profile)?; let repo = repo.canonicalize()?; let db = db::Db::open(&repo.join(".hx/orch.db"))?; - let s = if let Some(id) = resume { + if let Some(id) = &restart { + db.reopen(id)?; + } + let s = if let Some(id) = resume.or(restart) { let s = db .session(&id)? .with_context(|| format!("no session {id}"))?; anyhow::ensure!( - !db.events(Some(&id), 0)?.iter().any(|e| e.kind == "end"), - "session {id} already ended; start a new one" + !db.events(Some(&id), 0)? + .iter() + .rfind(|e| matches!(e.kind.as_str(), "end" | "restart")) + .is_some_and(|e| e.kind == "end"), + "session {id} already ended; --restart continues a failed or escalated one, else start a new one" ); anyhow::ensure!( s.pid diff --git a/src/runner.rs b/src/runner.rs index a311c8b..067c354 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -1279,6 +1279,45 @@ next = "done" let _ = std::fs::remove_dir_all(&e.dir); } + #[test] + fn a_failed_session_restarts_at_the_state_where_it_failed() { + let e = env("restart"); + let m = Machine::parse(&format!( + r#"name = "m" +[[state]] +name = "a" +kind = "start" +steps = [{{ name = "once", run = "computer", cmd = "echo ran >> a.log" }}] +next = "b" +[[state]] +name = "b" +steps = [{{ name = "s", run = "computer", cmd = "test -f fixed && echo b >> b.log" }}] +next = "done" +{TAIL}"# + )) + .unwrap(); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), + "failed" + ); + std::fs::write(e.dir.join("wt/s1/fixed"), "").unwrap(); + e.db.reopen("s1").unwrap(); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(), + "merged" + ); + let ks = kinds(&e.db, "s1"); + let end = ks.iter().position(|k| k == "end").unwrap(); + assert_eq!(&ks[end + 1..end + 3], ["restart", "resume"]); + assert_eq!( + std::fs::read_to_string(e.dir.join("wt/s1/a.log")).unwrap(), + "ran\n", + "state a must not run again" + ); + let _ = std::fs::remove_dir_all(&e.dir); + } + fn one_step(step: &str) -> Machine { Machine::parse(&format!( "name = \"m\"\n[[state]]\nname = \"a\"\nkind = \"start\"\nsteps = [{step}]\nnext = \"done\"\n{TAIL}" diff --git a/src/tui/mod.rs b/src/tui/mod.rs index 78b55c8..5640068 100644 --- a/src/tui/mod.rs +++ b/src/tui/mod.rs @@ -203,6 +203,27 @@ impl App { Ok(ids.len()) } + /// `R`: reopens a failed or escalated session and hands it to the host. The error is why it cannot restart. + fn restart(&mut self, id: &str) -> Result<()> { + let Some(db) = &self.db else { + bail!("no database") + }; + db.reopen(id)?; + self.ensure_host()?.submit(id); + self.refresh(); + Ok(()) + } + + fn restart_or_show(&mut self, id: &str) { + if let Err(e) = self.restart(id) { + self.pager = Some(Pager { + title: "restart".into(), + lines: vec![format!("{e:#}")], + scroll: 0, + }); + } + } + /// Creates a session row from the form and hands it to the host, which runs it as soon as a slot is free. /// Any problem (no machine, broken machine file, worktree in use) comes back as the error to show in the form. fn start_session(&mut self, f: &newform::Form) -> Result { @@ -882,6 +903,11 @@ fn on_key( }); } } + KeyCode::Char('R') => { + if let Some(id) = app.overview.rows.get(app.sel).map(|r| r.id.clone()) { + app.restart_or_show(&id); + } + } // every other letter acts on the focused Needs-you item KeyCode::Char(c) => { if let Some(n) = app.overview.needs.get(app.need_sel).cloned() { @@ -999,6 +1025,7 @@ fn on_key( serde_json::json!({"state": start, "why": "replan"}), ); } + KeyCode::Char('R') => app.restart_or_show(&id), KeyCode::Char('t') => app.pager = Some(test_output(app, &id)), KeyCode::Char('l') => app.pager = Some(transcript(app, &id)), KeyCode::Char('d') => { diff --git a/src/tui/overview.rs b/src/tui/overview.rs index 6e9ead2..edb448c 100644 --- a/src/tui/overview.rs +++ b/src/tui/overview.rs @@ -30,6 +30,9 @@ pub fn draw(f: &mut Frame, o: &Overview, h: &Header, sel: usize, need_sel: usize if o.resumable > 0 { keys.insert(3, ("u", resume.as_str())); } + if o.rows.get(sel).is_some_and(|r| r.status == Status::Fail) { + 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 sessions_h = rows_h.clamp(5, area.height.saturating_sub(14).max(5)); diff --git a/src/tui/session.rs b/src/tui/session.rs index 498b542..c5bf74b 100644 --- a/src/tui/session.rs +++ b/src/tui/session.rs @@ -18,7 +18,11 @@ const W_SETS: usize = 14; pub fn draw(f: &mut Frame, d: &Detail, h: &Header) { let area = f.area(); - let key_lines = theme::key_lines(&keys_for(d.looping.is_some()), area.width); + let mut keys = keys_for(d.looping.is_some()); + if d.status == Status::Fail { + keys.push(("R", "restart")); + } + let key_lines = theme::key_lines(&keys, area.width); let [head, body, keys] = Layout::vertical([ Constraint::Length(1), Constraint::Fill(1), diff --git a/src/view.rs b/src/view.rs index 356f629..1718e14 100644 --- a/src/view.rs +++ b/src/view.rs @@ -346,6 +346,9 @@ fn scan(evs: &[&Event], s: &Session, machine: Option<&Machine>) -> Scan { let ok = p["status"].as_str().is_some_and(|x| x != "failed"); marks.insert(cur.clone(), if ok { Mark::Done } else { Mark::Failed }); } + "restart" => { + marks.insert(cur.clone(), Mark::Active); + } "test" => { let (pass, fail) = ( p["passed"].as_u64().unwrap_or(0), @@ -428,6 +431,7 @@ fn describe(e: &Event) -> String { "catch" => format!("{} ✗ {}", str_of(p, "state"), str_of(p, "catch")), "end" => format!("ended: {}", str_of(p, "status")), "resume" => "resumed".into(), + "restart" => "restarted".into(), "status" => str_of(p, "label"), "intent" => str_of(p, "text"), "tool" => str_of(p, "title"), @@ -461,6 +465,7 @@ fn line_text(e: &Event) -> String { }, "status" => format!("■ {}", str_of(p, "label")), "resume" => format!("resumed in {}", str_of(p, "state")), + "restart" => format!("restarted after {}", str_of(p, "from")), "edit" => format!("{} +{} −{}", str_of(p, "path"), p["added"], p["removed"]), "tool" => str_of(p, "title"), "permission" => format!(