14 Commits
Author SHA1 Message Date
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
Johannes KresnerandClaude Opus 5.5 20f88d88df feat: orch up starts issue sessions in existing worktrees
build / version (push) Successful in 1m20s
build / build (aarch64-apple-darwin) (push) Successful in 5m55s
build / build (x86_64-unknown-linux-musl) (push) Successful in 4m1s
build / release (push) Successful in 21s
orch up MANIFEST reads an issue manifest (a path, or NAME in manifest_dir,
default <config>/manifests, set in <config>/config.toml) and starts one
detached session per listed worktree, across repos. Each worktree brings its
own machine, profile and .hx/task.md; the task text now reaches the agent.
Sessions live in <state>/issues.db; orch issues shows them grouped by issue.

Also: liveness checks use kill(pid, 0) instead of /proc (broken on macOS),
the same branch name in two repos no longer counts as the same place, and
the merge queue column ticket is renamed to issue (migrated on open).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:56:58 +01:00
gitea-actions 440b19180e ci: bin.json v0.1.6 2026-11-15 22:21:54 +00:00
johannesandClaude Sonnet 5.5 f652e607f6 fix: diff view lists files in new folders and shows untracked content
build / version (push) Successful in 9s
build / build (aarch64-apple-darwin) (push) Successful in 4m27s
build / build (x86_64-unknown-linux-musl) (push) Successful in 3m47s
build / release (push) Successful in 19s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 23:13:12 +01:00
gitea-actions 8c4361acee ci: bin.json v0.1.5 2026-11-15 21:59:36 +00:00
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
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
johannes 8539e0308d feat: add local profiles inspection before global
build / version (push) Successful in 9s
build / build (aarch64-apple-darwin) (push) Successful in 3m57s
build / build (x86_64-unknown-linux-musl) (push) Successful in 3m35s
build / release (push) Successful in 20s
2026-11-15 22:05:56 +01:00
gitea-actions ef53278466 ci: bin.json v0.1.1 2026-11-15 15:23:13 +00:00
21 changed files with 1002 additions and 99 deletions

No files matched your search

