8 Commits
Author SHA1 Message Date
Johannes KresnerandClaude Opus 5.5 a28b8f0123 ci: build in the cargo-zigbuild image instead of installing the toolchain per run
build / version (push) Successful in 12s
build / build (aarch64-apple-darwin) (push) Successful in 4m28s
build / build (x86_64-unknown-linux-musl) (push) Successful in 4m40s
build / release (push) Successful in 23s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:03:28 +01:00
Johannes KresnerandClaude Opus 5.5 9f6bd32d01 fix: the open-in-hx key resumes the session's hx conversation instead of starting a new one
build / version (push) Successful in 18s
build / build (aarch64-apple-darwin) (push) Successful in 2m42s
build / build (x86_64-unknown-linux-musl) (push) Successful in 5m40s
build / release (push) Successful in 28s
hx --session takes a file path, not orch's session id. Resolve the file
hx serve wrote (acp-<id>.jsonl under the sessions dir, following
HX_SESSIONS_DIR and the sessions_dir/sessions_host config keys) with the
session's own profile, and report a missing file instead of starting fresh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:50:53 +01:00
Johannes KresnerandClaude Opus 5.5 c59924fc0f 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 <noreply@anthropic.com>
2026-11-17 16:50:01 +01:00
gitea-actions bfc2693f9b ci: bin.json v0.1.9 2026-11-17 15:03:31 +00:00
Johannes KresnerandClaude Opus 5.5 db80d15ba2 fix: an hx error asks the user instead of taking the state's first catch
build / version (push) Successful in 12s
build / build (aarch64-apple-darwin) (push) Successful in 5m20s
build / build (x86_64-unknown-linux-musl) (push) Successful in 4m45s
build / release (push) Successful in 24s
hx reports its own failures (API, login, ...) as blocked with reason
"error" and no catch. orch then fell back to the state's first catch,
so with code's ToolDenied = "review" a failed agent looked like "review
ready" with no code written. Now the error lands in Needs-you; a reply
runs the step again with the reply as hint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:52:40 +01:00
gitea-actions 551e0efd7c ci: bin.json v0.1.8 2026-11-17 14:28:01 +00:00
Johannes KresnerandClaude Opus 5.5 71f58d7b30 fix: interactive sessions run with yolo under the sandbox, auto without
build / version (push) Successful in 12s
build / build (aarch64-apple-darwin) (push) Successful in 5m44s
build / build (x86_64-unknown-linux-musl) (push) Successful in 4m2s
build / release (push) Successful in 23s
orch dropped --yolo for ACP sessions (TUI, orch up), so hx started with a
bare --sandbox and asked for every edit. Interactive sessions now use the
same flags as batch runs: --sandbox --yolo when a sandbox is available,
--auto when not. A sandbox with yolo = false gets --sandbox --auto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:17:36 +01:00
gitea-actions c768ea79d4 ci: bin.json v0.1.7 2026-11-16 15:09:31 +00:00
12 changed files with 441 additions and 43 deletions

No files matched your search

