Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f652e607f6 | ||
|
|
8c4361acee | ||
|
|
db7ef65e4a | ||
|
|
d977e01d5d | ||
|
|
e50f90d299 | ||
|
|
0e57b04d25 | ||
|
|
a4df9c3b01 | ||
|
|
5611ad7e6a | ||
|
|
8539e0308d | ||
|
|
ef53278466 | ||
|
|
8ecbd504a2 | ||
|
|
3f396b112a |
No files matched your search
@@ -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
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
{
|
{
|
||||||
"version": "0.0.0",
|
"version": "0.1.5",
|
||||||
"sha256": {}
|
"sha256": {
|
||||||
|
"aarch64-apple-darwin": "388fedc4ffac34756cfb234953c4b7355017bd68b23a953f6f6ce908b33fbdab",
|
||||||
|
"x86_64-unknown-linux-musl": "f5911d985f2d392783c12e7e130f4ced098a8f4b2dea1a9ebb83fb7c73ef54aa"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+2
-1
@@ -11,7 +11,8 @@ allow = ["read", "write", "edit", "bash:cargo *", "bash:git status"]
|
|||||||
read_roots = ["/work/shared-docs"] # extra readable dirs besides the worktree
|
read_roots = ["/work/shared-docs"] # extra readable dirs besides the worktree
|
||||||
env = ["GITEA_*"] # orch env vars hx may see (default: PATH HOME USER LOGNAME SHELL TERM LANG LC_*
|
env = ["GITEA_*"] # orch env vars hx may see (default: PATH HOME USER LOGNAME SHELL TERM LANG LC_*
|
||||||
# TMPDIR CARGO_* RUST* NIX_*, plus HX_HOME only when `home` is unset)
|
# TMPDIR CARGO_* RUST* NIX_*, plus HX_HOME only when `home` is unset)
|
||||||
sandbox = true # hx --sandbox (bwrap); required for yolo = true
|
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.
|
||||||
```
|
```
|
||||||
|
|
||||||
## Allowlist (`allow`)
|
## Allowlist (`allow`)
|
||||||
|
|||||||
@@ -4,8 +4,9 @@
|
|||||||
hx = "hx"
|
hx = "hx"
|
||||||
# home = "/home/me/.hx-work" # own HOME, so the profile keeps its own ~/.hx/auth.json
|
# home = "/home/me/.hx-work" # own HOME, so the profile keeps its own ~/.hx/auth.json
|
||||||
# provider = "anthropic"
|
# provider = "anthropic"
|
||||||
sandbox = false
|
# Default: --sandbox --yolo when the platform has a sandbox (macOS, Linux with bwrap), else --auto.
|
||||||
# yolo = true # only together with sandbox = true
|
# sandbox = false # force unsandboxed (hx runs with --auto)
|
||||||
|
# yolo = false # sandbox without --yolo; yolo = true needs a sandbox
|
||||||
|
|
||||||
# Shell command run in the worktree after hx; exit 0 = pass.
|
# Shell command run in the worktree after hx; exit 0 = pass.
|
||||||
# gate = "cargo test"
|
# gate = "cargo test"
|
||||||
|
|||||||
+9
-2
@@ -63,8 +63,15 @@ impl Acp {
|
|||||||
pub fn spawn(p: &Profile, worktree: &Path, id: &str) -> Result<Self> {
|
pub fn spawn(p: &Profile, worktree: &Path, id: &str) -> Result<Self> {
|
||||||
let mut parts = p.hx.split_whitespace();
|
let mut parts = p.hx.split_whitespace();
|
||||||
let mut cmd = Command::new(parts.next().context("empty hx command")?);
|
let mut cmd = Command::new(parts.next().context("empty hx command")?);
|
||||||
cmd.args(parts)
|
// sandbox and permission flags are options of the root command, so they go before `serve`
|
||||||
.args(["serve", "--acp", "--cwd"])
|
// 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(["serve", "--acp", "--cwd"])
|
||||||
.arg(worktree)
|
.arg(worktree)
|
||||||
.args(["--session", id]);
|
.args(["--session", id]);
|
||||||
// same cleared environment as the batch runner: orch's secrets never reach the agent
|
// same cleared environment as the batch runner: orch's secrets never reach the agent
|
||||||
|
|||||||
+10
-2
@@ -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",
|
||||||
|
|||||||
@@ -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();
|
||||||
|
|||||||
+18
-8
@@ -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
|
||||||
@@ -454,7 +464,7 @@ fn process(
|
|||||||
telemetry: &Path,
|
telemetry: &Path,
|
||||||
) -> Result<state::Run> {
|
) -> Result<state::Run> {
|
||||||
let mut r = run::new_run(t, repo, profile)?;
|
let mut r = run::new_run(t, repo, profile)?;
|
||||||
if p.allow.is_none() && !p.sandbox {
|
if p.allow.is_none() && !p.sandboxed() {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"warning: profile {profile} has no `allow` list and no sandbox: hx may use every tool"
|
"warning: profile {profile} has no `allow` list and no sandbox: hx may use every tool"
|
||||||
);
|
);
|
||||||
@@ -463,7 +473,7 @@ fn process(
|
|||||||
let audit = |ev: &str, d: serde_json::Value| policy::audit(&policy::audit_path(), &id, ev, d);
|
let audit = |ev: &str, d: serde_json::Value| policy::audit(&policy::audit_path(), &id, ev, d);
|
||||||
audit(
|
audit(
|
||||||
"run_start",
|
"run_start",
|
||||||
serde_json::json!({"profile": profile, "repo": repo, "allow": p.allow, "sandbox": p.sandbox, "yolo": p.yolo, "task": t.id}),
|
serde_json::json!({"profile": profile, "repo": repo, "allow": p.allow, "sandbox": p.sandboxed(), "yolo": p.yolo_on(), "task": t.id}),
|
||||||
);
|
);
|
||||||
run::execute(&mut r, p, t)?;
|
run::execute(&mut r, p, t)?;
|
||||||
audit(
|
audit(
|
||||||
|
|||||||
+77
-15
@@ -1,9 +1,19 @@
|
|||||||
//! Profile: `<config>/profiles/NAME.toml`. One profile = one identity (own HOME/auth), budget and gate.
|
//! Profile: `./.hx/profiles/NAME.toml` (repo-local, checked first), else `<config>/profiles/NAME.toml`. One profile = one identity (own HOME/auth), budget and gate.
|
||||||
|
|
||||||
use anyhow::{Context, Result, bail};
|
use anyhow::{Context, Result, bail};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
/// `./.hx/profiles/NAME.toml` when it exists (repo-local wins), else `<config>/profiles/NAME.toml`.
|
||||||
|
fn profile_path(name: &str) -> PathBuf {
|
||||||
|
let file = format!("{name}.toml");
|
||||||
|
let local = PathBuf::from(".hx/profiles").join(&file);
|
||||||
|
if local.is_file() {
|
||||||
|
return local;
|
||||||
|
}
|
||||||
|
crate::config_dir().join("profiles").join(file)
|
||||||
|
}
|
||||||
|
|
||||||
/// [`Profile::add_allow`] on a file.
|
/// [`Profile::add_allow`] on a file.
|
||||||
fn add_allow_at(path: &std::path::Path, entry: &str) -> Result<bool> {
|
fn add_allow_at(path: &std::path::Path, entry: &str) -> Result<bool> {
|
||||||
crate::policy::check_entry(entry)?;
|
crate::policy::check_entry(entry)?;
|
||||||
@@ -33,6 +43,18 @@ fn add_allow_at(path: &std::path::Path, entry: &str) -> Result<bool> {
|
|||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// macOS ships a sandbox (seatbelt); Linux needs `bwrap` on PATH; elsewhere none.
|
||||||
|
pub fn sandbox_available() -> bool {
|
||||||
|
if cfg!(target_os = "macos") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
cfg!(target_os = "linux") && has_bwrap(&std::env::var("PATH").unwrap_or_default())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_bwrap(path: &str) -> bool {
|
||||||
|
std::env::split_paths(path).any(|d| d.join("bwrap").is_file())
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Default, Clone)]
|
#[derive(Deserialize, Debug, Default, Clone)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct Budget {
|
pub struct Budget {
|
||||||
@@ -61,11 +83,11 @@ pub struct Profile {
|
|||||||
/// HOME for hx, so each profile keeps its own `~/.hx/auth.json`.
|
/// HOME for hx, so each profile keeps its own `~/.hx/auth.json`.
|
||||||
pub home: Option<PathBuf>,
|
pub home: Option<PathBuf>,
|
||||||
pub provider: Option<String>,
|
pub provider: Option<String>,
|
||||||
#[serde(default)]
|
/// Passes `--sandbox`. Unset: on when the platform has a sandbox (macOS, Linux with bwrap).
|
||||||
pub sandbox: bool,
|
pub sandbox: Option<bool>,
|
||||||
/// Passes `--yolo`. Only allowed together with `sandbox = true`.
|
/// Passes `--yolo`. Only allowed together with a sandbox. Unset: on whenever the sandbox is on.
|
||||||
#[serde(default)]
|
/// With neither set and no sandbox available hx runs with `--auto`.
|
||||||
pub yolo: bool,
|
pub yolo: Option<bool>,
|
||||||
/// Shell command run in the worktree after hx; exit 0 = pass. None = no gate.
|
/// Shell command run in the worktree after hx; exit 0 = pass. None = no gate.
|
||||||
pub gate: Option<String>,
|
pub gate: Option<String>,
|
||||||
/// Extra hx attempts after a red gate (default 2). 0 = fail straight to needs-human.
|
/// Extra hx attempts after a red gate (default 2). 0 = fail straight to needs-human.
|
||||||
@@ -123,19 +145,44 @@ impl Profile {
|
|||||||
if p.workers == 0 || p.max_concurrent == Some(0) {
|
if p.workers == 0 || p.max_concurrent == Some(0) {
|
||||||
bail!("workers and max_concurrent must be >= 1");
|
bail!("workers and max_concurrent must be >= 1");
|
||||||
}
|
}
|
||||||
if p.yolo && !p.sandbox {
|
if p.yolo == Some(true) && p.sandbox == Some(false) {
|
||||||
bail!("yolo = true requires sandbox = true");
|
bail!("yolo = true requires sandbox = true");
|
||||||
}
|
}
|
||||||
|
if p.yolo == Some(true) && p.sandbox.is_none() && !sandbox_available() {
|
||||||
|
bail!("yolo = true requires a sandbox, and none is available (Linux needs bwrap)");
|
||||||
|
}
|
||||||
Ok(p)
|
Ok(p)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether hx runs sandboxed: explicit setting, else whatever the platform offers.
|
||||||
|
pub fn sandboxed(&self) -> bool {
|
||||||
|
self.sandbox.unwrap_or_else(sandbox_available)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether hx gets `--yolo`: explicit setting, else on with the sandbox.
|
||||||
|
pub fn yolo_on(&self) -> bool {
|
||||||
|
self.yolo.unwrap_or(self.sandboxed()) && self.sandboxed()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Permission flags for hx: `--sandbox [--yolo]`, or `--auto` when unsandboxed.
|
||||||
|
pub fn hx_flags(&self) -> Vec<&'static str> {
|
||||||
|
let mut f = Vec::new();
|
||||||
|
if self.sandboxed() {
|
||||||
|
f.push("--sandbox");
|
||||||
|
if self.yolo_on() {
|
||||||
|
f.push("--yolo");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
f.push("--auto");
|
||||||
|
}
|
||||||
|
f
|
||||||
|
}
|
||||||
|
|
||||||
pub fn load(name: &str) -> Result<Self> {
|
pub fn load(name: &str) -> Result<Self> {
|
||||||
if name.is_empty() || name.contains(['/', '.']) {
|
if name.is_empty() || name.contains(['/', '.']) {
|
||||||
bail!("bad profile name {name:?}");
|
bail!("bad profile name {name:?}");
|
||||||
}
|
}
|
||||||
let path = crate::config_dir()
|
let path = profile_path(name);
|
||||||
.join("profiles")
|
|
||||||
.join(format!("{name}.toml"));
|
|
||||||
let s = match std::fs::read_to_string(&path) {
|
let s = match std::fs::read_to_string(&path) {
|
||||||
// only the implicit profile may be missing; a typo in any other name must still fail
|
// only the implicit profile may be missing; a typo in any other name must still fail
|
||||||
Err(e) if name == "default" && e.kind() == std::io::ErrorKind::NotFound => {
|
Err(e) if name == "default" && e.kind() == std::io::ErrorKind::NotFound => {
|
||||||
@@ -153,10 +200,7 @@ impl Profile {
|
|||||||
if name.is_empty() || name.contains(['/', '.']) {
|
if name.is_empty() || name.contains(['/', '.']) {
|
||||||
bail!("bad profile name {name:?}");
|
bail!("bad profile name {name:?}");
|
||||||
}
|
}
|
||||||
let path = crate::config_dir()
|
add_allow_at(&profile_path(name), entry)
|
||||||
.join("profiles")
|
|
||||||
.join(format!("{name}.toml"));
|
|
||||||
add_allow_at(&path, entry)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn account<'a>(&'a self, profile: &'a str) -> &'a str {
|
pub fn account<'a>(&'a self, profile: &'a str) -> &'a str {
|
||||||
@@ -214,10 +258,28 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_yolo_without_sandbox_and_unknown_keys() {
|
fn rejects_yolo_without_sandbox_and_unknown_keys() {
|
||||||
assert!(Profile::parse("yolo=true").is_err());
|
assert!(Profile::parse("sandbox=false\nyolo=true").is_err());
|
||||||
assert!(Profile::parse("bogus=1").is_err());
|
assert!(Profile::parse("bogus=1").is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flags_follow_sandbox_setting() {
|
||||||
|
let f = |s| Profile::parse(s).unwrap().hx_flags();
|
||||||
|
assert_eq!(f("sandbox=true"), ["--sandbox", "--yolo"]);
|
||||||
|
assert_eq!(f("sandbox=true\nyolo=false"), ["--sandbox"]);
|
||||||
|
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()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
assert!(!has_bwrap(dir.to_str().unwrap()));
|
||||||
|
std::fs::write(dir.join("bwrap"), "").unwrap();
|
||||||
|
assert!(has_bwrap(&format!("/nonexistent:{}", dir.display())));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_path_like_names() {
|
fn rejects_path_like_names() {
|
||||||
assert!(Profile::load("../x").is_err());
|
assert!(Profile::load("../x").is_err());
|
||||||
|
|||||||
+1
-6
@@ -275,12 +275,7 @@ fn run_hx(
|
|||||||
if let Some(s) = session {
|
if let Some(s) = session {
|
||||||
cmd.args(["--session", s]);
|
cmd.args(["--session", s]);
|
||||||
}
|
}
|
||||||
if p.sandbox {
|
cmd.args(p.hx_flags());
|
||||||
cmd.arg("--sandbox");
|
|
||||||
}
|
|
||||||
if p.yolo {
|
|
||||||
cmd.arg("--yolo");
|
|
||||||
}
|
|
||||||
if let Some(prov) = &p.provider {
|
if let Some(prov) = &p.provider {
|
||||||
cmd.args(["--provider", prov]);
|
cmd.args(["--provider", prov]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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}"
|
||||||
|
|||||||
+60
-5
@@ -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> {
|
||||||
@@ -736,7 +757,7 @@ fn test_output(app: &App, id: &str) -> Pager {
|
|||||||
fn diff_of(worktree: &str) -> Pager {
|
fn diff_of(worktree: &str) -> Pager {
|
||||||
let git = |a: &[&str]| crate::run::git(Path::new(worktree), a);
|
let git = |a: &[&str]| crate::run::git(Path::new(worktree), a);
|
||||||
let mut text = String::new();
|
let mut text = String::new();
|
||||||
match git(&["status", "--short"]) {
|
match git(&["status", "--short", "--untracked-files=all"]) {
|
||||||
Ok(s) if !s.trim().is_empty() => text.push_str(&format!("{s}\n")),
|
Ok(s) if !s.trim().is_empty() => text.push_str(&format!("{s}\n")),
|
||||||
Ok(_) => {}
|
Ok(_) => {}
|
||||||
Err(e) => text.push_str(&format!("{e:#}\n")),
|
Err(e) => text.push_str(&format!("{e:#}\n")),
|
||||||
@@ -746,6 +767,20 @@ fn diff_of(worktree: &str) -> Pager {
|
|||||||
Ok(s) => text.push_str(&s),
|
Ok(s) => text.push_str(&s),
|
||||||
Err(e) => text.push_str(&format!("{e:#}")),
|
Err(e) => text.push_str(&format!("{e:#}")),
|
||||||
}
|
}
|
||||||
|
// `git diff HEAD` skips untracked files: show them as additions too.
|
||||||
|
// `--no-index` exits 1 when the files differ, so read stdout and ignore the status.
|
||||||
|
for f in git(&["ls-files", "--others", "--exclude-standard"])
|
||||||
|
.unwrap_or_default()
|
||||||
|
.lines()
|
||||||
|
{
|
||||||
|
if let Ok(o) = std::process::Command::new("git")
|
||||||
|
.args(["diff", "--no-index", "--", "/dev/null", f])
|
||||||
|
.current_dir(worktree)
|
||||||
|
.output()
|
||||||
|
{
|
||||||
|
text.push_str(&String::from_utf8_lossy(&o.stdout));
|
||||||
|
}
|
||||||
|
}
|
||||||
Pager {
|
Pager {
|
||||||
title: "diff".into(),
|
title: "diff".into(),
|
||||||
lines: lines_of(&text),
|
lines: lines_of(&text),
|
||||||
@@ -768,12 +803,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 +917,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 +1039,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 +1049,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(),
|
||||||
@@ -1402,6 +1449,14 @@ end = "escalated"
|
|||||||
assert!(tr.lines.last().unwrap().contains("ended: escalated"));
|
assert!(tr.lines.last().unwrap().contains("ended: escalated"));
|
||||||
// the agent's (here: the shell's) untracked file shows up in the diff view
|
// the agent's (here: the shell's) untracked file shows up in the diff view
|
||||||
assert!(diff_of(&d.worktree).lines.iter().any(|l| l == "?? n"));
|
assert!(diff_of(&d.worktree).lines.iter().any(|l| l == "?? n"));
|
||||||
|
// files inside a new folder are listed one by one, not collapsed to "sub/"
|
||||||
|
std::fs::create_dir_all(Path::new(&d.worktree).join("sub")).unwrap();
|
||||||
|
std::fs::write(Path::new(&d.worktree).join("sub/f"), "x").unwrap();
|
||||||
|
let lines = diff_of(&d.worktree).lines;
|
||||||
|
assert!(lines.iter().any(|l| l == "?? sub/f"));
|
||||||
|
// and its content appears as an added file
|
||||||
|
assert!(lines.iter().any(|l| l == "+++ b/sub/f"), "{lines:?}");
|
||||||
|
assert!(lines.iter().any(|l| l == "+x"), "{lines:?}");
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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
@@ -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),
|
||||||
|
|||||||
@@ -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!(
|
||||||
|
|||||||
Reference in new issue
Block a user