From 015561530a5950bbadc7e5b7f6935853387715d2 Mon Sep 17 00:00:00 2001 From: hermes Date: Fri, 13 Nov 2026 00:19:45 +0000 Subject: [PATCH] O6: telemetry, orch report, orch eval, orch bench and eval cases (closes #7) --- README.md | 50 ++- eval/README.md | 13 + eval/add-function/files/test_text.py | 8 + eval/add-function/files/text.py | 2 + eval/add-function/gate.sh | 1 + eval/add-function/solution/text.py | 9 + eval/add-function/task.md | 3 + eval/fix-off-by-one/files/lib.py | 2 + eval/fix-off-by-one/files/test_lib.py | 6 + eval/fix-off-by-one/gate.sh | 1 + eval/fix-off-by-one/solution/lib.py | 2 + eval/fix-off-by-one/task.md | 3 + eval/fix-typo-readme/files/README.md | 3 + eval/fix-typo-readme/gate.sh | 1 + eval/fix-typo-readme/solution/README.md | 3 + eval/fix-typo-readme/task.md | 3 + eval/rename-symbol/files/cart.py | 5 + eval/rename-symbol/files/pricing.py | 2 + eval/rename-symbol/files/test_cart.py | 4 + eval/rename-symbol/gate.sh | 1 + eval/rename-symbol/solution/cart.py | 5 + eval/rename-symbol/solution/pricing.py | 2 + eval/rename-symbol/task.md | 3 + src/main.rs | 142 ++++++- src/report.rs | 471 ++++++++++++++++++++++++ src/run.rs | 1 + src/state.rs | 4 + tests/all.sh | 1 + tests/e2e.py | 48 +++ tests/fake_hx.py | 9 + tests/real_hx.py | 4 + 31 files changed, 809 insertions(+), 3 deletions(-) create mode 100644 eval/README.md create mode 100644 eval/add-function/files/test_text.py create mode 100644 eval/add-function/files/text.py create mode 100644 eval/add-function/gate.sh create mode 100644 eval/add-function/solution/text.py create mode 100644 eval/add-function/task.md create mode 100644 eval/fix-off-by-one/files/lib.py create mode 100644 eval/fix-off-by-one/files/test_lib.py create mode 100644 eval/fix-off-by-one/gate.sh create mode 100644 eval/fix-off-by-one/solution/lib.py create mode 100644 eval/fix-off-by-one/task.md create mode 100644 eval/fix-typo-readme/files/README.md create mode 100644 eval/fix-typo-readme/gate.sh create mode 100644 eval/fix-typo-readme/solution/README.md create mode 100644 eval/fix-typo-readme/task.md create mode 100644 eval/rename-symbol/files/cart.py create mode 100644 eval/rename-symbol/files/pricing.py create mode 100644 eval/rename-symbol/files/test_cart.py create mode 100644 eval/rename-symbol/gate.sh create mode 100644 eval/rename-symbol/solution/cart.py create mode 100644 eval/rename-symbol/solution/pricing.py create mode 100644 eval/rename-symbol/task.md create mode 100644 src/report.rs diff --git a/README.md b/README.md index d478935..bb3edbd 100644 --- a/README.md +++ b/README.md @@ -1 +1,49 @@ -TODO: add text \ No newline at end of file +# orch + +Runs many [hx](https://git.jokresner.de/johannes/hx) coding agents on tasks, one git worktree each. Not tied to a +git host: tasks come from a folder or any JSON command, results go to a local branch or any JSON command. + + orch run TASK.md --repo DIR --profile NAME one task + orch pull --profile NAME [--limit N] everything the profile's source lists, `workers` at a time + orch status [ID] orch logs ID runs and their raw logs + orch report [FILE] success rate, tokens, retries, duration per profile and hx version + orch bench eval --profile NAME --out A.jsonl run the eval cases; then: orch eval A.jsonl B.jsonl + orch audit [ID] every allowed/denied tool call + +## How a run goes + +queued, running (hx `-p --mode json`), gating (profile gate), retry with the gate output on the same session, then +done, failed, needs-human (gate still red, or the agent wanted something the allowlist forbids) or requeued +(provider quota used up, the account is paused until its window resets). The work always stays on branch +`orch/ID`. Every finished run appends one line to `/telemetry.jsonl`. + +## Profile (`~/.config/orch/profiles/NAME.toml`) + +```toml +hx = "hx" # command +home = "/work/hxhome" # own HOME => own hx login +provider = "claude" +gate = "sh tests/all.sh" # exit 0 = pass +max_retries = 2 +workers = 2 +account = "work-claude" # profiles on one login share quota pause and max_concurrent +allow = ["read", "write", "edit", "bash:cargo *"] +[budget] +wall_secs = 1800 # per attempt +max_turns = 40 # whole run +max_tokens = 400000 +[source] # dir | cmd +kind = "dir" +path = "/work/tasks" +[sink] # local-branch | cmd +kind = "cmd" +command = "python3 /work/adapters/gitea.py" +``` + +## More + +- [docs/cmd-protocol.md](docs/cmd-protocol.md): task sources and result sinks as external commands (+ JSON schema) +- [docs/safety.md](docs/safety.md): allowlist, credential separation, audit log +- [eval/README.md](eval/README.md): the regression case set +- `sh tests/all.sh`: the full local gate +- `spike/` is the throwaway Python O0 spike, kept for reference diff --git a/eval/README.md b/eval/README.md new file mode 100644 index 0000000..41db8b4 --- /dev/null +++ b/eval/README.md @@ -0,0 +1,13 @@ +# Eval cases + +Each directory is one case for `orch bench`: + +- `task.md` - the prompt (first `#` heading = title) +- `files/` - the initial repository content (a fresh git repo per run) +- `gate.sh` - exit 0 = solved; runs in the worktree after hx +- `solution/` - optional overlay that solves the case; only used by `orch bench eval --check`, never shown to the agent + + orch bench eval --check # every case fails untouched and passes with its solution + orch bench eval --profile NAME --out a.jsonl # run all cases with a profile + orch eval a.jsonl b.jsonl # compare two runs per case, exit 1 on a lower success rate + orch report a.jsonl # per profile and hx version diff --git a/eval/add-function/files/test_text.py b/eval/add-function/files/test_text.py new file mode 100644 index 0000000..283d19b --- /dev/null +++ b/eval/add-function/files/test_text.py @@ -0,0 +1,8 @@ +from text import slugify, shout + +assert slugify('Hello, World!') == 'hello-world' +assert slugify(' a b ') == 'a-b' +assert slugify('---') == '' +assert slugify('x1_y2') == 'x1-y2' +assert shout('a') == 'A!' +print('ok') diff --git a/eval/add-function/files/text.py b/eval/add-function/files/text.py new file mode 100644 index 0000000..846d738 --- /dev/null +++ b/eval/add-function/files/text.py @@ -0,0 +1,2 @@ +def shout(s): + return s.upper() + '!' diff --git a/eval/add-function/gate.sh b/eval/add-function/gate.sh new file mode 100644 index 0000000..da84b95 --- /dev/null +++ b/eval/add-function/gate.sh @@ -0,0 +1 @@ +python3 test_text.py diff --git a/eval/add-function/solution/text.py b/eval/add-function/solution/text.py new file mode 100644 index 0000000..03176cc --- /dev/null +++ b/eval/add-function/solution/text.py @@ -0,0 +1,9 @@ +import re + + +def shout(s): + return s.upper() + '!' + + +def slugify(s): + return re.sub(r'[^a-z0-9]+', '-', s.lower()).strip('-') diff --git a/eval/add-function/task.md b/eval/add-function/task.md new file mode 100644 index 0000000..547313f --- /dev/null +++ b/eval/add-function/task.md @@ -0,0 +1,3 @@ +# Add slugify + +Add a function `slugify(s)` to `text.py`: lowercase, every run of non-alphanumeric characters becomes a single `-`, no leading or trailing `-`. Example: `slugify('Hello, World!')` is `'hello-world'`. diff --git a/eval/fix-off-by-one/files/lib.py b/eval/fix-off-by-one/files/lib.py new file mode 100644 index 0000000..006c4cf --- /dev/null +++ b/eval/fix-off-by-one/files/lib.py @@ -0,0 +1,2 @@ +def last_n(xs, n): + return xs[len(xs) - n + 1:] diff --git a/eval/fix-off-by-one/files/test_lib.py b/eval/fix-off-by-one/files/test_lib.py new file mode 100644 index 0000000..5dd7b3d --- /dev/null +++ b/eval/fix-off-by-one/files/test_lib.py @@ -0,0 +1,6 @@ +from lib import last_n + +assert last_n([1, 2, 3, 4], 2) == [3, 4] +assert last_n([1, 2, 3], 3) == [1, 2, 3] +assert last_n([1], 1) == [1] +print('ok') diff --git a/eval/fix-off-by-one/gate.sh b/eval/fix-off-by-one/gate.sh new file mode 100644 index 0000000..305d64d --- /dev/null +++ b/eval/fix-off-by-one/gate.sh @@ -0,0 +1 @@ +python3 test_lib.py diff --git a/eval/fix-off-by-one/solution/lib.py b/eval/fix-off-by-one/solution/lib.py new file mode 100644 index 0000000..cce6e2d --- /dev/null +++ b/eval/fix-off-by-one/solution/lib.py @@ -0,0 +1,2 @@ +def last_n(xs, n): + return xs[len(xs) - n:] diff --git a/eval/fix-off-by-one/task.md b/eval/fix-off-by-one/task.md new file mode 100644 index 0000000..668b9d9 --- /dev/null +++ b/eval/fix-off-by-one/task.md @@ -0,0 +1,3 @@ +# Fix the off-by-one in last_n + +`last_n(xs, n)` in `lib.py` must return the last n items of the list, but it returns one too few. Fix it. Do not change the tests. diff --git a/eval/fix-typo-readme/files/README.md b/eval/fix-typo-readme/files/README.md new file mode 100644 index 0000000..00d914d --- /dev/null +++ b/eval/fix-typo-readme/files/README.md @@ -0,0 +1,3 @@ +# demo + +Instal with pip install demo. diff --git a/eval/fix-typo-readme/gate.sh b/eval/fix-typo-readme/gate.sh new file mode 100644 index 0000000..f31aa32 --- /dev/null +++ b/eval/fix-typo-readme/gate.sh @@ -0,0 +1 @@ +grep -q 'Install with pip install demo.' README.md && ! grep -q 'Instal ' README.md && [ "$(wc -l < README.md)" -eq 3 ] diff --git a/eval/fix-typo-readme/solution/README.md b/eval/fix-typo-readme/solution/README.md new file mode 100644 index 0000000..95f5bb4 --- /dev/null +++ b/eval/fix-typo-readme/solution/README.md @@ -0,0 +1,3 @@ +# demo + +Install with pip install demo. diff --git a/eval/fix-typo-readme/task.md b/eval/fix-typo-readme/task.md new file mode 100644 index 0000000..d2456d4 --- /dev/null +++ b/eval/fix-typo-readme/task.md @@ -0,0 +1,3 @@ +# Fix the typo in README + +The README says `Instal with pip`. Fix the spelling of that word and nothing else. diff --git a/eval/rename-symbol/files/cart.py b/eval/rename-symbol/files/cart.py new file mode 100644 index 0000000..185afab --- /dev/null +++ b/eval/rename-symbol/files/cart.py @@ -0,0 +1,5 @@ +from pricing import compute + + +def checkout(items): + return round(compute(items) * 1.2, 2) diff --git a/eval/rename-symbol/files/pricing.py b/eval/rename-symbol/files/pricing.py new file mode 100644 index 0000000..cd0286a --- /dev/null +++ b/eval/rename-symbol/files/pricing.py @@ -0,0 +1,2 @@ +def compute(items): + return sum(i['price'] * i['qty'] for i in items) diff --git a/eval/rename-symbol/files/test_cart.py b/eval/rename-symbol/files/test_cart.py new file mode 100644 index 0000000..a4e7bf4 --- /dev/null +++ b/eval/rename-symbol/files/test_cart.py @@ -0,0 +1,4 @@ +from cart import checkout + +assert checkout([{'price': 10, 'qty': 2}]) == 24.0 +print('ok') diff --git a/eval/rename-symbol/gate.sh b/eval/rename-symbol/gate.sh new file mode 100644 index 0000000..fce5f02 --- /dev/null +++ b/eval/rename-symbol/gate.sh @@ -0,0 +1 @@ +! grep -rq 'compute' --include=*.py . && grep -q 'def total_price' pricing.py && python3 test_cart.py diff --git a/eval/rename-symbol/solution/cart.py b/eval/rename-symbol/solution/cart.py new file mode 100644 index 0000000..91f0597 --- /dev/null +++ b/eval/rename-symbol/solution/cart.py @@ -0,0 +1,5 @@ +from pricing import total_price + + +def checkout(items): + return round(total_price(items) * 1.2, 2) diff --git a/eval/rename-symbol/solution/pricing.py b/eval/rename-symbol/solution/pricing.py new file mode 100644 index 0000000..e54b364 --- /dev/null +++ b/eval/rename-symbol/solution/pricing.py @@ -0,0 +1,2 @@ +def total_price(items): + return sum(i['price'] * i['qty'] for i in items) diff --git a/eval/rename-symbol/task.md b/eval/rename-symbol/task.md new file mode 100644 index 0000000..cd53f11 --- /dev/null +++ b/eval/rename-symbol/task.md @@ -0,0 +1,3 @@ +# Rename compute to total_price + +Rename the function `compute` to `total_price` everywhere (definition and all callers, in every file). Behaviour must not change. diff --git a/src/main.rs b/src/main.rs index 3ec14e5..416acf4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,6 +2,7 @@ mod adapter; mod lock; mod policy; mod profile; +mod report; mod run; mod state; @@ -37,6 +38,30 @@ enum Cmd { #[arg(long)] limit: Option, }, + /// Success rate, tokens, retries and duration per profile and hx version, from the telemetry log. + Report { + /// Telemetry file (default: /telemetry.jsonl). + file: Option, + }, + /// Compare two telemetry files per case; exit 1 when B's success rate is below A's. + Eval { a: PathBuf, b: PathBuf }, + /// Run the eval cases in DIR (task.md, files/, gate.sh each) through a profile; writes telemetry to --out. + Bench { + dir: PathBuf, + #[arg(long, default_value = "default")] + profile: String, + #[arg(long)] + out: Option, + /// Runs per case. + #[arg(long, default_value_t = 1)] + repeat: u32, + /// Only this case. + #[arg(long)] + case: Option, + /// No hx: check that every case fails untouched and passes with its solution/ overlay. + #[arg(long)] + check: bool, + }, /// hx extension that enforces a run's tool allowlist (started by hx, not by hand). #[command(hide = true)] Guard { policy: PathBuf }, @@ -82,7 +107,7 @@ fn main() -> Result { let p = profile::Profile::load(&profile)?; 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)?; + let r = process(&t, &repo, &profile, &p, None, &report::default_path())?; Ok(code(r.status == state::Status::Done)) } Cmd::Pull { profile, limit } => { @@ -125,7 +150,14 @@ fn main() -> Result { if !src.claim(&t)? { continue; } - let r = process(&t, &repo, &profile, &p, Some(src.as_ref()))?; + let r = process( + &t, + &repo, + &profile, + &p, + Some(src.as_ref()), + &report::default_path(), + )?; if r.status != state::Status::Done && r.status != state::Status::Requeued { @@ -142,6 +174,31 @@ fn main() -> Result { }); Ok(code(ok.load(Ordering::SeqCst))) } + Cmd::Report { file } => { + print!( + "{}", + report::report(&report::load(&file.unwrap_or_else(report::default_path))?) + ); + Ok(0.into()) + } + Cmd::Eval { a, b } => { + let (text, regressed) = report::compare( + &report::load(&a)?, + &report::load(&b)?, + &a.to_string_lossy(), + &b.to_string_lossy(), + ); + print!("{text}"); + Ok(code(!regressed)) + } + Cmd::Bench { + dir, + profile, + out, + repeat, + case, + check, + } => bench(&dir, &profile, out, repeat, case.as_deref(), check), Cmd::Guard { policy } => { policy::guard(&policy)?; Ok(0.into()) @@ -195,6 +252,7 @@ fn process( profile: &str, p: &profile::Profile, src: Option<&dyn adapter::Source>, + telemetry: &Path, ) -> Result { let mut r = run::new_run(t, repo, profile)?; if p.allow.is_none() && !p.sandbox { @@ -213,6 +271,10 @@ fn process( "run_end", serde_json::json!({"status": r.status, "reason": r.reason, "attempts": r.attempts}), ); + // a telemetry failure must not lose the run + if let Err(e) = report::append(telemetry, &report::rec(&r, &report::hx_version(p))) { + eprintln!("{}: telemetry: {e:#}", r.id); + } 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, @@ -243,3 +305,79 @@ fn process( ); Ok(r) } + +/// `orch bench`: every case gets a fresh git repo of its files and its own gate (`gate.sh`); the profile decides +/// everything else (hx, allowlist, retries, budget). Sink and source are ignored: nothing is published. +fn bench( + dir: &Path, + profile: &str, + out: Option, + repeat: u32, + only: Option<&str>, + check: bool, +) -> Result { + let mut cases = report::cases(dir)?; + if let Some(o) = only { + cases.retain(|c| c.name == o); + anyhow::ensure!(!cases.is_empty(), "no case named {o:?}"); + } + if check { + return bench_check(&cases); + } + let mut p = profile::Profile::load(profile)?; + (p.source, p.sink) = (None, None); + let out = out.unwrap_or_else(|| state_dir().join("bench.jsonl")); + let mut ok = true; + for c in &cases { + for _ in 0..repeat { + let repo = report::fixture(c)?; + let gate = c.dir.join("gate.sh").canonicalize()?; + p.gate = Some(format!("sh {}", gate.display())); + let t = + adapter::parse_task_md(&c.name, &std::fs::read_to_string(c.dir.join("task.md"))?); + ok &= process(&t, &repo, profile, &p, None, &out)?.status == state::Status::Done; + } + } + println!("telemetry: {}", out.display()); + Ok(code(ok)) +} + +/// Case-set sanity without an agent: the gate must fail on the untouched files and pass after `solution/`. +fn bench_check(cases: &[report::Case]) -> Result { + let gate = |dir: &Path, g: &Path| -> Result { + Ok(std::process::Command::new("sh") + .arg(g) + .current_dir(dir) + .output()? + .status + .success()) + }; + let mut ok = true; + for c in cases { + let g = c.dir.join("gate.sh").canonicalize()?; + let repo = report::fixture(c)?; + let before = gate(&repo, &g)?; + let sol = c.dir.join("solution"); + let after = if sol.is_dir() { + std::process::Command::new("cp") + .arg("-R") + .arg(format!("{}/.", sol.display())) + .arg(&repo) + .status()?; + Some(gate(&repo, &g)?) + } else { + None + }; + let good = !before && after != Some(false); + let solved = match after { + None => "no solution/", + Some(true) => "pass", + Some(false) => "FAIL (bad)", + }; + let untouched = if before { "PASS (bad)" } else { "fail" }; + let flag = if good { "" } else { " <-- broken case" }; + println!("{:<20} untouched={untouched} solved={solved}{flag}", c.name); + ok &= good; + } + Ok(code(ok)) +} diff --git a/src/report.rs b/src/report.rs new file mode 100644 index 0000000..8f56c31 --- /dev/null +++ b/src/report.rs @@ -0,0 +1,471 @@ +//! Telemetry (one JSONL line per finished run), `orch report`, `orch eval A B` and the `orch bench` case runner. + +use crate::profile::Profile; +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::io::Write; +use std::path::{Path, PathBuf}; + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +pub struct Rec { + pub ts: u64, + pub run: String, + /// Task id (eval: case name). + pub task: String, + pub profile: String, + pub hx_version: String, + /// done | failed | needs-human | requeued + pub status: String, + pub reason: Option, + pub attempts: u32, + pub turns: u64, + pub input_tokens: u64, + pub output_tokens: u64, + pub seconds: u64, +} + +impl Rec { + pub fn tokens(&self) -> u64 { + self.input_tokens + self.output_tokens + } +} + +pub fn default_path() -> PathBuf { + crate::state_dir().join("telemetry.jsonl") +} + +pub fn rec(r: &crate::state::Run, hx_version: &str) -> Rec { + let mut reason = r.reason.clone(); + if let Some(s) = &mut reason { + *s = s.chars().take(200).collect(); // keep every line far below PIPE_BUF: appends stay atomic + } + Rec { + ts: crate::state::now(), + run: r.id.clone(), + task: r.task.clone(), + profile: r.profile.clone(), + hx_version: hx_version.into(), + status: serde_json::to_value(r.status) + .ok() + .and_then(|v| v.as_str().map(String::from)) + .unwrap_or_default(), + reason, + attempts: r.attempts, + turns: r.turns, + input_tokens: r.input_tokens, + output_tokens: r.output_tokens, + seconds: r + .ended + .unwrap_or_else(crate::state::now) + .saturating_sub(r.started), + } +} + +pub fn append(path: &Path, r: &Rec) -> Result<()> { + if let Some(d) = path.parent() { + std::fs::create_dir_all(d)?; + } + // leading newline: a line cut short by a crash must not swallow this record (load skips blank lines) + let mut line = format!("\n{}", serde_json::to_string(r)?); + line.push('\n'); + std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path)? + .write_all(line.as_bytes())?; + Ok(()) +} + +/// Unparseable lines are skipped and counted on stderr (a half-written line must not kill the report). +pub fn load(path: &Path) -> Result> { + let s = + std::fs::read_to_string(path).with_context(|| format!("telemetry {}", path.display()))?; + let (mut v, mut bad) = (vec![], 0); + for l in s.lines().filter(|l| !l.trim().is_empty()) { + match serde_json::from_str(l) { + Ok(r) => v.push(r), + Err(_) => bad += 1, + } + } + if bad > 0 { + eprintln!("{}: skipped {bad} unreadable line(s)", path.display()); + } + Ok(v) +} + +/// `hx --version` with the same cleared environment hx runs with. "unknown" when it cannot be told. +/// ponytail: no timeout; clap's --version returns at once. Add one if a wrapper script ever hangs here. +pub fn hx_version(p: &Profile) -> String { + let mut parts = p.hx.split_whitespace(); + let Some(bin) = parts.next() else { + return "unknown".into(); + }; + let mut cmd = std::process::Command::new(bin); + cmd.args(parts) + .arg("--version") + .env_clear() + .envs(crate::run::hx_env(std::env::vars(), p)); + if let Some(h) = &p.home { + cmd.env("HOME", h); + } + cmd.stdin(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()); + match cmd.output() { + Ok(o) if o.status.success() => { + let s = String::from_utf8_lossy(&o.stdout).trim().to_string(); + if s.is_empty() { "unknown".into() } else { s } + } + _ => "unknown".into(), + } +} + +// ---- aggregation ----------------------------------------------------------------------------- + +#[derive(Default, Debug, PartialEq)] +pub struct Agg { + pub runs: u64, + pub done: u64, + pub needs_human: u64, + pub failed: u64, + pub requeued: u64, + pub retries: u64, + pub tokens: u64, + pub tokens_done: u64, + pub secs: Vec, +} + +impl Agg { + pub fn add(&mut self, r: &Rec) { + self.runs += 1; + match r.status.as_str() { + "done" => { + self.done += 1; + self.tokens_done += r.tokens(); + } + "needs-human" => self.needs_human += 1, + "requeued" => { + self.requeued += 1; + return; // never attempted to completion: no quality or cost signal + } + _ => self.failed += 1, + } + self.retries += u64::from(r.attempts.saturating_sub(1)); + self.tokens += r.tokens(); + self.secs.push(r.seconds); + } + pub fn finished(&self) -> u64 { + self.runs - self.requeued + } + pub fn rate(&self) -> Option { + (self.finished() > 0).then(|| self.done as f64 * 100.0 / self.finished() as f64) + } + pub fn tok_per_run(&self) -> Option { + (self.finished() > 0).then(|| self.tokens / self.finished()) + } + pub fn tok_per_done(&self) -> Option { + (self.done > 0).then(|| self.tokens_done / self.done) + } + pub fn median_secs(&self) -> Option { + let mut s = self.secs.clone(); + s.sort_unstable(); + (!s.is_empty()).then(|| s[s.len() / 2]) + } +} + +fn group<'a, K: Ord>(recs: &'a [Rec], key: impl Fn(&'a Rec) -> K) -> BTreeMap { + let mut m: BTreeMap = BTreeMap::new(); + for r in recs { + m.entry(key(r)).or_default().add(r); + } + m +} + +fn n(v: Option) -> String { + v.map_or("-".into(), |v| v.to_string()) +} + +fn pct(v: Option) -> String { + v.map_or("-".into(), |v| format!("{v:.0}%")) +} + +pub fn report(recs: &[Rec]) -> String { + let mut out = format!( + "{:<14} {:<22} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6}\n", + "profile", + "hx-version", + "runs", + "done", + "rate", + "human", + "failed", + "requeue", + "tok/run", + "tok/done", + "med-s" + ); + let mut line = |a: &str, b: &str, g: &Agg| { + out.push_str(&format!( + "{:<14} {:<22} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6}\n", + a, + b, + g.runs, + g.done, + pct(g.rate()), + g.needs_human, + g.failed, + g.requeued, + n(g.tok_per_run()), + n(g.tok_per_done()), + n(g.median_secs()) + )); + }; + for ((p, v), g) in group(recs, |r| (r.profile.clone(), r.hx_version.clone())) { + line(&p, &v, &g); + } + let mut all = Agg::default(); + recs.iter().for_each(|r| all.add(r)); + line("all", "", &all); + out.push_str(&format!( + "retries (extra hx attempts after a red gate): {}\n", + all.retries + )); + out +} + +/// Per case: done/finished and tokens per run, A vs B, plus a verdict. Returns (text, regressed). +pub fn compare(a: &[Rec], b: &[Rec], a_name: &str, b_name: &str) -> (String, bool) { + let (ga, gb) = (group(a, |r| r.task.clone()), group(b, |r| r.task.clone())); + let mut cases: Vec<&String> = ga.keys().chain(gb.keys()).collect(); + cases.sort(); + cases.dedup(); + let cell = |g: Option<&Agg>| match g { + Some(g) if g.finished() > 0 => format!("{}/{}", g.done, g.finished()), + _ => "-".into(), + }; + let delta = |x: Option, y: Option| match (x, y) { + (Some(x), Some(y)) if x > 0 => format!("{:+.0}%", (y as f64 - x as f64) * 100.0 / x as f64), + _ => "-".into(), + }; + let mut out = format!("A = {a_name}\nB = {b_name}\n\n"); + out.push_str(&format!( + "{:<24} {:>7} {:>7} {:>9} {:>9} {:>7}\n", + "case", "A done", "B done", "A tok/run", "B tok/run", "tokens" + )); + for c in cases { + let (x, y) = (ga.get(c), gb.get(c)); + let (tx, ty) = (x.and_then(Agg::tok_per_run), y.and_then(Agg::tok_per_run)); + out.push_str(&format!( + "{:<24} {:>7} {:>7} {:>9} {:>9} {:>7}\n", + c, + cell(x), + cell(y), + n(tx), + n(ty), + delta(tx, ty) + )); + } + let (mut ta, mut tb) = (Agg::default(), Agg::default()); + a.iter().for_each(|r| ta.add(r)); + b.iter().for_each(|r| tb.add(r)); + out.push_str(&format!( + "{:<24} {:>7} {:>7} {:>9} {:>9} {:>7}\n", + "total", + cell(Some(&ta)), + cell(Some(&tb)), + n(ta.tok_per_run()), + n(tb.tok_per_run()), + delta(ta.tok_per_run(), tb.tok_per_run()) + )); + let regressed = matches!((ta.rate(), tb.rate()), (Some(x), Some(y)) if y < x - 1e-9); + let diff = match (ta.rate(), tb.rate()) { + (Some(x), Some(y)) => format!("{:+.0} pp", y - x), + _ => "n/a".into(), + }; + out.push_str(&format!( + "\nsuccess rate A {} -> B {} ({diff}){}\n", + pct(ta.rate()), + pct(tb.rate()), + if regressed { " REGRESSION" } else { "" } + )); + (out, regressed) +} + +// ---- bench ----------------------------------------------------------------------------------- + +/// Case dir: `task.md`, `files/` (initial repo content), `gate.sh` (exit 0 = solved). Optional `solution/` overlay +/// (used by the case-set self-check, never shown to the agent). +pub struct Case { + pub name: String, + pub dir: PathBuf, +} + +pub fn cases(dir: &Path) -> Result> { + let mut v = vec![]; + for e in std::fs::read_dir(dir) + .with_context(|| format!("eval dir {}", dir.display()))? + .flatten() + { + let d = e.path(); + if d.join("task.md").is_file() { + for need in ["files", "gate.sh"] { + if !d.join(need).exists() { + bail!("case {} lacks {need}", d.display()); + } + } + v.push(Case { + name: e.file_name().to_string_lossy().into(), + dir: d, + }); + } + } + v.sort_by(|a, b| a.name.cmp(&b.name)); + if v.is_empty() { + bail!("no cases (dirs with task.md) in {}", dir.display()); + } + Ok(v) +} + +fn copy_tree(from: &Path, to: &Path) -> Result<()> { + std::fs::create_dir_all(to)?; + for e in std::fs::read_dir(from)?.flatten() { + let (src, dst) = (e.path(), to.join(e.file_name())); + if src.is_dir() { + copy_tree(&src, &dst)?; + } else { + std::fs::copy(&src, &dst)?; + } + } + Ok(()) +} + +/// Fresh git repo with the case's initial files, returns its path. +pub fn fixture(c: &Case) -> Result { + let repo = + crate::state_dir() + .join("bench") + .join(format!("{}-{}", c.name, crate::state::now_ms())); + copy_tree(&c.dir.join("files"), &repo)?; + for args in [ + vec!["init", "-q", "-b", "main"], + vec!["add", "-A"], + vec!["commit", "-qm", "case"], + ] { + let st = std::process::Command::new("git") + .args(["-c", "user.name=orch", "-c", "user.email=orch@localhost"]) + .args(&args) + .current_dir(&repo) + .status()?; + anyhow::ensure!( + st.success(), + "git {} failed in {}", + args.join(" "), + repo.display() + ); + } + Ok(repo) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn r(task: &str, status: &str, attempts: u32, tok: u64, secs: u64) -> Rec { + Rec { + ts: 1, + run: format!("{task}-1"), + task: task.into(), + profile: "p".into(), + hx_version: "v1".into(), + status: status.into(), + reason: None, + attempts, + turns: 1, + input_tokens: tok, + output_tokens: 0, + seconds: secs, + } + } + + #[test] + fn aggregation() { + let mut g = Agg::default(); + for x in [ + r("a", "done", 1, 100, 10), + r("b", "done", 3, 300, 30), + r("c", "needs-human", 3, 500, 20), + r("d", "failed", 1, 0, 1), + r("e", "requeued", 1, 999, 99), + ] { + g.add(&x); + } + assert_eq!((g.runs, g.finished(), g.done, g.retries), (5, 4, 2, 4)); + assert_eq!(g.rate(), Some(50.0)); + assert_eq!( + (g.tok_per_run(), g.tok_per_done(), g.median_secs()), + (Some(225), Some(200), Some(20)) + ); + assert_eq!(Agg::default().rate(), None); + } + + #[test] + fn report_groups_by_profile_and_version() { + let mut b = r("a", "done", 1, 100, 5); + b.hx_version = "v2".into(); + let t = report(&[r("a", "done", 1, 200, 5), r("b", "failed", 1, 0, 5), b]); + assert!( + t.contains("v1") && t.contains("v2") && t.contains("50%") && t.contains("100%"), + "{t}" + ); + assert!(t.lines().last().unwrap().starts_with("retries"), "{t}"); + } + + #[test] + fn compare_flags_regressions_only() { + let a = [r("x", "done", 1, 100, 1), r("y", "done", 1, 100, 1)]; + let b_bad = [r("x", "done", 1, 150, 1), r("y", "failed", 1, 80, 1)]; + let (t, reg) = compare(&a, &b_bad, "A", "B"); + assert!( + reg && t.contains("REGRESSION") && t.contains("-50 pp") && t.contains("+50%"), + "{t}" + ); + let (t, reg) = compare(&b_bad, &a, "A", "B"); + assert!(!reg && t.contains("+50 pp"), "{t}"); + // a case only in B shows up with "-" for A; requeued runs do not count + let (t, reg) = compare( + &a, + &[ + r("x", "done", 1, 100, 1), + r("z", "done", 1, 1, 1), + r("y", "requeued", 1, 0, 0), + ], + "A", + "B", + ); + assert!( + !reg && t.lines().any(|l| l.starts_with('z') && l.contains(" - ")), + "{t}" + ); + } + + #[test] + fn roundtrip_and_bad_lines() { + let d = std::env::temp_dir().join(format!("orch-tel-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + let p = d.join("t.jsonl"); + append(&p, &r("a", "done", 1, 1, 1)).unwrap(); + std::fs::OpenOptions::new() + .append(true) + .open(&p) + .unwrap() + .write_all(b"{half a li") + .unwrap(); + append(&p, &r("b", "done", 1, 1, 1)).unwrap(); + assert_eq!( + load(&p).unwrap().len(), + 2, + "garbage line skipped, neighbours kept" + ); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/src/run.rs b/src/run.rs index b58df99..6c51282 100644 --- a/src/run.rs +++ b/src/run.rs @@ -52,6 +52,7 @@ pub fn new_run(task: &Task, repo: &Path, profile: &str) -> Result { worktree: crate::state_dir().join("worktrees").join(&id), id, title: task.title.clone(), + task: task.id.clone(), profile: profile.into(), repo, status: Status::Queued, diff --git a/src/state.rs b/src/state.rs index cffd1c8..f6ab507 100644 --- a/src/state.rs +++ b/src/state.rs @@ -29,6 +29,9 @@ impl Status { pub struct Run { pub id: String, pub title: String, + /// Task id from the source (eval: case name). + #[serde(default)] + pub task: String, pub profile: String, pub repo: PathBuf, pub branch: String, @@ -151,6 +154,7 @@ mod tests { Run { id: id.into(), title: "t".into(), + task: "t".into(), profile: "p".into(), repo: "/r".into(), branch: "b".into(), diff --git a/tests/all.sh b/tests/all.sh index 895f19a..79098d6 100644 --- a/tests/all.sh +++ b/tests/all.sh @@ -8,5 +8,6 @@ cargo test -q cargo build -q python3 tests/e2e.py python3 spike/check.py +./target/debug/orch bench eval --check python3 tests/real_hx.py diff --git a/tests/e2e.py b/tests/e2e.py index e37b05c..c59bb79 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -268,6 +268,54 @@ assert len((tmp / "g-audit.log").read_text().splitlines()) == 4 # warning for unrestricted profiles assert "no `allow` list" in run("warn", "p", body="WRITE").stderr +# --- telemetry, report, eval, bench (O6) --- +tel = tmp / "state/telemetry.jsonl" +recs = [json.loads(l) for l in tel.read_text().splitlines() if l.strip()] +assert len(recs) >= 30, len(recs) +ok_rec = next(r for r in recs if r["task"] == "ok") +assert (ok_rec["status"], ok_rec["profile"], ok_rec["hx_version"], ok_rec["input_tokens"], ok_rec["attempts"]) == ("done", "p", "hx 9.9.9", 100, 1), ok_rec +assert next(r for r in recs if r["task"] == "nowrite")["status"] == "needs-human" +assert next(r for r in recs if r["task"] == "nowrite")["attempts"] == 3 +assert any(r["status"] == "requeued" for r in recs) +rep = subprocess.run([orch, "report"], env=env, capture_output=True, text=True).stdout +assert "hx 9.9.9" in rep and "profile" in rep and rep.splitlines()[-1].startswith("retries"), rep +allrow = next(l for l in rep.splitlines() if l.startswith("all")) +assert allrow.split()[1] == str(len([r for r in recs])), (allrow, len(recs)) +# a half-written line (crash) is skipped and does not hide the next record +with open(tel, "a") as f: + f.write('{"ts": 1, "run": "cut') +run("after-cut", "p", body="WRITE") +rep2 = subprocess.run([orch, "report"], env=env, capture_output=True, text=True) +assert "skipped 1 unreadable" in rep2.stderr and rep2.returncode == 0, rep2 +assert len(subprocess.run([orch, "report"], env=env, capture_output=True, text=True).stdout.splitlines()) == len(rep.splitlines()) # same table shape + +# bench: the shipped eval cases, with a fake hx that solves every case but one +ev = root / "eval" +chk = subprocess.run([orch, "bench", str(ev), "--check"], env=env, capture_output=True, text=True) +assert chk.returncode == 0 and chk.stdout.count("untouched=fail solved=pass") == 4, chk +profile("bb", f'env = ["SOLVE_DIR", "SOLVE_SKIP", "FAKE_VERSION"]\ngate = "false"\nmax_retries = 0\n') +a_out, b_out = tmp / "a.jsonl", tmp / "b.jsonl" +benv = {**env, "SOLVE_DIR": str(ev)} +pa = subprocess.run([orch, "bench", str(ev), "--profile", "bb", "--out", str(a_out), "--repeat", "2"], env={**benv, "FAKE_VERSION": "1.0"}, capture_output=True, text=True) +assert pa.returncode == 0, pa # every case solved; the profile gate ("false") is replaced by the case's gate.sh +pb = subprocess.run([orch, "bench", str(ev), "--profile", "bb", "--out", str(b_out)], env={**benv, "SOLVE_SKIP": "rename-symbol", "FAKE_VERSION": "2.0"}, capture_output=True, text=True) +assert pb.returncode == 1, pb # one case unsolved -> bench exit 1 +ra, rb = report_load = [[json.loads(l) for l in f.read_text().splitlines() if l.strip()] for f in (a_out, b_out)] +assert len(ra) == 8 and {r["hx_version"] for r in ra} == {"hx 1.0"} and {r["task"] for r in ra} == {"add-function", "fix-off-by-one", "fix-typo-readme", "rename-symbol"} +assert [r["status"] for r in rb if r["task"] == "rename-symbol"] == ["needs-human"] and len(rb) == 4 +ev_out = subprocess.run([orch, "eval", str(a_out), str(b_out)], env=env, capture_output=True, text=True) +assert ev_out.returncode == 1 and "REGRESSION" in ev_out.stdout and "-25 pp" in ev_out.stdout, ev_out +line = next(l for l in ev_out.stdout.splitlines() if l.startswith("rename-symbol")) +assert line.split()[1:3] == ["2/2", "0/1"], line +ev_ok = subprocess.run([orch, "eval", str(b_out), str(a_out)], env=env, capture_output=True, text=True) +assert ev_ok.returncode == 0 and "REGRESSION" not in ev_ok.stdout and "+25 pp" in ev_ok.stdout, ev_ok # B better than A: no failure +# a broken case set is caught by --check +broken = tmp / "broken" +shutil.copytree(ev, broken) +(broken / "add-function/solution/text.py").write_text("def slugify(s):\n return s\n") +bad = subprocess.run([orch, "bench", str(broken), "--check"], env=env, capture_output=True, text=True) +assert bad.returncode == 1 and "broken case" in bad.stdout, bad + # 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"], diff --git a/tests/fake_hx.py b/tests/fake_hx.py index 2e84f60..bdb1fb2 100644 --- a/tests/fake_hx.py +++ b/tests/fake_hx.py @@ -1,4 +1,7 @@ import json, sys, time, os +if "--version" in sys.argv: + print("hx " + os.environ.get("FAKE_VERSION", "9.9.9")) + sys.exit(0) body = sys.argv[sys.argv.index("-p") + 1] e = lambda o: print(json.dumps(o), flush=True) e({"type": "session_start"}) @@ -30,6 +33,12 @@ for n, l in enumerate(x for x in body.splitlines() if x.startswith("CALL ")): elif name == "write": open(arg, "w").write("x"); f.write("WROTE " + arg + "\n") else: f.write("RAN " + arg + "\n") e({"type": "tool_result", "id": f"c{n}", "name": name, "args": args, "content": "ok", "is_error": False}) +if os.environ.get("SOLVE_DIR"): + # eval cases: solve by overlaying the case's solution/ unless the task title is listed in SOLVE_SKIP + for c in (d for d in os.listdir(os.environ["SOLVE_DIR"]) if os.path.isfile(os.path.join(os.environ["SOLVE_DIR"], d, "task.md"))): + t = open(os.path.join(os.environ["SOLVE_DIR"], c, "task.md")).read().split("\n", 2)[2].strip() + if t == body.strip() and c not in os.environ.get("SOLVE_SKIP", "").split(","): + subprocess.run(["cp", "-R", os.path.join(os.environ["SOLVE_DIR"], c, "solution") + "/.", "."], check=True) if "ENVDUMP" in body: open("env.txt", "w").write("\n".join(sorted(os.environ))) if "NOJSON" in body: sys.exit(1) if "HANG" in body: diff --git a/tests/real_hx.py b/tests/real_hx.py index 3b2d950..364fa12 100644 --- a/tests/real_hx.py +++ b/tests/real_hx.py @@ -46,6 +46,10 @@ try: # hx itself saw the block from the guard extension (or orch killed it first; either way the file was not read) audit = subprocess.run([orch, "audit", rid], env=env, capture_output=True, text=True).stdout assert '"decision":"deny"' in audit.replace(" ", ""), audit + # telemetry carries the real `hx --version` + tel = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()] + ver = subprocess.run([str(hx), "--version"], capture_output=True, text=True).stdout.strip() + assert ver and tel[-1]["hx_version"] == ver and tel[-1]["status"] == "needs-human", (tel, ver) print("real hx e2e ok:", st["reason"], "| audit by:", sorted({json.loads(l)["detail"].get("by", "guard") for l in audit.splitlines() if "decision" in l})) finally: srv.terminate() -- 2.54.1