+11 -19
View File
@@ -4,8 +4,6 @@ on:
branches: [main]
paths-ignore: [bin.json]
workflow_dispatch:
env:
MACOS_SDK: "14.5"
jobs:
# next version = highest vX.Y.Z tag with the patch bumped; push a tag by hand for minor/major
version:
@@ -33,28 +31,22 @@ jobs:
fail-fast: false
matrix:
target: [x86_64-unknown-linux-musl, aarch64-apple-darwin]
# rust, zig, cargo-zigbuild, both targets and a macOS SDK (SDKROOT) prebuilt;
# the runner keeps the pulled image, so no per-run toolchain/SDK setup
container:
image: ghcr.io/rust-cross/cargo-zigbuild:0.24.1
steps:
# the image has no node, which act_runner needs for the JS actions below
- run: |
case "$(uname -m)" in x86_64) a=x64 ;; aarch64) a=arm64 ;; esac
curl -fsSL "https://nodejs.org/dist/v22.11.0/node-v22.11.0-linux-$a.tar.xz" \
| tar -xJ -C /usr/local --strip-components=1
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
# caches ~/.cargo registry/git and target/, keyed on Cargo.lock + toolchain
# caches ~/.cargo registry/git and target/, keyed on Cargo.lock + toolchain;
# a no-op until the runner's cache server is enabled
- uses: Swatinem/rust-cache@v2
with:
key: ${{ matrix.target }}
# zig as cross C compiler/linker for both musl and macOS (rusqlite bundles sqlite)
- run: pip install ziglang cargo-zigbuild
# macOS: Apple SDK for system frameworks
- if: matrix.target == 'aarch64-apple-darwin'
id: sdk-cache
uses: actions/cache@v4
with:
path: ~/MacOSX${{ env.MACOS_SDK }}.sdk
key: macos-sdk-${{ env.MACOS_SDK }}
- if: matrix.target == 'aarch64-apple-darwin' && steps.sdk-cache.outputs.cache-hit != 'true'
run: curl -fsSL "https://github.com/joseluisq/macosx-sdks/releases/download/${MACOS_SDK}/MacOSX${MACOS_SDK}.sdk.tar.xz" | tar -xJ -C "$HOME"
- if: matrix.target == 'aarch64-apple-darwin'
run: echo "SDKROOT=$HOME/MacOSX${MACOS_SDK}.sdk" >> "$GITHUB_ENV"
- run: cargo zigbuild --release --locked --target ${{ matrix.target }}
env:
ORCH_VERSION: ${{ needs.version.outputs.version }}
+6 -2
View File
@@ -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
`<state>/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, `<state>/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 `<config>/manifests` and is set in
`<config>/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 `<config>/manifests` and is set in `<config>/config.toml` (`~/.config/orch/config.toml`):
```toml
manifest_dir = "~/notes/manifests"
+3 -3
View File
@@ -1,7 +1,7 @@
{
"version": "0.1.6",
"version": "0.1.9",
"sha256": {
"aarch64-apple-darwin": "1a6b4944c20f086015368ae5d43f1ca6f11ea1dffd82c41f12e8ed7891e90555",
"x86_64-unknown-linux-musl": "8d85f036b9a0db9306ae421ac7d4ce1fc813daecc901080e80425391da823228"
"aarch64-apple-darwin": "a4b5d69d4b55893dd6202c1d36f2eebbac6ab72954a7462983f8d7b833ef14b1",
"x86_64-unknown-linux-musl": "395019a2154cb4f8cfdda0ffa63130c6fc9693286bced1648d77586b8995bec3"
}
}
+1
View File
@@ -13,6 +13,7 @@ env = ["GITEA_*"] # orch env vars hx may see (default: PATH HOME
# TMPDIR CARGO_* RUST* NIX_*, plus HX_HOME only when `home` is unset)
sandbox = true # hx --sandbox (bwrap/seatbelt). Default: on when available (macOS, Linux with bwrap),
# together with --yolo (yolo = false opts out). Unsandboxed hx runs with --auto.
# Interactive sessions (TUI, orch up) with yolo = false get --sandbox --auto.
```
## Allowlist (`allow`)
+152 -8
View File
@@ -7,13 +7,94 @@ use crate::profile::Profile;
use crate::run::hx_env;
use anyhow::{Context, Result, anyhow, bail};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::io::{BufRead, Write};
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
/// The conversation file `hx serve --cwd <worktree> --session <id>` writes, for `hx --session <file>` to
/// resume. Resolved from the environment the agent ran with (`hx_env` plus the profile's `HOME`), not orch's own.
pub fn session_file(p: &Profile, worktree: &Path, id: &str) -> PathBuf {
let mut env: HashMap<String, String> = hx_env(std::env::vars(), p).into_iter().collect();
if let Some(h) = &p.home {
env.insert("HOME".into(), h.to_string_lossy().into());
}
// hx runs in the canonical cwd (`/private/tmp`, not `/tmp`), so the slug comes from that
let cwd = worktree
.canonicalize()
.unwrap_or_else(|_| worktree.to_path_buf());
let hostname = || std::fs::read_to_string("/etc/hostname").ok();
hx_session_file(&env, &cwd, id, hostname)
}
/// hx's own path rule: `<root>/<[host/]cwd slug>/acp-<id>.jsonl`. The root is `$HX_SESSIONS_DIR`, else
/// `sessions_dir` from `$HX_HOME/config.toml` or `<cwd>/.hx/config.toml` (the latter wins, `~` is `$HOME`),
/// else `$HX_HOME/sessions`; `sessions_host = true` puts the host name in front of the slug.
fn hx_session_file(
env: &HashMap<String, String>,
cwd: &Path,
id: &str,
hostname: impl Fn() -> Option<String>,
) -> PathBuf {
let var = |k: &str| env.get(k).filter(|v| !v.is_empty());
let home = PathBuf::from(var("HOME").map_or("", String::as_str));
let hx_home = var("HX_HOME").map_or_else(|| home.join(".hx"), PathBuf::from);
let (mut dir, mut host) = (None, None);
for f in [hx_home.join("config.toml"), cwd.join(".hx/config.toml")] {
let Some(t) = std::fs::read_to_string(f)
.ok()
.and_then(|s| s.parse::<toml::Table>().ok())
else {
continue;
};
if let Some(d) = t.get("sessions_dir").and_then(|v| v.as_str()) {
dir = Some(d.to_string());
}
if let Some(h) = t.get("sessions_host").and_then(toml::Value::as_bool) {
host = Some(h);
}
}
let root = match var("HX_SESSIONS_DIR").cloned().or(dir) {
Some(s) if !s.is_empty() => match s.strip_prefix('~') {
Some(r) => home.join(r.trim_start_matches('/')),
None => s.into(),
},
_ => hx_home.join("sessions"),
};
let host = host.unwrap_or(false).then(|| {
["HOSTNAME", "HOST", "COMPUTERNAME"]
.iter()
.find_map(|k| env.get(*k).cloned())
.or_else(hostname)
.map_or("host".into(), |h| h.trim().to_string())
});
let cwd = cwd.to_string_lossy();
let slug: String = host
.as_deref()
.into_iter()
.chain([cwd.trim_matches('/')])
.collect::<Vec<_>>()
.join("/")
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect();
let id: String = id
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || "-_.".contains(c) {
c
} else {
'_'
}
})
.collect();
root.join(slug.trim_matches('-'))
.join(format!("acp-{id}.jsonl"))
}
/// Receives what hx reports while a step runs.
pub trait Sink {
/// Notifications: `hx/intent`, `hx/edit`, `hx/usage`, `hx/decision`, `hx/plan`, `session/update`.
@@ -64,13 +145,7 @@ impl Acp {
let mut parts = p.hx.split_whitespace();
let mut cmd = Command::new(parts.next().context("empty hx command")?);
// 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(parts).args(
flags
.iter()
.filter(|f| **f != "--yolo" || p.yolo == Some(true)),
);
cmd.args(parts).args(p.acp_flags());
cmd.args(["serve", "--acp", "--cwd"])
.arg(worktree)
.args(["--session", id]);
@@ -262,3 +337,72 @@ impl Drop for Acp {
let _ = self.child.wait();
}
}
#[cfg(test)]
mod tests {
use super::*;
fn env(kv: &[(&str, &str)]) -> HashMap<String, String> {
kv.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect()
}
#[test]
fn session_file_defaults_to_hx_home_sessions() {
let e = env(&[("HOME", "/nonexistent/h")]);
let f = hx_session_file(&e, Path::new("/w/a.b/s1"), "s1", || None);
assert_eq!(
f,
Path::new("/nonexistent/h/.hx/sessions/w-a-b-s1/acp-s1.jsonl")
);
}
#[test]
fn session_file_follows_hx_config_and_env() {
let t = std::env::temp_dir().join(format!("orch-acp-cfg-{}", std::process::id()));
let (home, wt) = (t.join("h"), t.join("wt"));
std::fs::create_dir_all(home.join(".hx")).unwrap();
std::fs::create_dir_all(wt.join(".hx")).unwrap();
std::fs::write(home.join(".hx/config.toml"), "sessions_dir = \"~/cloud\"\n").unwrap();
let e = env(&[("HOME", home.to_str().unwrap())]);
let slug = |p: &Path| -> String {
p.to_string_lossy()
.trim_matches('/')
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect()
};
let f = hx_session_file(&e, &wt, "s1", || None);
assert_eq!(f, home.join("cloud").join(slug(&wt)).join("acp-s1.jsonl"));
// the worktree's config wins, and sessions_host prefixes the host name
std::fs::write(
wt.join(".hx/config.toml"),
"sessions_dir = \"/sd\"\nsessions_host = true\n",
)
.unwrap();
let f = hx_session_file(&e, &wt, "s1", || Some("box\n".into()));
assert_eq!(
f,
Path::new("/sd")
.join(format!("box-{}", slug(&wt)))
.join("acp-s1.jsonl")
);
// HX_SESSIONS_DIR beats both config files
let e = env(&[
("HOME", home.to_str().unwrap()),
("HX_SESSIONS_DIR", "/env"),
("HOST", "h2"),
]);
let f = hx_session_file(&e, &wt, "s1", || None);
assert_eq!(
f,
Path::new("/env")
.join(format!("h2-{}", slug(&wt)))
.join("acp-s1.jsonl")
);
std::fs::remove_dir_all(&t).unwrap();
}
}
+11
View File
@@ -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<u32>) -> Result<()> {
self.conn.execute(
"update sessions set pid = ?2 where id = ?1",
+161
View File
@@ -245,6 +245,7 @@ pub fn up(arg: &str) -> Result<Vec<Outcome>> {
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<Vec<Outcome>> {
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<Vec<Outcome>> {
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::<Vec<_>>();
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<Vec<Outcome>> {
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<String> {
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<Outcome>| out.into_iter().map(|o| o.what).collect::<Vec<_>>();
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();
+13
View File
@@ -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<std::process::ExitCode> {
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}");
+19
View File
@@ -178,6 +178,16 @@ impl Profile {
f
}
/// Flags for an interactive (ACP) session: like `hx_flags` (sandbox brings yolo, no sandbox falls back to
/// `--auto`), but a sandbox with `yolo = false` gets `--auto` too, so not every edit asks.
pub fn acp_flags(&self) -> Vec<&'static str> {
let mut f = self.hx_flags();
if f == ["--sandbox"] {
f.push("--auto");
}
f
}
/// A profile file named by its path (an issue session's profile in its worktree).
pub fn load_path(path: &std::path::Path) -> Result<Self> {
let s =
@@ -277,6 +287,15 @@ mod tests {
assert_eq!(f("sandbox=false"), ["--auto"]);
}
#[test]
fn acp_flags_yolo_with_sandbox_else_auto() {
let f = |s| Profile::parse(s).unwrap().acp_flags();
assert_eq!(f("sandbox=true"), ["--sandbox", "--yolo"]);
assert_eq!(f("sandbox=true\nyolo=true"), ["--sandbox", "--yolo"]);
assert_eq!(f("sandbox=true\nyolo=false"), ["--sandbox", "--auto"]);
assert_eq!(f("sandbox=false"), ["--auto"]);
}
#[test]
fn bwrap_lookup_scans_path() {
let dir = std::env::temp_dir().join(format!("orch-bwrap-{}", std::process::id()));
+36 -6
View File
@@ -774,6 +774,18 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result<StepRes> {
cx.ctl.stop_for_budget(format!("hx limit: {}", r.summary));
Err(Stopped.into())
}
"blocked" if r.catch.is_none() && r.reason.as_deref() == Some("error") => {
// hx itself failed (API, login, ...): no catch fits, so ask instead of guessing one
let payload = json!({
"key": format!("{}/{}/error", st.name, step.name),
"state": st.name, "step": step.name, "title": "agent error",
"detail": format!("hx failed: {}. Fix the cause, then reply to run the step again (abort to give up)", r.summary),
});
let answer = ask(&cx.ctl, &cx.s.id, &st.name, "input", payload, true)?;
let reply = answer.strip_prefix("reply:").unwrap_or(&answer).trim();
hint = (!reply.is_empty()).then(|| reply.to_string());
continue;
}
"blocked" => Ok(StepRes {
ok: false,
exit: None,
@@ -2178,17 +2190,35 @@ next = "done"
}
#[test]
fn hx_blocked_with_another_reason_is_not_a_budget() {
fn hx_error_asks_the_user_and_the_reply_retries_the_step() {
let e = env("hx-error");
let m = ctl_machine(LIMIT_MACHINE);
// the state has a catch: an hx error must not be filed under it
let m = ctl_machine(&LIMIT_MACHINE.replace(
"next = \"done\"",
"next = \"done\"\ncatch = { ToolDenied = \"done\" }",
));
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
let user = answerer(e.dir.join("orch.db"), &["reply: logged in again"]);
let p = fake("FAKE_MODE=error");
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(),
"failed"
run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap();
let seen = user.join().unwrap();
assert_eq!(seen.len(), 1);
assert_eq!(seen[0].0, "input");
assert!(
seen[0].1["detail"]
.as_str()
.unwrap()
.contains("hit the error")
);
let ev = e.db.events(Some("s1"), 0).unwrap();
assert!(ev.iter().all(|v| v.kind != "budget" && v.kind != "goto"));
assert!(
ev.iter()
.all(|v| !matches!(v.kind.as_str(), "budget" | "goto" | "catch"))
);
let ok = ev
.iter()
.filter(|v| v.kind == "step" && v.payload["ok"] == true);
assert_eq!(ok.count(), 1, "the retried step finished");
let _ = std::fs::remove_dir_all(&e.dir);
}
+26 -3
View File
@@ -837,15 +837,37 @@ fn transcript(app: &App, id: &str) -> Pager {
/// 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,
db: Option<&Db>,
worktree: &str,
session: &str,
) -> Option<String> {
let hx = crate::profile::Profile::load("default").map_or_else(|_| "hx".into(), |p| p.hx);
use crate::profile::Profile;
// the session's own profile: its home holds the conversation hx serve wrote
let p = db
.and_then(|db| db.options(session).ok())
.and_then(|o| o.get("profile")?.as_str().map(PathBuf::from))
.and_then(|path| Profile::load_path(&path).ok())
.or_else(|| Profile::load(PROFILE).ok());
let hx = p.as_ref().map_or_else(|| "hx".into(), |p| p.hx.clone());
let file = match &p {
Some(p) => crate::acp::session_file(p, Path::new(worktree), session),
None => return Some(format!("could not load profile {PROFILE:?}")),
};
if !file.exists() {
return Some(format!(
"no hx conversation for {session} at {}",
file.display()
));
}
let mut parts = hx.split_whitespace();
let mut cmd = std::process::Command::new(parts.next()?);
cmd.args(parts)
.args(["--session", session])
.arg("--session")
.arg(&file)
.current_dir(worktree);
if let Some(h) = p.as_ref().and_then(|p| p.home.as_ref()) {
cmd.env("HOME", h).env_remove("HX_HOME");
}
ratatui::restore();
let res = cmd.status();
*term = ratatui::init();
@@ -1082,7 +1104,8 @@ fn on_key(
}
KeyCode::Char('o') => {
if let Some(d) = &app.detail
&& let Some(err) = open_in_hx(term, &d.worktree.clone(), &d.id.clone())
&& let Some(err) =
open_in_hx(term, app.db.as_ref(), &d.worktree.clone(), &d.id.clone())
{
app.pager = Some(Pager {
title: "open worktree".into(),
+2 -2
View File
@@ -9,7 +9,7 @@ Behaviour per `hx/step`, chosen with FAKE_MODE (orch passes FAKE_* through the p
slow works until hx/interrupt (records hx/message and hx/compact in messages.txt / compact.txt), then
answers done; a retried step with context.hint finishes at once
limit step_result blocked, no catch, reason "limit" (hx hit a limit from hx/step)
error step_result blocked, no catch, reason "error"
error step_result blocked, no catch, reason "error"; finishes when the retried step has a context.hint
crash exits without a step_result
FAKE_UNDERSCORE=1 sends every custom method as `_hx/...`.
FAKE_USAGE="ctx_used,ctx_limit,cost" makes every step report that usage first.
@@ -90,7 +90,7 @@ def step(params):
if mode == "needs_input" and not params.get("context", {}).get("hint"):
note("hx/step_result", {"status": "needs_input", "question": "Which provider?"})
return
if mode in ("limit", "error"): # blocked without a catch, only the reason differs
if mode == "limit" or mode == "error" and not params.get("context", {}).get("hint"): # blocked without a catch, only the reason differs
note("hx/step_result", {"status": "blocked", "reason": mode, "summary": f"hit the {mode}"})
return
blocked = mode == "blocked"