Add Needs-you queue and goal view with acceptance checks

- needs table: human steps, permission requests and agent questions wait
  for an answer written to the database; a/c/d, y/Y/n, r keys in the TUI
- goal view (g): task graph, critical path, decisions, acceptance checks;
  e edit goal, + add check, R run all checks on main
- checks.rs: acceptance checks on a branch or on main in a clean worktree
- runner: wait for --after dependencies, one session in merge at a time,
  all checks again on main after each merge
- orch goal / check / checks commands, ORCH_DB and {{repo}} for machine steps
- example machines merge with git merge --ff-only

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
johannesandClaude Sonnet 5.5 committed 2026-11-14 12:38:46 +01:00
1 parent 5b659fa8ba
commit 7bf0986640
16 files changed
+2551 -105

No files matched your search

+655 -70
View File
@@ -1,6 +1,8 @@
//! Session runner (ORCHESTRATOR.md section 4): walks one session through its machine and writes every step to
//! the event table. `computer` steps run as shell commands, `agent` steps go to hx over ACP. `human` steps
//! and `needs_input` results wait for the Needs-you queue (milestone 6) and fail the session for now.
//! the event table. `computer` steps run as shell commands, `agent` steps go to hx over ACP, `human` steps and
//! agent questions wait in the Needs-you queue. A session waits for its dependencies before it starts and for its
//! turn in the merge queue before it enters the state that ends in `merged`; after the merge all acceptance
//! checks run again on main.
use crate::acp::{Acp, Sink, StepResult};
use crate::db::{Db, Session, Task};
@@ -11,7 +13,7 @@ use anyhow::{Context, Result, bail};
use serde_json::{Value, json};
use std::path::Path;
use std::process::Command;
use std::time::Instant;
use std::time::{Duration, Instant};
/// Safety cap against catch loops that have no `retry` limit (e.g. build -> code -> build with a no-op code).
const MAX_TRANSITIONS: u32 = 500;
@@ -19,14 +21,30 @@ const MAX_TRANSITIONS: u32 = 500;
const OUTPUT_TAIL: usize = 8000;
/// Creates the task and session rows for a new session. The worktree is made by [`run_session`].
#[cfg(test)]
pub fn create(
db: &Db,
worktrees: &Path,
name: &str,
subtitle: &str,
machine: &str,
) -> Result<Session> {
create_after(db, worktrees, name, subtitle, machine, &[])
}
/// Like [`create`], for a task that may only start once the sessions in `after` have merged.
pub fn create_after(
db: &Db,
worktrees: &Path,
name: &str,
subtitle: &str,
machine: &str,
after: &[String],
) -> Result<Session> {
let id = db.next_session_id()?;
for d in after {
anyhow::ensure!(db.session(d)?.is_some(), "no session {d} to wait for");
}
let slug: String = name
.chars()
.map(|c| {
@@ -42,7 +60,7 @@ pub fn create(
name: name.into(),
subtitle: subtitle.into(),
machine: machine.into(),
depends_on: vec![],
depends_on: after.to_vec(),
};
let s = Session {
branch: format!("hx/{id}-{slug}"),
@@ -58,11 +76,12 @@ pub fn create(
Ok(s)
}
fn render(cmd: &str, s: &Session, scope: &str) -> String {
fn render(cmd: &str, s: &Session, scope: &str, repo: &Path) -> String {
cmd.replace("{{session}}", &s.id)
.replace("{{scope}}", scope)
.replace("{{worktree}}", &s.worktree)
.replace("{{branch}}", &s.branch)
.replace("{{repo}}", &repo.to_string_lossy())
}
fn ensure_worktree(repo: &Path, s: &Session) -> Result<()> {
@@ -87,6 +106,7 @@ struct Ctx<'a> {
task: &'a Task,
profile: &'a Profile,
scope: &'a str,
repo: &'a Path,
agent: Option<Acp>,
}
@@ -146,13 +166,131 @@ fn run_step(cx: &mut Ctx, st: &State, step: &Step) -> Result<StepRes> {
match step.run {
RunOn::Computer => run_command(cx, st, step),
RunOn::Agent => run_agent(cx, st, step),
RunOn::Human => bail!(
"step {:?}: human steps need the Needs-you queue (milestone 6)",
step.name
),
RunOn::Human => run_human(cx, st, step),
}
}
/// Puts an item into the Needs-you queue and blocks until somebody answers it in the database.
/// `reuse`: take over an unfinished item with the same key (orchestrator restarted while it was pending).
fn ask(
db: &Db,
session: &str,
state: &str,
kind: &str,
payload: Value,
reuse: bool,
) -> Result<String> {
let key = payload["key"].as_str().unwrap_or_default().to_string();
let existing = if reuse {
db.open_need(session, kind, &key)?
} else {
None
};
// waiting first: an item must never be visible while its session still claims to run
db.set_session(session, state, "waiting")?;
let id = match existing {
Some(n) => n.id,
None => {
let id = db.add_need(session, kind, &payload)?;
db.emit(
session,
"need",
json!({"id": id, "kind": kind, "title": payload["title"]}),
)?;
id
}
};
let answer = loop {
if let Some(a) = db.need_answer(id)? {
break a;
}
std::thread::sleep(Duration::from_millis(50));
};
db.finish_need(id)?;
db.emit(
session,
"answer",
json!({"id": id, "kind": kind, "answer": answer}),
)?;
db.set_session(session, state, "running")?;
Ok(answer)
}
/// "6 files, +318 −97, 52/52 tests pass": what the reviewer sees in the queue, built from the event stream.
fn review_summary(db: &Db, id: &str) -> Result<String> {
let evs = db.events(Some(id), 0)?;
let (mut files, mut added, mut removed) = (std::collections::BTreeSet::new(), 0, 0);
for e in evs.iter().filter(|e| e.kind == "edit") {
files.insert(e.payload["path"].as_str().unwrap_or_default().to_string());
added += e.payload["added"].as_u64().unwrap_or(0);
removed += e.payload["removed"].as_u64().unwrap_or(0);
}
let mut parts = vec![];
if !files.is_empty() {
parts.push(format!("{} files, +{added} −{removed}", files.len()));
}
if let Some(t) = evs.iter().rev().find(|e| e.kind == "test") {
let (p, f) = (
t.payload["passed"].as_u64().unwrap_or(0),
t.payload["failed"].as_u64().unwrap_or(0),
);
parts.push(if f == 0 {
format!("{p}/{p} tests pass")
} else {
format!("{p}/{} tests, {f} fail", p + f)
});
}
Ok(parts.join(", "))
}
/// A `human` step: approve, or send it back with a comment (`changes: text`), which raises the step's catch.
fn run_human(cx: &Ctx, st: &State, step: &Step) -> Result<StepRes> {
let title = if st.kind == Kind::Gate {
"review ready".to_string()
} else {
step.name.clone()
};
let payload = json!({
"key": format!("{}/{}", st.name, step.name),
"state": st.name, "step": step.name, "title": title,
"detail": review_summary(cx.db, &cx.s.id)?,
});
let answer = ask(cx.db, &cx.s.id, &st.name, "review", payload, true)?;
if answer == "approve" {
return Ok(StepRes {
ok: true,
exit: Some(0),
out: "approved".into(),
catch: None,
});
}
let Some(comment) = answer.strip_prefix("changes") else {
bail!("unknown answer {answer:?} to human step {:?}", step.name);
};
let comment = comment.trim_start_matches(':').trim();
if !comment.is_empty() {
cx.db.emit(&cx.s.id, "comment", json!({"text": comment}))?;
}
Ok(StepRes {
ok: false,
exit: None,
out: format!("changes requested: {comment}"),
catch: None,
})
}
/// A comment from a reviewer that no agent step has seen yet.
fn pending_comment(db: &Db, id: &str) -> Result<Option<String>> {
for e in db.events(Some(id), 0)?.into_iter().rev() {
match e.kind.as_str() {
"comment" => return Ok(e.payload["text"].as_str().map(String::from)),
"step" if e.payload["run"] == "agent" => return Ok(None),
_ => {}
}
}
Ok(None)
}
/// Where a `report = "junit"` step writes its report. Next to the worktree, not in it: it must not dirty git.
fn report_path(s: &Session) -> String {
format!("{}.junit.xml", s.worktree)
@@ -176,10 +314,14 @@ fn run_command(cx: &Ctx, st: &State, step: &Step) -> Result<StepRes> {
"-c",
&format!(
"({}) 2>&1",
render(cmd, cx.s, cx.scope).replace("{{report}}", &report)
render(cmd, cx.s, cx.scope, cx.repo).replace("{{report}}", &report)
),
])
.env("ORCH_REPORT", &report)
// so `orch goal --export` and `orch checks` find the goal from inside a worktree
.env("ORCH_DB", cx.db.path())
.env("ORCH_REPO", cx.repo)
.env("ORCH_SESSION", &cx.s.id)
.current_dir(&cx.s.worktree)
.output()?;
let mut out = tail(&o.stdout, OUTPUT_TAIL);
@@ -246,37 +388,56 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result<StepRes> {
cx.agent = Some(Acp::spawn(cx.profile, Path::new(&cx.s.worktree), &cx.s.id)?);
}
let goal = cx.db.goal()?;
let context = json!({"state": st.name, "last_failure": last_failure(cx.db, &cx.s.id)?});
let mut sink = DbSink {
db: cx.db,
session: &cx.s.id,
};
let agent = cx.agent.as_mut().expect("spawned above");
let r: StepResult = agent.step(
kind,
&instruction(kind, goal.as_deref(), cx.task),
context,
json!({}),
&mut sink,
)?;
match r.status.as_str() {
"done" => Ok(StepRes {
ok: true,
exit: Some(0),
out: r.summary,
catch: None,
}),
"blocked" => Ok(StepRes {
ok: false,
exit: None,
out: r.summary,
catch: r.catch,
}),
"needs_input" => bail!(
"hx asked {:?}; needs_input needs the Needs-you queue (milestone 6)",
r.question.unwrap_or_default()
),
other => bail!("hx sent unknown step status {other:?}"),
// a reviewer's comment, or the answer to a question hx asked, rides along as the hint
let mut hint = pending_comment(cx.db, &cx.s.id)?;
loop {
let context = json!({
"state": st.name, "last_failure": last_failure(cx.db, &cx.s.id)?, "hint": hint,
});
let mut sink = DbSink {
db: cx.db,
session: &cx.s.id,
state: &st.name,
};
let agent = cx.agent.as_mut().expect("spawned above");
let r: StepResult = agent.step(
kind,
&instruction(kind, goal.as_deref(), cx.task),
context,
json!({}),
&mut sink,
)?;
return match r.status.as_str() {
"done" => Ok(StepRes {
ok: true,
exit: Some(0),
out: r.summary,
catch: None,
}),
"blocked" => Ok(StepRes {
ok: false,
exit: None,
out: r.summary,
catch: r.catch,
}),
"needs_input" => {
let question = r.question.unwrap_or_default();
let payload = json!({
"key": format!("{}/{}/input", st.name, step.name),
"state": st.name, "step": step.name, "title": "question", "detail": question,
});
let answer = ask(cx.db, &cx.s.id, &st.name, "input", payload, true)?;
hint = Some(
answer
.strip_prefix("reply:")
.unwrap_or(&answer)
.trim()
.to_string(),
);
continue; // same step again, now with the answer in the context
}
other => bail!("hx sent unknown step status {other:?}"),
};
}
}
@@ -284,6 +445,28 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result<StepRes> {
struct DbSink<'a> {
db: &'a Db,
session: &'a str,
state: &'a str,
}
/// The `optionId` of the first option whose kind is one of `kinds`.
fn option_id(options: &Value, kinds: &[&str]) -> Option<String> {
kinds.iter().find_map(|k| {
options
.as_array()?
.iter()
.find_map(|o| (o["kind"] == *k).then(|| o["optionId"].as_str().map(String::from))?)
})
}
/// `allow_always` earlier in this session for the same tool: hx is not asked about it again.
fn always_allowed(db: &Db, session: &str, tool: &str) -> bool {
db.events(Some(session), 0).is_ok_and(|evs| {
evs.iter().any(|e| {
e.kind == "permission"
&& e.payload["tool"] == tool
&& e.payload["decision"] == "allow_always"
})
})
}
impl Sink for DbSink<'_> {
@@ -309,19 +492,38 @@ impl Sink for DbSink<'_> {
Ok(())
}
/// Until the Needs-you queue exists (milestone 6) every permission request is denied and recorded.
/// Goes to the Needs-you queue and blocks hx (which waits for our reply) until the user decides.
/// An error while waiting cancels the request.
fn permission(&mut self, p: &Value) -> Option<String> {
let deny = p["options"].as_array().and_then(|o| {
o.iter()
.find(|o| o["kind"].as_str().is_some_and(|k| k.starts_with("reject")))
.and_then(|o| o["optionId"].as_str().map(String::from))
});
let tool = p["toolCall"]["title"].as_str().unwrap_or("tool call");
let opts = &p["options"];
let answer = if always_allowed(self.db, self.session, tool) {
"allow_always".to_string()
} else {
let payload = json!({
"key": "", "state": self.state, "title": "permission", "tool": tool,
"detail": format!("wants to run {tool}"), "options": opts,
});
ask(
self.db,
self.session,
self.state,
"permission",
payload,
false,
)
.ok()?
};
let _ = self.db.emit(
self.session,
"permission",
json!({"tool": p["toolCall"]["title"], "decision": "denied"}),
json!({"tool": tool, "decision": answer}),
);
deny
match answer.as_str() {
"allow_once" => option_id(opts, &["allow_once", "allow_always"]),
"allow_always" => option_id(opts, &["allow_always", "allow_once"]),
_ => option_id(opts, &["reject_once", "reject_always"]),
}
}
}
@@ -343,6 +545,9 @@ pub fn run_session(
.into_iter()
.find(|t| t.id == s.task_id)
.with_context(|| format!("no task {}", s.task_id))?;
if s.state.is_empty() {
wait_for_dependencies(db, &s, &task)?;
}
ensure_worktree(repo, &s)?;
let mut cx = Ctx {
db,
@@ -350,6 +555,7 @@ pub fn run_session(
task: &task,
profile,
scope,
repo,
agent: None,
};
let mut resumed = !s.state.is_empty();
@@ -370,7 +576,22 @@ pub fn run_session(
}
resumed = false;
db.set_session(id, &cur, "running")?;
let outcome = match run_state(&mut cx, st) {
// the state that ends the session as `merged` is the merge: one session at a time, first come first served
let merging = st.end.as_deref() == Some("merged");
if merging {
enter_merge_queue(db, id)?;
}
let result = run_state(&mut cx, st);
if merging {
// all acceptance checks again on main, while this session still holds the merge slot
if matches!(result, Ok(Outcome::Ok))
&& let Err(e) = crate::checks::run_on_main(db, repo)
{
db.emit(id, "check_error", json!({"error": format!("{e:#}")}))?;
}
let _ = db.queue_leave(id);
}
let outcome = match result {
Ok(o) => o,
Err(e) => return finish(db, id, &cur, "failed", Some(format!("{e:#}"))),
};
@@ -411,6 +632,63 @@ pub fn run_session(
)
}
const POLL: Duration = Duration::from_millis(100);
/// A task whose dependencies have not merged stays `queued` (BLOCKED on screen) and nothing of it starts.
fn wait_for_dependencies(db: &Db, s: &Session, t: &Task) -> Result<()> {
let mut announced = false;
loop {
let unmet: Vec<&String> = t
.depends_on
.iter()
.filter(|d| {
db.session(d)
.ok()
.flatten()
.is_none_or(|x| x.status != "merged")
})
.collect();
if unmet.is_empty() {
return Ok(());
}
if !announced {
db.emit(&s.id, "blocked", json!({"on": unmet}))?;
announced = true;
}
std::thread::sleep(POLL);
}
}
/// Is the orchestrator process of this session still alive? A session that crashed inside the merge must not
/// block the queue forever.
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)
}
/// Joins the merge queue and blocks until this session is at the head.
fn enter_merge_queue(db: &Db, id: &str) -> Result<()> {
db.queue_join(id)?;
let pos = db.queue_position(id)?;
if pos > 1 {
db.emit(id, "queue", json!({"position": pos}))?;
}
loop {
match db.queue_head()? {
Some(h) if h == id => return Ok(()),
Some(h) if !alive(db, &h) => db.queue_leave(&h)?,
None => {
db.queue_join(id)?; // pruned by somebody else's mistake: stand in line again
}
_ => std::thread::sleep(POLL),
}
}
}
fn finish(db: &Db, id: &str, state: &str, status: &str, reason: Option<String>) -> Result<String> {
db.set_session(id, state, status)?;
db.set_pid(id, None)?;
@@ -627,16 +905,105 @@ next = "done"
let _ = std::fs::remove_dir_all(&e.dir);
}
/// What the answering thread saw: (kind, payload, session status at that moment).
type Seen = Vec<(String, Value, String)>;
/// Plays the user: answers the pending queue items one by one with `answers` from another connection.
fn answerer(
db_path: std::path::PathBuf,
answers: &'static [&'static str],
) -> std::thread::JoinHandle<Seen> {
std::thread::spawn(move || {
let db = Db::open(&db_path).unwrap();
let mut seen = vec![];
let deadline = Instant::now() + Duration::from_secs(20);
while seen.len() < answers.len() && Instant::now() < deadline {
if let Some(n) = db.pending_needs().unwrap().first() {
let status = db.session(&n.session).unwrap().unwrap().status;
db.answer_need(n.id, answers[seen.len()]).unwrap();
seen.push((n.kind.clone(), n.payload.clone(), status));
}
std::thread::sleep(Duration::from_millis(20));
}
seen
})
}
#[test]
fn human_step_fails_the_session_cleanly() {
fn human_review_waits_in_the_queue_and_changes_requested_loops_back() {
let e = env("human");
let m = one_step(r#"{ name = "ok", run = "human" }"#);
let m = Machine::parse(&format!(
r#"name = "m"
[[state]]
name = "code"
kind = "start"
steps = [{{ name = "edit", run = "computer", cmd = "echo x >> n" }}]
next = "review"
[[state]]
name = "review"
kind = "gate"
steps = [{{ name = "wait-approval", run = "human", sets = "waiting" }}]
catch = {{ ChangesRequested = "code" }}
next = "done"
{TAIL}"#
))
.unwrap();
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
let user = answerer(e.dir.join("orch.db"), &["changes: rename it", "approve"]);
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(),
"failed"
"merged"
);
assert!(failure_reason(&e).contains("milestone 6"));
let seen = user.join().unwrap();
assert_eq!(
states(&e.db, "s1"),
["code", "review", "code", "review", "done"]
);
assert_eq!(seen.len(), 2);
assert_eq!(
(seen[0].0.as_str(), seen[0].1["title"].as_str()),
("review", Some("review ready"))
);
assert_eq!(
seen[0].2, "waiting",
"the session shows as waiting while the item is open"
);
assert_eq!(
e.db.catch_count("s1", "review", "ChangesRequested")
.unwrap(),
1
);
let ev = e.db.events(Some("s1"), 0).unwrap();
let comment = ev.iter().find(|v| v.kind == "comment").unwrap();
assert_eq!(comment.payload["text"], "rename it");
assert_eq!(ev.iter().filter(|v| v.kind == "need").count(), 2);
assert_eq!(ev.iter().filter(|v| v.kind == "answer").count(), 2);
assert!(e.db.pending_needs().unwrap().is_empty());
let _ = std::fs::remove_dir_all(&e.dir);
}
#[test]
fn restart_takes_over_the_pending_item_instead_of_asking_twice() {
let e = env("reuse");
let m = one_step(r#"{ name = "ok", run = "human" }"#);
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
// the first orchestrator died while the item was open; the user answers it afterwards
let n =
e.db.add_need("s1", "review", &json!({"key": "a/ok", "title": "ok"}))
.unwrap();
e.db.answer_need(n, "approve").unwrap();
e.db.set_session("s1", "a", "waiting").unwrap();
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(),
"merged"
);
let ev = e.db.events(Some("s1"), 0).unwrap();
assert_eq!(
ev.iter().filter(|v| v.kind == "need").count(),
0,
"no second question"
);
assert_eq!(ev.iter().filter(|v| v.kind == "answer").count(), 1);
let _ = std::fs::remove_dir_all(&e.dir);
}
@@ -732,44 +1099,262 @@ next = "done"
}
#[test]
fn permission_requests_are_denied_and_recorded() {
let e = env("perm");
fn permission_request_waits_for_the_user_and_deny_reaches_hx() {
let e = env("deny");
let m = one_step(r#"{ name = "ag", run = "agent", prompt = "implement" }"#);
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
let user = answerer(e.dir.join("orch.db"), &["deny"]);
let p = fake("FAKE_MODE=permission");
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(),
"merged"
);
let seen = user.join().unwrap();
assert_eq!(seen[0].0, "permission");
assert_eq!(seen[0].1["tool"], "docker compose up -d redis");
assert_eq!(seen[0].2, "waiting");
let answer = std::fs::read_to_string(e.dir.join("wt/s1/permission.txt")).unwrap();
assert!(answer.contains("\"optionId\": \"deny\""), "{answer}");
let ev = e.db.events(Some("s1"), 0).unwrap();
let perm = ev.iter().find(|v| v.kind == "permission").unwrap();
assert_eq!(perm.payload["tool"], "docker compose up -d redis");
let _ = std::fs::remove_dir_all(&e.dir);
}
#[test]
fn needs_input_and_a_crashing_hx_fail_the_session() {
let e = env("fail");
fn allow_always_is_remembered_for_the_session() {
let e = env("always");
let step = r#"{ name = "ag", run = "agent", prompt = "implement" }"#;
let m = one_step(&format!("{step}, {step}"));
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
let user = answerer(e.dir.join("orch.db"), &["allow_always"]);
let p = fake("FAKE_MODE=permission");
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(),
"merged"
);
user.join().unwrap();
let ev = e.db.events(Some("s1"), 0).unwrap();
// hx asked twice, the user was asked once
assert_eq!(ev.iter().filter(|v| v.kind == "permission").count(), 2);
assert_eq!(ev.iter().filter(|v| v.kind == "need").count(), 1);
let answer = std::fs::read_to_string(e.dir.join("wt/s1/permission.txt")).unwrap();
assert!(answer.contains("\"optionId\": \"allow\""), "{answer}");
let _ = std::fs::remove_dir_all(&e.dir);
}
#[test]
fn needs_input_is_asked_in_the_queue_and_the_reply_goes_back_to_hx() {
let e = env("input");
let log = e.dir.join("fake.log");
let m = one_step(r#"{ name = "ag", run = "agent", prompt = "implement" }"#);
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
let p = fake("FAKE_MODE=needs_input");
let user = answerer(e.dir.join("orch.db"), &["reply: use claude"]);
let p = fake(&format!("FAKE_MODE=needs_input FAKE_LOG={}", log.display()));
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(),
"merged"
);
let seen = user.join().unwrap();
assert_eq!(
(seen[0].0.as_str(), seen[0].1["detail"].as_str()),
("input", Some("Which provider?"))
);
let steps: Vec<Value> = std::fs::read_to_string(&log)
.unwrap()
.lines()
.map(|l| serde_json::from_str::<Value>(l).unwrap())
.filter(|m| m["method"] == "hx/step")
.collect();
assert_eq!(steps.len(), 2, "the same step runs again with the answer");
assert_eq!(steps[0]["params"]["context"]["hint"], Value::Null);
assert_eq!(steps[1]["params"]["context"]["hint"], "use claude");
let _ = std::fs::remove_dir_all(&e.dir);
}
#[test]
fn a_crashing_hx_fails_the_session() {
let e = env("crash");
let m = one_step(r#"{ name = "ag", run = "agent", prompt = "implement" }"#);
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
let p = fake("FAKE_MODE=crash");
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(),
"failed"
);
assert!(failure_reason(&e).contains("Which provider?"));
assert!(failure_reason(&e).contains("hx closed its output"));
let _ = std::fs::remove_dir_all(&e.dir);
}
let e2 = env("crash");
create(&e2.db, &e2.dir.join("wt"), "t", "", "m").unwrap();
let p = fake("FAKE_MODE=crash");
/// Runs a session on its own connection in a thread, like another orchestrator process would.
fn spawn_session(e: &Env, m: &Machine, id: &str) -> std::thread::JoinHandle<String> {
let (path, repo, m, id) = (
e.dir.join("orch.db"),
e.repo.clone(),
m.clone(),
id.to_string(),
);
std::thread::spawn(move || {
let db = Db::open(&path).unwrap();
run_session(&db, &m, &id, &repo, "", &plain()).unwrap()
})
}
#[test]
fn a_task_waits_for_its_dependencies_to_merge() {
let e = env("deps");
let m = Machine::parse(&format!(
r#"name = "m"
[[state]]
name = "a"
kind = "start"
steps = [{{ name = "w", run = "computer", cmd = "true" }}]
next = "done"
{TAIL}"#
))
.unwrap();
let wt = e.dir.join("wt");
create(&e.db, &wt, "first", "", "m").unwrap();
create_after(&e.db, &wt, "second", "", "m", &["s1".to_string()]).unwrap();
assert!(create_after(&e.db, &wt, "bad", "", "m", &["s9".to_string()]).is_err());
let second = spawn_session(&e, &m, "s2");
std::thread::sleep(Duration::from_millis(500));
let s2 = e.db.session("s2").unwrap().unwrap();
assert_eq!(s2.status, "queued", "blocked: not started");
assert!(
!Path::new(&s2.worktree).exists(),
"nothing of it exists yet"
);
assert!(kinds(&e.db, "s2").contains(&"blocked".to_string()));
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(),
"merged"
);
assert_eq!(second.join().unwrap(), "merged");
let first_end = e.db.events(Some("s1"), 0).unwrap().last().unwrap().id;
let second_start =
e.db.events(Some("s2"), 0)
.unwrap()
.iter()
.find(|v| v.kind == "state")
.unwrap()
.id;
assert!(second_start > first_end, "s2 started only after s1 merged");
let _ = std::fs::remove_dir_all(&e.dir);
}
#[test]
fn only_one_session_is_in_merge_at_a_time() {
let e = env("queue");
let log = e.dir.join("merge.log");
let m = Machine::parse(&format!(
r#"name = "m"
[[state]]
name = "a"
kind = "start"
steps = [{{ name = "w", run = "computer", cmd = "true" }}]
next = "merge"
[[state]]
name = "merge"
kind = "exit"
steps = [{{ name = "slow", run = "computer", cmd = "echo start >> {0}; sleep 0.3; echo end >> {0}" }}]
end = "merged"
"#,
log.display()
))
.unwrap();
let wt = e.dir.join("wt");
for n in ["a", "b", "c"] {
create(&e.db, &wt, n, "", "m").unwrap();
}
let runs: Vec<_> = ["s1", "s2", "s3"]
.iter()
.map(|id| spawn_session(&e, &m, id))
.collect();
for r in runs {
assert_eq!(r.join().unwrap(), "merged");
}
let lines: Vec<String> = std::fs::read_to_string(&log)
.unwrap()
.lines()
.map(String::from)
.collect();
assert_eq!(
lines,
["start", "end", "start", "end", "start", "end"],
"merges never overlap"
);
assert_eq!(e.db.queue_head().unwrap(), None, "everybody left the queue");
let _ = std::fs::remove_dir_all(&e.dir);
}
#[test]
fn a_dead_session_does_not_block_the_merge_queue() {
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
e.db.add_session(&Session {
id: "s9".into(),
task_id: "s1".into(),
branch: "b".into(),
worktree: "/nowhere".into(),
pid: Some(2_000_000_000),
state: "merge".into(),
status: "running".into(),
})
.unwrap();
e.db.queue_join("s9").unwrap();
// one_step ends in `done` (merged), which is the merge state
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(),
"merged"
);
assert_eq!(e.db.queue_head().unwrap(), None);
let _ = std::fs::remove_dir_all(&e.dir);
}
#[test]
fn merge_fast_forwards_main_and_all_checks_run_on_main_afterwards() {
let e = env("main");
let m = Machine::parse(
r#"name = "m"
[[state]]
name = "code"
kind = "start"
steps = [{ name = "feature", run = "computer", cmd = "echo hi > feature.txt && git add -A && git -c user.name=t -c user.email=t@t commit -qm feature" }]
next = "merge"
[[state]]
name = "merge"
kind = "exit"
steps = [
{ name = "ff", run = "computer", cmd = "git -C {{repo}} merge --ff-only {{branch}}" },
{ name = "mark-merged", run = "computer", sets = "merged" },
]
end = "merged"
"#,
)
.unwrap();
e.db.add_check("feature on main", "test -f feature.txt", None)
.unwrap();
e.db.add_check("still red", "exit 1", Some("s1")).unwrap();
create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap();
assert_eq!(
run_session(&e.db, &m, "s1", &e.repo, "", &plain()).unwrap(),
"merged"
);
assert!(e.repo.join("feature.txt").exists(), "main moved forward");
let st: Vec<_> =
e.db.checks()
.unwrap()
.into_iter()
.map(|c| c.last_status.unwrap())
.collect();
assert_eq!(
run_session(&e2.db, &m, "s1", &e2.repo, "", &p).unwrap(),
"failed"
st,
["pass", "fail"],
"every check ran on main, owner or not"
);
assert!(failure_reason(&e2).contains("hx closed its output"));
assert_eq!(e.db.events(Some(crate::checks::GOAL), 0).unwrap().len(), 2);
let _ = std::fs::remove_dir_all(&e.dir);
let _ = std::fs::remove_dir_all(&e2.dir);
}
}