4 Commits
Author SHA1 Message Date
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
17 changed files with 817 additions and 69 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**:
+32
View File
@@ -17,6 +17,8 @@ git host: tasks come from a folder or any JSON command, results go to a local br
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
@@ -104,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.4", "version": "0.1.6",
"sha256": { "sha256": {
"aarch64-apple-darwin": "ba5711a2cf4b27f5b37963e9562088f6f0159b3f87fdca1a4ca8258f510667d0", "aarch64-apple-darwin": "1a6b4944c20f086015368ae5d43f1ca6f11ea1dffd82c41f12e8ed7891e90555",
"x86_64-unknown-linux-musl": "3d134d6cbc0035f609772dcda2a3dfa55f688c7bb5a30410e2091fa1f13aeba0" "x86_64-unknown-linux-musl": "8d85f036b9a0db9306ae421ac7d4ce1fc813daecc901080e80425391da823228"
} }
} }
+56 -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),
)?; )?;
@@ -382,7 +391,11 @@ impl Db {
); );
self.set_session(id, &s.state, "suspended")?; self.set_session(id, &s.state, "suspended")?;
self.set_pid(id, None)?; self.set_pid(id, None)?;
self.emit(id, "restart", serde_json::json!({"from": s.status, "state": s.state}))?; self.emit(
id,
"restart",
serde_json::json!({"from": s.status, "state": s.state}),
)?;
Ok(()) Ok(())
} }
@@ -394,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(
@@ -558,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");
+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 {
+47 -3
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;
@@ -143,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 },
@@ -194,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 {
@@ -284,8 +329,7 @@ fn main() -> Result<std::process::ExitCode> {
); );
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()),
+7
View File
@@ -178,6 +178,13 @@ impl Profile {
f 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:?}");
+49 -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.
@@ -1795,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
+69 -13
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 {
@@ -209,7 +231,11 @@ impl App {
bail!("no database") bail!("no database")
}; };
db.reopen(id)?; db.reopen(id)?;
self.ensure_host()?.submit(id); if self.issues {
crate::issue::spawn(db, id)?;
} else {
self.ensure_host()?.submit(id);
}
self.refresh(); self.refresh();
Ok(()) Ok(())
} }
@@ -247,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);
} }
@@ -272,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());
@@ -287,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()
} }
@@ -429,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![],
@@ -451,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);
@@ -496,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,
@@ -757,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")),
@@ -767,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),
@@ -893,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 {
@@ -1133,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(),
@@ -1435,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);
} }
@@ -1899,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}");
+16 -1
View File
@@ -34,7 +34,7 @@ pub fn draw(f: &mut Frame, o: &Overview, h: &Header, sel: usize, need_sel: usize
keys.push(("R", "restart")); 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),
@@ -206,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);
@@ -233,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))
+48
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
@@ -713,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"])