4 Commits
Author SHA1 Message Date
johannesandClaude Sonnet 5.5 e50f90d299 feat: restart a failed or escalated session at the state where it stopped
build / version (push) Successful in 10s
build / build (aarch64-apple-darwin) (push) Successful in 4m5s
build / build (x86_64-unknown-linux-musl) (push) Successful in 3m34s
build / release (push) Successful in 16s
Adds orch session --restart sN and R in the TUI. A restart event gives the
session fresh budgets and retry counts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 22:36:10 +01:00
gitea-actions 0e57b04d25 ci: bin.json v0.1.3 2026-11-15 21:31:56 +00:00
johannesandClaude Sonnet 5.5 a4df9c3b01 feat: open the session in hx with --session from the TUI
build / version (push) Successful in 10s
build / build (aarch64-apple-darwin) (push) Successful in 4m30s
build / build (x86_64-unknown-linux-musl) (push) Successful in 3m44s
build / release (push) Successful in 25s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 22:23:05 +01:00
gitea-actions 5611ad7e6a ci: bin.json v0.1.2 2026-11-15 21:14:00 +00:00
10 changed files with 154 additions and 18 deletions

No files matched your search

+4 -1
View File
@@ -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 orch session --repo DIR --machine M --name N create a state-machine session and run it
[--profile P] [--after s1,s2] [--scope S] [--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 --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 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 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 checks [--owner sN | --main] run acceptance checks here, or on a clean copy of main
@@ -54,7 +55,7 @@ command = "python3 /work/adapters/gitea.py"
## State-machine sessions and the TUI ## State-machine sessions and the TUI
`orch` without a subcommand opens the TUI: sessions overview (`enter` on a row opens the session detail, `esc` goes `orch` without a subcommand opens the TUI: sessions overview (`enter` on a row opens the session detail, `esc` goes
back; `t` full test output, `d` diff, `l` event transcript, `o` open the worktree in hx). It reads `.hx/orch.db` of the back; `t` full test output, `d` diff, `l` event transcript, `o` open the session in hx, `hx --session sN` in its worktree). It reads `.hx/orch.db` of the
current directory. `orch session --repo . --machine task --name NAME [--profile P]` creates a session and runs it. current directory. `orch session --repo . --machine task --name NAME [--profile P]` creates a session and runs it.
`orch session --repo . --resume s1` continues an unfinished session (for example after a crash or a closed terminal) `orch session --repo . --resume s1` continues an unfinished session (for example after a crash or a closed terminal)
from its saved state; `--machine`, `--name` and `--after` are not allowed with it. Machines are TOML files in from its saved state; `--machine`, `--name` and `--after` are not allowed with it. Machines are TOML files in
@@ -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 `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 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. 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 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 once every pending request that asks for the same thing (any session), and `P` save an allow rule to the profile
+3 -3
View File
@@ -1,7 +1,7 @@
{ {
"version": "0.1.1", "version": "0.1.3",
"sha256": { "sha256": {
"aarch64-apple-darwin": "f7859070acf2b34527a14fa031e0deff8a07540e61a32138b1a5f1b19c4025e4", "aarch64-apple-darwin": "b2cbabcd87ae7bda6c14638c24f5b80e37553954409a46828fd0bddb0aa1e7bc",
"x86_64-unknown-linux-musl": "202c05f892e29f16e5446b4e6b51ec24f8fd55ee73fc1359b202fe7bfa8cc28f" "x86_64-unknown-linux-musl": "0f003750f85b40499036e3bf1591fa488b7bd34ad19787471c0bc968ab545427"
} }
} }
+10 -2
View File
@@ -62,7 +62,10 @@ pub struct Exceeded {
pub limit: String, pub limit: String,
} }
pub fn exceeded(evs: &[&Event], cfg: &BudgetCfg, now_ms: u64) -> Option<Exceeded> { /// 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<Exceeded> {
let restarted = all.iter().rposition(|e| e.kind == "restart");
let evs = &all[restarted.unwrap_or(0)..];
if let Some(limit) = cfg.wall_secs { if let Some(limit) = cfg.wall_secs {
let used = active_secs(evs, now_ms); let used = active_secs(evs, now_ms);
if used > limit { if used > limit {
@@ -74,7 +77,12 @@ pub fn exceeded(evs: &[&Event], cfg: &BudgetCfg, now_ms: u64) -> Option<Exceeded
} }
} }
if let Some(limit) = cfg.cost { if let Some(limit) = cfg.cost {
let used = cost(evs); // usage after a restart belongs to the new hx, whose total starts again
let used = if restarted.is_some() {
cost(&evs[1..])
} else {
cost(evs)
};
if used > limit { if used > limit {
return Some(Exceeded { return Some(Exceeded {
what: "cost", what: "cost",
+32 -1
View File
@@ -369,6 +369,23 @@ impl Db {
Ok(()) 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<u32>) -> Result<()> { pub fn set_pid(&self, id: &str, pid: Option<u32>) -> Result<()> {
self.conn.execute( self.conn.execute(
"update sessions set pid = ?2 where id = ?1", "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). /// 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<u32> { pub fn catch_count(&self, session: &str, state: &str, catch: &str) -> Result<u32> {
let n: i64 = self.conn.query_row( let n: i64 = self.conn.query_row(
"select count(*) from events where session_id = ?1 and kind = 'catch' "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], params![session, state, catch],
|r| r.get(0), |r| r.get(0),
)?; )?;
@@ -566,6 +585,18 @@ mod tests {
assert_eq!(db.catch_count("s1", "test", "U").unwrap(), 0); assert_eq!(db.catch_count("s1", "test", "U").unwrap(), 0);
assert_eq!(db.events(Some("s1"), 0).unwrap().len(), 2); assert_eq!(db.events(Some("s1"), 0).unwrap().len(), 2);
assert_eq!(db.events(None, last - 1).unwrap().len(), 1); 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()); assert!(db.events(Some("s9"), 0).unwrap().is_empty());
// checks keep their last result; decisions list in insertion order // checks keep their last result; decisions list in insertion order
let c = db.add_check("build", "true", Some("s1")).unwrap(); let c = db.add_check("build", "true", Some("s1")).unwrap();
+16 -6
View File
@@ -126,13 +126,16 @@ enum Cmd {
#[arg(long)] #[arg(long)]
repo: PathBuf, repo: PathBuf,
/// Machine file name, without .toml (looked up in REPO/.hx/machines, then ~/.hx/machines). /// 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<String>, machine: Option<String>,
#[arg(long, required_unless_present = "resume")] #[arg(long, required_unless_present_any = ["resume", "restart"])]
name: Option<String>, name: Option<String>,
/// Continue this unfinished session (e.g. s1) from its saved state instead of creating one. /// 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<String>, resume: Option<String>,
/// 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<String>,
/// Value for {{scope}} in machine commands. /// Value for {{scope}} in machine commands.
#[arg(long, default_value = "")] #[arg(long, default_value = "")]
scope: String, scope: String,
@@ -258,19 +261,26 @@ fn main() -> Result<std::process::ExitCode> {
machine, machine,
name, name,
resume, resume,
restart,
scope, scope,
profile, profile,
} => { } => {
let profile = profile::Profile::load(&profile)?; let profile = profile::Profile::load(&profile)?;
let repo = repo.canonicalize()?; let repo = repo.canonicalize()?;
let db = db::Db::open(&repo.join(".hx/orch.db"))?; 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 let s = db
.session(&id)? .session(&id)?
.with_context(|| format!("no session {id}"))?; .with_context(|| format!("no session {id}"))?;
anyhow::ensure!( anyhow::ensure!(
!db.events(Some(&id), 0)?.iter().any(|e| e.kind == "end"), !db.events(Some(&id), 0)?
"session {id} already ended; start a new one" .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!( anyhow::ensure!(
s.pid s.pid
+39
View File
@@ -1279,6 +1279,45 @@ next = "done"
let _ = std::fs::remove_dir_all(&e.dir); 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 { fn one_step(step: &str) -> Machine {
Machine::parse(&format!( Machine::parse(&format!(
"name = \"m\"\n[[state]]\nname = \"a\"\nkind = \"start\"\nsteps = [{step}]\nnext = \"done\"\n{TAIL}" "name = \"m\"\n[[state]]\nname = \"a\"\nkind = \"start\"\nsteps = [{step}]\nnext = \"done\"\n{TAIL}"
+37 -4
View File
@@ -203,6 +203,27 @@ impl App {
Ok(ids.len()) 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. /// 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. /// 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<String> { fn start_session(&mut self, f: &newform::Form) -> Result<String> {
@@ -768,12 +789,18 @@ fn transcript(app: &App, id: &str) -> Pager {
} }
} }
/// Opens hx in the worktree: the TUI steps aside for the time hx runs. /// Opens hx on the session's conversation in the worktree: the TUI steps aside for the time hx runs.
fn open_in_hx(term: &mut ratatui::DefaultTerminal, worktree: &str) -> Option<String> { fn open_in_hx(
term: &mut ratatui::DefaultTerminal,
worktree: &str,
session: &str,
) -> Option<String> {
let hx = crate::profile::Profile::load("default").map_or_else(|_| "hx".into(), |p| p.hx); let hx = crate::profile::Profile::load("default").map_or_else(|_| "hx".into(), |p| p.hx);
let mut parts = hx.split_whitespace(); let mut parts = hx.split_whitespace();
let mut cmd = std::process::Command::new(parts.next()?); let mut cmd = std::process::Command::new(parts.next()?);
cmd.args(parts).current_dir(worktree); cmd.args(parts)
.args(["--session", session])
.current_dir(worktree);
ratatui::restore(); ratatui::restore();
let res = cmd.status(); let res = cmd.status();
*term = ratatui::init(); *term = ratatui::init();
@@ -876,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 // every other letter acts on the focused Needs-you item
KeyCode::Char(c) => { KeyCode::Char(c) => {
if let Some(n) = app.overview.needs.get(app.need_sel).cloned() { if let Some(n) = app.overview.needs.get(app.need_sel).cloned() {
@@ -993,6 +1025,7 @@ fn on_key(
serde_json::json!({"state": start, "why": "replan"}), 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('t') => app.pager = Some(test_output(app, &id)),
KeyCode::Char('l') => app.pager = Some(transcript(app, &id)), KeyCode::Char('l') => app.pager = Some(transcript(app, &id)),
KeyCode::Char('d') => { KeyCode::Char('d') => {
@@ -1002,7 +1035,7 @@ fn on_key(
} }
KeyCode::Char('o') => { KeyCode::Char('o') => {
if let Some(d) = &app.detail if let Some(d) = &app.detail
&& let Some(err) = open_in_hx(term, &d.worktree.clone()) && let Some(err) = open_in_hx(term, &d.worktree.clone(), &d.id.clone())
{ {
app.pager = Some(Pager { app.pager = Some(Pager {
title: "open worktree".into(), title: "open worktree".into(),
+3
View File
@@ -30,6 +30,9 @@ pub fn draw(f: &mut Frame, o: &Overview, h: &Header, sel: usize, need_sel: usize
if o.resumable > 0 { if o.resumable > 0 {
keys.insert(3, ("u", resume.as_str())); 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 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 + 3) as u16;
let sessions_h = rows_h.clamp(5, area.height.saturating_sub(14).max(5)); let sessions_h = rows_h.clamp(5, area.height.saturating_sub(14).max(5));
+5 -1
View File
@@ -18,7 +18,11 @@ const W_SETS: usize = 14;
pub fn draw(f: &mut Frame, d: &Detail, h: &Header) { pub fn draw(f: &mut Frame, d: &Detail, h: &Header) {
let area = f.area(); 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([ let [head, body, keys] = Layout::vertical([
Constraint::Length(1), Constraint::Length(1),
Constraint::Fill(1), Constraint::Fill(1),
+5
View File
@@ -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"); let ok = p["status"].as_str().is_some_and(|x| x != "failed");
marks.insert(cur.clone(), if ok { Mark::Done } else { Mark::Failed }); marks.insert(cur.clone(), if ok { Mark::Done } else { Mark::Failed });
} }
"restart" => {
marks.insert(cur.clone(), Mark::Active);
}
"test" => { "test" => {
let (pass, fail) = ( let (pass, fail) = (
p["passed"].as_u64().unwrap_or(0), 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")), "catch" => format!("{} ✗ {}", str_of(p, "state"), str_of(p, "catch")),
"end" => format!("ended: {}", str_of(p, "status")), "end" => format!("ended: {}", str_of(p, "status")),
"resume" => "resumed".into(), "resume" => "resumed".into(),
"restart" => "restarted".into(),
"status" => str_of(p, "label"), "status" => str_of(p, "label"),
"intent" => str_of(p, "text"), "intent" => str_of(p, "text"),
"tool" => str_of(p, "title"), "tool" => str_of(p, "title"),
@@ -461,6 +465,7 @@ fn line_text(e: &Event) -> String {
}, },
"status" => format!("■ {}", str_of(p, "label")), "status" => format!("■ {}", str_of(p, "label")),
"resume" => format!("resumed in {}", str_of(p, "state")), "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"]), "edit" => format!("{} +{} −{}", str_of(p, "path"), p["added"], p["removed"]),
"tool" => str_of(p, "title"), "tool" => str_of(p, "title"),
"permission" => format!( "permission" => format!(