Files
2026-11-12 23:15:06 +00:00

78 lines
3.2 KiB
Python

#!/usr/bin/env python3
"""O0 spike: one task -> worktree -> `hx -p ... --mode json` -> gate -> JSONL telemetry. Throwaway; Rust rewrite is O1.
usage: orch.py TASK.md --repo DIR [--hx CMD] [--gate CMD] [--timeout SECS] [--telemetry FILE]
Result: done | gate-failed | hx-failed | timeout. Exit code 0 only for done.
"""
import argparse, json, pathlib, shlex, subprocess, sys, time
def git(cwd, *a):
return subprocess.run(["git", "-c", "user.name=orch", "-c", "user.email=orch@localhost", *a],
cwd=cwd, capture_output=True, text=True, check=True).stdout
def read_task(p):
lines = pathlib.Path(p).read_text().splitlines()
title = next((l.lstrip("# ").strip() for l in lines if l.startswith("#")), pathlib.Path(p).stem)
body = "\n".join(l for l in lines if not l.startswith("#")).strip() or title
return title, body
def run_hx(hx, body, cwd, timeout):
"""Returns (result, done_event, rc, events). result is None when hx finished normally."""
try:
p = subprocess.run([*shlex.split(hx), "-p", body, "--mode", "json"], cwd=cwd,
capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired: # subprocess.run kills the child
return "timeout", None, None, 0
events = []
for l in p.stdout.splitlines():
try:
events.append(json.loads(l))
except ValueError:
pass # ponytail: non-JSON stdout lines are dropped; keep them in a log from O1 on
done = next((e for e in reversed(events) if e.get("type") == "done"), None)
if p.returncode != 0 or done is None or done.get("error"):
return "hx-failed", done, p.returncode, len(events)
return None, done, p.returncode, len(events)
def main(argv=None):
a = argparse.ArgumentParser()
a.add_argument("task")
a.add_argument("--repo", required=True)
a.add_argument("--hx", default="hx")
a.add_argument("--gate", default="sh tests/all.sh")
a.add_argument("--timeout", type=float, default=1800)
a.add_argument("--telemetry", default="telemetry.jsonl")
a = a.parse_args(argv)
repo = pathlib.Path(a.repo).resolve()
tid = pathlib.Path(a.task).stem
title, body = read_task(a.task)
branch, wt = f"orch/{tid}", repo.parent / ".orch" / tid
git(repo, "worktree", "add", "-b", branch, str(wt), "HEAD")
t0 = time.time()
result, done, hx_rc, n_events = run_hx(a.hx, body, wt, a.timeout)
gate_rc = None
if git(wt, "status", "--porcelain"): # keep hx's work on the branch even if the gate fails
git(wt, "add", "-A")
git(wt, "commit", "-qm", f"orch: {title}")
if result is None:
gate_rc = subprocess.run(a.gate, shell=True, cwd=wt).returncode
result = "done" if gate_rc == 0 else "gate-failed"
rec = {"task": tid, "title": title, "branch": branch, "result": result, "hx_exit": hx_rc,
"gate_exit": gate_rc, "events": n_events, "usage": (done or {}).get("usage"),
"session": (done or {}).get("session"), "seconds": round(time.time() - t0, 2)}
with open(a.telemetry, "a") as f:
f.write(json.dumps(rec) + "\n")
print(json.dumps(rec))
return 0 if result == "done" else 1
if __name__ == "__main__":
sys.exit(main())