4 Commits
Author SHA1 Message Date
johannes db7ef65e4a fix: sandbox mode not working
build / version (push) Successful in 9s
build / build (aarch64-apple-darwin) (push) Successful in 3m56s
build / build (x86_64-unknown-linux-musl) (push) Successful in 3m47s
build / release (push) Successful in 17s
2026-11-15 22:51:24 +01:00
gitea-actions d977e01d5d ci: bin.json v0.1.4 2026-11-15 21:44:17 +00:00
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
11 changed files with 148 additions and 18 deletions

No files matched your search

+3
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
[--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
+3 -3
View File
@@ -1,7 +1,7 @@
{
"version": "0.1.2",
"version": "0.1.4",
"sha256": {
"aarch64-apple-darwin": "90d260baec2247624a9f718fc5c66a6dfd87e11981a2660ec0caddac4b7aa066",
"x86_64-unknown-linux-musl": "6dd90621ba50e40a6efff5ecbd5f870c36ca579ec00030b0e76c4022151871e8"
"aarch64-apple-darwin": "ba5711a2cf4b27f5b37963e9562088f6f0159b3f87fdca1a4ca8258f510667d0",
"x86_64-unknown-linux-musl": "3d134d6cbc0035f609772dcda2a3dfa55f688c7bb5a30410e2091fa1f13aeba0"
}
}
+5 -5
View File
@@ -63,17 +63,17 @@ impl Acp {
pub fn spawn(p: &Profile, worktree: &Path, id: &str) -> Result<Self> {
let mut parts = p.hx.split_whitespace();
let mut cmd = Command::new(parts.next().context("empty hx command")?);
cmd.args(parts)
.args(["serve", "--acp", "--cwd"])
.arg(worktree)
.args(["--session", id]);
// sandbox and permission flags are options of the root command, so they go before `serve`
// the TUI answers permission requests itself, so yolo only when the profile asks for it explicitly
let flags = p.hx_flags();
cmd.args(
cmd.args(parts).args(
flags
.iter()
.filter(|f| **f != "--yolo" || p.yolo == Some(true)),
);
cmd.args(["serve", "--acp", "--cwd"])
.arg(worktree)
.args(["--session", id]);
// same cleared environment as the batch runner: orch's secrets never reach the agent
cmd.env_clear().envs(hx_env(std::env::vars(), p));
if let Some(h) = &p.home {
+10 -2
View File
@@ -62,7 +62,10 @@ pub struct Exceeded {
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 {
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<Exceeded
}
}
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 {
return Some(Exceeded {
what: "cost",
+32 -1
View File
@@ -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<u32>) -> 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<u32> {
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();
+16 -6
View File
@@ -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<String>,
#[arg(long, required_unless_present = "resume")]
#[arg(long, required_unless_present_any = ["resume", "restart"])]
name: Option<String>,
/// 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>,
/// 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.
#[arg(long, default_value = "")]
scope: String,
@@ -258,19 +261,26 @@ fn main() -> Result<std::process::ExitCode> {
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
+39
View File
@@ -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}"
+27
View File
@@ -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<String> {
@@ -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') => {
+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 {
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));
+5 -1
View File
@@ -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),
+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");
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!(