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
@@ -0,0 +1,55 @@
|
||||
# `cmd` adapter protocol
|
||||
|
||||
A `cmd` adapter is any executable. orch runs `COMMAND OP` (COMMAND is split on whitespace, OP is appended),
|
||||
writes one JSON object to stdin, and expects one JSON object on stdout and exit code 0. Anything else
|
||||
(non-zero exit, non-JSON stdout, no answer within 120 s) is an adapter error. stderr is passed through.
|
||||
|
||||
Profile:
|
||||
|
||||
```toml
|
||||
repo = "/work/myrepo" # default repo for tasks without `repo`
|
||||
|
||||
[source]
|
||||
kind = "cmd"
|
||||
command = "python3 /path/to/adapter.py"
|
||||
|
||||
[sink]
|
||||
kind = "cmd" # or "local-branch" (default)
|
||||
command = "python3 /path/to/adapter.py"
|
||||
```
|
||||
|
||||
Schema: [`cmd-protocol.schema.json`](cmd-protocol.schema.json).
|
||||
|
||||
## Task
|
||||
|
||||
`{"id", "title", "body", "repo"?, ...}`. `id` is unique per source and becomes the run and branch name (orch
|
||||
sanitizes it). `repo` is a local clone path. Every other field is adapter-private (issue number, URL, ...) and
|
||||
is echoed back verbatim in later calls, so adapters stay stateless.
|
||||
|
||||
## Operations
|
||||
|
||||
| op | stdin | stdout |
|
||||
|---|---|---|
|
||||
| `list` (source) | `{}` | `{"tasks": [Task, ...]}` |
|
||||
| `claim` (source) | `{"task": Task}` | `{"claimed": bool}`; false = someone else took it, orch skips it |
|
||||
| `report` (source) | `{"task": Task, "run": Run}` | `{}`; called when a run ends in any state |
|
||||
| `publish` (sink) | `{"task": Task, "run": Run}` | `{"url": "..."}` (url optional); only for runs that ended `done` |
|
||||
|
||||
`Run`: `id, status (done|failed|needs-human), reason, branch, repo, worktree, attempts, input_tokens,
|
||||
output_tokens, published`. The work is on local branch `branch` in `repo`; a sink pushes it and opens a PR/MR,
|
||||
posts a comment, or whatever the host needs. Host credentials live in the adapter, never in orch.
|
||||
|
||||
A failing `publish` or `report` never fails the run: the error is printed and, for publish, stored in the run's
|
||||
`published` field as `publish-failed: ...`.
|
||||
|
||||
## Built-ins
|
||||
|
||||
- source `dir`: `[source] kind = "dir"`, `path = "/tasks"`. Each `*.md` file is a task (first `#` heading = title,
|
||||
rest = prompt). Claim moves it to `.running/`, report to `.done/` or `.failed/`.
|
||||
- sink `local-branch`: nothing to publish, the branch stays in the local clone.
|
||||
|
||||
## Example
|
||||
|
||||
`examples/gitea_adapter.py`: source = open issues with label `orch`, claim swaps the label to `orch-running`,
|
||||
report comments and sets `orch-done` / `orch-failed`, publish pushes the branch and opens a PR. Auth comes from
|
||||
`git credential fill`. Env: `ORCH_GITEA_HOST`, `ORCH_GITEA_REPO` (`owner/name`), `ORCH_GITEA_CLONE` (local clone).
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "orch cmd adapter protocol",
|
||||
"$defs": {
|
||||
"Task": {
|
||||
"type": "object",
|
||||
"required": ["id", "title", "body"],
|
||||
"properties": {
|
||||
"id": {"type": "string", "minLength": 1},
|
||||
"title": {"type": "string"},
|
||||
"body": {"type": "string"},
|
||||
"repo": {"type": "string", "description": "local clone path"}
|
||||
},
|
||||
"additionalProperties": true
|
||||
},
|
||||
"Run": {
|
||||
"type": "object",
|
||||
"required": ["id", "status", "branch", "repo"],
|
||||
"properties": {
|
||||
"id": {"type": "string"},
|
||||
"status": {"enum": ["queued", "running", "gating", "done", "failed", "needs-human"]},
|
||||
"reason": {"type": ["string", "null"]},
|
||||
"branch": {"type": "string"},
|
||||
"repo": {"type": "string"},
|
||||
"worktree": {"type": "string"},
|
||||
"attempts": {"type": "integer"},
|
||||
"input_tokens": {"type": "integer"},
|
||||
"output_tokens": {"type": "integer"},
|
||||
"published": {"type": ["string", "null"]}
|
||||
}
|
||||
}
|
||||
},
|
||||
"oneOf": [
|
||||
{"title": "list: stdin", "type": "object", "maxProperties": 0},
|
||||
{"title": "list: stdout", "type": "object", "required": ["tasks"],
|
||||
"properties": {"tasks": {"type": "array", "items": {"$ref": "#/$defs/Task"}}}},
|
||||
{"title": "claim: stdin", "type": "object", "required": ["task"],
|
||||
"properties": {"task": {"$ref": "#/$defs/Task"}}},
|
||||
{"title": "claim: stdout", "type": "object", "required": ["claimed"],
|
||||
"properties": {"claimed": {"type": "boolean"}}},
|
||||
{"title": "report/publish: stdin", "type": "object", "required": ["task", "run"],
|
||||
"properties": {"task": {"$ref": "#/$defs/Task"}, "run": {"$ref": "#/$defs/Run"}}},
|
||||
{"title": "publish: stdout", "type": "object", "properties": {"url": {"type": "string"}}}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Example orch `cmd` adapter for Gitea (source + sink). See docs/cmd-protocol.md.
|
||||
|
||||
Env: ORCH_GITEA_HOST (git.example.com), ORCH_GITEA_REPO (owner/name), ORCH_GITEA_CLONE (local clone path).
|
||||
Issues labeled `orch` are tasks. Labels orch-running / orch-done / orch-failed track state; create them first.
|
||||
"""
|
||||
import base64, json, os, subprocess, sys, urllib.error, urllib.request
|
||||
|
||||
HOST, REPO, CLONE = (os.environ[k] for k in ("ORCH_GITEA_HOST", "ORCH_GITEA_REPO", "ORCH_GITEA_CLONE"))
|
||||
|
||||
|
||||
def auth():
|
||||
out = subprocess.run(["git", "credential", "fill"], input=f"protocol=https\nhost={HOST}\n\n",
|
||||
capture_output=True, text=True, check=True).stdout
|
||||
c = dict(l.split("=", 1) for l in out.splitlines() if "=" in l)
|
||||
return "Basic " + base64.b64encode(f"{c['username']}:{c['password']}".encode()).decode()
|
||||
|
||||
|
||||
def api(method, path, body=None):
|
||||
r = urllib.request.Request(f"https://{HOST}/api/v1/repos/{REPO}/{path}", method=method,
|
||||
data=None if body is None else json.dumps(body).encode(),
|
||||
headers={"Authorization": auth(), "Content-Type": "application/json",
|
||||
"User-Agent": "curl/8.5.0"}) # Cloudflare blocks the python UA
|
||||
raw = urllib.request.urlopen(r).read()
|
||||
return json.loads(raw) if raw.strip() else {}
|
||||
|
||||
|
||||
def label_ids():
|
||||
return {l["name"]: l["id"] for l in api("GET", "labels?limit=100")}
|
||||
|
||||
|
||||
def set_label(num, remove, add):
|
||||
ids = label_ids()
|
||||
try:
|
||||
api("DELETE", f"issues/{num}/labels/{ids[remove]}")
|
||||
except urllib.error.HTTPError:
|
||||
pass # label not on the issue
|
||||
api("POST", f"issues/{num}/labels", {"labels": [ids[add]]})
|
||||
|
||||
|
||||
def task(i):
|
||||
return {"id": f"issue-{i['number']}", "title": i["title"], "body": f"{i['title']}\n\n{i['body']}",
|
||||
"repo": CLONE, "number": i["number"]}
|
||||
|
||||
|
||||
def main(op):
|
||||
data = json.load(sys.stdin)
|
||||
if op == "list":
|
||||
issues = api("GET", "issues?state=open&type=issues&labels=orch&limit=50")
|
||||
return {"tasks": [task(i) for i in issues]}
|
||||
t = data["task"]
|
||||
if op == "claim":
|
||||
cur = api("GET", f"issues/{t['number']}")
|
||||
if any(l["name"] == "orch-running" for l in cur["labels"]):
|
||||
return {"claimed": False}
|
||||
set_label(t["number"], "orch", "orch-running") # ponytail: not atomic; a lock arrives with O4
|
||||
return {"claimed": True}
|
||||
run = data["run"]
|
||||
if op == "report":
|
||||
ok = run["status"] == "done"
|
||||
set_label(t["number"], "orch-running", "orch-done" if ok else "orch-failed")
|
||||
api("POST", f"issues/{t['number']}/comments",
|
||||
{"body": f"orch run `{run['id']}`: **{run['status']}**" + (f" ({run['reason']})" if run["reason"] else "")
|
||||
+ f", {run['attempts']} attempt(s), {run['input_tokens'] + run['output_tokens']} tokens."})
|
||||
return {}
|
||||
if op == "publish":
|
||||
subprocess.run(["git", "push", "-q", "origin", run["branch"]], cwd=run["repo"], check=True)
|
||||
pr = api("POST", "pulls", {"head": run["branch"], "base": "main", "title": t["title"],
|
||||
"body": f"Closes #{t['number']}\n\nAutomated by orch run `{run['id']}`."})
|
||||
return {"url": pr.get("html_url")}
|
||||
raise SystemExit(f"unknown op {op}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(json.dumps(main(sys.argv[1])))
|
||||
+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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -90,6 +90,46 @@ check(run("tokens", "k", body="TURNS=5"), "failed", "budget:tokens")
|
||||
profile("y", "yolo = true\n")
|
||||
assert run("yolo", "y", body="x").returncode != 0
|
||||
|
||||
# --- sources and sinks (O3) ---
|
||||
tasks = tmp / "tasks"
|
||||
tasks.mkdir()
|
||||
(tasks / "b-ok.md").write_text("# B ok\nWRITE\n")
|
||||
(tasks / "a-bad.md").write_text("# A bad\nFAIL\n")
|
||||
profile("d", f'repo = "{repo}"\ngate = "test -f out.txt"\n[source]\nkind = "dir"\npath = "{tasks}"\n')
|
||||
p = subprocess.run([orch, "pull", "--profile", "d"], env=env, capture_output=True, text=True)
|
||||
assert p.returncode == 1, p # one task failed
|
||||
assert (tasks / ".done/b-ok.md").exists() and (tasks / ".failed/a-bad.md").exists()
|
||||
assert not list((tasks / ".running").glob("*.md"))
|
||||
assert "-> branch orch/b-ok-" in p.stdout, p.stdout # default sink = local-branch
|
||||
p = subprocess.run([orch, "pull", "--profile", "d"], env=env, capture_output=True, text=True)
|
||||
assert p.returncode == 0 and p.stdout == "", p # nothing left
|
||||
|
||||
ad = tmp / "ad"
|
||||
ad.mkdir()
|
||||
cmd = f"{sys.executable} {root / 'tests/fake_adapter.py'}"
|
||||
profile("c", f'repo = "{repo}"\ngate = "test -f out.txt"\n[source]\nkind = "cmd"\ncommand = "{cmd}"\n[sink]\nkind = "cmd"\ncommand = "{cmd}"\n')
|
||||
aenv = {**env, "ADAPTER_DIR": str(ad), "REPO": str(repo)}
|
||||
p = subprocess.run([orch, "pull", "--profile", "c"], env=aenv, capture_output=True, text=True)
|
||||
assert p.returncode == 1, p
|
||||
calls = [json.loads(l) for l in (ad / "calls.log").read_text().splitlines()]
|
||||
ops = [(c["op"], c["in"].get("task", {}).get("id")) for c in calls]
|
||||
assert ops == [("list", None), ("claim", "t-good"), ("publish", "t-good"), ("report", "t-good"),
|
||||
("claim", "t-taken"), ("claim", "t-bad"), ("report", "t-bad")], ops # taken skipped, bad not published
|
||||
pub = next(c for c in calls if c["op"] == "publish")["in"]
|
||||
assert pub["task"]["number"] == 7, pub # adapter-private field echoed back
|
||||
assert pub["run"]["status"] == "done" and pub["run"]["branch"].startswith("orch/t-good-"), pub
|
||||
assert "-> http://example/pr/1" in p.stdout, p.stdout
|
||||
rep = [c for c in calls if c["op"] == "report"]
|
||||
assert [c["in"]["run"]["status"] for c in rep] == ["done", "failed"], rep
|
||||
|
||||
# broken adapter output: publish error never loses the run; broken list is a hard error
|
||||
(ad / "calls.log").unlink()
|
||||
p = subprocess.run([orch, "pull", "--profile", "c", "--limit", "1"], env={**aenv, "BREAK": "publish"}, capture_output=True, text=True)
|
||||
assert "publish failed" in p.stderr and "publish-failed" in p.stdout, p
|
||||
assert subprocess.run([orch, "pull", "--profile", "c"], env={**aenv, "BREAK": "list"}, capture_output=True, text=True).returncode != 0
|
||||
profile("u", '[source]\nkind = "ftp"\n')
|
||||
assert subprocess.run([orch, "pull", "--profile", "u"], env=env, capture_output=True, text=True).returncode != 0
|
||||
|
||||
# kill orch mid-run: status must say interrupted and hx must be dead after the next orch call
|
||||
pidfile = tmp / "hx.pid"
|
||||
p = subprocess.Popen([orch, "run", str(task("killed", "HANG")), "--repo", str(repo), "--profile", "p"],
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fake cmd adapter for tests/e2e.py. State/log in $ADAPTER_DIR. Implements the protocol in docs/cmd-protocol.md."""
|
||||
import json, os, sys
|
||||
|
||||
d = os.environ["ADAPTER_DIR"]
|
||||
op = sys.argv[1]
|
||||
data = json.load(sys.stdin)
|
||||
open(f"{d}/calls.log", "a").write(json.dumps({"op": op, "in": data}) + "\n")
|
||||
if os.environ.get("BREAK") == op:
|
||||
print("not json")
|
||||
sys.exit(0)
|
||||
if op == "list":
|
||||
out = {"tasks": [
|
||||
{"id": "t-good", "title": "Good", "body": "WRITE", "repo": os.environ["REPO"], "number": 7},
|
||||
{"id": "t-taken", "title": "Taken", "body": "WRITE", "repo": os.environ["REPO"]},
|
||||
{"id": "t-bad", "title": "Bad", "body": "FAIL", "repo": os.environ["REPO"]},
|
||||
]}
|
||||
elif op == "claim":
|
||||
out = {"claimed": data["task"]["id"] != "t-taken"}
|
||||
elif op == "publish":
|
||||
out = {"url": "http://example/pr/1"}
|
||||
else:
|
||||
out = {}
|
||||
print(json.dumps(out))
|
||||
Reference in new issue
Block a user