+1 -1
View File
@@ -17,7 +17,7 @@ A point where a session waits on the human: a permission request, a review, a qu
_Avoid_: Prompt, interrupt (an interrupt is something the human sends) _Avoid_: Prompt, interrupt (an interrupt is something the human sends)
**Named worktree**: **Named worktree**:
A worktree or branch the human picks for a session, such as a ticket branch, instead of the default `hx/sN-slug`. orch never deletes one it did not create. A worktree or branch the human picks for a session, such as an issue branch, instead of the default `hx/sN-slug`. orch never deletes one it did not create.
_Avoid_: Custom branch, existing worktree _Avoid_: Custom branch, existing worktree
**Host**: **Host**:
+36 -1
View File
@@ -13,9 +13,12 @@ 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
orch up MANIFEST one detached session per worktree of an issue (any repos)
orch issues TUI on the sessions `orch up` started, grouped by issue
## How a run goes ## How a run goes
@@ -54,7 +57,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 +74,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
@@ -101,6 +106,36 @@ first served); after each merge all checks run again on main in a clean worktree
`ORCH_REPO` and `ORCH_SESSION`, and `{{repo}}` in `cmd`; the example machines merge with `ORCH_REPO` and `ORCH_SESSION`, and `{{repo}}` in `cmd`; the example machines merge with
`git -C {{repo}} merge --ff-only {{branch}}` in `mark-merged`. `git -C {{repo}} merge --ff-only {{branch}}` in `mark-merged`.
## Issues: `orch up`
For work on an issue that spans worktrees you made yourself, in one repo or several. Each worktree has its own
machine, profile and task text in its `.hx/` (`.hx` should be git-ignored). A manifest lists them:
```toml
# <manifest_dir>/ABC-123.toml
issue = "ABC-123"
[[session]]
worktree = "~/Repos/api/.worktrees/abc-123" # an existing linked worktree; its repo follows from it
name = "api endpoint"
machine = "abc-123" # <worktree>/.hx/machines/, then the repo's .hx/machines/, then ~/.hx/machines/
profile = "abc-123" # <worktree>/.hx/profiles/, then <config>/profiles/
# task = ".hx/task.md" # default, relative to the worktree; given to the agent with every prompt
# merge = false # default: the session ends at `done` and the branch stays for a pull request
```
`orch up ABC-123` reads `<manifest_dir>/ABC-123.toml` (or takes a path), checks every entry first and starts nothing
when one is broken, then starts one detached session per worktree and returns. Logs go to
`<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`):
```toml
manifest_dir = "~/notes/manifests"
```
## More ## More
- [docs/cmd-protocol.md](docs/cmd-protocol.md): task sources and result sinks as external commands (+ JSON schema) - [docs/cmd-protocol.md](docs/cmd-protocol.md): task sources and result sinks as external commands (+ JSON schema)
+3 -3
View File
@@ -1,7 +1,7 @@
{ {
"version": "0.1.0", "version": "0.1.7",
"sha256": { "sha256": {
"aarch64-apple-darwin": "910820e932ae36b65e313a23fa66c5ca5c0a0aa93fc00dc3dbf8441be1a2bcb5", "aarch64-apple-darwin": "b98180cf50d2a7d2f3864b2535f9776e496b91bb451f790de5c9a8cfb00fc8d6",
"x86_64-unknown-linux-musl": "9964dc4ff29edc7289503d52b07ae45de9a604343d6003710718bc11c3d87076" "x86_64-unknown-linux-musl": "5dc06c2d43afb92611a6b3a6fcd7270a22cef06c0985338b851ef278cb2292e7"
} }
} }
+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) # 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), 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. # 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`) ## Allowlist (`allow`)
+3 -9
View File
@@ -63,17 +63,11 @@ 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"]) cmd.args(parts).args(p.acp_flags());
cmd.args(["serve", "--acp", "--cwd"])
.arg(worktree) .arg(worktree)
.args(["--session", id]); .args(["--session", id]);
// the TUI answers permission requests itself, so yolo only when the profile asks for it explicitly
let flags = p.hx_flags();
cmd.args(
flags
.iter()
.filter(|f| **f != "--yolo" || p.yolo == Some(true)),
);
// 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
cmd.env_clear().envs(hx_env(std::env::vars(), p)); cmd.env_clear().envs(hx_env(std::env::vars(), p));
if let Some(h) = &p.home { if let Some(h) = &p.home {
+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",
+87 -7
View File
@@ -30,7 +30,7 @@ create table if not exists commands(
id integer primary key autoincrement, session_id text not null, kind text not null, id integer primary key autoincrement, session_id text not null, kind text not null,
payload text not null default '{}', at integer not null, done integer not null default 0); payload text not null default '{}', at integer not null, done integer not null default 0);
create table if not exists merge_queue( create table if not exists merge_queue(
ticket integer primary key autoincrement, session_id text not null unique); issue integer primary key autoincrement, session_id text not null unique);
create table if not exists needs( create table if not exists needs(
id integer primary key autoincrement, session_id text not null, kind text not null, id integer primary key autoincrement, session_id text not null, kind text not null,
payload text not null default '{}', created_at integer not null, answer text, payload text not null default '{}', created_at integer not null, answer text,
@@ -119,6 +119,15 @@ impl Db {
conn.busy_timeout(std::time::Duration::from_secs(5))?; conn.busy_timeout(std::time::Duration::from_secs(5))?;
conn.pragma_update(None, "journal_mode", "WAL")?; conn.pragma_update(None, "journal_mode", "WAL")?;
conn.execute_batch(SCHEMA)?; conn.execute_batch(SCHEMA)?;
// databases from before the rename call the merge queue's number `ticket`
let old: bool = conn.query_row(
"select count(*) > 0 from pragma_table_info('merge_queue') where name = 'ticket'",
[],
|r| r.get(0),
)?;
if old {
conn.execute_batch("alter table merge_queue rename column ticket to issue")?;
}
Ok(Self { Ok(Self {
conn, conn,
path: path.to_path_buf(), path: path.to_path_buf(),
@@ -184,14 +193,14 @@ impl Db {
Ok(rows.collect::<rusqlite::Result<_>>()?) Ok(rows.collect::<rusqlite::Result<_>>()?)
} }
/// Joins the merge queue (once) and returns the ticket; lower tickets merge first. /// Joins the merge queue (once) and returns the issue; lower issues merge first.
pub fn queue_join(&self, session: &str) -> Result<i64> { pub fn queue_join(&self, session: &str) -> Result<i64> {
self.conn.execute( self.conn.execute(
"insert or ignore into merge_queue(session_id) values (?1)", "insert or ignore into merge_queue(session_id) values (?1)",
[session], [session],
)?; )?;
Ok(self.conn.query_row( Ok(self.conn.query_row(
"select ticket from merge_queue where session_id = ?1", "select issue from merge_queue where session_id = ?1",
[session], [session],
|r| r.get(0), |r| r.get(0),
)?) )?)
@@ -202,7 +211,7 @@ impl Db {
Ok(self Ok(self
.conn .conn
.query_row( .query_row(
"select session_id from merge_queue order by ticket limit 1", "select session_id from merge_queue order by issue limit 1",
[], [],
|r| r.get(0), |r| r.get(0),
) )
@@ -212,8 +221,8 @@ impl Db {
/// 1 = head of the queue. /// 1 = head of the queue.
pub fn queue_position(&self, session: &str) -> Result<usize> { pub fn queue_position(&self, session: &str) -> Result<usize> {
let n: i64 = self.conn.query_row( let n: i64 = self.conn.query_row(
"select count(*) from merge_queue where ticket <= "select count(*) from merge_queue where issue <=
(select ticket from merge_queue where session_id = ?1)", (select issue from merge_queue where session_id = ?1)",
[session], [session],
|r| r.get(0), |r| r.get(0),
)?; )?;
@@ -369,6 +378,27 @@ 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",
@@ -377,6 +407,20 @@ impl Db {
Ok(()) Ok(())
} }
/// Every `options` event of a session merged into one object, later keys win (`no_merge`, and for an issue
/// session `issue`, `repo`, `profile` and `task`).
pub fn options(&self, session: &str) -> Result<serde_json::Map<String, Value>> {
let mut m = serde_json::Map::new();
for e in self.events(Some(session), 0)? {
if e.kind == "options"
&& let Value::Object(o) = e.payload
{
m.extend(o);
}
}
Ok(m)
}
/// Append one event; returns its id. /// Append one event; returns its id.
pub fn emit(&self, session: &str, kind: &str, payload: Value) -> Result<i64> { pub fn emit(&self, session: &str, kind: &str, payload: Value) -> Result<i64> {
self.conn.execute( self.conn.execute(
@@ -493,10 +537,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),
)?; )?;
@@ -539,6 +585,28 @@ mod tests {
(Db::open(&d.join("orch.db")).unwrap(), d) (Db::open(&d.join("orch.db")).unwrap(), d)
} }
#[test]
fn old_merge_queue_column_is_renamed() {
let d = std::env::temp_dir().join(format!("orch-db-mq-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
let path = d.join("orch.db");
Connection::open(&path)
.unwrap()
.execute_batch(
"create table merge_queue(ticket integer primary key autoincrement, session_id text not null unique);
insert into merge_queue(session_id) values ('s1');",
)
.unwrap();
let db = Db::open(&path).unwrap();
assert_eq!(db.queue_head().unwrap().as_deref(), Some("s1"));
db.queue_join("s2").unwrap();
assert_eq!(db.queue_position("s2").unwrap(), 2);
drop(db);
Db::open(&path).unwrap(); // a second open finds nothing to rename
let _ = std::fs::remove_dir_all(&d);
}
#[test] #[test]
fn roundtrip() { fn roundtrip() {
let (db, dir) = temp_db("rt"); let (db, dir) = temp_db("rt");
@@ -566,6 +634,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();
+337
View File
@@ -0,0 +1,337 @@
//! Issues: `orch up MANIFEST` starts one detached session per worktree an issue manifest lists. The worktrees may
//! belong to different repos, so these sessions live in one database of their own, `<state>/issues.db`, which
//! `orch issues` shows. Each session keeps its repo, profile file and task text in an `options` event.
use crate::db::Db;
use crate::machine::Machine;
use crate::place::Place;
use crate::profile::Profile;
use crate::run::git;
use anyhow::{Context, Result, bail, ensure};
use serde::Deserialize;
use serde_json::json;
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
/// `<config>/config.toml`. Every key is optional.
#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct Config {
/// Where `orch up NAME` looks for `NAME.toml` (default `<config>/manifests`).
manifest_dir: Option<String>,
}
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct Manifest {
issue: String,
#[serde(default, rename = "session")]
sessions: Vec<Entry>,
}
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct Entry {
/// Path of an existing linked worktree (`~` allowed).
worktree: String,
name: String,
/// `<worktree>/.hx/machines/NAME.toml`, then the repo's `.hx/machines/`, then `~/.hx/machines/`.
machine: String,
/// `<worktree>/.hx/profiles/NAME.toml`, then `<config>/profiles/NAME.toml`.
profile: String,
/// Task text for the agent, relative to the worktree.
#[serde(default = "default_task")]
task: String,
/// Run the machine's merge state; by default the session stops at `done` and the branch stays for a PR.
#[serde(default)]
merge: bool,
}
fn default_task() -> String {
".hx/task.md".into()
}
/// A checked manifest entry: everything it names exists and parses.
struct Planned {
name: String,
worktree: PathBuf,
branch: String,
repo: PathBuf,
machine: PathBuf,
profile: PathBuf,
task: String,
merge: bool,
}
pub fn db_path() -> PathBuf {
crate::state_dir().join("issues.db")
}
fn expand(p: &str) -> PathBuf {
match p.strip_prefix("~/") {
Some(rest) => PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(rest),
None => PathBuf::from(p),
}
}
fn manifest_dir() -> Result<PathBuf> {
let file = crate::config_dir().join("config.toml");
let cfg: Config = match std::fs::read_to_string(&file) {
Ok(s) => toml::from_str(&s).with_context(|| file.display().to_string())?,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Config::default(),
Err(e) => return Err(e).with_context(|| file.display().to_string()),
};
Ok(cfg
.manifest_dir
.map_or_else(|| crate::config_dir().join("manifests"), |d| expand(&d)))
}
/// A manifest file as given, else `<manifest_dir>/ARG.toml`.
fn manifest_path(arg: &str) -> Result<PathBuf> {
let p = expand(arg);
if p.is_file() {
return Ok(p);
}
let dir = manifest_dir()?;
let file = if arg.ends_with(".toml") {
dir.join(arg)
} else {
dir.join(format!("{arg}.toml"))
};
ensure!(
file.is_file(),
"no manifest {arg:?}: neither a file nor {}",
file.display()
);
Ok(file)
}
fn first_file(candidates: &[PathBuf], what: &str) -> Result<PathBuf> {
candidates
.iter()
.find(|p| p.is_file())
.cloned()
.with_context(|| format!("{what} not found in {candidates:?}"))
}
fn plan(e: &Entry) -> Result<Planned> {
let wt = expand(&e.worktree)
.canonicalize()
.with_context(|| format!("worktree {}", e.worktree))?;
let common = git(
&wt,
&["rev-parse", "--path-format=absolute", "--git-common-dir"],
)
.with_context(|| format!("{} is not in a git repo", wt.display()))?;
let common = PathBuf::from(common.trim()).canonicalize()?;
let repo = common
.parent()
.context("git common dir has no parent")?
.to_path_buf();
let Place::Worktree { path, branch } = crate::place::resolve(&repo, &wt.to_string_lossy())?
else {
bail!(
"{} is not a linked worktree of {}",
wt.display(),
repo.display()
);
};
let home = PathBuf::from(std::env::var_os("HOME").unwrap_or_default());
let mfile = format!("{}.toml", e.machine);
let machine = first_file(
&[
wt.join(".hx/machines").join(&mfile),
repo.join(".hx/machines").join(&mfile),
home.join(".hx/machines").join(&mfile),
],
&format!("machine {:?}", e.machine),
)?;
Machine::load(&machine)?;
let pfile = format!("{}.toml", e.profile);
let profile = first_file(
&[
wt.join(".hx/profiles").join(&pfile),
crate::config_dir().join("profiles").join(&pfile),
],
&format!("profile {:?}", e.profile),
)?;
Profile::load_path(&profile)?;
let task_file = wt.join(&e.task);
let task = std::fs::read_to_string(&task_file)
.with_context(|| format!("task file {}", task_file.display()))?;
Ok(Planned {
name: e.name.clone(),
worktree: path,
branch,
repo,
machine,
profile,
task,
merge: e.merge,
})
}
/// Starts `orch launch ID` in its own process session: it outlives the terminal and logs to `<state>/logs/`.
pub fn spawn(db: &Db, id: &str) -> Result<()> {
let logs = crate::state_dir().join("logs");
std::fs::create_dir_all(&logs)?;
let log = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(logs.join(format!("issue-{id}.log")))?;
let mut cmd = Command::new(std::env::current_exe()?);
cmd.args(["launch", id])
.stdin(Stdio::null())
.stdout(log.try_clone()?)
.stderr(log);
// SAFETY: setsid is async-signal-safe; it detaches the child from this terminal's session.
unsafe {
cmd.pre_exec(|| {
libc::setsid();
Ok(())
});
}
let child = cmd.spawn()?;
// the child runs the session with this very pid: a second `orch up` sees it as live right away
db.set_pid(id, Some(child.id()))?;
Ok(())
}
/// What `orch up` did with one manifest entry.
pub struct Outcome {
pub session: String,
pub name: String,
pub what: String,
}
/// Checks every entry of the manifest first and starts nothing when one is broken. Then, per worktree: a new
/// session is created and started; one that is still running or done is left alone; one that stopped unfinished
/// (suspended, or its process died) is started again. A failed one is left for `R` in `orch issues`.
pub fn up(arg: &str) -> 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())?;
ensure!(
!m.issue.trim().is_empty(),
"{}: issue is empty",
file.display()
);
ensure!(!m.sessions.is_empty(), "{}: no [[session]]", file.display());
let planned = m
.sessions
.iter()
.map(|e| plan(e).with_context(|| format!("session {:?}", e.name)))
.collect::<Result<Vec<_>>>()?;
for (i, p) in planned.iter().enumerate() {
ensure!(
planned[..i].iter().all(|q| q.worktree != p.worktree),
"{} is listed twice",
p.worktree.display()
);
}
let db = Db::open(&db_path())?;
let mut out = vec![];
for p in planned {
let wt = p.worktree.to_string_lossy().into_owned();
let last = db.sessions()?.into_iter().rev().find(|s| s.worktree == wt);
let (session, what) = match last {
Some(s) => {
let live = s.pid.is_some_and(crate::state::pid_alive);
let what = match s.status.as_str() {
"done" | "merged" => "done already".to_string(),
_ if live => "running already".into(),
"suspended" | "running" | "waiting" | "queued" => {
spawn(&db, &s.id)?;
"started again".into()
}
other => format!("{other}: restart it with R in orch issues"),
};
(s.id, what)
}
None => {
let place = Place::Worktree {
path: p.worktree.clone(),
branch: p.branch.clone(),
};
let repo_name = p.repo.file_name().unwrap_or_default().to_string_lossy();
let s = crate::runner::create_in(
&db,
&crate::state_dir().join("worktrees"),
&p.name,
&repo_name,
&p.machine.to_string_lossy(),
&[],
&place,
!p.merge,
)?;
db.emit(
&s.id,
"options",
json!({
"issue": m.issue, "repo": p.repo, "profile": p.profile, "task": p.task,
}),
)?;
spawn(&db, &s.id)?;
(s.id, "started".into())
}
};
out.push(Outcome {
session,
name: p.name,
what,
});
}
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())?;
let s = db
.session(id)?
.with_context(|| format!("no session {id}"))?;
ensure!(
!matches!(
s.status.as_str(),
"done" | "merged" | "failed" | "escalated" | "aborted"
),
"session {id} already ended ({})",
s.status
);
let fallback = Profile::load("default")?;
let (m, repo, profile) = crate::runner::launch(&db, id, Path::new("."), &fallback)?;
crate::runner::run_session(&db, &m, id, &repo, "", &profile)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn manifest_defaults_and_unknown_keys() {
let m: Manifest = toml::from_str(
r#"issue = "ABC-1"
[[session]]
worktree = "~/wt"
name = "api"
machine = "m"
profile = "p"
"#,
)
.unwrap();
assert_eq!(m.sessions[0].task, ".hx/task.md");
assert!(!m.sessions[0].merge);
assert!(
toml::from_str::<Manifest>("issue = \"x\"\nworkers = 2").is_err(),
"a typo must not pass silently"
);
}
#[test]
fn tilde_expands_to_home() {
let home = std::env::var("HOME").unwrap();
assert_eq!(expand("~/a/b"), PathBuf::from(home).join("a/b"));
assert_eq!(expand("/x"), PathBuf::from("/x"));
}
}
+5 -1
View File
@@ -134,8 +134,12 @@ impl Machine {
v v
} }
/// `<name>.toml` in `<repo>/.hx/machines/`, then `~/.hx/machines/`. /// `<name>.toml` in `<repo>/.hx/machines/`, then `~/.hx/machines/`. An absolute path to a `.toml` file (what
/// `orch up` stores for an issue session) is loaded as it is.
pub fn find(name: &str, repo: &Path) -> Result<Self> { pub fn find(name: &str, repo: &Path) -> Result<Self> {
if Path::new(name).is_absolute() && name.ends_with(".toml") {
return Self::load(Path::new(name));
}
let file = format!("{name}.toml"); let file = format!("{name}.toml");
let dirs = Self::dirs(repo); let dirs = Self::dirs(repo);
for d in &dirs { for d in &dirs {
+63 -9
View File
@@ -6,6 +6,7 @@ mod db;
mod detail; mod detail;
mod goal; mod goal;
mod init; mod init;
mod issue;
mod junit; mod junit;
mod lock; mod lock;
mod machine; mod machine;
@@ -126,13 +127,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,
@@ -140,6 +144,13 @@ enum Cmd {
#[arg(long, default_value = "default")] #[arg(long, default_value = "default")]
profile: String, profile: String,
}, },
/// Start one detached session per worktree of an issue manifest (a file, or NAME in `manifest_dir`).
Up { manifest: String },
/// 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).
#[command(hide = true)]
Launch { id: String },
/// hx extension that enforces a run's tool allowlist (started by hx, not by hand). /// hx extension that enforces a run's tool allowlist (started by hx, not by hand).
#[command(hide = true)] #[command(hide = true)]
Guard { policy: PathBuf }, Guard { policy: PathBuf },
@@ -191,10 +202,47 @@ fn code(ok: bool) -> std::process::ExitCode {
fn main() -> Result<std::process::ExitCode> { fn main() -> Result<std::process::ExitCode> {
let Some(cmd) = Cli::parse().cmd else { let Some(cmd) = Cli::parse().cmd else {
tui::run()?; tui::run(false)?;
return Ok(code(true)); return Ok(code(true));
}; };
match cmd { match cmd {
Cmd::Issues => {
tui::run(true)?;
Ok(code(true))
}
Cmd::Up { manifest } => {
for o in issue::up(&manifest)? {
println!("{} {}: {}", o.session, o.name, o.what);
}
println!("watch them with: orch issues");
Ok(code(true))
}
Cmd::Launch { id } => match issue::launch(&id) {
Ok(status) => {
println!("{id} -> {status}");
Ok(code(status == "merged" || status == "done"))
}
Err(e) => {
// the TUI shows why; without this the session would sit there as queued
if let Ok(db) = db::Db::open(&issue::db_path())
&& db.session(&id).ok().flatten().is_some_and(|s| {
!matches!(
s.status.as_str(),
"done" | "merged" | "failed" | "escalated" | "aborted"
)
})
{
let _ = db.set_session(&id, "", "failed");
let _ = db.set_pid(&id, None);
let _ = db.emit(
&id,
"end",
serde_json::json!({"status": "failed", "reason": format!("{e:#}")}),
);
}
Err(e)
}
},
Cmd::Init { repo, force } => { Cmd::Init { repo, force } => {
let written = init::run(&repo, &config_dir(), force)?; let written = init::run(&repo, &config_dir(), force)?;
for p in &written { for p in &written {
@@ -258,24 +306,30 @@ 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
.is_none_or(|p| !Path::new(&format!("/proc/{p}")).exists() .is_none_or(|p| !state::pid_alive(p) || p == std::process::id()),
|| p == std::process::id()),
"session {id} is still running (pid {})", "session {id} is still running (pid {})",
s.pid.unwrap_or(0) s.pid.unwrap_or(0)
); );
+12 -9
View File
@@ -1,4 +1,4 @@
//! Where a new session works: a fresh branch and worktree (the default), or one the user names, such as a ticket //! Where a new session works: a fresh branch and worktree (the default), or one the user names, such as an issue
//! branch. orch never removes a worktree it did not create, so nothing here has a cleanup side. //! branch. orch never removes a worktree it did not create, so nothing here has a cleanup side.
use crate::db::Db; use crate::db::Db;
@@ -90,12 +90,12 @@ pub fn ensure_free(db: &Db, place: &Place) -> Result<()> {
let (branch, path) = match place { let (branch, path) = match place {
Place::Fresh => return Ok(()), Place::Fresh => return Ok(()),
Place::Branch(b) => (Some(b.as_str()), None), Place::Branch(b) => (Some(b.as_str()), None),
Place::Worktree { path, branch } => (Some(branch.as_str()), Some(path)), // the path alone: the same branch name in another repo (one issue, two repos) is another place
Place::Worktree { path, .. } => (None, Some(path)),
}; };
for s in db.sessions()? { for s in db.sessions()? {
let live = matches!(s.status.as_str(), "queued" | "running" | "waiting") let live = matches!(s.status.as_str(), "queued" | "running" | "waiting")
&& s.pid && s.pid.is_none_or(crate::state::pid_alive);
.is_none_or(|p| Path::new(&format!("/proc/{p}")).exists());
let same = Some(s.branch.as_str()) == branch let same = Some(s.branch.as_str()) == branch
|| path.is_some_and(|p| Path::new(&s.worktree) == p.as_path()); || path.is_some_and(|p| Path::new(&s.worktree) == p.as_path());
ensure!(!(live && same), "session {} already works there", s.id); ensure!(!(live && same), "session {} already works there", s.id);
@@ -158,7 +158,7 @@ end = "merged"
); );
assert!(resolve(&repo, "bad name").is_err()); assert!(resolve(&repo, "bad name").is_err());
assert!(resolve(&repo, "/nowhere/else").is_err()); assert!(resolve(&repo, "/nowhere/else").is_err());
let wt = dir.join("ticket"); let wt = dir.join("issue");
git( git(
&repo, &repo,
&["worktree", "add", "-b", "PROJ-9", &wt.to_string_lossy()], &["worktree", "add", "-b", "PROJ-9", &wt.to_string_lossy()],
@@ -173,7 +173,7 @@ end = "merged"
branch: "PROJ-9".into(), branch: "PROJ-9".into(),
}; };
assert_eq!(resolve(&repo, "PROJ-9").unwrap(), want, "by branch"); assert_eq!(resolve(&repo, "PROJ-9").unwrap(), want, "by branch");
assert_eq!(resolve(&repo, "ticket").unwrap(), want, "by directory name"); assert_eq!(resolve(&repo, "issue").unwrap(), want, "by directory name");
assert_eq!( assert_eq!(
resolve(&repo, &listed[0].path.to_string_lossy()).unwrap(), resolve(&repo, &listed[0].path.to_string_lossy()).unwrap(),
want, want,
@@ -185,18 +185,20 @@ end = "merged"
#[test] #[test]
fn named_worktree_is_used_kept_and_not_merged_on_request() { fn named_worktree_is_used_kept_and_not_merged_on_request() {
let (dir, repo, db) = setup("named"); let (dir, repo, db) = setup("named");
let wt = dir.join("ticket"); let wt = dir.join("issue");
git( git(
&repo, &repo,
&["worktree", "add", "-b", "PROJ-9", &wt.to_string_lossy()], &["worktree", "add", "-b", "PROJ-9", &wt.to_string_lossy()],
) )
.unwrap(); .unwrap();
let place = resolve(&repo, "PROJ-9").unwrap(); let place = resolve(&repo, "PROJ-9").unwrap();
let s = runner::create_in(&db, &dir.join("wts"), "t", "m", &[], &place, true).unwrap(); let s = runner::create_in(&db, &dir.join("wts"), "t", "", "m", &[], &place, true).unwrap();
assert_eq!(s.branch, "PROJ-9"); assert_eq!(s.branch, "PROJ-9");
assert_eq!(db.session(&s.id).unwrap().unwrap().worktree, s.worktree); assert_eq!(db.session(&s.id).unwrap().unwrap().worktree, s.worktree);
// a second session may not take the same worktree while the first is live // a second session may not take the same worktree while the first is live
assert!(runner::create_in(&db, &dir.join("wts"), "u", "m", &[], &place, false).is_err()); assert!(
runner::create_in(&db, &dir.join("wts"), "u", "", "m", &[], &place, false).is_err()
);
let m = Machine::parse(M).unwrap(); let m = Machine::parse(M).unwrap();
let status = let status =
runner::run_session(&db, &m, &s.id, &repo, "", &Profile::parse("").unwrap()).unwrap(); runner::run_session(&db, &m, &s.id, &repo, "", &Profile::parse("").unwrap()).unwrap();
@@ -219,6 +221,7 @@ end = "merged"
&db, &db,
&dir.join("wts"), &dir.join("wts"),
b, b,
"",
"m", "m",
&[], &[],
&Place::Branch(b.into()), &Place::Branch(b.into()),
+39 -8
View File
@@ -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)?;
@@ -168,13 +178,28 @@ impl Profile {
f 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 =
std::fs::read_to_string(path).with_context(|| format!("profile {}", path.display()))?;
Self::parse(&s).with_context(|| path.display().to_string())
}
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 => {
@@ -192,10 +217,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 {
@@ -265,6 +287,15 @@ mod tests {
assert_eq!(f("sandbox=false"), ["--auto"]); 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] #[test]
fn bwrap_lookup_scans_path() { fn bwrap_lookup_scans_path() {
let dir = std::env::temp_dir().join(format!("orch-bwrap-{}", std::process::id())); let dir = std::env::temp_dir().join(format!("orch-bwrap-{}", std::process::id()));
+88 -13
View File
@@ -15,7 +15,7 @@ use serde_json::{Value, json};
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::io::Read; use std::io::Read;
use std::os::unix::process::CommandExt; use std::os::unix::process::CommandExt;
use std::path::Path; use std::path::{Path, PathBuf};
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
@@ -82,10 +82,12 @@ pub fn create_after(
/// Like [`create_after`], working in a branch or worktree the user named. With `no_merge` the session stops at /// Like [`create_after`], working in a branch or worktree the user named. With `no_merge` the session stops at
/// `done` where its machine would run the state that ends as `merged`, and leaves the branch for a pull request. /// `done` where its machine would run the state that ends as `merged`, and leaves the branch for a pull request.
#[allow(clippy::too_many_arguments)] // shortcut: one caller each in the TUI form and `orch up`
pub fn create_in( pub fn create_in(
db: &Db, db: &Db,
worktrees: &Path, worktrees: &Path,
name: &str, name: &str,
subtitle: &str,
machine: &str, machine: &str,
after: &[String], after: &[String],
place: &crate::place::Place, place: &crate::place::Place,
@@ -93,7 +95,7 @@ pub fn create_in(
) -> Result<Session> { ) -> Result<Session> {
use crate::place::Place; use crate::place::Place;
crate::place::ensure_free(db, place)?; crate::place::ensure_free(db, place)?;
let mut s = create_after(db, worktrees, name, "", machine, after)?; let mut s = create_after(db, worktrees, name, subtitle, machine, after)?;
match place { match place {
Place::Fresh => {} Place::Fresh => {}
Place::Branch(b) => s.branch = b.clone(), Place::Branch(b) => s.branch = b.clone(),
@@ -127,7 +129,7 @@ fn ensure_worktree(repo: &Path, s: &Session) -> Result<()> {
std::fs::create_dir_all(wt.parent().context("worktree has no parent")?)?; std::fs::create_dir_all(wt.parent().context("worktree has no parent")?)?;
// git races on its own locks when worktrees are added in parallel // git races on its own locks when worktrees are added in parallel
let _l = crate::lock::lock(&repo.join(".git/orch-worktree.lock"))?; let _l = crate::lock::lock(&repo.join(".git/orch-worktree.lock"))?;
// a branch the user named may exist already (a ticket branch): check it out instead of creating it // a branch the user named may exist already (an issue branch): check it out instead of creating it
let exists = git( let exists = git(
repo, repo,
&[ &[
@@ -386,6 +388,8 @@ struct Ctx<'a> {
repo: &'a Path, repo: &'a Path,
ctl: Ctl<'a>, ctl: Ctl<'a>,
agent: Option<Acp>, agent: Option<Acp>,
/// The task text (`orch up` reads it from the worktree's task file); empty for other sessions.
body: String,
} }
enum Outcome { enum Outcome {
@@ -676,7 +680,7 @@ fn run_command(cx: &Ctx, st: &State, step: &Step) -> Result<StepRes> {
} }
/// Instruction text for a prompt kind. The kind itself is sent too, so hx can use its own prompts. /// Instruction text for a prompt kind. The kind itself is sent too, so hx can use its own prompts.
fn instruction(kind: &str, goal: Option<&str>, t: &Task) -> String { fn instruction(kind: &str, goal: Option<&str>, t: &Task, body: &str) -> String {
let lead = match kind { let lead = match kind {
"plan" => "Plan the work for this task. Report the plan with hx/plan.", "plan" => "Plan the work for this task. Report the plan with hx/plan.",
"implement" => "Implement this task, following the plan.", "implement" => "Implement this task, following the plan.",
@@ -689,6 +693,9 @@ fn instruction(kind: &str, goal: Option<&str>, t: &Task) -> String {
if let Some(g) = goal { if let Some(g) = goal {
s.push_str(&format!("\nGoal: {g}")); s.push_str(&format!("\nGoal: {g}"));
} }
if !body.trim().is_empty() {
s.push_str(&format!("\n\n{}", body.trim()));
}
s s
} }
@@ -730,7 +737,7 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result<StepRes> {
let agent = cx.agent.as_mut().expect("spawned above"); let agent = cx.agent.as_mut().expect("spawned above");
let r: StepResult = agent.step( let r: StepResult = agent.step(
kind, kind,
&instruction(kind, goal.as_deref(), cx.task), &instruction(kind, goal.as_deref(), cx.task, &cx.body),
context, context,
json!({}), json!({}),
&mut sink, &mut sink,
@@ -887,6 +894,34 @@ impl Sink for DbSink<'_> {
} }
} }
/// What session `id` runs with: its machine, repo and profile. A issue session (`orch up`) carries its own repo
/// and profile file in its options; any other session uses `repo` and `profile`.
pub fn launch(
db: &Db,
id: &str,
repo: &Path,
profile: &Profile,
) -> Result<(Machine, PathBuf, Profile)> {
let s = db
.session(id)?
.with_context(|| format!("no session {id}"))?;
let task = db
.tasks()?
.into_iter()
.find(|t| t.id == s.task_id)
.with_context(|| format!("no task {}", s.task_id))?;
let o = db.options(id)?;
let repo = o
.get("repo")
.and_then(Value::as_str)
.map_or_else(|| repo.to_path_buf(), PathBuf::from);
let profile = match o.get("profile").and_then(Value::as_str) {
Some(p) => Profile::load_path(Path::new(p))?,
None => profile.clone(),
};
Ok((Machine::find(&task.machine, &repo)?, repo, profile))
}
/// Runs the session to the end of its machine and returns the final status (`merged`, `escalated`, `failed`, ...). /// Runs the session to the end of its machine and returns the final status (`merged`, `escalated`, `failed`, ...).
/// Resumes at `current_state` when the session was started before (orchestrator restart). /// Resumes at `current_state` when the session was started before (orchestrator restart).
pub fn run_session( pub fn run_session(
@@ -929,6 +964,12 @@ pub fn run_session(
repo, repo,
ctl, ctl,
agent: None, agent: None,
body: db
.options(id)?
.get("task")
.and_then(Value::as_str)
.unwrap_or_default()
.into(),
}; };
let mut resumed = !s.state.is_empty(); let mut resumed = !s.state.is_empty();
let (mut cur, mut from) = if resumed { let (mut cur, mut from) = if resumed {
@@ -938,10 +979,7 @@ pub fn run_session(
(m.start().name.clone(), String::new()) (m.start().name.clone(), String::new())
}; };
db.set_pid(id, Some(std::process::id()))?; db.set_pid(id, Some(std::process::id()))?;
let no_merge = db let no_merge = db.options(id)?.get("no_merge") == Some(&json!(true));
.events(Some(id), 0)?
.iter()
.any(|e| e.kind == "options" && e.payload["no_merge"] == true);
for _ in 0..MAX_TRANSITIONS { for _ in 0..MAX_TRANSITIONS {
let st = m let st = m
.state(&cur) .state(&cur)
@@ -1074,9 +1112,7 @@ fn alive(db: &Db, session: &str) -> bool {
let Some(pid) = db.session(session).ok().flatten().and_then(|s| s.pid) else { let Some(pid) = db.session(session).ok().flatten().and_then(|s| s.pid) else {
return false; return false;
}; };
// SAFETY: signal 0 only checks that the process exists. crate::state::pid_alive(pid)
let r = unsafe { libc::kill(pid as i32, 0) };
r == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
} }
/// Joins the merge queue and blocks until this session is at the head. /// Joins the merge queue and blocks until this session is at the head.
@@ -1279,6 +1315,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}"
@@ -1756,7 +1831,7 @@ end = "merged"
let e = env("stale"); let e = env("stale");
let m = one_step(r#"{ name = "w", run = "computer", cmd = "true" }"#); let m = one_step(r#"{ name = "w", run = "computer", cmd = "true" }"#);
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
// a crashed orchestrator left its ticket at the head; its pid is gone // a crashed orchestrator left its issue at the head; its pid is gone
e.db.add_session(&Session { e.db.add_session(&Session {
id: "s9".into(), id: "s9".into(),
task_id: "s1".into(), task_id: "s1".into(),
+7
View File
@@ -156,6 +156,13 @@ impl Run {
} }
} }
/// Does a process with this pid exist? Works on Linux and macOS (no `/proc` there).
pub fn pid_alive(pid: u32) -> bool {
// SAFETY: signal 0 only checks that the process exists.
let r = unsafe { libc::kill(pid as i32, 0) };
r == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
pub fn kill_group(pgid: u32) { pub fn kill_group(pgid: u32) {
// SAFETY: plain syscall; hx is spawned with process_group(0) so pgid == its pid. // SAFETY: plain syscall; hx is spawned with process_group(0) so pgid == its pid.
unsafe { libc::killpg(pgid as i32, libc::SIGKILL) }; unsafe { libc::killpg(pgid as i32, libc::SIGKILL) };
+14 -18
View File
@@ -2,16 +2,17 @@
//! suspends them (state kept), and `orch session --resume` or the TUI's resume key continues them. //! suspends them (state kept), and `orch session --resume` or the TUI's resume key continues them.
use crate::db::Db; use crate::db::Db;
use crate::machine::Machine;
use crate::profile::Profile; use crate::profile::Profile;
use crate::runner; use crate::runner;
use anyhow::{Context, Result}; use anyhow::Result;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::path::PathBuf; use std::path::PathBuf;
use std::thread::JoinHandle; use std::thread::JoinHandle;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
pub struct Host { pub struct Host {
/// The database the sessions live in: the repo's `.hx/orch.db`, or the issues database.
db_path: PathBuf,
repo: PathBuf, repo: PathBuf,
profile: Profile, profile: Profile,
/// Sessions that wait for a free slot, oldest first. /// Sessions that wait for a free slot, oldest first.
@@ -20,8 +21,9 @@ pub struct Host {
} }
impl Host { impl Host {
pub fn new(repo: PathBuf, profile: Profile) -> Self { pub fn new(db_path: PathBuf, repo: PathBuf, profile: Profile) -> Self {
Self { Self {
db_path,
repo, repo,
profile, profile,
pending: VecDeque::new(), pending: VecDeque::new(),
@@ -75,18 +77,10 @@ impl Host {
} }
fn start(&self, id: &str) -> Result<JoinHandle<()>> { fn start(&self, id: &str) -> Result<JoinHandle<()>> {
let (repo, profile, id) = (self.repo.clone(), self.profile.clone(), id.to_string()); let id = id.to_string();
// fail here, on the caller's thread, when the session or its machine is missing // fail here, on the caller's thread, when the session or its machine is missing
let db = Db::open(&repo.join(".hx/orch.db"))?; let db = Db::open(&self.db_path)?;
let s = db let (m, repo, profile) = runner::launch(&db, &id, &self.repo, &self.profile)?;
.session(&id)?
.with_context(|| format!("no session {id}"))?;
let task = db
.tasks()?
.into_iter()
.find(|t| t.id == s.task_id)
.with_context(|| format!("no task {}", s.task_id))?;
let m = Machine::find(&task.machine, &repo)?;
Ok(std::thread::spawn(move || { Ok(std::thread::spawn(move || {
if let Err(e) = runner::run_session(&db, &m, &id, &repo, "", &profile) { if let Err(e) = runner::run_session(&db, &m, &id, &repo, "", &profile) {
let _ = db.set_session(&id, "", "failed"); let _ = db.set_session(&id, "", "failed");
@@ -126,9 +120,7 @@ pub fn resumable(db: &Db) -> Vec<String> {
.into_iter() .into_iter()
.filter(|s| match s.status.as_str() { .filter(|s| match s.status.as_str() {
"suspended" => true, "suspended" => true,
"running" | "waiting" => s "running" | "waiting" => s.pid.is_none_or(|p| !crate::state::pid_alive(p)),
.pid
.is_none_or(|p| !std::path::Path::new(&format!("/proc/{p}")).exists()),
_ => false, _ => false,
}) })
.map(|s| s.id) .map(|s| s.id)
@@ -210,7 +202,11 @@ end = "merged"
for n in ["one", "two"] { for n in ["one", "two"] {
runner::create_after(&db, &dir.join("wt"), n, "", "sleeper", &[]).unwrap(); runner::create_after(&db, &dir.join("wt"), n, "", "sleeper", &[]).unwrap();
} }
let mut host = Host::new(repo.clone(), Profile::parse("workers = 1").unwrap()); let mut host = Host::new(
repo.join(".hx/orch.db"),
repo.clone(),
Profile::parse("workers = 1").unwrap(),
);
host.submit("s1"); host.submit("s1");
host.submit("s2"); host.submit("s2");
host.submit("s2"); // twice is once host.submit("s2"); // twice is once
+105 -16
View File
@@ -18,11 +18,17 @@ use std::io::IsTerminal;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::time::Duration; use std::time::Duration;
pub fn run() -> Result<()> { /// The TUI on the current directory's `.hx/orch.db`, or with `issues` on the database of `orch up`.
pub fn run(issues: bool) -> Result<()> {
if !std::io::stdout().is_terminal() { if !std::io::stdout().is_terminal() {
bail!("orch needs a terminal; use a subcommand (orch --help) in scripts"); bail!("orch needs a terminal; use a subcommand (orch --help) in scripts");
} }
let mut app = App::new(std::env::current_dir()?); let mut app = App::new(std::env::current_dir()?);
if issues {
app.db_path = crate::issue::db_path();
app.issues = true;
app.rev = "all repos".into();
}
let mut term = ratatui::init(); let mut term = ratatui::init();
let res = event_loop(&mut term, &mut app); let res = event_loop(&mut term, &mut app);
ratatui::restore(); ratatui::restore();
@@ -155,6 +161,10 @@ struct Pager {
struct App { struct App {
repo: PathBuf, repo: PathBuf,
/// `<repo>/.hx/orch.db`, or the issues database.
db_path: PathBuf,
/// Showing the sessions of `orch up` (many repos): no new-session form and no checks on main.
issues: bool,
/// Opened lazily: launching `orch` in a directory without a goal must not create `.hx/orch.db`. /// Opened lazily: launching `orch` in a directory without a goal must not create `.hx/orch.db`.
db: Option<Db>, db: Option<Db>,
events: Vec<Event>, events: Vec<Event>,
@@ -185,7 +195,11 @@ impl App {
fn ensure_host(&mut self) -> Result<&mut host::Host> { fn ensure_host(&mut self) -> Result<&mut host::Host> {
if self.host.is_none() { if self.host.is_none() {
let profile = crate::profile::Profile::load(PROFILE)?; let profile = crate::profile::Profile::load(PROFILE)?;
self.host = Some(host::Host::new(self.repo.clone(), profile)); self.host = Some(host::Host::new(
self.db_path.clone(),
self.repo.clone(),
profile,
));
} }
Ok(self.host.as_mut().expect("just created")) Ok(self.host.as_mut().expect("just created"))
} }
@@ -194,6 +208,14 @@ impl App {
fn resume_all(&mut self) -> Result<usize> { fn resume_all(&mut self) -> Result<usize> {
let Some(db) = &self.db else { return Ok(0) }; let Some(db) = &self.db else { return Ok(0) };
let ids = host::resumable(db); let ids = host::resumable(db);
if self.issues {
// issue sessions run detached, like `orch up` starts them: they outlive this TUI
for id in &ids {
crate::issue::spawn(db, id)?;
}
self.refresh();
return Ok(ids.len());
}
let host = self.ensure_host()?; let host = self.ensure_host()?;
let ids: Vec<String> = ids.into_iter().filter(|id| !host.hosts(id)).collect(); let ids: Vec<String> = ids.into_iter().filter(|id| !host.hosts(id)).collect();
for id in &ids { for id in &ids {
@@ -203,6 +225,31 @@ 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)?;
if self.issues {
crate::issue::spawn(db, id)?;
} else {
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> {
@@ -226,7 +273,7 @@ impl App {
let db = self.db.as_ref().expect("db_or_create opened it"); let db = self.db.as_ref().expect("db_or_create opened it");
let base = self.repo.file_name().unwrap_or_default(); let base = self.repo.file_name().unwrap_or_default();
let wts = crate::state_dir().join("worktrees").join(base); let wts = crate::state_dir().join("worktrees").join(base);
let s = crate::runner::create_in(db, &wts, name, machine, &after, &place, f.no_merge)?; let s = crate::runner::create_in(db, &wts, name, "", machine, &after, &place, f.no_merge)?;
if let Some(h) = &mut self.host { if let Some(h) = &mut self.host {
h.submit(&s.id); h.submit(&s.id);
} }
@@ -251,7 +298,7 @@ impl App {
/// Runs every check on main in the background; the goal view shows `running…` meanwhile. /// Runs every check on main in the background; the goal view shows `running…` meanwhile.
fn run_all_checks(&mut self) { fn run_all_checks(&mut self) {
use std::sync::atomic::Ordering; use std::sync::atomic::Ordering;
if self.checks_running.swap(true, Ordering::SeqCst) { if self.issues || self.checks_running.swap(true, Ordering::SeqCst) {
return; // already running return; // already running
} }
let (repo, flag) = (self.repo.clone(), self.checks_running.clone()); let (repo, flag) = (self.repo.clone(), self.checks_running.clone());
@@ -266,7 +313,7 @@ impl App {
/// The goal database, created on first use by actions that only make sense with one (edit goal, add check). /// The goal database, created on first use by actions that only make sense with one (edit goal, add check).
fn db_or_create(&mut self) -> Option<&Db> { fn db_or_create(&mut self) -> Option<&Db> {
if self.db.is_none() { if self.db.is_none() {
self.db = Db::open(&self.repo.join(".hx/orch.db")).ok(); self.db = Db::open(&self.db_path).ok();
} }
self.db.as_ref() self.db.as_ref()
} }
@@ -408,6 +455,8 @@ impl App {
fn new(repo: PathBuf) -> Self { fn new(repo: PathBuf) -> Self {
let rev = git_rev(&repo); let rev = git_rev(&repo);
Self { Self {
db_path: repo.join(".hx/orch.db"),
issues: false,
repo, repo,
db: None, db: None,
events: vec![], events: vec![],
@@ -430,9 +479,8 @@ impl App {
} }
fn refresh(&mut self) { fn refresh(&mut self) {
let path = self.repo.join(".hx/orch.db"); if self.db.is_none() && self.db_path.exists() {
if self.db.is_none() && path.exists() { self.db = Db::open(&self.db_path).ok();
self.db = Db::open(&path).ok();
} }
if let (Some(h), Some(db)) = (&mut self.host, &self.db) { if let (Some(h), Some(db)) = (&mut self.host, &self.db) {
h.tick(db); h.tick(db);
@@ -475,7 +523,11 @@ impl App {
fn header(&self) -> Header { fn header(&self) -> Header {
let home = std::env::var("HOME").unwrap_or_default(); let home = std::env::var("HOME").unwrap_or_default();
let repo = self.repo.to_string_lossy().into_owned(); let repo = if self.issues {
"issues".to_string()
} else {
self.repo.to_string_lossy().into_owned()
};
let repo = match repo.strip_prefix(&home) { let repo = match repo.strip_prefix(&home) {
Some(rest) if !home.is_empty() => format!("~{rest}"), Some(rest) if !home.is_empty() => format!("~{rest}"),
_ => repo, _ => repo,
@@ -736,7 +788,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 +798,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 +834,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();
@@ -866,7 +938,9 @@ fn on_key(
app.screen = Screen::Goal; app.screen = Screen::Goal;
app.refresh(); app.refresh();
} }
KeyCode::Char('N') => app.form = Some(newform::Form::new(&app.repo)), KeyCode::Char('N') if !app.issues => {
app.form = Some(newform::Form::new(&app.repo));
}
KeyCode::Char('u') if app.overview.resumable > 0 => { KeyCode::Char('u') if app.overview.resumable > 0 => {
if let Err(e) = app.resume_all() { if let Err(e) = app.resume_all() {
app.pager = Some(Pager { app.pager = Some(Pager {
@@ -876,6 +950,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 +1072,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 +1082,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(),
@@ -1100,6 +1180,7 @@ mod tests {
ok, ok,
last: &str| Row { last: &str| Row {
id: id.into(), id: id.into(),
group: String::new(),
status, status,
task: task.into(), task: task.into(),
sub: sub.into(), sub: sub.into(),
@@ -1402,6 +1483,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);
} }
@@ -1866,7 +1955,7 @@ end = "merged"
} }
let err = app.start_session(&form).unwrap_err().to_string(); let err = app.start_session(&form).unwrap_err().to_string();
assert!(err.contains("name"), "{err}"); assert!(err.contains("name"), "{err}");
form.name = "ticket work".into(); form.name = "issue work".into();
form.after = "s1, s9".into(); form.after = "s1, s9".into();
let err = app.start_session(&form).unwrap_err().to_string(); let err = app.start_session(&form).unwrap_err().to_string();
assert!(err.contains("no session s9"), "{err}"); assert!(err.contains("no session s9"), "{err}");
+19 -1
View File
@@ -30,8 +30,11 @@ 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 + groups(o) + 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));
let [head, stats, sessions, lower, keys] = Layout::vertical([ let [head, stats, sessions, lower, keys] = Layout::vertical([
Constraint::Length(1), Constraint::Length(1),
@@ -203,6 +206,15 @@ fn ctx_bar(pct: u8) -> Span<'static> {
) )
} }
/// Group heading lines: one per run of rows with the same non-empty issue.
fn groups(o: &Overview) -> usize {
o.rows
.iter()
.enumerate()
.filter(|(i, r)| !r.group.is_empty() && (*i == 0 || o.rows[i - 1].group != r.group))
.count()
}
fn sessions_box(f: &mut Frame, area: Rect, o: &Overview, sel: usize) { fn sessions_box(f: &mut Frame, area: Rect, o: &Overview, sel: usize) {
let block = boxed("Sessions", Some(o.rows.len()), theme::TEXT, theme::BORDER); let block = boxed("Sessions", Some(o.rows.len()), theme::TEXT, theme::BORDER);
let inner = block.inner(area); let inner = block.inner(area);
@@ -230,6 +242,12 @@ fn sessions_box(f: &mut Frame, area: Rect, o: &Overview, sel: usize) {
head.push(Span::raw("last activity")); head.push(Span::raw("last activity"));
let mut lines = vec![Line::from(head).style(fg(theme::DIM))]; let mut lines = vec![Line::from(head).style(fg(theme::DIM))];
for (i, r) in o.rows.iter().enumerate() { for (i, r) in o.rows.iter().enumerate() {
if !r.group.is_empty() && (i == 0 || o.rows[i - 1].group != r.group) {
lines.push(Line::from(Span::styled(
format!(" ── {}", r.group),
bold(theme::TEXT),
)));
}
let on = i == sel; let on = i == sel;
let cursor = if on { let cursor = if on {
Span::styled("▶ ", fg(theme::RUN)) Span::styled("▶ ", fg(theme::RUN))
+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),
+53
View File
@@ -47,6 +47,8 @@ pub struct Chip {
#[derive(Clone, PartialEq, Debug)] #[derive(Clone, PartialEq, Debug)]
pub struct Row { pub struct Row {
pub id: String, pub id: String,
/// The issue of an `orch up` session; rows are sorted by it and the overview heads each group.
pub group: String,
pub status: Status, pub status: Status,
pub task: String, pub task: String,
pub sub: String, pub sub: String,
@@ -248,8 +250,19 @@ pub fn build(i: &Input) -> Overview {
Status::Fail => {} Status::Fail => {}
} }
o.cost += scan.cost; o.cost += scan.cost;
let group = evs
.iter()
.rev()
.find_map(|e| {
(e.kind == "options")
.then(|| e.payload["issue"].as_str())
.flatten()
})
.unwrap_or_default()
.to_string();
o.rows.push(Row { o.rows.push(Row {
id: s.id.clone(), id: s.id.clone(),
group,
status, status,
task: task.name.clone(), task: task.name.clone(),
sub: task.subtitle.clone(), sub: task.subtitle.clone(),
@@ -265,6 +278,7 @@ pub fn build(i: &Input) -> Overview {
last, last,
}); });
} }
o.rows.sort_by(|a, b| a.group.cmp(&b.group)); // stable: within a group, session order stays
o.needs.extend(escalated); o.needs.extend(escalated);
if !i.checks.is_empty() { if !i.checks.is_empty() {
let green = i let green = i
@@ -346,6 +360,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 +445,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 +479,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!(
@@ -708,6 +727,40 @@ mod tests {
); );
} }
#[test]
fn rows_group_by_issue_in_session_order() {
let events = vec![
ev(1, "s1", "options", json!({"issue": "B-2"})),
ev(2, "s2", "options", json!({"issue": "A-1"})),
ev(3, "s3", "options", json!({"no_merge": true})),
ev(4, "s4", "options", json!({"issue": "B-2"})),
];
let tasks: Vec<_> = ["s1", "s2", "s3", "s4"].map(|i| task(i, i, &[])).into();
let sessions: Vec<_> = ["s1", "s2", "s3", "s4"]
.map(|i| session(i, i, "", "queued"))
.into();
let o = build(&Input {
goal: None,
tasks: &tasks,
sessions: &sessions,
events: &events,
machines: &machines(),
needs: &[],
checks: &[],
decisions: &[],
now_ms: 0,
});
let got: Vec<_> = o
.rows
.iter()
.map(|r| (r.id.as_str(), r.group.as_str()))
.collect();
assert_eq!(
got,
[("s3", ""), ("s2", "A-1"), ("s1", "B-2"), ("s4", "B-2")]
);
}
#[test] #[test]
fn helpers() { fn helpers() {
assert_eq!(ago(5), "5s"); assert_eq!(ago(5), "5s");
+1
View File
@@ -7,6 +7,7 @@ cargo clippy -q --all-targets -- -D warnings
cargo test -q cargo test -q
cargo build -q cargo build -q
python3 tests/e2e.py python3 tests/e2e.py
python3 tests/issues.py
python3 spike/check.py python3 spike/check.py
./target/debug/orch bench eval --check ./target/debug/orch bench eval --check
+113
View File
@@ -0,0 +1,113 @@
"""orch up: one manifest, worktrees in two repos, detached sessions in the issues database, rerun, kill."""
import json, os, pathlib, sqlite3, subprocess, sys, tempfile, time
root = pathlib.Path(__file__).resolve().parent.parent
orch = sys.argv[1] if len(sys.argv) > 1 else str(root / "target/debug/orch")
tmp = pathlib.Path(tempfile.mkdtemp())
cfg, state = tmp / "cfg", tmp / "state"
env = {**os.environ, "ORCH_CONFIG_DIR": str(cfg), "ORCH_STATE_DIR": str(state)}
QUICK = """name = "quick"
[[state]]
name = "work"
kind = "start"
steps = [{ name = "w", run = "computer", cmd = "cp .hx/task.md seen.txt" }]
next = "merge"
[[state]]
name = "merge"
kind = "exit"
steps = [{ name = "never", run = "computer", cmd = "touch merged-it" }]
end = "merged"
"""
SLOW = QUICK.replace('"quick"', '"slow"').replace("cp .hx/task.md seen.txt", "sleep 60")
def git(cwd, *a):
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *a], cwd=cwd, check=True, capture_output=True)
def worktree(repo_name, machine):
repo = tmp / repo_name
repo.mkdir()
git(repo, "init", "-q", "-b", "main")
(repo / "f").write_text("x")
git(repo, "add", "-A")
git(repo, "commit", "-qm", "init")
wt = tmp / f"{repo_name}-abc"
git(repo, "worktree", "add", "-q", "-b", "abc-1", str(wt))
(wt / ".hx/machines").mkdir(parents=True)
(wt / ".hx/profiles").mkdir(parents=True)
(wt / ".hx/machines/abc.toml").write_text(machine)
(wt / ".hx/profiles/abc.toml").write_text("max_retries = 0\n")
(wt / ".hx/task.md").write_text(f"do the {repo_name} part\n")
return repo, wt
api, api_wt = worktree("api", QUICK)
web, web_wt = worktree("web", SLOW)
# the manifest lives where config.toml says, not in the default place
issues = tmp / "my-manifests"
issues.mkdir()
cfg.mkdir()
(cfg / "config.toml").write_text(f'manifest_dir = "{issues}"\n')
entry = lambda wt, name: f'[[session]]\nworktree = "{wt}"\nname = "{name}"\nmachine = "abc"\nprofile = "abc"\n'
(issues / "ABC-1.toml").write_text('issue = "ABC-1"\n' + entry(api_wt, "api part") + entry(web_wt, "web part"))
def up(name="ABC-1"):
return subprocess.run([orch, "up", name], env=env, capture_output=True, text=True, timeout=30)
def sessions():
c = sqlite3.connect(state / "issues.db")
rows = c.execute("select id, worktree, status, pid from sessions order by id").fetchall()
c.close()
return {r[0]: {"worktree": r[1], "status": r[2], "pid": r[3]} for r in rows}
def wait(sid, statuses, secs=20):
end = time.time() + secs
while time.time() < end:
s = sessions().get(sid)
if s and s["status"] in statuses:
return s
time.sleep(0.1)
raise AssertionError(f"{sid} never reached {statuses}: {sessions()} {(state / 'logs' / f'issue-{sid}.log').read_text()}")
# a broken entry starts nothing
(issues / "BAD.toml").write_text('issue = "BAD"\n' + entry(api_wt, "ok") + entry(tmp / "nope", "missing"))
p = up("BAD")
assert p.returncode != 0 and "missing" in p.stderr, p.stderr
assert not (state / "issues.db").exists() or not sessions(), "nothing may start when one entry is broken"
p = up()
assert p.returncode == 0, p.stderr
assert "s1 api part: started" in p.stdout and "s2 web part: started" in p.stdout, p.stdout
wait("s1", {"done"})
assert (api_wt / "seen.txt").read_text() == "do the api part\n", "the step ran in the user's worktree"
assert not (api_wt / "merged-it").exists(), "stops at done, no merge"
wait("s2", {"running"})
c = sqlite3.connect(state / "issues.db")
opts = [json.loads(r[0]) for r in c.execute("select payload from events where session_id = 's1' and kind = 'options'")]
merged = {k: v for o in opts for k, v in o.items()}
assert merged["issue"] == "ABC-1" and merged["task"] == "do the api part\n" and merged["no_merge"] is True, merged
assert merged["repo"] == str(api.resolve()), merged
sub = c.execute("select subtitle from tasks where id = 's2'").fetchone()[0]
assert sub == "web", sub
# running it again starts nothing twice
p = up()
assert "s1 api part: done already" in p.stdout and "s2 web part: running already" in p.stdout, p.stdout
assert len(sessions()) == 2
# kill, as the TUI's k does: an abort command through the database reaches the detached process
c.execute("insert into commands(session_id, kind, payload, at) values ('s2', 'abort', '{}', 0)")
c.commit()
s = wait("s2", {"aborted", "failed"})
c.close()
print("issues ok", s["status"])