O3: task sources and result sinks (#11)
This commit was merged in pull request #11.
This commit is contained in:
1 parent
2f79b69977
commit
afafc41376
10 files changed
+594
-76
No files matched your search
+257
@@ -0,0 +1,257 @@
|
||||
//! Task sources and result sinks. Host-agnostic: built-ins are `dir` and `local-branch`; everything else
|
||||
//! (Gitea, GitHub, Jira, ...) is an external `cmd` adapter speaking JSON, see docs/cmd-protocol.md.
|
||||
|
||||
use crate::state::Run;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
pub struct Task {
|
||||
/// Stable, unique per source; used for branch and run names (sanitized by orch).
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub body: String,
|
||||
/// Local clone to work in; falls back to the profile's `repo`.
|
||||
#[serde(default)]
|
||||
pub repo: Option<PathBuf>,
|
||||
/// Adapter-private fields (issue number, URL, ...): echoed back verbatim on claim/report/publish.
|
||||
#[serde(flatten)]
|
||||
pub extra: Map<String, Value>,
|
||||
}
|
||||
|
||||
pub trait Source {
|
||||
fn list(&self) -> Result<Vec<Task>>;
|
||||
/// false = somebody else got it; skip silently.
|
||||
fn claim(&self, t: &Task) -> Result<bool>;
|
||||
fn report(&self, t: &Task, r: &Run) -> Result<()>;
|
||||
}
|
||||
|
||||
pub trait Sink {
|
||||
/// Called for runs that ended `done`. Returns a URL or note to store on the run.
|
||||
fn publish(&self, t: &Task, r: &Run) -> Result<Option<String>>;
|
||||
}
|
||||
|
||||
/// `[source]` / `[sink]` profile section.
|
||||
#[derive(Deserialize, Debug, Clone)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Adapter {
|
||||
/// source: dir | cmd. sink: local-branch | cmd.
|
||||
pub kind: String,
|
||||
/// dir: folder with `*.md` tasks.
|
||||
pub path: Option<PathBuf>,
|
||||
/// cmd: program and fixed args (whitespace-split); orch appends the operation name.
|
||||
pub command: Option<String>,
|
||||
}
|
||||
|
||||
pub fn source(a: &Adapter) -> Result<Box<dyn Source>> {
|
||||
Ok(match a.kind.as_str() {
|
||||
"dir" => Box::new(DirSource(
|
||||
a.path.clone().context("source dir needs `path`")?,
|
||||
)),
|
||||
"cmd" => Box::new(Cmd(a
|
||||
.command
|
||||
.clone()
|
||||
.context("source cmd needs `command`")?)),
|
||||
k => bail!("unknown source kind {k:?} (dir | cmd)"),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn sink(a: Option<&Adapter>) -> Result<Box<dyn Sink>> {
|
||||
Ok(match a.map(|a| (a.kind.as_str(), a)) {
|
||||
None | Some(("local-branch", _)) => Box::new(LocalBranch),
|
||||
Some(("cmd", a)) => Box::new(Cmd(a
|
||||
.command
|
||||
.clone()
|
||||
.context("sink cmd needs `command`")?)),
|
||||
Some((k, _)) => bail!("unknown sink kind {k:?} (local-branch | cmd)"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Markdown task: first `#` heading = title, rest = prompt. Shared with `orch run FILE`.
|
||||
pub fn parse_task_md(id: &str, s: &str) -> Task {
|
||||
let title = s
|
||||
.lines()
|
||||
.find(|l| l.starts_with('#'))
|
||||
.map(|l| l.trim_start_matches('#').trim().to_string());
|
||||
let body: String = s
|
||||
.lines()
|
||||
.filter(|l| !l.starts_with('#'))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let title = title.unwrap_or_else(|| id.to_string());
|
||||
let body = if body.trim().is_empty() {
|
||||
title.clone()
|
||||
} else {
|
||||
body.trim().to_string()
|
||||
};
|
||||
Task {
|
||||
id: id.into(),
|
||||
title,
|
||||
body,
|
||||
repo: None,
|
||||
extra: Map::new(),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- dir -------------------------------------------------------------------------------------
|
||||
|
||||
/// `*.md` files in a folder. Claim = atomic rename into `.running/`; report moves to `.done/` or `.failed/`.
|
||||
pub struct DirSource(PathBuf);
|
||||
|
||||
impl DirSource {
|
||||
fn mv(&self, id: &str, from: &str, to: &str) -> Result<bool> {
|
||||
let dest = self.0.join(to);
|
||||
std::fs::create_dir_all(&dest)?;
|
||||
let src = if from.is_empty() {
|
||||
self.0.clone()
|
||||
} else {
|
||||
self.0.join(from)
|
||||
};
|
||||
match std::fs::rename(src.join(format!("{id}.md")), dest.join(format!("{id}.md"))) {
|
||||
Ok(()) => Ok(true),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false), // lost the race
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Source for DirSource {
|
||||
fn list(&self) -> Result<Vec<Task>> {
|
||||
let mut v = vec![];
|
||||
for e in std::fs::read_dir(&self.0)
|
||||
.with_context(|| format!("source dir {}", self.0.display()))?
|
||||
.flatten()
|
||||
{
|
||||
let p = e.path();
|
||||
if p.extension().is_some_and(|x| x == "md") && p.is_file() {
|
||||
let id = p.file_stem().and_then(|s| s.to_str()).unwrap_or("task");
|
||||
v.push(parse_task_md(id, &std::fs::read_to_string(&p)?));
|
||||
}
|
||||
}
|
||||
v.sort_by(|a, b| a.id.cmp(&b.id));
|
||||
Ok(v)
|
||||
}
|
||||
fn claim(&self, t: &Task) -> Result<bool> {
|
||||
self.mv(&t.id, "", ".running")
|
||||
}
|
||||
fn report(&self, t: &Task, r: &Run) -> Result<()> {
|
||||
let to = if r.status == crate::state::Status::Done {
|
||||
".done"
|
||||
} else {
|
||||
".failed"
|
||||
};
|
||||
self.mv(&t.id, ".running", to)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ---- local branch ----------------------------------------------------------------------------
|
||||
|
||||
/// Fallback sink: the work already sits on the local branch `orch/ID`; nothing to push.
|
||||
pub struct LocalBranch;
|
||||
impl Sink for LocalBranch {
|
||||
fn publish(&self, _t: &Task, r: &Run) -> Result<Option<String>> {
|
||||
Ok(Some(format!("branch {} in {}", r.branch, r.repo.display())))
|
||||
}
|
||||
}
|
||||
|
||||
// ---- cmd -------------------------------------------------------------------------------------
|
||||
|
||||
/// External adapter: `COMMAND OP` with a JSON object on stdin, a JSON object on stdout, exit 0.
|
||||
pub struct Cmd(String);
|
||||
|
||||
const CMD_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
|
||||
pub fn call(command: &str, op: &str, input: &Value) -> Result<Value> {
|
||||
let mut parts = command.split_whitespace();
|
||||
let mut child = Command::new(parts.next().context("empty adapter command")?)
|
||||
.args(parts)
|
||||
.arg(op)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.with_context(|| format!("adapter {command}"))?;
|
||||
child
|
||||
.stdin
|
||||
.take()
|
||||
.unwrap()
|
||||
.write_all(input.to_string().as_bytes())?; // dropped = EOF
|
||||
let mut out = child.stdout.take().unwrap();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut s = String::new();
|
||||
let _ = tx.send(out.read_to_string(&mut s).map(|_| s));
|
||||
});
|
||||
let Ok(res) = rx.recv_timeout(CMD_TIMEOUT) else {
|
||||
let _ = child.kill();
|
||||
bail!(
|
||||
"adapter {command} {op}: timed out after {}s",
|
||||
CMD_TIMEOUT.as_secs()
|
||||
);
|
||||
};
|
||||
let st = child.wait()?;
|
||||
if !st.success() {
|
||||
bail!("adapter {command} {op}: exit {}", st.code().unwrap_or(-1));
|
||||
}
|
||||
serde_json::from_str(res?.trim()).with_context(|| format!("adapter {op}: stdout is not JSON"))
|
||||
}
|
||||
|
||||
fn run_json(t: &Task, r: &Run) -> Value {
|
||||
json!({"task": t, "run": {
|
||||
"id": r.id, "status": r.status, "reason": r.reason, "branch": r.branch, "repo": r.repo,
|
||||
"worktree": r.worktree, "attempts": r.attempts, "input_tokens": r.input_tokens,
|
||||
"output_tokens": r.output_tokens, "published": r.published,
|
||||
}})
|
||||
}
|
||||
|
||||
impl Source for Cmd {
|
||||
fn list(&self) -> Result<Vec<Task>> {
|
||||
let v = call(&self.0, "list", &json!({}))?;
|
||||
serde_json::from_value(v["tasks"].clone())
|
||||
.context("list: `tasks` must be an array of tasks")
|
||||
}
|
||||
fn claim(&self, t: &Task) -> Result<bool> {
|
||||
let v = call(&self.0, "claim", &json!({"task": t}))?;
|
||||
v["claimed"]
|
||||
.as_bool()
|
||||
.context("claim: `claimed` must be a bool")
|
||||
}
|
||||
fn report(&self, t: &Task, r: &Run) -> Result<()> {
|
||||
call(&self.0, "report", &run_json(t, r)).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
impl Sink for Cmd {
|
||||
fn publish(&self, t: &Task, r: &Run) -> Result<Option<String>> {
|
||||
let v = call(&self.0, "publish", &run_json(t, r))?;
|
||||
Ok(v["url"].as_str().map(String::from))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn task_md_and_wire_format() {
|
||||
let t = parse_task_md("fix-it", "# Fix it\n\nDo the thing\nplease\n");
|
||||
assert_eq!(
|
||||
(t.title.as_str(), t.body.as_str()),
|
||||
("Fix it", "Do the thing\nplease")
|
||||
);
|
||||
assert_eq!(parse_task_md("x", "just text").title, "x");
|
||||
assert_eq!(parse_task_md("x", "# Only title").body, "Only title");
|
||||
// unknown fields survive a round trip (adapters stay stateless)
|
||||
let t: Task =
|
||||
serde_json::from_str(r#"{"id":"a","title":"t","body":"b","number":7,"url":"u"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(serde_json::to_value(&t).unwrap()["number"], 7);
|
||||
assert!(serde_json::from_str::<Task>(r#"{"id":"a"}"#).is_err());
|
||||
}
|
||||
}
|
||||
+83
-19
@@ -1,10 +1,11 @@
|
||||
mod adapter;
|
||||
mod profile;
|
||||
mod run;
|
||||
mod state;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::{Parser, Subcommand};
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(version, about = "Run hx coding agents on tasks")]
|
||||
@@ -23,6 +24,14 @@ enum Cmd {
|
||||
#[arg(long, default_value = "default")]
|
||||
profile: String,
|
||||
},
|
||||
/// Run every task the profile's source lists, one after another (parallel pool: O4).
|
||||
Pull {
|
||||
#[arg(long, default_value = "default")]
|
||||
profile: String,
|
||||
/// Stop after N claimed tasks.
|
||||
#[arg(long)]
|
||||
limit: Option<usize>,
|
||||
},
|
||||
/// List runs, or show one.
|
||||
Status { id: Option<String> },
|
||||
/// Print the raw log (hx events, stderr, gate output) of a run.
|
||||
@@ -49,6 +58,10 @@ pub fn state_dir() -> PathBuf {
|
||||
env_dir("ORCH_STATE_DIR", "XDG_STATE_HOME", ".local/state")
|
||||
}
|
||||
|
||||
fn code(ok: bool) -> std::process::ExitCode {
|
||||
u8::from(!ok).into()
|
||||
}
|
||||
|
||||
fn main() -> Result<std::process::ExitCode> {
|
||||
match Cli::parse().cmd {
|
||||
Cmd::Run {
|
||||
@@ -57,23 +70,32 @@ fn main() -> Result<std::process::ExitCode> {
|
||||
profile,
|
||||
} => {
|
||||
let p = profile::Profile::load(&profile)?;
|
||||
let mut r = run::new_run(&task, &repo, &profile)?;
|
||||
run::execute(&mut r, &p, &task)?;
|
||||
println!(
|
||||
"{} {}{}",
|
||||
r.id,
|
||||
serde_json::to_value(r.status)?.as_str().unwrap(),
|
||||
r.reason
|
||||
.as_ref()
|
||||
.map(|x| format!(" ({x})"))
|
||||
.unwrap_or_default()
|
||||
);
|
||||
Ok(if r.status == state::Status::Done {
|
||||
0
|
||||
} else {
|
||||
1
|
||||
let id = task.file_stem().and_then(|s| s.to_str()).unwrap_or("task");
|
||||
let t = adapter::parse_task_md(id, &std::fs::read_to_string(&task)?);
|
||||
let r = process(&t, &repo, &profile, &p, None)?;
|
||||
Ok(code(r.status == state::Status::Done))
|
||||
}
|
||||
Cmd::Pull { profile, limit } => {
|
||||
let p = profile::Profile::load(&profile)?;
|
||||
let src = adapter::source(p.source.as_ref().context("profile has no [source]")?)?;
|
||||
let (mut ok, mut n) = (true, 0);
|
||||
for t in src.list()? {
|
||||
if limit.is_some_and(|l| n >= l) {
|
||||
break;
|
||||
}
|
||||
let Some(repo) = t.repo.clone().or_else(|| p.repo.clone()) else {
|
||||
eprintln!("{}: no repo (task `repo` or profile `repo`), skipped", t.id);
|
||||
ok = false;
|
||||
continue;
|
||||
};
|
||||
if !src.claim(&t)? {
|
||||
continue;
|
||||
}
|
||||
n += 1;
|
||||
let r = process(&t, &repo, &profile, &p, Some(src.as_ref()))?;
|
||||
ok &= r.status == state::Status::Done;
|
||||
}
|
||||
.into())
|
||||
Ok(code(ok))
|
||||
}
|
||||
Cmd::Status { id: Some(id) } => {
|
||||
println!("{}", serde_json::to_string_pretty(&state::Run::load(&id)?)?);
|
||||
@@ -84,7 +106,7 @@ fn main() -> Result<std::process::ExitCode> {
|
||||
let st = serde_json::to_value(r.status)?;
|
||||
let end = r.ended.unwrap_or_else(state::now);
|
||||
println!(
|
||||
"{:<28} {:<8} {:>5}s {:>8} tok {}{}",
|
||||
"{:<28} {:<11} {:>5}s {:>8} tok {}{}",
|
||||
r.id,
|
||||
st.as_str().unwrap(),
|
||||
end.saturating_sub(r.started),
|
||||
@@ -104,3 +126,45 @@ fn main() -> Result<std::process::ExitCode> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One task through the pipeline: run, publish via the sink when done, report to the source.
|
||||
/// A failing adapter never loses the run: the error is printed and kept in `published`.
|
||||
fn process(
|
||||
t: &adapter::Task,
|
||||
repo: &Path,
|
||||
profile: &str,
|
||||
p: &profile::Profile,
|
||||
src: Option<&dyn adapter::Source>,
|
||||
) -> Result<state::Run> {
|
||||
let mut r = run::new_run(t, repo, profile)?;
|
||||
run::execute(&mut r, p, t)?;
|
||||
if r.status == state::Status::Done {
|
||||
match adapter::sink(p.sink.as_ref()).and_then(|s| s.publish(t, &r)) {
|
||||
Ok(note) => r.published = note,
|
||||
Err(e) => {
|
||||
eprintln!("{}: publish failed: {e:#}", r.id);
|
||||
r.published = Some(format!("publish-failed: {e:#}"));
|
||||
}
|
||||
}
|
||||
r.save()?;
|
||||
}
|
||||
if let Some(src) = src
|
||||
&& let Err(e) = src.report(t, &r)
|
||||
{
|
||||
eprintln!("{}: report failed: {e:#}", r.id);
|
||||
}
|
||||
println!(
|
||||
"{} {}{}{}",
|
||||
r.id,
|
||||
serde_json::to_value(r.status)?.as_str().unwrap(),
|
||||
r.reason
|
||||
.as_ref()
|
||||
.map(|x| format!(" ({x})"))
|
||||
.unwrap_or_default(),
|
||||
r.published
|
||||
.as_ref()
|
||||
.map(|x| format!(" -> {x}"))
|
||||
.unwrap_or_default()
|
||||
);
|
||||
Ok(r)
|
||||
}
|
||||
@@ -36,6 +36,10 @@ pub struct Profile {
|
||||
pub max_retries: u32,
|
||||
#[serde(default)]
|
||||
pub budget: Budget,
|
||||
/// Default repo for tasks that name none (`orch pull`).
|
||||
pub repo: Option<PathBuf>,
|
||||
pub source: Option<crate::adapter::Adapter>,
|
||||
pub sink: Option<crate::adapter::Adapter>,
|
||||
}
|
||||
|
||||
fn default_retries() -> u32 {
|
||||
|
||||
+7
-57
@@ -1,5 +1,6 @@
|
||||
//! One run: worktree -> hx (NDJSON, budgets, process group) -> commit -> gate -> final state.
|
||||
|
||||
use crate::adapter::Task;
|
||||
use crate::profile::Profile;
|
||||
use crate::state::{Run, Status, gate_log_path, kill_group, log_path, now};
|
||||
use anyhow::{Context, Result, bail};
|
||||
@@ -27,35 +28,8 @@ fn git(dir: &Path, args: &[&str]) -> Result<String> {
|
||||
Ok(String::from_utf8_lossy(&o.stdout).into_owned())
|
||||
}
|
||||
|
||||
/// Task file: first `#` heading = title, the rest = prompt.
|
||||
pub fn read_task(path: &Path) -> Result<(String, String)> {
|
||||
let s = std::fs::read_to_string(path).with_context(|| format!("task {}", path.display()))?;
|
||||
let title = s
|
||||
.lines()
|
||||
.find(|l| l.starts_with('#'))
|
||||
.map(|l| l.trim_start_matches('#').trim().to_string());
|
||||
let body: String = s
|
||||
.lines()
|
||||
.filter(|l| !l.starts_with('#'))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let stem = path
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("task")
|
||||
.to_string();
|
||||
let title = title.unwrap_or(stem);
|
||||
let body = if body.trim().is_empty() {
|
||||
title.clone()
|
||||
} else {
|
||||
body.trim().to_string()
|
||||
};
|
||||
Ok((title, body))
|
||||
}
|
||||
|
||||
pub fn new_run(task: &Path, repo: &Path, profile: &str) -> Result<Run> {
|
||||
let (title, _) = read_task(task)?;
|
||||
let stem = task.file_stem().and_then(|s| s.to_str()).unwrap_or("task");
|
||||
pub fn new_run(task: &Task, repo: &Path, profile: &str) -> Result<Run> {
|
||||
let stem = task.id.as_str();
|
||||
let stem: String = stem
|
||||
.chars()
|
||||
.map(|c| {
|
||||
@@ -74,7 +48,7 @@ pub fn new_run(task: &Path, repo: &Path, profile: &str) -> Result<Run> {
|
||||
branch: format!("orch/{id}"),
|
||||
worktree: crate::state_dir().join("worktrees").join(&id),
|
||||
id,
|
||||
title,
|
||||
title: task.title.clone(),
|
||||
profile: profile.into(),
|
||||
repo,
|
||||
status: Status::Queued,
|
||||
@@ -91,6 +65,7 @@ pub fn new_run(task: &Path, repo: &Path, profile: &str) -> Result<Run> {
|
||||
attempts: 0,
|
||||
turns: 0,
|
||||
spent_tokens: 0,
|
||||
published: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -124,8 +99,8 @@ fn retry_prompt(gate: &str, code: Option<i32>, out: &[u8], resumed: bool, body:
|
||||
|
||||
/// Runs the whole pipeline. Errors only for orch-internal problems; task failures end as `Failed` or
|
||||
/// `NeedsHuman` state. After a failed gate hx gets the gate output on the same session, up to `max_retries`.
|
||||
pub fn execute(r: &mut Run, p: &Profile, task: &Path) -> Result<()> {
|
||||
let (_, body) = read_task(task)?;
|
||||
pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> {
|
||||
let body = task.body.clone();
|
||||
r.save()?;
|
||||
std::fs::create_dir_all(r.worktree.parent().unwrap())?;
|
||||
let wt = r.worktree.to_string_lossy().into_owned();
|
||||
@@ -298,28 +273,3 @@ fn run_hx(
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn task_parsing() {
|
||||
let d = std::env::temp_dir().join(format!("orch-task-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let f = d.join("fix-it.md");
|
||||
std::fs::write(&f, "# Fix it\n\nDo the thing\nplease\n").unwrap();
|
||||
assert_eq!(
|
||||
read_task(&f).unwrap(),
|
||||
("Fix it".into(), "Do the thing\nplease".into())
|
||||
);
|
||||
std::fs::write(&f, "no heading, just text").unwrap();
|
||||
assert_eq!(
|
||||
read_task(&f).unwrap(),
|
||||
("fix-it".into(), "no heading, just text".into())
|
||||
);
|
||||
std::fs::write(&f, "# Only title").unwrap();
|
||||
assert_eq!(read_task(&f).unwrap().1, "Only title");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,9 @@ pub struct Run {
|
||||
pub turns: u64,
|
||||
#[serde(default)]
|
||||
pub spent_tokens: u64,
|
||||
/// Sink result (PR URL, branch note) once published.
|
||||
#[serde(default)]
|
||||
pub published: Option<String>,
|
||||
}
|
||||
|
||||
pub fn now() -> u64 {
|
||||
@@ -161,6 +164,7 @@ mod tests {
|
||||
attempts: 0,
|
||||
turns: 0,
|
||||
spent_tokens: 0,
|
||||
published: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user