Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f6bd32d01 | ||
|
|
c59924fc0f | ||
|
|
bfc2693f9b | ||
|
|
db80d15ba2 | ||
|
|
551e0efd7c | ||
|
|
71f58d7b30 | ||
|
|
c768ea79d4 | ||
|
|
20f88d88df | ||
|
|
440b19180e | ||
|
|
f652e607f6 | ||
|
|
8c4361acee | ||
|
|
db7ef65e4a | ||
|
|
d977e01d5d |
No files matched your search
+1
-1
@@ -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)
|
||||
|
||||
**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
|
||||
|
||||
**Host**:
|
||||
|
||||
@@ -17,6 +17,9 @@ 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 check NAME CMD [--owner sN] add an acceptance check (pass = exit 0)
|
||||
orch checks [--owner sN | --main] run acceptance checks here, or on a clean copy of main
|
||||
orch up MANIFEST one detached session per worktree of an issue (any repos)
|
||||
orch down MANIFEST [--forget] stop those sessions; --forget also deletes them
|
||||
orch issues TUI on the sessions `orch up` started, grouped by issue
|
||||
|
||||
## How a run goes
|
||||
|
||||
@@ -104,6 +107,39 @@ 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
|
||||
`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. `orch down ABC-123` stops the issue's sessions: running ones get the
|
||||
same abort as `k`, unfinished ones whose process is gone are marked aborted, so `orch up` leaves them alone.
|
||||
`--forget` then deletes the sessions and their logs (it waits up to a minute for aborted ones to exit), so `orch
|
||||
issues` no longer lists them and the next `orch up` starts fresh. Worktrees and branches stay. `manifest_dir`
|
||||
defaults to `<config>/manifests` and is set in `<config>/config.toml` (`~/.config/orch/config.toml`):
|
||||
|
||||
```toml
|
||||
manifest_dir = "~/notes/manifests"
|
||||
```
|
||||
|
||||
## More
|
||||
|
||||
- [docs/cmd-protocol.md](docs/cmd-protocol.md): task sources and result sinks as external commands (+ JSON schema)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.9",
|
||||
"sha256": {
|
||||
"aarch64-apple-darwin": "b2cbabcd87ae7bda6c14638c24f5b80e37553954409a46828fd0bddb0aa1e7bc",
|
||||
"x86_64-unknown-linux-musl": "0f003750f85b40499036e3bf1591fa488b7bd34ad19787471c0bc968ab545427"
|
||||
"aarch64-apple-darwin": "a4b5d69d4b55893dd6202c1d36f2eebbac6ab72954a7462983f8d7b833ef14b1",
|
||||
"x86_64-unknown-linux-musl": "395019a2154cb4f8cfdda0ffa63130c6fc9693286bced1648d77586b8995bec3"
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ env = ["GITEA_*"] # orch env vars hx may see (default: PATH HOME
|
||||
# TMPDIR CARGO_* RUST* NIX_*, plus HX_HOME only when `home` is unset)
|
||||
sandbox = true # hx --sandbox (bwrap/seatbelt). Default: on when available (macOS, Linux with bwrap),
|
||||
# together with --yolo (yolo = false opts out). Unsandboxed hx runs with --auto.
|
||||
# Interactive sessions (TUI, orch up) with yolo = false get --sandbox --auto.
|
||||
```
|
||||
|
||||
## Allowlist (`allow`)
|
||||
|
||||
+154
-10
@@ -7,13 +7,94 @@ use crate::profile::Profile;
|
||||
use crate::run::hx_env;
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::io::{BufRead, Write};
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The conversation file `hx serve --cwd <worktree> --session <id>` writes, for `hx --session <file>` to
|
||||
/// resume. Resolved from the environment the agent ran with (`hx_env` plus the profile's `HOME`), not orch's own.
|
||||
pub fn session_file(p: &Profile, worktree: &Path, id: &str) -> PathBuf {
|
||||
let mut env: HashMap<String, String> = hx_env(std::env::vars(), p).into_iter().collect();
|
||||
if let Some(h) = &p.home {
|
||||
env.insert("HOME".into(), h.to_string_lossy().into());
|
||||
}
|
||||
// hx runs in the canonical cwd (`/private/tmp`, not `/tmp`), so the slug comes from that
|
||||
let cwd = worktree
|
||||
.canonicalize()
|
||||
.unwrap_or_else(|_| worktree.to_path_buf());
|
||||
let hostname = || std::fs::read_to_string("/etc/hostname").ok();
|
||||
hx_session_file(&env, &cwd, id, hostname)
|
||||
}
|
||||
|
||||
/// hx's own path rule: `<root>/<[host/]cwd slug>/acp-<id>.jsonl`. The root is `$HX_SESSIONS_DIR`, else
|
||||
/// `sessions_dir` from `$HX_HOME/config.toml` or `<cwd>/.hx/config.toml` (the latter wins, `~` is `$HOME`),
|
||||
/// else `$HX_HOME/sessions`; `sessions_host = true` puts the host name in front of the slug.
|
||||
fn hx_session_file(
|
||||
env: &HashMap<String, String>,
|
||||
cwd: &Path,
|
||||
id: &str,
|
||||
hostname: impl Fn() -> Option<String>,
|
||||
) -> PathBuf {
|
||||
let var = |k: &str| env.get(k).filter(|v| !v.is_empty());
|
||||
let home = PathBuf::from(var("HOME").map_or("", String::as_str));
|
||||
let hx_home = var("HX_HOME").map_or_else(|| home.join(".hx"), PathBuf::from);
|
||||
let (mut dir, mut host) = (None, None);
|
||||
for f in [hx_home.join("config.toml"), cwd.join(".hx/config.toml")] {
|
||||
let Some(t) = std::fs::read_to_string(f)
|
||||
.ok()
|
||||
.and_then(|s| s.parse::<toml::Table>().ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if let Some(d) = t.get("sessions_dir").and_then(|v| v.as_str()) {
|
||||
dir = Some(d.to_string());
|
||||
}
|
||||
if let Some(h) = t.get("sessions_host").and_then(toml::Value::as_bool) {
|
||||
host = Some(h);
|
||||
}
|
||||
}
|
||||
let root = match var("HX_SESSIONS_DIR").cloned().or(dir) {
|
||||
Some(s) if !s.is_empty() => match s.strip_prefix('~') {
|
||||
Some(r) => home.join(r.trim_start_matches('/')),
|
||||
None => s.into(),
|
||||
},
|
||||
_ => hx_home.join("sessions"),
|
||||
};
|
||||
let host = host.unwrap_or(false).then(|| {
|
||||
["HOSTNAME", "HOST", "COMPUTERNAME"]
|
||||
.iter()
|
||||
.find_map(|k| env.get(*k).cloned())
|
||||
.or_else(hostname)
|
||||
.map_or("host".into(), |h| h.trim().to_string())
|
||||
});
|
||||
let cwd = cwd.to_string_lossy();
|
||||
let slug: String = host
|
||||
.as_deref()
|
||||
.into_iter()
|
||||
.chain([cwd.trim_matches('/')])
|
||||
.collect::<Vec<_>>()
|
||||
.join("/")
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
|
||||
.collect();
|
||||
let id: String = id
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() || "-_.".contains(c) {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
root.join(slug.trim_matches('-'))
|
||||
.join(format!("acp-{id}.jsonl"))
|
||||
}
|
||||
|
||||
/// Receives what hx reports while a step runs.
|
||||
pub trait Sink {
|
||||
/// Notifications: `hx/intent`, `hx/edit`, `hx/usage`, `hx/decision`, `hx/plan`, `session/update`.
|
||||
@@ -63,17 +144,11 @@ impl Acp {
|
||||
pub fn spawn(p: &Profile, worktree: &Path, id: &str) -> Result<Self> {
|
||||
let mut parts = p.hx.split_whitespace();
|
||||
let mut cmd = Command::new(parts.next().context("empty hx command")?);
|
||||
cmd.args(parts)
|
||||
.args(["serve", "--acp", "--cwd"])
|
||||
// sandbox and permission flags are options of the root command, so they go before `serve`
|
||||
cmd.args(parts).args(p.acp_flags());
|
||||
cmd.args(["serve", "--acp", "--cwd"])
|
||||
.arg(worktree)
|
||||
.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
|
||||
cmd.env_clear().envs(hx_env(std::env::vars(), p));
|
||||
if let Some(h) = &p.home {
|
||||
@@ -262,3 +337,72 @@ impl Drop for Acp {
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn env(kv: &[(&str, &str)]) -> HashMap<String, String> {
|
||||
kv.iter()
|
||||
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_file_defaults_to_hx_home_sessions() {
|
||||
let e = env(&[("HOME", "/nonexistent/h")]);
|
||||
let f = hx_session_file(&e, Path::new("/w/a.b/s1"), "s1", || None);
|
||||
assert_eq!(
|
||||
f,
|
||||
Path::new("/nonexistent/h/.hx/sessions/w-a-b-s1/acp-s1.jsonl")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_file_follows_hx_config_and_env() {
|
||||
let t = std::env::temp_dir().join(format!("orch-acp-cfg-{}", std::process::id()));
|
||||
let (home, wt) = (t.join("h"), t.join("wt"));
|
||||
std::fs::create_dir_all(home.join(".hx")).unwrap();
|
||||
std::fs::create_dir_all(wt.join(".hx")).unwrap();
|
||||
std::fs::write(home.join(".hx/config.toml"), "sessions_dir = \"~/cloud\"\n").unwrap();
|
||||
let e = env(&[("HOME", home.to_str().unwrap())]);
|
||||
let slug = |p: &Path| -> String {
|
||||
p.to_string_lossy()
|
||||
.trim_matches('/')
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
|
||||
.collect()
|
||||
};
|
||||
let f = hx_session_file(&e, &wt, "s1", || None);
|
||||
assert_eq!(f, home.join("cloud").join(slug(&wt)).join("acp-s1.jsonl"));
|
||||
|
||||
// the worktree's config wins, and sessions_host prefixes the host name
|
||||
std::fs::write(
|
||||
wt.join(".hx/config.toml"),
|
||||
"sessions_dir = \"/sd\"\nsessions_host = true\n",
|
||||
)
|
||||
.unwrap();
|
||||
let f = hx_session_file(&e, &wt, "s1", || Some("box\n".into()));
|
||||
assert_eq!(
|
||||
f,
|
||||
Path::new("/sd")
|
||||
.join(format!("box-{}", slug(&wt)))
|
||||
.join("acp-s1.jsonl")
|
||||
);
|
||||
|
||||
// HX_SESSIONS_DIR beats both config files
|
||||
let e = env(&[
|
||||
("HOME", home.to_str().unwrap()),
|
||||
("HX_SESSIONS_DIR", "/env"),
|
||||
("HOST", "h2"),
|
||||
]);
|
||||
let f = hx_session_file(&e, &wt, "s1", || None);
|
||||
assert_eq!(
|
||||
f,
|
||||
Path::new("/env")
|
||||
.join(format!("h2-{}", slug(&wt)))
|
||||
.join("acp-s1.jsonl")
|
||||
);
|
||||
std::fs::remove_dir_all(&t).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ create table if not exists commands(
|
||||
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);
|
||||
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(
|
||||
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,
|
||||
@@ -119,6 +119,15 @@ impl Db {
|
||||
conn.busy_timeout(std::time::Duration::from_secs(5))?;
|
||||
conn.pragma_update(None, "journal_mode", "WAL")?;
|
||||
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 {
|
||||
conn,
|
||||
path: path.to_path_buf(),
|
||||
@@ -184,14 +193,14 @@ impl Db {
|
||||
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> {
|
||||
self.conn.execute(
|
||||
"insert or ignore into merge_queue(session_id) values (?1)",
|
||||
[session],
|
||||
)?;
|
||||
Ok(self.conn.query_row(
|
||||
"select ticket from merge_queue where session_id = ?1",
|
||||
"select issue from merge_queue where session_id = ?1",
|
||||
[session],
|
||||
|r| r.get(0),
|
||||
)?)
|
||||
@@ -202,7 +211,7 @@ impl Db {
|
||||
Ok(self
|
||||
.conn
|
||||
.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),
|
||||
)
|
||||
@@ -212,8 +221,8 @@ impl Db {
|
||||
/// 1 = head of the queue.
|
||||
pub fn queue_position(&self, session: &str) -> Result<usize> {
|
||||
let n: i64 = self.conn.query_row(
|
||||
"select count(*) from merge_queue where ticket <=
|
||||
(select ticket from merge_queue where session_id = ?1)",
|
||||
"select count(*) from merge_queue where issue <=
|
||||
(select issue from merge_queue where session_id = ?1)",
|
||||
[session],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
@@ -382,7 +391,22 @@ impl Db {
|
||||
);
|
||||
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}))?;
|
||||
self.emit(
|
||||
id,
|
||||
"restart",
|
||||
serde_json::json!({"from": s.status, "state": s.state}),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deletes a session and everything recorded for it.
|
||||
pub fn forget(&self, id: &str) -> Result<()> {
|
||||
let tx = self.conn.unchecked_transaction()?;
|
||||
for t in ["events", "decisions", "commands", "merge_queue", "needs"] {
|
||||
tx.execute(&format!("delete from {t} where session_id = ?1"), [id])?;
|
||||
}
|
||||
tx.execute("delete from sessions where id = ?1", [id])?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -394,6 +418,20 @@ impl Db {
|
||||
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.
|
||||
pub fn emit(&self, session: &str, kind: &str, payload: Value) -> Result<i64> {
|
||||
self.conn.execute(
|
||||
@@ -558,6 +596,28 @@ mod tests {
|
||||
(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]
|
||||
fn roundtrip() {
|
||||
let (db, dir) = temp_db("rt");
|
||||
|
||||
+498
@@ -0,0 +1,498 @@
|
||||
//! 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()
|
||||
}
|
||||
"aborted" => "aborted: orch down --forget, then orch up starts it fresh".into(),
|
||||
other => format!("{other}: restart it with R in orch issues"),
|
||||
};
|
||||
(s.id, what)
|
||||
}
|
||||
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 down MANIFEST [--forget]`: stops every session of the manifest's worktrees. A live one gets the same
|
||||
/// abort as `k` in the TUI (hx stops, the machine runs its `on abort` state); one whose process is gone is marked
|
||||
/// aborted, so `orch up` does not start it again. With `forget`, sessions are deleted with their logs once their
|
||||
/// process has exited, and a later `orch up` starts fresh. The worktrees and branches stay.
|
||||
pub fn down(arg: &str, forget: bool) -> Result<Vec<Outcome>> {
|
||||
let file = manifest_path(arg)?;
|
||||
let m: Manifest = toml::from_str(&std::fs::read_to_string(&file)?)
|
||||
.with_context(|| file.display().to_string())?;
|
||||
// no `plan`: a worktree that is gone by now must not keep its sessions from being stopped
|
||||
let entries = m
|
||||
.sessions
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let p = expand(&e.worktree);
|
||||
(e.name.clone(), p.canonicalize().unwrap_or(p))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let db = Db::open(&db_path())?;
|
||||
let out = down_in(&db, &entries, forget, std::time::Duration::from_secs(60))?;
|
||||
for o in out.iter().filter(|o| o.what == "forgotten") {
|
||||
let log = format!("issue-{}.log", o.session);
|
||||
let _ = std::fs::remove_file(crate::state_dir().join("logs").join(log));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn down_in(
|
||||
db: &Db,
|
||||
entries: &[(String, PathBuf)],
|
||||
forget: bool,
|
||||
wait: std::time::Duration,
|
||||
) -> Result<Vec<Outcome>> {
|
||||
let live = |s: &crate::db::Session| s.pid.is_some_and(crate::state::pid_alive);
|
||||
let mut out = vec![];
|
||||
let mut aborted = vec![];
|
||||
for (name, wt) in entries {
|
||||
let wt = wt.to_string_lossy();
|
||||
let sessions: Vec<_> = db
|
||||
.sessions()?
|
||||
.into_iter()
|
||||
.filter(|s| s.worktree == wt)
|
||||
.collect();
|
||||
if sessions.is_empty() {
|
||||
out.push(Outcome {
|
||||
session: "-".into(),
|
||||
name: name.clone(),
|
||||
what: "no session".into(),
|
||||
});
|
||||
}
|
||||
for s in sessions {
|
||||
let what = match s.status.as_str() {
|
||||
"done" | "merged" | "failed" | "escalated" | "aborted" if !live(&s) => {
|
||||
format!("{} already", s.status)
|
||||
}
|
||||
_ if live(&s) => {
|
||||
db.add_command(&s.id, "abort", &json!({}))?;
|
||||
aborted.push(s.id.clone());
|
||||
"aborting".into()
|
||||
}
|
||||
_ => {
|
||||
db.set_session(&s.id, &s.state, "aborted")?;
|
||||
db.set_pid(&s.id, None)?;
|
||||
"aborted (its process was gone)".into()
|
||||
}
|
||||
};
|
||||
out.push(Outcome {
|
||||
session: s.id,
|
||||
name: name.clone(),
|
||||
what,
|
||||
});
|
||||
}
|
||||
}
|
||||
if !forget {
|
||||
return Ok(out);
|
||||
}
|
||||
let until = std::time::Instant::now() + wait;
|
||||
while std::time::Instant::now() < until
|
||||
&& aborted
|
||||
.iter()
|
||||
.any(|id| db.session(id).ok().flatten().is_some_and(|s| live(&s)))
|
||||
{
|
||||
std::thread::sleep(std::time::Duration::from_millis(250));
|
||||
}
|
||||
for o in out.iter_mut().filter(|o| o.session != "-") {
|
||||
match db.session(&o.session)? {
|
||||
Some(s) if live(&s) => {
|
||||
o.what = "still running after the abort; run orch down --forget again".into();
|
||||
}
|
||||
Some(_) => {
|
||||
db.forget(&o.session)?;
|
||||
o.what = "forgotten".into();
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `orch launch ID`: runs one session of the issues database to its end (started by [`spawn`]).
|
||||
pub fn launch(id: &str) -> Result<String> {
|
||||
let db = Db::open(&db_path())?;
|
||||
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 down_stops_then_forgets() {
|
||||
let d = std::env::temp_dir().join(format!("orch-down-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
let db = Db::open(&d.join("issues.db")).unwrap();
|
||||
let add = |id: &str, wt: &str, status: &str| {
|
||||
db.add_session(&crate::db::Session {
|
||||
id: id.into(),
|
||||
task_id: id.into(),
|
||||
branch: "b".into(),
|
||||
worktree: wt.into(),
|
||||
pid: None,
|
||||
state: "work".into(),
|
||||
status: status.into(),
|
||||
})
|
||||
.unwrap();
|
||||
db.emit(id, "options", json!({"issue": "X"})).unwrap();
|
||||
};
|
||||
add("s1", "/wt/a", "suspended");
|
||||
add("s2", "/wt/b", "done");
|
||||
add("s3", "/wt/other", "suspended");
|
||||
let entries = [
|
||||
("a".to_string(), PathBuf::from("/wt/a")),
|
||||
("b".to_string(), PathBuf::from("/wt/b")),
|
||||
("c".to_string(), PathBuf::from("/wt/c")),
|
||||
];
|
||||
let zero = std::time::Duration::ZERO;
|
||||
let what = |out: Vec<Outcome>| out.into_iter().map(|o| o.what).collect::<Vec<_>>();
|
||||
|
||||
let out = down_in(&db, &entries, false, zero).unwrap();
|
||||
assert_eq!(
|
||||
what(out),
|
||||
["aborted (its process was gone)", "done already", "no session"]
|
||||
);
|
||||
assert_eq!(db.session("s1").unwrap().unwrap().status, "aborted");
|
||||
|
||||
let out = down_in(&db, &entries, true, zero).unwrap();
|
||||
assert_eq!(what(out), ["forgotten", "forgotten", "no session"]);
|
||||
assert!(db.session("s1").unwrap().is_none());
|
||||
assert!(db.events(Some("s2"), 0).unwrap().is_empty());
|
||||
assert_eq!(
|
||||
db.session("s3").unwrap().unwrap().status,
|
||||
"suspended",
|
||||
"another issue's session is untouched"
|
||||
);
|
||||
|
||||
// a live process gets the abort command and is kept until it exits
|
||||
let mut child = Command::new("sleep").arg("30").spawn().unwrap();
|
||||
add("s4", "/wt/a", "running");
|
||||
db.set_pid("s4", Some(child.id())).unwrap();
|
||||
let ms = std::time::Duration::from_millis(300);
|
||||
let out = down_in(&db, &entries[..1], true, ms).unwrap();
|
||||
child.kill().unwrap();
|
||||
child.wait().unwrap();
|
||||
assert_eq!(
|
||||
what(out),
|
||||
["still running after the abort; run orch down --forget again"]
|
||||
);
|
||||
let cmds = db.take_commands("s4").unwrap();
|
||||
assert_eq!(cmds[0].0, "abort");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tilde_expands_to_home() {
|
||||
let home = std::env::var("HOME").unwrap();
|
||||
assert_eq!(expand("~/a/b"), PathBuf::from(home).join("a/b"));
|
||||
assert_eq!(expand("/x"), PathBuf::from("/x"));
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -134,8 +134,12 @@ impl Machine {
|
||||
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> {
|
||||
if Path::new(name).is_absolute() && name.ends_with(".toml") {
|
||||
return Self::load(Path::new(name));
|
||||
}
|
||||
let file = format!("{name}.toml");
|
||||
let dirs = Self::dirs(repo);
|
||||
for d in &dirs {
|
||||
|
||||
+60
-3
@@ -6,6 +6,7 @@ mod db;
|
||||
mod detail;
|
||||
mod goal;
|
||||
mod init;
|
||||
mod issue;
|
||||
mod junit;
|
||||
mod lock;
|
||||
mod machine;
|
||||
@@ -143,6 +144,20 @@ enum Cmd {
|
||||
#[arg(long, default_value = "default")]
|
||||
profile: String,
|
||||
},
|
||||
/// Start one detached session per worktree of an issue manifest (a file, or NAME in `manifest_dir`).
|
||||
Up { manifest: String },
|
||||
/// Stop the sessions of an issue manifest: live ones are aborted, the rest marked aborted. Worktrees stay.
|
||||
Down {
|
||||
manifest: String,
|
||||
/// Then delete the sessions and their logs, so `orch issues` no longer shows them and `orch up` starts fresh.
|
||||
#[arg(long)]
|
||||
forget: bool,
|
||||
},
|
||||
/// The TUI on the sessions `orch up` started, grouped by issue.
|
||||
Issues,
|
||||
/// Run one session of the issues database (started by `orch up`, not by hand).
|
||||
#[command(hide = true)]
|
||||
Launch { id: String },
|
||||
/// hx extension that enforces a run's tool allowlist (started by hx, not by hand).
|
||||
#[command(hide = true)]
|
||||
Guard { policy: PathBuf },
|
||||
@@ -194,10 +209,53 @@ fn code(ok: bool) -> std::process::ExitCode {
|
||||
|
||||
fn main() -> Result<std::process::ExitCode> {
|
||||
let Some(cmd) = Cli::parse().cmd else {
|
||||
tui::run()?;
|
||||
tui::run(false)?;
|
||||
return Ok(code(true));
|
||||
};
|
||||
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::Down { manifest, forget } => {
|
||||
for o in issue::down(&manifest, forget)? {
|
||||
println!("{} {}: {}", o.session, o.name, o.what);
|
||||
}
|
||||
Ok(code(true))
|
||||
}
|
||||
Cmd::Launch { id } => match issue::launch(&id) {
|
||||
Ok(status) => {
|
||||
println!("{id} -> {status}");
|
||||
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 } => {
|
||||
let written = init::run(&repo, &config_dir(), force)?;
|
||||
for p in &written {
|
||||
@@ -284,8 +342,7 @@ fn main() -> Result<std::process::ExitCode> {
|
||||
);
|
||||
anyhow::ensure!(
|
||||
s.pid
|
||||
.is_none_or(|p| !Path::new(&format!("/proc/{p}")).exists()
|
||||
|| p == std::process::id()),
|
||||
.is_none_or(|p| !state::pid_alive(p) || p == std::process::id()),
|
||||
"session {id} is still running (pid {})",
|
||||
s.pid.unwrap_or(0)
|
||||
);
|
||||
|
||||
+12
-9
@@ -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.
|
||||
|
||||
use crate::db::Db;
|
||||
@@ -90,12 +90,12 @@ pub fn ensure_free(db: &Db, place: &Place) -> Result<()> {
|
||||
let (branch, path) = match place {
|
||||
Place::Fresh => return Ok(()),
|
||||
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()? {
|
||||
let live = matches!(s.status.as_str(), "queued" | "running" | "waiting")
|
||||
&& s.pid
|
||||
.is_none_or(|p| Path::new(&format!("/proc/{p}")).exists());
|
||||
&& s.pid.is_none_or(crate::state::pid_alive);
|
||||
let same = Some(s.branch.as_str()) == branch
|
||||
|| path.is_some_and(|p| Path::new(&s.worktree) == p.as_path());
|
||||
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, "/nowhere/else").is_err());
|
||||
let wt = dir.join("ticket");
|
||||
let wt = dir.join("issue");
|
||||
git(
|
||||
&repo,
|
||||
&["worktree", "add", "-b", "PROJ-9", &wt.to_string_lossy()],
|
||||
@@ -173,7 +173,7 @@ end = "merged"
|
||||
branch: "PROJ-9".into(),
|
||||
};
|
||||
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!(
|
||||
resolve(&repo, &listed[0].path.to_string_lossy()).unwrap(),
|
||||
want,
|
||||
@@ -185,18 +185,20 @@ end = "merged"
|
||||
#[test]
|
||||
fn named_worktree_is_used_kept_and_not_merged_on_request() {
|
||||
let (dir, repo, db) = setup("named");
|
||||
let wt = dir.join("ticket");
|
||||
let wt = dir.join("issue");
|
||||
git(
|
||||
&repo,
|
||||
&["worktree", "add", "-b", "PROJ-9", &wt.to_string_lossy()],
|
||||
)
|
||||
.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!(db.session(&s.id).unwrap().unwrap().worktree, s.worktree);
|
||||
// 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 status =
|
||||
runner::run_session(&db, &m, &s.id, &repo, "", &Profile::parse("").unwrap()).unwrap();
|
||||
@@ -219,6 +221,7 @@ end = "merged"
|
||||
&db,
|
||||
&dir.join("wts"),
|
||||
b,
|
||||
"",
|
||||
"m",
|
||||
&[],
|
||||
&Place::Branch(b.into()),
|
||||
|
||||
@@ -178,6 +178,23 @@ impl Profile {
|
||||
f
|
||||
}
|
||||
|
||||
/// Flags for an interactive (ACP) session: like `hx_flags` (sandbox brings yolo, no sandbox falls back to
|
||||
/// `--auto`), but a sandbox with `yolo = false` gets `--auto` too, so not every edit asks.
|
||||
pub fn acp_flags(&self) -> Vec<&'static str> {
|
||||
let mut f = self.hx_flags();
|
||||
if f == ["--sandbox"] {
|
||||
f.push("--auto");
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
/// A profile file named by its path (an issue session's profile in its worktree).
|
||||
pub fn load_path(path: &std::path::Path) -> Result<Self> {
|
||||
let s =
|
||||
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> {
|
||||
if name.is_empty() || name.contains(['/', '.']) {
|
||||
bail!("bad profile name {name:?}");
|
||||
@@ -270,6 +287,15 @@ mod tests {
|
||||
assert_eq!(f("sandbox=false"), ["--auto"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acp_flags_yolo_with_sandbox_else_auto() {
|
||||
let f = |s| Profile::parse(s).unwrap().acp_flags();
|
||||
assert_eq!(f("sandbox=true"), ["--sandbox", "--yolo"]);
|
||||
assert_eq!(f("sandbox=true\nyolo=true"), ["--sandbox", "--yolo"]);
|
||||
assert_eq!(f("sandbox=true\nyolo=false"), ["--sandbox", "--auto"]);
|
||||
assert_eq!(f("sandbox=false"), ["--auto"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bwrap_lookup_scans_path() {
|
||||
let dir = std::env::temp_dir().join(format!("orch-bwrap-{}", std::process::id()));
|
||||
|
||||
+85
-19
@@ -15,7 +15,7 @@ use serde_json::{Value, json};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::io::Read;
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
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
|
||||
/// `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(
|
||||
db: &Db,
|
||||
worktrees: &Path,
|
||||
name: &str,
|
||||
subtitle: &str,
|
||||
machine: &str,
|
||||
after: &[String],
|
||||
place: &crate::place::Place,
|
||||
@@ -93,7 +95,7 @@ pub fn create_in(
|
||||
) -> Result<Session> {
|
||||
use crate::place::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 {
|
||||
Place::Fresh => {}
|
||||
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")?)?;
|
||||
// git races on its own locks when worktrees are added in parallel
|
||||
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(
|
||||
repo,
|
||||
&[
|
||||
@@ -386,6 +388,8 @@ struct Ctx<'a> {
|
||||
repo: &'a Path,
|
||||
ctl: Ctl<'a>,
|
||||
agent: Option<Acp>,
|
||||
/// The task text (`orch up` reads it from the worktree's task file); empty for other sessions.
|
||||
body: String,
|
||||
}
|
||||
|
||||
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.
|
||||
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 {
|
||||
"plan" => "Plan the work for this task. Report the plan with hx/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 {
|
||||
s.push_str(&format!("\nGoal: {g}"));
|
||||
}
|
||||
if !body.trim().is_empty() {
|
||||
s.push_str(&format!("\n\n{}", body.trim()));
|
||||
}
|
||||
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 r: StepResult = agent.step(
|
||||
kind,
|
||||
&instruction(kind, goal.as_deref(), cx.task),
|
||||
&instruction(kind, goal.as_deref(), cx.task, &cx.body),
|
||||
context,
|
||||
json!({}),
|
||||
&mut sink,
|
||||
@@ -767,6 +774,18 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result<StepRes> {
|
||||
cx.ctl.stop_for_budget(format!("hx limit: {}", r.summary));
|
||||
Err(Stopped.into())
|
||||
}
|
||||
"blocked" if r.catch.is_none() && r.reason.as_deref() == Some("error") => {
|
||||
// hx itself failed (API, login, ...): no catch fits, so ask instead of guessing one
|
||||
let payload = json!({
|
||||
"key": format!("{}/{}/error", st.name, step.name),
|
||||
"state": st.name, "step": step.name, "title": "agent error",
|
||||
"detail": format!("hx failed: {}. Fix the cause, then reply to run the step again (abort to give up)", r.summary),
|
||||
});
|
||||
let answer = ask(&cx.ctl, &cx.s.id, &st.name, "input", payload, true)?;
|
||||
let reply = answer.strip_prefix("reply:").unwrap_or(&answer).trim();
|
||||
hint = (!reply.is_empty()).then(|| reply.to_string());
|
||||
continue;
|
||||
}
|
||||
"blocked" => Ok(StepRes {
|
||||
ok: false,
|
||||
exit: None,
|
||||
@@ -887,6 +906,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`, ...).
|
||||
/// Resumes at `current_state` when the session was started before (orchestrator restart).
|
||||
pub fn run_session(
|
||||
@@ -929,6 +976,12 @@ pub fn run_session(
|
||||
repo,
|
||||
ctl,
|
||||
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 cur, mut from) = if resumed {
|
||||
@@ -938,10 +991,7 @@ pub fn run_session(
|
||||
(m.start().name.clone(), String::new())
|
||||
};
|
||||
db.set_pid(id, Some(std::process::id()))?;
|
||||
let no_merge = db
|
||||
.events(Some(id), 0)?
|
||||
.iter()
|
||||
.any(|e| e.kind == "options" && e.payload["no_merge"] == true);
|
||||
let no_merge = db.options(id)?.get("no_merge") == Some(&json!(true));
|
||||
for _ in 0..MAX_TRANSITIONS {
|
||||
let st = m
|
||||
.state(&cur)
|
||||
@@ -1074,9 +1124,7 @@ fn alive(db: &Db, session: &str) -> bool {
|
||||
let Some(pid) = db.session(session).ok().flatten().and_then(|s| s.pid) else {
|
||||
return false;
|
||||
};
|
||||
// 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)
|
||||
crate::state::pid_alive(pid)
|
||||
}
|
||||
|
||||
/// Joins the merge queue and blocks until this session is at the head.
|
||||
@@ -1795,7 +1843,7 @@ end = "merged"
|
||||
let e = env("stale");
|
||||
let m = one_step(r#"{ name = "w", run = "computer", cmd = "true" }"#);
|
||||
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 {
|
||||
id: "s9".into(),
|
||||
task_id: "s1".into(),
|
||||
@@ -2142,17 +2190,35 @@ next = "done"
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hx_blocked_with_another_reason_is_not_a_budget() {
|
||||
fn hx_error_asks_the_user_and_the_reply_retries_the_step() {
|
||||
let e = env("hx-error");
|
||||
let m = ctl_machine(LIMIT_MACHINE);
|
||||
// the state has a catch: an hx error must not be filed under it
|
||||
let m = ctl_machine(&LIMIT_MACHINE.replace(
|
||||
"next = \"done\"",
|
||||
"next = \"done\"\ncatch = { ToolDenied = \"done\" }",
|
||||
));
|
||||
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
|
||||
let user = answerer(e.dir.join("orch.db"), &["reply: logged in again"]);
|
||||
let p = fake("FAKE_MODE=error");
|
||||
assert_eq!(
|
||||
run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(),
|
||||
"failed"
|
||||
run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap();
|
||||
let seen = user.join().unwrap();
|
||||
assert_eq!(seen.len(), 1);
|
||||
assert_eq!(seen[0].0, "input");
|
||||
assert!(
|
||||
seen[0].1["detail"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("hit the error")
|
||||
);
|
||||
let ev = e.db.events(Some("s1"), 0).unwrap();
|
||||
assert!(ev.iter().all(|v| v.kind != "budget" && v.kind != "goto"));
|
||||
assert!(
|
||||
ev.iter()
|
||||
.all(|v| !matches!(v.kind.as_str(), "budget" | "goto" | "catch"))
|
||||
);
|
||||
let ok = ev
|
||||
.iter()
|
||||
.filter(|v| v.kind == "step" && v.payload["ok"] == true);
|
||||
assert_eq!(ok.count(), 1, "the retried step finished");
|
||||
let _ = std::fs::remove_dir_all(&e.dir);
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
// SAFETY: plain syscall; hx is spawned with process_group(0) so pgid == its pid.
|
||||
unsafe { libc::killpg(pgid as i32, libc::SIGKILL) };
|
||||
|
||||
+14
-18
@@ -2,16 +2,17 @@
|
||||
//! suspends them (state kept), and `orch session --resume` or the TUI's resume key continues them.
|
||||
|
||||
use crate::db::Db;
|
||||
use crate::machine::Machine;
|
||||
use crate::profile::Profile;
|
||||
use crate::runner;
|
||||
use anyhow::{Context, Result};
|
||||
use anyhow::Result;
|
||||
use std::collections::VecDeque;
|
||||
use std::path::PathBuf;
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub struct Host {
|
||||
/// The database the sessions live in: the repo's `.hx/orch.db`, or the issues database.
|
||||
db_path: PathBuf,
|
||||
repo: PathBuf,
|
||||
profile: Profile,
|
||||
/// Sessions that wait for a free slot, oldest first.
|
||||
@@ -20,8 +21,9 @@ pub struct Host {
|
||||
}
|
||||
|
||||
impl Host {
|
||||
pub fn new(repo: PathBuf, profile: Profile) -> Self {
|
||||
pub fn new(db_path: PathBuf, repo: PathBuf, profile: Profile) -> Self {
|
||||
Self {
|
||||
db_path,
|
||||
repo,
|
||||
profile,
|
||||
pending: VecDeque::new(),
|
||||
@@ -75,18 +77,10 @@ impl Host {
|
||||
}
|
||||
|
||||
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
|
||||
let db = Db::open(&repo.join(".hx/orch.db"))?;
|
||||
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 m = Machine::find(&task.machine, &repo)?;
|
||||
let db = Db::open(&self.db_path)?;
|
||||
let (m, repo, profile) = runner::launch(&db, &id, &self.repo, &self.profile)?;
|
||||
Ok(std::thread::spawn(move || {
|
||||
if let Err(e) = runner::run_session(&db, &m, &id, &repo, "", &profile) {
|
||||
let _ = db.set_session(&id, "", "failed");
|
||||
@@ -126,9 +120,7 @@ pub fn resumable(db: &Db) -> Vec<String> {
|
||||
.into_iter()
|
||||
.filter(|s| match s.status.as_str() {
|
||||
"suspended" => true,
|
||||
"running" | "waiting" => s
|
||||
.pid
|
||||
.is_none_or(|p| !std::path::Path::new(&format!("/proc/{p}")).exists()),
|
||||
"running" | "waiting" => s.pid.is_none_or(|p| !crate::state::pid_alive(p)),
|
||||
_ => false,
|
||||
})
|
||||
.map(|s| s.id)
|
||||
@@ -210,7 +202,11 @@ end = "merged"
|
||||
for n in ["one", "two"] {
|
||||
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("s2");
|
||||
host.submit("s2"); // twice is once
|
||||
|
||||
+95
-16
@@ -18,11 +18,17 @@ use std::io::IsTerminal;
|
||||
use std::path::{Path, PathBuf};
|
||||
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() {
|
||||
bail!("orch needs a terminal; use a subcommand (orch --help) in scripts");
|
||||
}
|
||||
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 res = event_loop(&mut term, &mut app);
|
||||
ratatui::restore();
|
||||
@@ -155,6 +161,10 @@ struct Pager {
|
||||
|
||||
struct App {
|
||||
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`.
|
||||
db: Option<Db>,
|
||||
events: Vec<Event>,
|
||||
@@ -185,7 +195,11 @@ impl App {
|
||||
fn ensure_host(&mut self) -> Result<&mut host::Host> {
|
||||
if self.host.is_none() {
|
||||
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"))
|
||||
}
|
||||
@@ -194,6 +208,14 @@ impl App {
|
||||
fn resume_all(&mut self) -> Result<usize> {
|
||||
let Some(db) = &self.db else { return Ok(0) };
|
||||
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 ids: Vec<String> = ids.into_iter().filter(|id| !host.hosts(id)).collect();
|
||||
for id in &ids {
|
||||
@@ -209,7 +231,11 @@ impl App {
|
||||
bail!("no database")
|
||||
};
|
||||
db.reopen(id)?;
|
||||
self.ensure_host()?.submit(id);
|
||||
if self.issues {
|
||||
crate::issue::spawn(db, id)?;
|
||||
} else {
|
||||
self.ensure_host()?.submit(id);
|
||||
}
|
||||
self.refresh();
|
||||
Ok(())
|
||||
}
|
||||
@@ -247,7 +273,7 @@ impl App {
|
||||
let db = self.db.as_ref().expect("db_or_create opened it");
|
||||
let base = self.repo.file_name().unwrap_or_default();
|
||||
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 {
|
||||
h.submit(&s.id);
|
||||
}
|
||||
@@ -272,7 +298,7 @@ impl App {
|
||||
/// Runs every check on main in the background; the goal view shows `running…` meanwhile.
|
||||
fn run_all_checks(&mut self) {
|
||||
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
|
||||
}
|
||||
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).
|
||||
fn db_or_create(&mut self) -> Option<&Db> {
|
||||
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()
|
||||
}
|
||||
@@ -429,6 +455,8 @@ impl App {
|
||||
fn new(repo: PathBuf) -> Self {
|
||||
let rev = git_rev(&repo);
|
||||
Self {
|
||||
db_path: repo.join(".hx/orch.db"),
|
||||
issues: false,
|
||||
repo,
|
||||
db: None,
|
||||
events: vec![],
|
||||
@@ -451,9 +479,8 @@ impl App {
|
||||
}
|
||||
|
||||
fn refresh(&mut self) {
|
||||
let path = self.repo.join(".hx/orch.db");
|
||||
if self.db.is_none() && path.exists() {
|
||||
self.db = Db::open(&path).ok();
|
||||
if self.db.is_none() && self.db_path.exists() {
|
||||
self.db = Db::open(&self.db_path).ok();
|
||||
}
|
||||
if let (Some(h), Some(db)) = (&mut self.host, &self.db) {
|
||||
h.tick(db);
|
||||
@@ -496,7 +523,11 @@ impl App {
|
||||
|
||||
fn header(&self) -> Header {
|
||||
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) {
|
||||
Some(rest) if !home.is_empty() => format!("~{rest}"),
|
||||
_ => repo,
|
||||
@@ -757,7 +788,7 @@ fn test_output(app: &App, id: &str) -> Pager {
|
||||
fn diff_of(worktree: &str) -> Pager {
|
||||
let git = |a: &[&str]| crate::run::git(Path::new(worktree), a);
|
||||
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(_) => {}
|
||||
Err(e) => text.push_str(&format!("{e:#}\n")),
|
||||
@@ -767,6 +798,20 @@ fn diff_of(worktree: &str) -> Pager {
|
||||
Ok(s) => text.push_str(&s),
|
||||
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 {
|
||||
title: "diff".into(),
|
||||
lines: lines_of(&text),
|
||||
@@ -792,15 +837,37 @@ fn transcript(app: &App, id: &str) -> Pager {
|
||||
/// Opens hx on the session's conversation in the worktree: the TUI steps aside for the time hx runs.
|
||||
fn open_in_hx(
|
||||
term: &mut ratatui::DefaultTerminal,
|
||||
db: Option<&Db>,
|
||||
worktree: &str,
|
||||
session: &str,
|
||||
) -> Option<String> {
|
||||
let hx = crate::profile::Profile::load("default").map_or_else(|_| "hx".into(), |p| p.hx);
|
||||
use crate::profile::Profile;
|
||||
// the session's own profile: its home holds the conversation hx serve wrote
|
||||
let p = db
|
||||
.and_then(|db| db.options(session).ok())
|
||||
.and_then(|o| o.get("profile")?.as_str().map(PathBuf::from))
|
||||
.and_then(|path| Profile::load_path(&path).ok())
|
||||
.or_else(|| Profile::load(PROFILE).ok());
|
||||
let hx = p.as_ref().map_or_else(|| "hx".into(), |p| p.hx.clone());
|
||||
let file = match &p {
|
||||
Some(p) => crate::acp::session_file(p, Path::new(worktree), session),
|
||||
None => return Some(format!("could not load profile {PROFILE:?}")),
|
||||
};
|
||||
if !file.exists() {
|
||||
return Some(format!(
|
||||
"no hx conversation for {session} at {}",
|
||||
file.display()
|
||||
));
|
||||
}
|
||||
let mut parts = hx.split_whitespace();
|
||||
let mut cmd = std::process::Command::new(parts.next()?);
|
||||
cmd.args(parts)
|
||||
.args(["--session", session])
|
||||
.arg("--session")
|
||||
.arg(&file)
|
||||
.current_dir(worktree);
|
||||
if let Some(h) = p.as_ref().and_then(|p| p.home.as_ref()) {
|
||||
cmd.env("HOME", h).env_remove("HX_HOME");
|
||||
}
|
||||
ratatui::restore();
|
||||
let res = cmd.status();
|
||||
*term = ratatui::init();
|
||||
@@ -893,7 +960,9 @@ fn on_key(
|
||||
app.screen = Screen::Goal;
|
||||
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 => {
|
||||
if let Err(e) = app.resume_all() {
|
||||
app.pager = Some(Pager {
|
||||
@@ -1035,7 +1104,8 @@ fn on_key(
|
||||
}
|
||||
KeyCode::Char('o') => {
|
||||
if let Some(d) = &app.detail
|
||||
&& let Some(err) = open_in_hx(term, &d.worktree.clone(), &d.id.clone())
|
||||
&& let Some(err) =
|
||||
open_in_hx(term, app.db.as_ref(), &d.worktree.clone(), &d.id.clone())
|
||||
{
|
||||
app.pager = Some(Pager {
|
||||
title: "open worktree".into(),
|
||||
@@ -1133,6 +1203,7 @@ mod tests {
|
||||
ok,
|
||||
last: &str| Row {
|
||||
id: id.into(),
|
||||
group: String::new(),
|
||||
status,
|
||||
task: task.into(),
|
||||
sub: sub.into(),
|
||||
@@ -1435,6 +1506,14 @@ end = "escalated"
|
||||
assert!(tr.lines.last().unwrap().contains("ended: escalated"));
|
||||
// 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"));
|
||||
// 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);
|
||||
}
|
||||
|
||||
@@ -1899,7 +1978,7 @@ end = "merged"
|
||||
}
|
||||
let err = app.start_session(&form).unwrap_err().to_string();
|
||||
assert!(err.contains("name"), "{err}");
|
||||
form.name = "ticket work".into();
|
||||
form.name = "issue work".into();
|
||||
form.after = "s1, s9".into();
|
||||
let err = app.start_session(&form).unwrap_err().to_string();
|
||||
assert!(err.contains("no session s9"), "{err}");
|
||||
|
||||
+16
-1
@@ -34,7 +34,7 @@ pub fn draw(f: &mut Frame, o: &Overview, h: &Header, sel: usize, need_sel: usize
|
||||
keys.push(("R", "restart"));
|
||||
}
|
||||
let key_lines = theme::key_lines(&keys, area.width);
|
||||
let rows_h = (o.rows.len().max(1) * 2 + 3) as u16;
|
||||
let 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 [head, stats, sessions, lower, keys] = Layout::vertical([
|
||||
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) {
|
||||
let block = boxed("Sessions", Some(o.rows.len()), theme::TEXT, theme::BORDER);
|
||||
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"));
|
||||
let mut lines = vec![Line::from(head).style(fg(theme::DIM))];
|
||||
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 cursor = if on {
|
||||
Span::styled("▶ ", fg(theme::RUN))
|
||||
|
||||
+48
@@ -47,6 +47,8 @@ pub struct Chip {
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub struct Row {
|
||||
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 task: String,
|
||||
pub sub: String,
|
||||
@@ -248,8 +250,19 @@ pub fn build(i: &Input) -> Overview {
|
||||
Status::Fail => {}
|
||||
}
|
||||
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 {
|
||||
id: s.id.clone(),
|
||||
group,
|
||||
status,
|
||||
task: task.name.clone(),
|
||||
sub: task.subtitle.clone(),
|
||||
@@ -265,6 +278,7 @@ pub fn build(i: &Input) -> Overview {
|
||||
last,
|
||||
});
|
||||
}
|
||||
o.rows.sort_by(|a, b| a.group.cmp(&b.group)); // stable: within a group, session order stays
|
||||
o.needs.extend(escalated);
|
||||
if !i.checks.is_empty() {
|
||||
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]
|
||||
fn helpers() {
|
||||
assert_eq!(ago(5), "5s");
|
||||
|
||||
@@ -7,6 +7,7 @@ cargo clippy -q --all-targets -- -D warnings
|
||||
cargo test -q
|
||||
cargo build -q
|
||||
python3 tests/e2e.py
|
||||
python3 tests/issues.py
|
||||
python3 spike/check.py
|
||||
./target/debug/orch bench eval --check
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ Behaviour per `hx/step`, chosen with FAKE_MODE (orch passes FAKE_* through the p
|
||||
slow works until hx/interrupt (records hx/message and hx/compact in messages.txt / compact.txt), then
|
||||
answers done; a retried step with context.hint finishes at once
|
||||
limit step_result blocked, no catch, reason "limit" (hx hit a limit from hx/step)
|
||||
error step_result blocked, no catch, reason "error"
|
||||
error step_result blocked, no catch, reason "error"; finishes when the retried step has a context.hint
|
||||
crash exits without a step_result
|
||||
FAKE_UNDERSCORE=1 sends every custom method as `_hx/...`.
|
||||
FAKE_USAGE="ctx_used,ctx_limit,cost" makes every step report that usage first.
|
||||
@@ -90,7 +90,7 @@ def step(params):
|
||||
if mode == "needs_input" and not params.get("context", {}).get("hint"):
|
||||
note("hx/step_result", {"status": "needs_input", "question": "Which provider?"})
|
||||
return
|
||||
if mode in ("limit", "error"): # blocked without a catch, only the reason differs
|
||||
if mode == "limit" or mode == "error" and not params.get("context", {}).get("hint"): # blocked without a catch, only the reason differs
|
||||
note("hx/step_result", {"status": "blocked", "reason": mode, "summary": f"hit the {mode}"})
|
||||
return
|
||||
blocked = mode == "blocked"
|
||||
|
||||
+113
@@ -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"])
|
||||
Reference in new issue
Block a user