#!/usr/bin/env python3 """End-to-end test for the orch binary with a fake hx. Run: python3 tests/e2e.py [path/to/orch]""" import json, os, pathlib, signal, 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()) env = {**os.environ, "ORCH_CONFIG_DIR": str(tmp / "cfg"), "ORCH_STATE_DIR": str(tmp / "state")} repo = tmp / "repo" repo.mkdir() subprocess.run(["git", "init", "-q", "-b", "main"], cwd=repo, check=True) subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "i"], cwd=repo, check=True) (tmp / "cfg/profiles").mkdir(parents=True) fake = tmp / "fake_hx.py" fake.write_text(''' import json, sys, time, os body = sys.argv[sys.argv.index("-p") + 1] e = lambda o: print(json.dumps(o), flush=True) e({"type": "session_start"}) if "NOJSON" in body: sys.exit(1) if "HANG" in body: open(os.environ.get("PIDFILE", "/dev/null"), "w").write(str(os.getpid())) time.sleep(300) for i in range(int(body.split("TURNS=")[1].split()[0]) if "TURNS=" in body else 1): e({"type": "turn_start"}) e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50}}}) if "WRITE" in body: open("out.txt", "w").write("x") if "--session" in sys.argv: open("retry-prompt.txt", "w").write(body) if "RETRYFIX" in os.environ.get("MODE", "RETRYFIX"): open("out.txt", "w").write("x") e({"type": "done", "error": "boom" if "FAIL" in body else None, "usage": {"input_tokens": 100, "output_tokens": 50}, "session": "/s.jsonl"}) ''') def profile(name, extra=""): (tmp / f"cfg/profiles/{name}.toml").write_text(f'hx = "{sys.executable} {fake}"\n{extra}') def task(name, body): f = tmp / f"{name}.md" f.write_text(f"# Title {name}\n{body}\n") return f def run(name, profile_name="p", **kw): return subprocess.run([orch, "run", str(task(name, kw.pop("body"))), "--repo", str(repo), "--profile", profile_name], env={**env, **kw.pop("env", {})}, capture_output=True, text=True, timeout=60) def status(id): return json.loads(subprocess.run([orch, "status", id], env=env, capture_output=True, text=True).stdout) def check(p, st, reason=None): id = p.stdout.split()[0] s = status(id) assert s["status"] == st and (reason is None or (s["reason"] or "").startswith(reason)), (p.stdout, p.stderr, s) return s profile("p", 'gate = "test -f out.txt || { echo MARKER-GATE-OUT; exit 3; }"\n') s = check(run("ok", body="WRITE"), "done") assert s["gate_exit"] == 0 and s["input_tokens"] == 100 and s["session"] == "/s.jsonl", s assert "out.txt" in subprocess.run(["git", "ls-tree", "--name-only", s["branch"]], cwd=repo, capture_output=True, text=True).stdout s = check(run("nowrite", body="NEVERFIX", env={"MODE": "NEVER"}), "needs-human", "gate-failed") assert s["attempts"] == 3 and s["gate_exit"] != 0, s # 1 + 2 retries assert "MARKER-GATE-OUT" in (tmp / "state/runs" / (s["id"] + ".gate.log")).read_text() profile("r", 'gate = "test -f out.txt || { echo MARKER-GATE-OUT; exit 3; }"\nmax_retries = 1\n') s = check(run("fixes", "r", body="x"), "done") assert s["attempts"] == 2 and s["gate_exit"] == 0 and s["reason"] is None, s sent = subprocess.run(["git", "show", s["branch"] + ":retry-prompt.txt"], cwd=repo, capture_output=True, text=True).stdout assert "MARKER-GATE-OUT" in sent and "exit 3" in sent, sent # failure log reached hx on the resumed session profile("z", 'gate = "false"\nmax_retries = 0\n') s = check(run("noretry", "z", body="x"), "needs-human") assert s["attempts"] == 1, s profile("b", 'gate = "false"\nmax_retries = 2\n[budget]\nmax_turns = 2\n') s = check(run("budget-across", "b", body="x"), "failed", "budget:turns") # budget spans attempts assert (s["attempts"], s["turns"]) == (3, 3), s # 1 turn per attempt; 3rd turn exceeds 2 check(run("hxerr", body="FAIL WRITE"), "failed", "hx-failed: boom") check(run("nojson", body="NOJSON"), "failed", "hx-failed") profile("t", "[budget]\nwall_secs = 1\n") check(run("slow", "t", body="HANG"), "failed", "timeout") profile("m", "[budget]\nmax_turns = 2\n") check(run("turns", "m", body="TURNS=5"), "failed", "budget:turns") profile("k", "[budget]\nmax_tokens = 200\n") check(run("tokens", "k", body="TURNS=5"), "failed", "budget:tokens") # yolo without sandbox is refused at load time profile("y", "yolo = true\n") assert run("yolo", "y", body="x").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"], env={**env, "PIDFILE": str(pidfile)}, stdout=subprocess.PIPE, text=True) for _ in range(100): if pidfile.exists() and pidfile.read_text(): break time.sleep(0.1) hx_pid = int(pidfile.read_text()) p.send_signal(signal.SIGKILL) p.wait() time.sleep(0.2) out = subprocess.run([orch, "status"], env=env, capture_output=True, text=True).stdout line = next(l for l in out.splitlines() if l.startswith("killed-")) assert "failed" in line and "[interrupted]" in line, out time.sleep(0.5) try: os.kill(hx_pid, 0) raise AssertionError("orphan hx still alive") except ProcessLookupError: pass logs = subprocess.run([orch, "logs", s["id"]], env=env, capture_output=True, text=True).stdout assert '"type": "done"' in logs or '"type":"done"' in logs, logs print("e2e ok")