From 54b4e66425fce3eb621dbe808f56864d0c3fafb4 Mon Sep 17 00:00:00 2001 From: d41sys <57945677+d41sys@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:57:58 +0100 Subject: [PATCH] agentcore: add 12-scenario harness scorecard, oscillating doom-loop guard, and 16-task eval suite --- .gitignore | 2 + agentcore/src/turn.rs | 31 +- agentcore/tests/harness_eval.rs | 859 +++++++++++++++++++++++++++ evals/README.md | 68 +++ evals/analyze.py | 317 ++++++++++ evals/driver.py | 332 +++++++++++ evals/mock_mcp.py | 156 +++++ evals/run.py | 136 +++++ evals/tasks.py | 998 ++++++++++++++++++++++++++++++++ evals/test_evals.py | 211 +++++++ 10 files changed, 3107 insertions(+), 3 deletions(-) create mode 100644 agentcore/tests/harness_eval.rs create mode 100644 evals/README.md create mode 100644 evals/analyze.py create mode 100644 evals/driver.py create mode 100644 evals/mock_mcp.py create mode 100644 evals/run.py create mode 100644 evals/tasks.py create mode 100644 evals/test_evals.py diff --git a/.gitignore b/.gitignore index 1935461a..cd6481ac 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ window/gen/ window/permissions/autogenerated/ window/ui/node_modules/ window/ui/dist/ +evals/runs/ +evals/__pycache__/ diff --git a/agentcore/src/turn.rs b/agentcore/src/turn.rs index 66c5e1a7..d3ca52bf 100644 --- a/agentcore/src/turn.rs +++ b/agentcore/src/turn.rs @@ -313,18 +313,33 @@ fn fit(mut result: Value, most: usize) -> Value { /// again is stuck, and the result says so from the `REPEATS`th time on. #[derive(Default)] struct Repeats { + prev: u64, last: u64, times: u32, + cycle_times: u32, } impl Repeats { - /// Gives the model's copy of `call`'s `result`, with the note when it is a repeat. + /// Gives the model's copy of `call`'s `result`, with a nudge when the model is stuck in a + /// consecutive repeat (`A, A, A`) or an oscillating 2-call cycle (`A, B, A, B, A, B`). fn note(&mut self, call: &Call, mut result: Value) -> Value { let mut hash = DefaultHasher::new(); (&call.name, &call.arguments, result["content"].as_str()).hash(&mut hash); let hash = hash.finish(); - self.times = if hash == self.last { self.times + 1 } else { 1 }; - self.last = hash; + if hash == self.last { + self.times += 1; + self.cycle_times = 0; + } else if hash == self.prev && self.last != 0 { + self.times = 1; + self.cycle_times += 1; + self.prev = self.last; + self.last = hash; + } else { + self.times = 1; + self.cycle_times = 0; + self.prev = self.last; + self.last = hash; + } if self.times >= REPEATS && let Some(content) = result["content"].as_str() { @@ -334,6 +349,16 @@ impl Repeats { self.times ) .into(); + } else if self.cycle_times >= REPEATS + && let Some(content) = result["content"].as_str() + { + result["content"] = format!( + "{content}\n[You have alternated between the same two calls with the same results \ + {} times. Repeating this cycle will not change it: try another approach, or \ + answer with what you have.]", + self.cycle_times + ) + .into(); } result } diff --git a/agentcore/tests/harness_eval.rs b/agentcore/tests/harness_eval.rs new file mode 100644 index 00000000..c032b26c --- /dev/null +++ b/agentcore/tests/harness_eval.rs @@ -0,0 +1,859 @@ +//! Offline, deterministic Agent Core Harness Scorecard (CI-gated, 0 API cost). +//! +//! Isolates `agentcore` harness quality from LLM intelligence across the failure modes +//! highlighted by Harness-Bench, CompactBench, OpenClaw/Hermes/MausBot evals, and Bate's +//! own Terminal-Bench 2.0 failure taxonomy: +//! +//! 1. Consecutive doom-loop interception & recovery +//! 2. Oscillating 2-call (A->B->A->B) doom-loop interception & recovery +//! 3. Multi-cycle compaction preserving constraints & assistant/tool_call pairing +//! 4. Reactive overflow compaction recovery +//! 5. Edit resilience: exact, loose whitespace, ambiguous refusal, UTF-8, undo safety +//! 6. Giant & non-UTF-8 tool output budgeting without context/JSON corruption +//! 7. Mid-turn fallback model failover preserving prior tool work +//! 8. Abort mid-tool-batch leaving session well-formed for next turn +//! 9. Late steer arriving during final reply preventing premature turn end +//! 10. Parallel tool calls & unnamed call IDs across turns +//! 11. Permission denial & error observation recovery without crashing the loop +//! 12. Step-limit graceful wrap-up + check-before-finish early-stop guard + +use proto::permissions::APPROVE; +use proto::{CheckResult, Event, MAX_EVENT_FRAME, MAX_OP_FRAME, Op, Request, TurnEnd}; +use serde_json::{Value, json}; +use std::fs; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::mpsc::{self, Receiver}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::{Duration, Instant}; + +const WAIT: Duration = Duration::from_secs(15); + +fn temp_dir(label: &str) -> PathBuf { + static NEXT: AtomicU64 = AtomicU64::new(1); + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!( + "bate-harness-eval-{}-{label}-{n}", + std::process::id() + )); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +struct MockModel { + url: String, + requests: Arc>>, +} + +fn sse_body(chunks: Vec) -> Vec { + let mut body = String::new(); + for chunk in chunks { + body.push_str(&format!("data: {chunk}\n\n")); + } + body.push_str("data: [DONE]\n\n"); + body.into_bytes() +} + +fn http_err(status: &str, message: &str) -> Vec { + let payload = json!({"error": {"message": message}}).to_string(); + format!( + "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{payload}", + payload.len() + ) + .into_bytes() +} + +impl MockModel { + fn serve(replies: Vec>) -> Self { + Self::raw(replies.into_iter().map(sse_body).collect()) + } + + fn raw(bodies: Vec>) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}/v1", listener.local_addr().unwrap()); + let requests = Arc::new(Mutex::new(Vec::new())); + let seen = requests.clone(); + thread::spawn(move || { + for (stream, reply) in listener.incoming().zip(bodies) { + let Ok(mut stream) = stream else { break }; + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut length = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { + break; + } + if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") { + length = v.trim().parse().unwrap_or(0); + } + } + let mut body = vec![0; length]; + if reader.read_exact(&mut body).is_ok() + && let Ok(parsed) = serde_json::from_slice(&body) + { + seen.lock().unwrap().push(parsed); + } + if !reply.starts_with(b"HTTP/") { + let head = "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n"; + let _ = stream.write_all(head.as_bytes()); + } + let _ = stream.write_all(&reply); + } + }); + Self { url, requests } + } + + fn requests(&self) -> Vec { + self.requests.lock().unwrap().clone() + } +} + +fn delta(d: Value) -> Value { + json!({"choices": [{"index": 0, "delta": d}]}) +} +fn text_chunk(t: &str) -> Value { + delta(json!({"content": t})) +} +fn call_chunk(index: usize, id: &str, tool: &str, args: Value) -> Value { + delta(json!({ + "tool_calls": [{ + "index": index, + "id": id, + "type": "function", + "function": {"name": tool, "arguments": args.to_string()} + }] + })) +} +fn usage_chunk(input: u64, output: u64) -> Value { + json!({"choices": [], "usage": {"prompt_tokens": input, "completion_tokens": output}}) +} + +struct Harness { + child: Child, + input: Arc>, + events: Receiver, + next_id: u32, +} + +impl Harness { + fn start(dir: &Path, model: &MockModel, context: Option, env: &[(&str, &str)]) -> Self { + let mut child = Command::new(env!("CARGO_BIN_EXE_agentcore")) + .current_dir(dir) + .env_remove("BATE_MODEL_API_KEY") + .env_remove("BATE_MODEL") + .env_remove("BATE_MODEL_CONTEXT") + .env("BATE_RETRY_MS", "5") + .envs(env.iter().copied()) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let input = Arc::new(Mutex::new(child.stdin.take().unwrap())); + let mut output = BufReader::new(child.stdout.take().unwrap()); + let (tx, events) = mpsc::channel(); + let loop_input = input.clone(); + let model_url = model.url.clone(); + thread::spawn(move || { + let mut buf = Vec::new(); + while let Ok(Some(event)) = + proto::read_frame::(&mut output, MAX_EVENT_FRAME, &mut buf) + { + if let Event::Response { ref id, .. } = event + && id == "auto-tok" + { + continue; + } + if let Event::Token { ref request, .. } = event { + let op = Request { + id: "auto-tok".into(), + op: Op::Token { + request: request.clone(), + url: Some(model_url.clone()), + key: None, + api: None, + model: None, + context, + checker: None, + error: None, + }, + }; + let _ = proto::write_frame(&mut *loop_input.lock().unwrap(), &op, MAX_OP_FRAME); + continue; + } + if matches!(event, Event::Usage { .. } | Event::Context { .. }) { + continue; + } + if tx.send(event).is_err() { + return; + } + } + }); + let h = Self { + child, + input, + events, + next_id: 0, + }; + assert_eq!( + h.next(), + Event::Ready { + protocol: proto::PROTOCOL + } + ); + h + } + + fn next(&self) -> Event { + self.events + .recv_timeout(WAIT) + .expect("harness event in time") + } + + fn send(&mut self, op: Op) { + self.next_id += 1; + let req = Request { + id: format!("h{}", self.next_id), + op, + }; + proto::write_frame(&mut *self.input.lock().unwrap(), &req, MAX_OP_FRAME).unwrap(); + } + + fn init(&mut self, model: &str) { + self.send(Op::Start { bot: "eval".into() }); + self.send(Op::SetModel { + model: model.into(), + effort: None, + }); + // Drain start + set_model responses & session event. + let mut saw_session = false; + let mut responses = 0; + while !saw_session || responses < 2 { + match self.next() { + Event::Session { .. } => saw_session = true, + Event::Response { error: None, .. } => responses += 1, + other => panic!("unexpected init event: {other:?}"), + } + } + } + + /// Runs a prompt, answering every approval question with `decider`, until `TurnEnd`. + fn run_prompt( + &mut self, + nonce: &str, + prompt: &str, + check: bool, + mut decider: impl FnMut(&str, &str) -> &'static str, + ) -> (TurnEnd, Vec) { + self.send(Op::Prompt { + nonce: nonce.into(), + text: prompt.into(), + check, + check_back: false, + }); + let mut seen = Vec::new(); + loop { + let ev = self.next(); + match &ev { + Event::Question { + question, + title, + target, + .. + } => { + let choice = decider(title, target.as_deref().unwrap_or("")); + self.send(Op::Answer { + question: question.clone(), + choice: choice.into(), + }); + } + Event::TurnEnd { reason, .. } => { + let end = *reason; + seen.push(ev); + return (end, seen); + } + _ => {} + } + seen.push(ev); + } + } +} + +impl Drop for Harness { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// Validates that every `tool` message in a request follows an `assistant` message carrying its +/// matching `tool_call_id` (detects orphaned tool messages after compaction or abort). +fn assert_tool_pairing_valid(req: &Value) { + let msgs = req["messages"].as_array().expect("messages array"); + let mut open_ids: Vec = Vec::new(); + for msg in msgs { + match msg["role"].as_str() { + Some("assistant") => { + assert!( + open_ids.is_empty(), + "unanswered tool_calls {open_ids:?} before next assistant message" + ); + if let Some(calls) = msg["tool_calls"].as_array() { + for c in calls { + open_ids.push(c["id"].as_str().unwrap().to_owned()); + } + } + } + Some("tool") => { + let id = msg["tool_call_id"].as_str().expect("tool_call_id"); + let pos = open_ids + .iter() + .position(|x| x == id) + .unwrap_or_else(|| panic!("orphaned tool result for `{id}` in {msgs:?}")); + open_ids.remove(pos); + } + _ => { + assert!( + open_ids.is_empty(), + "unanswered tool_calls {open_ids:?} before role {:?}", + msg["role"] + ); + } + } + } + assert!( + open_ids.is_empty(), + "trailing unanswered tool_calls {open_ids:?}" + ); +} + +// ---- Scenario 1: Consecutive doom-loop interception & recovery ---- +fn eval_consecutive_doom_loop() { + let dir = temp_dir("doom-consecutive"); + fs::write(dir.join("note.txt"), "hello").unwrap(); + let bad_call = || vec![call_chunk(0, "c1", "read", json!({"path": "missing.txt"}))]; + let model = MockModel::serve(vec![ + bad_call(), + bad_call(), + bad_call(), + vec![text_chunk("Stopped retrying missing.txt and adapted.")], + ]); + let mut h = Harness::start(&dir, &model, None, &[]); + h.init("primary"); + let (end, _) = h.run_prompt("n1", "read missing.txt", false, |_, _| APPROVE); + assert_eq!(end, TurnEnd::Done); + + let reqs = model.requests(); + assert_eq!(reqs.len(), 4); + let last_tool = reqs[3]["messages"].as_array().unwrap().last().unwrap(); + let content = last_tool["content"].as_str().unwrap(); + assert!( + content.contains("3 times in a row"), + "expected consecutive doom-loop nudge, got: {content}" + ); +} + +// ---- Scenario 2: Oscillating 2-call (A->B->A->B) doom-loop interception ---- +fn eval_oscillating_doom_loop() { + let dir = temp_dir("doom-oscillating"); + let call_a = |id: &str| vec![call_chunk(0, id, "read", json!({"path": "a.txt"}))]; + let call_b = |id: &str| vec![call_chunk(0, id, "read", json!({"path": "b.txt"}))]; + // A, B, A, B, A -> 3rd cycle repetition triggers oscillating nudge. + let model = MockModel::serve(vec![ + call_a("c1"), + call_b("c2"), + call_a("c3"), + call_b("c4"), + call_a("c5"), + vec![text_chunk("Broke out of the A/B cycle.")], + ]); + let mut h = Harness::start(&dir, &model, None, &[]); + h.init("primary"); + let (end, _) = h.run_prompt("n1", "check files", false, |_, _| APPROVE); + assert_eq!(end, TurnEnd::Done); + + let reqs = model.requests(); + assert_eq!(reqs.len(), 6); + let last_tool = reqs[5]["messages"].as_array().unwrap().last().unwrap(); + let content = last_tool["content"].as_str().unwrap(); + assert!( + content.contains("alternated between the same two calls"), + "expected oscillating doom-loop nudge, got: {content}" + ); +} + +// ---- Scenario 3: Multi-cycle compaction preserving constraints & valid tool pairing ---- +fn eval_multi_cycle_compaction() { + let dir = temp_dir("compaction-multi"); + fs::write(dir.join("a.txt"), "alpha").unwrap(); + fs::write(dir.join("b.txt"), "beta").unwrap(); + fs::write(dir.join("c.txt"), "gamma").unwrap(); + fs::write(dir.join("d.txt"), "delta").unwrap(); + // Context window 1000 tokens -> 80% threshold = 800 tokens; KEEP = 4 recent messages. + // Round 1+2 build >4 messages, round 2 reports 900 tokens -> triggers compaction #1! + // Round 3+4 build >4 more messages, round 4 reports 950 tokens -> triggers compaction #2! + // Round 5 produces final answer with PINNED_KEY=9412 still in context. + let model = MockModel::serve(vec![ + vec![ + call_chunk(0, "c1", "read", json!({"path": "a.txt"})), + usage_chunk(200, 10), + ], + vec![ + call_chunk(0, "c2", "read", json!({"path": "b.txt"})), + usage_chunk(900, 10), + ], + // Compaction #1 summary: + vec![text_chunk( + "Summary 1: constraint PINNED_KEY=9412, read a.txt and b.txt", + )], + vec![ + call_chunk(0, "c3", "read", json!({"path": "c.txt"})), + usage_chunk(300, 10), + ], + vec![ + call_chunk(0, "c4", "read", json!({"path": "d.txt"})), + usage_chunk(950, 10), + ], + // Compaction #2 summary: + vec![text_chunk( + "Summary 2: constraint PINNED_KEY=9412, read a/b/c/d", + )], + vec![text_chunk("Done with PINNED_KEY=9412")], + ]); + let mut h = Harness::start(&dir, &model, Some(1000), &[]); + h.init("primary"); + let (end, _) = h.run_prompt("n1", "keep PINNED_KEY=9412", false, |_, _| APPROVE); + assert_eq!(end, TurnEnd::Done); + + let reqs = model.requests(); + assert_eq!(reqs.len(), 7, "expected 5 turn rounds + 2 compactions"); + // Every model request must have strictly valid assistant/tool pairing. + for req in &reqs { + assert_tool_pairing_valid(req); + } + let final_req_str = reqs[6]["messages"].to_string(); + assert!( + final_req_str.contains("PINNED_KEY=9412"), + "pinned constraint lost after 2 compaction cycles: {final_req_str}" + ); +} + +// ---- Scenario 4: Reactive overflow compaction recovery ---- +fn eval_reactive_overflow_compaction() { + let dir = temp_dir("compaction-overflow"); + fs::write(dir.join("big1.txt"), "line1-payload-data\n".repeat(400)).unwrap(); + fs::write(dir.join("s2.txt"), "two").unwrap(); + fs::write(dir.join("s3.txt"), "three").unwrap(); + let model = MockModel::raw(vec![ + sse_body(vec![ + call_chunk(0, "c1", "read", json!({"path": "big1.txt"})), + usage_chunk(100, 10), + ]), + sse_body(vec![ + call_chunk(0, "c2", "read", json!({"path": "s2.txt"})), + usage_chunk(200, 10), + ]), + sse_body(vec![ + call_chunk(0, "c3", "read", json!({"path": "s3.txt"})), + usage_chunk(300, 10), + ]), + // Server rejects both the initial oversized request and model.rs's stream_options probe: + http_err("400 Bad Request", "maximum context length exceeded"), + http_err("400 Bad Request", "maximum context length exceeded"), + sse_body(vec![text_chunk("Summary: read big1.txt")]), + sse_body(vec![text_chunk("Recovered cleanly after overflow")]), + ]); + let mut h = Harness::start(&dir, &model, Some(200_000), &[]); + h.init("primary"); + let (end, _) = h.run_prompt("n1", "read big files", false, |_, _| APPROVE); + assert_eq!(end, TurnEnd::Done); + + let reqs = model.requests(); + assert_eq!(reqs.len(), 7); + assert_tool_pairing_valid(&reqs[6]); +} + +// ---- Scenario 5: Edit resilience (exact, loose whitespace, ambiguous refusal, UTF-8, undo) ---- +fn eval_edit_resilience() { + let dir = temp_dir("edit-resilience"); + let target = dir.join("code.py"); + fs::write( + &target, + "# café header\ndef dup():\n return 1\n\ndef dup():\n return 1\n\ndef unique():\n x = 1 \n return x\n", + ) + .unwrap(); + let model = MockModel::serve(vec![ + // 1. Ambiguous edit (matches twice) -> must fail without mutating file! + vec![call_chunk( + 0, + "e1", + "edit", + json!({"path": "code.py", "old": "def dup():\n return 1", "new": "def dup():\n return 2"}), + )], + // 2. Loose edit on unique() (trailing spaces omitted in old) -> must succeed! + vec![call_chunk( + 0, + "e2", + "edit", + json!({"path": "code.py", "old": "def unique():\n x = 1\n return x", "new": "def unique():\n x = 42\n return x"}), + )], + vec![text_chunk("Edited unique() safely.")], + ]); + let mut h = Harness::start(&dir, &model, None, &[]); + h.init("primary"); + let (end, events) = h.run_prompt("n1", "update code.py", false, |_, _| APPROVE); + assert_eq!(end, TurnEnd::Done); + + let tool_ends: Vec<_> = events + .iter() + .filter_map(|e| match e { + Event::ToolEnd { + call, + is_error, + output, + undo, + } => Some((call.as_str(), !*is_error, output.as_str(), undo.is_some())), + _ => None, + }) + .collect(); + assert_eq!(tool_ends.len(), 2); + assert!(!tool_ends[0].1, "ambiguous edit must fail"); + assert!( + tool_ends[1].1, + "loose whitespace edit must succeed: {}", + tool_ends[1].2 + ); + assert!(tool_ends[1].3, "successful edit must record undo snapshot"); + + let after = fs::read_to_string(&target).unwrap(); + assert!(after.contains("# café header"), "UTF-8 preserved"); + assert!(after.contains("x = 42"), "loose edit applied"); + assert_eq!( + after.matches("return 1").count(), + 2, + "ambiguous edit did not mutate file" + ); +} + +// ---- Scenario 6: Giant & non-UTF-8 tool output budgeting ---- +fn eval_giant_and_binary_output() { + let dir = temp_dir("giant-binary"); + let model = MockModel::serve(vec![ + vec![call_chunk( + 0, + "r1", + "run", + json!({"command": "python3 -c 'import sys; sys.stdout.buffer.write(b\"HEAD_MARK\\n\" + b\"x\"*180000 + b\"\\xff\\xfe\\nTAIL_MARK\\n\")'"}), + )], + vec![text_chunk("Handled giant binary output.")], + ]); + let mut h = Harness::start(&dir, &model, Some(16_000), &[]); + h.init("primary"); + let (end, events) = h.run_prompt("n1", "run big command", false, |_, _| APPROVE); + assert_eq!(end, TurnEnd::Done); + + let tool_ok = events.iter().any(|e| { + matches!( + e, + Event::ToolEnd { + is_error: false, + .. + } + ) + }); + assert!(tool_ok, "giant/binary command should complete cleanly"); + let reqs = model.requests(); + let model_saw = reqs[1]["messages"].as_array().unwrap().last().unwrap()["content"] + .as_str() + .unwrap(); + assert!( + model_saw.len() < 40_000, + "giant tool output was not capped for model context: {} bytes", + model_saw.len() + ); +} + +// ---- Scenario 7: Mid-turn fallback model failover preserving prior tool work ---- +fn eval_mid_turn_fallback() { + let dir = temp_dir("mid-turn-fallback"); + fs::write(dir.join("data.txt"), "SECRET_FACT=7741").unwrap(); + let model = MockModel::raw(vec![ + // Round 1 on primary: reads data.txt + sse_body(vec![call_chunk( + 0, + "r1", + "read", + json!({"path": "data.txt"}), + )]), + // Round 2 on primary: hits 429 quota -> agentcore switches to fallback_model + http_err("429 Too Many Requests", "insufficient_quota"), + // Round 2 retried on backup model with Round 1 tool result intact! + sse_body(vec![text_chunk("Backup saw SECRET_FACT=7741")]), + ]); + let mut h = Harness::start(&dir, &model, None, &[]); + h.init("primary-model"); + h.send(Op::FallbackModel { + model: "backup-model".into(), + }); + assert!(matches!(h.next(), Event::Response { error: None, .. })); + + let (end, events) = h.run_prompt("n1", "read data.txt", false, |_, _| APPROVE); + assert_eq!(end, TurnEnd::Done); + assert!( + events.iter().any(|e| matches!( + e, + Event::Fallback { from, to, .. } if from == "primary-model" && to == "backup-model" + )), + "expected Fallback event" + ); + let reqs = model.requests(); + assert_eq!(reqs.len(), 3); + assert_eq!(reqs[2]["model"], "backup-model"); + assert!( + reqs[2]["messages"].to_string().contains("SECRET_FACT=7741"), + "backup model lost prior tool output" + ); +} + +// ---- Scenario 8: Abort mid-tool-batch keeps session valid for next turn ---- +fn eval_abort_mid_batch_resume() { + let dir = temp_dir("abort-resume"); + let model = MockModel::serve(vec![ + // Turn 1: 2 tool calls; we abort while call 1 waits for approval. + vec![ + call_chunk(0, "a1", "run", json!({"command": "echo one"})), + call_chunk(1, "a2", "run", json!({"command": "echo two"})), + ], + // Turn 2: fresh prompt must succeed with valid paired history! + vec![text_chunk("Turn 2 recovered cleanly.")], + ]); + let mut h = Harness::start(&dir, &model, None, &[]); + h.init("primary"); + h.send(Op::Prompt { + nonce: "n1".into(), + text: "run two commands".into(), + check: false, + check_back: false, + }); + // Wait for first question, then abort instead of answering. + loop { + if matches!(h.next(), Event::Question { .. }) { + h.send(Op::Abort); + break; + } + } + loop { + if let Event::TurnEnd { reason, .. } = h.next() { + assert_eq!(reason, TurnEnd::Aborted); + break; + } + } + // Turn 2 must succeed cleanly and send valid tool pairing. + let (end2, _) = h.run_prompt("n2", "continue please", false, |_, _| APPROVE); + assert_eq!(end2, TurnEnd::Done); + let reqs = model.requests(); + assert_eq!(reqs.len(), 2); + assert_tool_pairing_valid(&reqs[1]); +} + +// ---- Scenario 9: Late steer prevents premature turn finish ---- +fn eval_late_steer_intercept() { + let dir = temp_dir("late-steer"); + fs::write(dir.join("x.txt"), "x").unwrap(); + let model = MockModel::serve(vec![ + vec![call_chunk(0, "s1", "read", json!({"path": "x.txt"}))], + vec![text_chunk("Final answer incorporating steer.")], + ]); + let mut h = Harness::start(&dir, &model, None, &[]); + h.init("primary"); + h.send(Op::Prompt { + nonce: "n1".into(), + text: "read x".into(), + check: false, + check_back: false, + }); + let mut steered = false; + loop { + match h.next() { + Event::Question { question, .. } => { + if !steered { + h.send(Op::Steer { + text: "ALSO_CHECK_Z".into(), + }); + steered = true; + } + h.send(Op::Answer { + question, + choice: APPROVE.into(), + }); + } + Event::TurnEnd { reason, .. } => { + assert_eq!(reason, TurnEnd::Done); + break; + } + _ => {} + } + } + let reqs = model.requests(); + assert!( + reqs[1]["messages"].to_string().contains("ALSO_CHECK_Z"), + "mid-turn steer was not delivered before round 2" + ); +} + +// ---- Scenario 10: Parallel tool calls & unnamed call IDs ---- +fn eval_parallel_and_unnamed_calls() { + let dir = temp_dir("parallel-unnamed"); + fs::write(dir.join("f1.txt"), "ONE").unwrap(); + fs::write(dir.join("f2.txt"), "TWO").unwrap(); + fs::write(dir.join("f3.txt"), "THREE").unwrap(); + let model = MockModel::serve(vec![ + vec![ + call_chunk(0, "", "read", json!({"path": "f1.txt"})), + call_chunk(1, "", "read", json!({"path": "f2.txt"})), + call_chunk(2, "", "read", json!({"path": "f3.txt"})), + ], + vec![text_chunk("Read ONE, TWO, THREE.")], + ]); + let mut h = Harness::start(&dir, &model, None, &[]); + h.init("primary"); + let (end, _) = h.run_prompt("n1", "read all three", false, |_, _| APPROVE); + assert_eq!(end, TurnEnd::Done); + + let reqs = model.requests(); + assert_tool_pairing_valid(&reqs[1]); + let body = reqs[1]["messages"].to_string(); + assert!(body.contains("ONE") && body.contains("TWO") && body.contains("THREE")); +} + +// ---- Scenario 11: Permission denial recovery without crashing loop ---- +fn eval_permission_denial_recovery() { + let dir = temp_dir("deny-recovery"); + fs::write(dir.join("safe.txt"), "SAFE_DATA").unwrap(); + let model = MockModel::serve(vec![ + vec![call_chunk( + 0, + "d1", + "run", + json!({"command": "rm -rf /tmp/nope"}), + )], + vec![call_chunk(0, "d2", "read", json!({"path": "safe.txt"}))], + vec![text_chunk("Used safe read instead.")], + ]); + let mut h = Harness::start(&dir, &model, None, &[]); + h.init("primary"); + let (end, _) = h.run_prompt("n1", "inspect safely", false, |_, target| { + if target.contains("rm -rf") { + "Deny" + } else { + APPROVE + } + }); + assert_eq!(end, TurnEnd::Done); + let reqs = model.requests(); + assert_eq!(reqs.len(), 3); + assert!(reqs[2]["messages"].to_string().contains("SAFE_DATA")); +} + +// ---- Scenario 12: Step limit graceful wrap-up + check-before-finish early-stop guard ---- +fn eval_step_limit_and_check_guard() { + // 12a: step limit wrap-up + let dir_a = temp_dir("step-limit"); + fs::write(dir_a.join("a.txt"), "alpha").unwrap(); + let model_a = MockModel::serve(vec![ + vec![call_chunk(0, "s1", "read", json!({"path": "a.txt"}))], + // Wrap-up call has no tools and writes summary before TurnEnd::Limit. + vec![text_chunk( + "Progress so far: read a.txt, ready to continue.", + )], + ]); + let mut ha = Harness::start(&dir_a, &model_a, None, &[]); + ha.init("primary"); + ha.send(Op::StepLimit { steps: 1 }); + assert!(matches!(ha.next(), Event::Response { error: None, .. })); + let (end_a, _) = ha.run_prompt("n1", "work", false, |_, _| APPROVE); + assert_eq!(end_a, TurnEnd::Limit); + + // 12b: check-before-finish catches weak early answer, bot runs verification tool & passes! + let dir_b = temp_dir("check-guard"); + fs::write(dir_b.join("app.py"), "print('OK')").unwrap(); + let model_b = MockModel::serve(vec![ + vec![call_chunk(0, "c1", "read", json!({"path": "app.py"}))], + vec![text_chunk("Looks fine.")], + // Checker rejects early stop without running app.py: + vec![text_chunk("FIX: You did not run app.py to verify output.")], + // Bot runs app.py: + vec![call_chunk( + 0, + "c2", + "run", + json!({"command": "python3 app.py"}), + )], + vec![text_chunk("Verified: python3 app.py printed OK.")], + // Second check passes: + vec![text_chunk("OK")], + ]); + let mut hb = Harness::start(&dir_b, &model_b, None, &[]); + hb.init("primary"); + let (end_b, events_b) = hb.run_prompt("n1", "verify app.py", true, |_, _| APPROVE); + assert_eq!(end_b, TurnEnd::Done); + let verdicts: Vec = events_b + .iter() + .filter_map(|e| match e { + Event::Checked { result, .. } => Some(*result), + _ => None, + }) + .collect(); + assert_eq!(verdicts, vec![CheckResult::Failed, CheckResult::Passed]); +} + +#[test] +fn agentcore_harness_scorecard() { + let cases: [(&str, fn()); 12] = [ + ("01_consecutive_doom_loop", eval_consecutive_doom_loop), + ("02_oscillating_doom_loop", eval_oscillating_doom_loop), + ("03_multi_cycle_compaction", eval_multi_cycle_compaction), + ( + "04_reactive_overflow_compaction", + eval_reactive_overflow_compaction, + ), + ("05_edit_resilience_and_undo", eval_edit_resilience), + ("06_giant_and_binary_output", eval_giant_and_binary_output), + ("07_mid_turn_fallback_failover", eval_mid_turn_fallback), + ("08_abort_mid_batch_and_resume", eval_abort_mid_batch_resume), + ("09_late_steer_intercept", eval_late_steer_intercept), + ( + "10_parallel_and_unnamed_calls", + eval_parallel_and_unnamed_calls, + ), + ( + "11_permission_denial_recovery", + eval_permission_denial_recovery, + ), + ( + "12_step_limit_and_check_guard", + eval_step_limit_and_check_guard, + ), + ]; + let started = Instant::now(); + let mut lines = Vec::with_capacity(cases.len()); + for (name, run) in cases { + let t0 = Instant::now(); + run(); + lines.push(format!( + "| {name:<34} | PASS | {:>5} ms |", + t0.elapsed().as_millis() + )); + } + eprintln!( + "\n=== AgentCore Harness Scorecard ({}/{} PASS in {} ms) ===\n{}\n", + lines.len(), + cases.len(), + started.elapsed().as_millis(), + lines.join("\n") + ); +} diff --git a/evals/README.md b/evals/README.md new file mode 100644 index 00000000..f39a3f83 --- /dev/null +++ b/evals/README.md @@ -0,0 +1,68 @@ +# Bate AgentCore Evaluation Suite + +Two complementary evaluation layers that tell you whether changes to `agentcore` actually make Bate better — offline in CI (0 API cost) and live against real LLMs or installed ACP agents. + +## Layer 1 — Offline Harness Scorecard (CI-gated, 0 API cost) + +Tests `agentcore` harness mechanics in isolation from LLM variance (`agentcore/tests/harness_eval.rs`): + +```bash +cargo test -p agentcore --test harness_eval -- --nocapture +``` + +Covers 12 deterministic failure-mode scenarios: +1. Consecutive doom-loop interception (`A, A, A`) +2. Oscillating 2-call doom-loop interception (`A, B, A, B, A`) +3. Multi-cycle proactive compaction preserving pinned constraints & valid `assistant`/`tool` pairing +4. Reactive overflow compaction recovery on HTTP 400 context overflow +5. Edit resilience (ambiguous refusal, loose whitespace matching, UTF-8 preservation, undo snapshot) +6. Giant (>180 KiB) and non-UTF-8 tool output budgeting +7. Mid-turn fallback model failover preserving prior tool results +8. Mid-batch abort leaving session JSONL valid for the next turn +9. Late steer interception before `TurnEnd::Done` +10. Parallel tool calls & unnamed call IDs +11. Permission denial recovery without crashing the loop +12. Step-limit graceful wrap-up + `check`-before-finish early-stop guard + +## Layer 2 — Local 16-Task Live Eval Suite + Trajectory Analyzer + +Runs the real compiled `agentcore` binary against 16 deterministically verified tasks across 5 categories (`coding`, `shell_data`, `edit_precision`, `bate_native` [cross-turn memory, `SKILL.md`, compaction needle recall, stdio MCP tools], and `safety_recovery`). + +### 1. List tasks +```bash +python3 evals/run.py --list +``` + +### 2. Zero-cost self-test (real `agentcore` + real tools + real stdio MCP + mock SSE server) +```bash +cargo build -p agentcore +python3 evals/run.py --mock --engine target/debug/agentcore --out /tmp/bate-eval-mock +python3 -m unittest discover -s evals -v +``` + +### 3. Live run against any OpenAI-compatible model endpoint (e.g. `omp` gateway, OpenAI, OpenRouter, Ollama) +```bash +python3 evals/run.py \ + --url http://127.0.0.1:4100/v1 \ + --model claude-sonnet-5 \ + --k 3 \ + --out /tmp/bate-eval-main +``` + +### 4. Compare Bate `agentcore` vs another commit OR vs an installed ACP agent (`claude-agent-acp` / `codex-acp`) +```bash +# Run an installed ACP agent on the exact same 16 tasks: +python3 evals/run.py --acp "claude-agent-acp" --out /tmp/bate-eval-claude + +# Paired McNemar exact test + token/tool deltas: +python3 evals/run.py compare /tmp/bate-eval-base /tmp/bate-eval-main + +# Or feed exported results.jsonl straight into d41sys/evalkit: +# evalkit compare /tmp/bate-eval-main/results.jsonl --all-pairs +``` + +Every run writes: +- `//t/trace.jsonl` — raw `agentcore` event stream +- `//t/result.json` — deterministic verifier verdict + timing +- `/results.jsonl` — `d41sys/evalkit`-compatible results with `failure_mode` (`pass`, `early_stop`, `doom_loop`, `edit_mismatch`, `step_limit`, `timeout`, `model_error`, `wrong_answer`) +- `/summary.md` — `pass@1`, `pass^k`, category table, and failure taxonomy diff --git a/evals/analyze.py b/evals/analyze.py new file mode 100644 index 00000000..f54bd8d9 --- /dev/null +++ b/evals/analyze.py @@ -0,0 +1,317 @@ +"""Trajectory analyzer, failure taxonomy classifier, EvalKit exporter, and paired A/B comparator.""" + +from __future__ import annotations + +import json +import math +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + + +def parse_trace(trace_path: Path) -> dict[str, Any]: + """Extract trajectory telemetry and loop/failure signals from an agentcore JSONL trace.""" + tool_calls: list[dict[str, Any]] = [] + tool_results: dict[str, dict[str, Any]] = {} + tokens_in = 0 + tokens_out = 0 + checks: list[str] = [] + fallbacks = 0 + compactions = 0 + last_context_used = 0 + + if not trace_path.exists(): + return { + "tool_calls": 0, + "run_calls": 0, + "edit_errors": 0, + "tool_errors": 0, + "tokens_in": 0, + "tokens_out": 0, + "checks": [], + "fallbacks": 0, + "compactions": 0, + "doom_loop": False, + } + + call_sigs: list[tuple[str, str, bool]] = [] + for raw in trace_path.read_text(encoding="utf-8").splitlines(): + if not raw.strip(): + continue + try: + ev = json.loads(raw) + except json.JSONDecodeError: + continue + et = ev.get("type") + if et == "tool_start": + tool_calls.append(ev) + elif et == "tool_end": + tool_results[str(ev.get("call", ""))] = ev + elif et == "usage": + tokens_in += int(ev.get("input", 0) or 0) + tokens_out += int(ev.get("output", 0) or 0) + elif et == "context": + used = int(ev.get("used", 0) or 0) + if last_context_used > 0 and used < last_context_used * 0.7: + compactions += 1 + last_context_used = used + elif et == "checked": + checks.append(str(ev.get("result", ""))) + elif et == "fallback": + fallbacks += 1 + + edit_errors = 0 + tool_errors = 0 + run_calls = 0 + for tc in tool_calls: + cid = str(tc.get("call", "")) + tname = str(tc.get("tool", "")) + args = tc.get("args") or {} + res = tool_results.get(cid, {}) + is_err = bool(res.get("isError")) + if tname == "run": + run_calls += 1 + if is_err: + tool_errors += 1 + if tname == "edit": + edit_errors += 1 + sig = (tname, json.dumps(args, sort_keys=True), is_err) + call_sigs.append(sig) + + # Detect consecutive (>=3) or alternating 2-call (>=3 cycles) doom loops. + doom_loop = False + consec = 1 + for i in range(1, len(call_sigs)): + if call_sigs[i] == call_sigs[i - 1]: + consec += 1 + if consec >= 3: + doom_loop = True + break + else: + consec = 1 + if not doom_loop and len(call_sigs) >= 6: + for i in range(len(call_sigs) - 5): + if ( + call_sigs[i] == call_sigs[i + 2] == call_sigs[i + 4] + and call_sigs[i + 1] == call_sigs[i + 3] == call_sigs[i + 5] + and call_sigs[i] != call_sigs[i + 1] + ): + doom_loop = True + break + + return { + "tool_calls": len(tool_calls), + "run_calls": run_calls, + "edit_errors": edit_errors, + "tool_errors": tool_errors, + "tokens_in": tokens_in, + "tokens_out": tokens_out, + "checks": checks, + "fallbacks": fallbacks, + "compactions": compactions, + "doom_loop": doom_loop, + } + + +def classify_failure(result: dict[str, Any], traj: dict[str, Any]) -> str: + """Assign a single actionable failure mode to a trial (matching TB2/evalkit taxonomy).""" + if result.get("passed"): + return "pass" + if result.get("timed_out"): + return "timeout" + reasons = result.get("turn_reasons") or [] + if "limit" in reasons: + return "step_limit" + if "error" in reasons: + return "model_error" + if traj.get("doom_loop"): + return "doom_loop" + if traj.get("tool_calls", 0) <= 2 and traj.get("run_calls", 0) == 0: + return "early_stop" + if traj.get("edit_errors", 0) >= 2: + return "edit_mismatch" + return "wrong_answer" + + +def enrich_run(run_dir: Path) -> dict[str, Any]: + """Analyze every trial under `run_dir`, export `results.jsonl` (evalkit format) and `summary.md`.""" + trial_rows: list[dict[str, Any]] = [] + for res_file in sorted(run_dir.glob("**/result.json")): + res = json.loads(res_file.read_text(encoding="utf-8")) + trace_path = Path(res.get("trace_path", res_file.parent / "trace.jsonl")) + traj = parse_trace(trace_path) + mode = classify_failure(res, traj) + row = { + **res, + **traj, + "failure_mode": mode, + "trial": res_file.parent.name, + } + trial_rows.append(row) + + # Export evalkit-compatible results.jsonl (`evalkit compare` / `evalkit trajectory`). + evalkit_path = run_dir / "results.jsonl" + with evalkit_path.open("w", encoding="utf-8") as f: + for idx, r in enumerate(trial_rows): + record = { + "task_id": r["category"], + "example_id": f"{r['task_id']}::{r['trial']}", + "model": r["model"], + "score": r["score"], + "latency_ms": r["wall_ms"], + "tokens_in": r["tokens_in"], + "tokens_out": r["tokens_out"], + "tool_calls": r["tool_calls"], + "failure_mode": r["failure_mode"], + "meta": { + "task": r["task_id"], + "compactions": r["compactions"], + "fallbacks": r["fallbacks"], + "checks": r["checks"], + "index": idx, + }, + } + f.write(json.dumps(record) + "\n") + + by_task: dict[str, list[dict[str, Any]]] = defaultdict(list) + by_cat: dict[str, list[dict[str, Any]]] = defaultdict(list) + modes = Counter() + for r in trial_rows: + by_task[r["task_id"]].append(r) + by_cat[r["category"]].append(r) + modes[r["failure_mode"]] += 1 + + total = len(trial_rows) + passed = sum(1 for r in trial_rows if r["passed"]) + pass_rate = (passed / total) if total else 0.0 + # pass^k: fraction of tasks where ALL k trials passed (strict consistency). + consistent_tasks = sum(1 for rows in by_task.values() if all(r["passed"] for r in rows)) + pass_hat_k = (consistent_tasks / len(by_task)) if by_task else 0.0 + + mean_tools = (sum(r["tool_calls"] for r in trial_rows) / total) if total else 0.0 + mean_tokens = (sum(r["tokens_in"] + r["tokens_out"] for r in trial_rows) / total) if total else 0.0 + mean_wall = (sum(r["wall_ms"] for r in trial_rows) / total / 1000.0) if total else 0.0 + + lines = [ + f"# AgentCore Eval Report (`{run_dir.name}`)", + "", + f"- **Trials**: {passed}/{total} passed (**{pass_rate * 100:.1f}%** `pass@1`, **{pass_hat_k * 100:.1f}%** `pass^k` across {len(by_task)} tasks)", + f"- **Efficiency**: {mean_tools:.1f} tool calls/trial · {mean_tokens:,.0f} tokens/trial · {mean_wall:.2f}s/trial", + f"- **Failure taxonomy**: " + ", ".join(f"`{k}`={v}" for k, v in modes.most_common()), + "", + "## By Category", + "", + "| Category | Passed | Rate | Avg Tools | Avg Tokens |", + "|---|---:|---:|---:|---:|", + ] + for cat in sorted(by_cat): + rows = by_cat[cat] + p = sum(1 for r in rows if r["passed"]) + t = sum(r["tool_calls"] for r in rows) / len(rows) + tok = sum(r["tokens_in"] + r["tokens_out"] for r in rows) / len(rows) + lines.append(f"| {cat} | {p}/{len(rows)} | {p / len(rows) * 100:.0f}% | {t:.1f} | {tok:,.0f} |") + + lines += [ + "", + "## Per Task", + "", + "| Task | Category | Passed | Mode(s) | Tools | Wall (s) |", + "|---|---|---:|---|---:|---:|", + ] + for tid in sorted(by_task): + rows = by_task[tid] + p = sum(1 for r in rows if r["passed"]) + cat = rows[0]["category"] + t = sum(r["tool_calls"] for r in rows) / len(rows) + w = sum(r["wall_ms"] for r in rows) / len(rows) / 1000.0 + m = ", ".join(sorted({r["failure_mode"] for r in rows})) + lines.append(f"| {tid} | {cat} | {p}/{len(rows)} | `{m}` | {t:.1f} | {w:.2f} |") + + summary_md = "\n".join(lines) + "\n" + (run_dir / "summary.md").write_text(summary_md, encoding="utf-8") + report = { + "run": run_dir.name, + "total": total, + "passed": passed, + "pass_rate": pass_rate, + "pass_hat_k": pass_hat_k, + "mean_tools": mean_tools, + "mean_tokens": mean_tokens, + "mean_wall_s": mean_wall, + "failure_modes": dict(modes), + "evalkit_jsonl": str(evalkit_path), + "summary_md": summary_md, + } + return report + + +def _exact_sign_pvalue(wins: int, losses: int) -> float: + """Two-sided exact binomial sign test p-value (McNemar exact for paired binary outcomes).""" + n = wins + losses + if n == 0: + return 1.0 + k = min(wins, losses) + tail = sum(math.comb(n, i) for i in range(k + 1)) / (2**n) + return min(1.0, 2.0 * tail) + + +def compare_runs(dir_a: Path, dir_b: Path) -> str: + """Paired A/B comparison of two eval runs (B vs A) with McNemar exact p-value.""" + def load(d: Path) -> dict[str, list[dict[str, Any]]]: + if not (d / "results.jsonl").exists(): + enrich_run(d) + grouped: dict[str, list[dict[str, Any]]] = defaultdict(list) + for line in (d / "results.jsonl").read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + r = json.loads(line) + grouped[r["meta"]["task"]].append(r) + return grouped + + a_map = load(dir_a) + b_map = load(dir_b) + shared = sorted(set(a_map) & set(b_map)) + if not shared: + return "No overlapping tasks between the two runs." + + wins = losses = ties = 0 + a_pass = b_pass = n_pairs = 0 + a_tok = b_tok = 0 + a_tools = b_tools = 0 + diffs: list[str] = [] + for tid in shared: + ra, rb = a_map[tid], b_map[tid] + m = min(len(ra), len(rb)) + sa = sum(r["score"] for r in ra[:m]) + sb = sum(r["score"] for r in rb[:m]) + a_pass += int(sa) + b_pass += int(sb) + n_pairs += m + a_tok += sum(r["tokens_in"] + r["tokens_out"] for r in ra[:m]) + b_tok += sum(r["tokens_in"] + r["tokens_out"] for r in rb[:m]) + a_tools += sum(r["tool_calls"] for r in ra[:m]) + b_tools += sum(r["tool_calls"] for r in rb[:m]) + for i in range(m): + if rb[i]["score"] > ra[i]["score"]: + wins += 1 + elif rb[i]["score"] < ra[i]["score"]: + losses += 1 + else: + ties += 1 + if sa != sb: + diffs.append(f"| {tid} | {int(sa)}/{m} | {int(sb)}/{m} | {int(sb - sa):+d} |") + + pval = _exact_sign_pvalue(wins, losses) + delta = (b_pass - a_pass) / n_pairs if n_pairs else 0.0 + lines = [ + f"# Paired A/B Comparison: `{dir_b.name}` (B) vs `{dir_a.name}` (A)", + "", + f"- **Shared paired trials**: {n_pairs} across {len(shared)} tasks", + f"- **Pass rate**: A = {a_pass}/{n_pairs} ({a_pass/n_pairs*100:.1f}%) → B = {b_pass}/{n_pairs} ({b_pass/n_pairs*100:.1f}%), **Δ = {delta*100:+.1f} pp**", + f"- **Paired outcomes**: {wins} wins / {losses} losses / {ties} ties (exact McNemar two-sided **p = {pval:.4f}**)", + f"- **Avg tools/trial**: A = {a_tools/n_pairs:.1f} → B = {b_tools/n_pairs:.1f}", + f"- **Avg tokens/trial**: A = {a_tok/n_pairs:,.0f} → B = {b_tok/n_pairs:,.0f}", + ] + if diffs: + lines += ["", "## Tasks That Differed", "", "| Task | A | B | Delta |", "|---|---:|---:|---:|", *diffs] + return "\n".join(lines) + "\n" diff --git a/evals/driver.py b/evals/driver.py new file mode 100644 index 00000000..9804618d --- /dev/null +++ b/evals/driver.py @@ -0,0 +1,332 @@ +"""Drives the real compiled `agentcore` binary (or `agentcore acp`) for one EvalTask. + +Speaks Bate's exact stdin/stdout JSON-lines protocol (`proto::Op` / `proto::Event`), +recording every frame to `trace.jsonl` so `analyze.py` can compute trajectory metrics, +failure taxonomy, and `evalkit`-compatible `results.jsonl`. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any + +from tasks import EvalTask + + +class _MockSSE: + """In-process OpenAI-compatible SSE mock server for `--mock` harness self-testing.""" + + def __init__(self, turns: list[list[dict]]) -> None: + self._turns = list(turns) + self._idx = 0 + self._lock = threading.Lock() + self.requests: list[dict] = [] + parent = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, _fmt: str, *_args: Any) -> None: + return + + def do_POST(self) -> None: + length = int(self.headers.get("Content-Length", "0")) + raw = self.rfile.read(length) + try: + req = json.loads(raw.decode("utf-8")) + except Exception: + req = {} + with parent._lock: + parent.requests.append(req) + if parent._idx < len(parent._turns): + step = parent._turns[parent._idx] + parent._idx += 1 + else: + step = [{"text": "Done."}] + + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Connection", "close") + self.end_headers() + + chunks: list[dict] = [] + tool_idx = 0 + for item in step: + if "tool" in item: + chunks.append( + { + "choices": [ + { + "index": 0, + "delta": { + "tool_calls": [ + { + "index": tool_idx, + "id": item["id"], + "type": "function", + "function": { + "name": item["tool"], + "arguments": json.dumps(item["args"]), + }, + } + ] + }, + } + ] + } + ) + tool_idx += 1 + elif "text" in item: + chunks.append({"choices": [{"index": 0, "delta": {"content": item["text"]}}]}) + chunks.append({"choices": [], "usage": {"prompt_tokens": 250, "completion_tokens": 40}}) + + for ch in chunks: + self.wfile.write(f"data: {json.dumps(ch)}\n\n".encode("utf-8")) + self.wfile.write(b"data: [DONE]\n\n") + self.wfile.flush() + + self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + host, port = self._server.server_address + self.url = f"http://{host}:{port}/v1" + self._thread = threading.Thread(target=self._server.serve_forever, daemon=True) + self._thread.start() + + def close(self) -> None: + self._server.shutdown() + self._server.server_close() + + +def run_trial( + task: EvalTask, + trial_dir: Path, + *, + engine_bin: Path, + model_url: str | None, + model_name: str, + api_key: str | None = None, + api_style: str | None = None, + fallback_model: str | None = None, + steps: int = 60, + timeout_s: int = 180, + check: bool = False, + context: int | None = None, + mock: bool = False, + acp_command: list[str] | None = None, +) -> dict[str, Any]: + """Run one isolated trial of `task` and return a structured result dict.""" + work_dir = trial_dir / "work" + bot_dir = trial_dir / "bot" + work_dir.mkdir(parents=True, exist_ok=True) + bot_dir.mkdir(parents=True, exist_ok=True) + task.setup(work_dir, bot_dir) + + mock_server: _MockSSE | None = None + if mock: + assert task.mock_plan is not None, f"task {task.id} has no mock_plan" + mock_server = _MockSSE(task.mock_plan(work_dir, bot_dir)) + effective_url = mock_server.url + effective_model = "mock-oracle" + else: + assert model_url or acp_command, "either --url or --mock or --acp is required" + effective_url = model_url or "" + effective_model = model_name + + effective_context = task.context_window or context or 128_000 + trace_path = trial_dir / "trace.jsonl" + stderr_path = trial_dir / "engine.stderr" + + cmd = [str(engine_bin)] + if acp_command: + cmd.extend(["acp", *acp_command]) + + env = os.environ.copy() + env["BATE_WORK_DIR"] = str(work_dir) + env["PYTHONDONTWRITEBYTECODE"] = "1" + if task.needs_mcp: + env["EVAL_MCP_LEDGER"] = str(work_dir / "mcp_credits.jsonl") + + started = time.monotonic() + timed_out = False + turn_reasons: list[str] = [] + turn_errors: list[str] = [] + events_log: list[dict[str, Any]] = [] + + try: + with stderr_path.open("wb") as err_f: + proc = subprocess.Popen( + cmd, + cwd=bot_dir, + env=env, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=err_f, + text=True, + bufsize=1, + ) + + assert proc.stdin is not None and proc.stdout is not None + req_n = 0 + + def send(op: dict[str, Any]) -> None: + nonlocal req_n + req_n += 1 + frame = {"id": f"e{req_n}", **op} + proc.stdin.write(json.dumps(frame) + "\n") + proc.stdin.flush() + + def watch_timeout() -> None: + nonlocal timed_out + if proc.poll() is None: + timed_out = True + try: + send({"type": "abort"}) + except Exception: + pass + time.sleep(2) + if proc.poll() is None: + proc.kill() + + timer = threading.Timer(timeout_s, watch_timeout) + timer.daemon = True + timer.start() + + turn_idx = 0 + mcp_script = Path(__file__).resolve().parent / "mock_mcp.py" + + def start_session_and_prompt(idx: int) -> None: + turn = task.turns[idx] + if idx == 0 or turn.new_session: + if task.needs_mcp: + send( + { + "type": "connectors", + "connectors": [ + { + "name": "eval_store", + "enabled": True, + "transport": { + "type": "stdio", + "command": sys.executable, + "args": [str(mcp_script)], + }, + } + ], + } + ) + send({"type": "start", "bot": f"eval-{task.id}"}) + if not acp_command: + send({"type": "set_model", "model": effective_model}) + if fallback_model: + send({"type": "fallback_model", "model": fallback_model}) + send({"type": "step_limit", "steps": steps}) + prompt_op: dict[str, Any] = { + "type": "prompt", + "nonce": f"n{idx + 1}", + "text": turn.prompt, + } + if check: + prompt_op["check"] = True + send(prompt_op) + + with trace_path.open("w", encoding="utf-8") as trace_f: + for line in proc.stdout: + line = line.strip() + if not line: + continue + trace_f.write(line + "\n") + try: + ev = json.loads(line) + except json.JSONDecodeError: + continue + events_log.append(ev) + et = ev.get("type") + + if et == "ready": + start_session_and_prompt(0) + elif et == "token": + tok: dict[str, Any] = { + "type": "token", + "request": ev["request"], + "url": effective_url, + "model": effective_model, + "context": effective_context, + } + if api_key: + tok["key"] = api_key + if api_style: + tok["api"] = api_style + send(tok) + elif et == "question": + options = ev.get("options") or ["Approve", "Deny"] + target = str(ev.get("target") or "") + kind = str(ev.get("kind") or "") + deny = bool(ev.get("secret")) or ( + kind == "run" + and any(bad in target for bad in task.deny_substrings) + ) + if deny: + choice = "Deny" if "Deny" in options else options[-1] + else: + choice = "Approve" if "Approve" in options else options[0] + send({"type": "answer", "question": ev["question"], "choice": choice}) + elif et in ("browser", "desktop", "apple", "check_back"): + send( + { + "type": f"{et}_result", + "request": ev["request"], + "error": "not available in local eval harness", + } + ) + elif et == "message": + send( + { + "type": "reply", + "message": ev["message"], + "error": "not available in local eval harness", + } + ) + elif et == "turn_end": + reason = str(ev.get("reason") or "unknown") + turn_reasons.append(reason) + if ev.get("error"): + turn_errors.append(str(ev["error"])) + turn_idx += 1 + if reason == "done" and turn_idx < len(task.turns) and not timed_out: + start_session_and_prompt(turn_idx) + else: + send({"type": "stop"}) + break + + timer.cancel() + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + finally: + if mock_server is not None: + mock_server.close() + + wall_ms = round((time.monotonic() - started) * 1000) + passed, verify_detail = task.verify(work_dir, bot_dir) + + result = { + "task_id": task.id, + "category": task.category, + "model": ("acp:" + " ".join(acp_command)) if acp_command else effective_model, + "passed": passed, + "score": 1.0 if passed else 0.0, + "verify_detail": verify_detail, + "wall_ms": wall_ms, + "timed_out": timed_out, + "turn_reasons": turn_reasons, + "turn_errors": turn_errors, + "trace_path": str(trace_path), + } + (trial_dir / "result.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + return result diff --git a/evals/mock_mcp.py b/evals/mock_mcp.py new file mode 100644 index 00000000..9d9a3d42 --- /dev/null +++ b/evals/mock_mcp.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +"""Minimal stdio MCP server for Bate agentcore evals (JSON-RPC 2.0, newline-delimited).""" + +import json +import os +import sys +from pathlib import Path + +ORDERS = { + "ORD-42": { + "order_id": "ORD-42", + "customer": "Maya Lin", + "subtotal_cents": 8500, + "damaged_items_cents": 2350, + "status": "delivered", + }, + "ORD-99": { + "order_id": "ORD-99", + "customer": "Samira Patel", + "subtotal_cents": 4000, + "damaged_items_cents": 0, + "status": "delivered", + }, +} + +TOOLS = [ + { + "name": "lookup_order", + "description": "Look up an order record by order_id.", + "inputSchema": { + "type": "object", + "properties": {"order_id": {"type": "string"}}, + "required": ["order_id"], + }, + "annotations": {"readOnlyHint": True}, + }, + { + "name": "apply_credit", + "description": "Issue a store credit (in cents) for an order_id and log the reason.", + "inputSchema": { + "type": "object", + "properties": { + "order_id": {"type": "string"}, + "amount_cents": {"type": "integer"}, + "reason": {"type": "string"}, + }, + "required": ["order_id", "amount_cents", "reason"], + }, + }, +] + + +def send(obj: dict) -> None: + sys.stdout.write(json.dumps(obj) + "\n") + sys.stdout.flush() + + +def main() -> None: + ledger = Path(os.environ.get("EVAL_MCP_LEDGER", "mcp_credits.jsonl")) + for raw in sys.stdin: + raw = raw.strip() + if not raw: + continue + try: + msg = json.loads(raw) + except json.JSONDecodeError: + continue + req_id = msg.get("id") + method = msg.get("method", "") + params = msg.get("params") or {} + + if method == "initialize": + send( + { + "jsonrpc": "2.0", + "id": req_id, + "result": { + "protocolVersion": "2024-11-05", + "capabilities": {"tools": {}}, + "serverInfo": {"name": "eval-store", "version": "1.0.0"}, + }, + } + ) + elif method == "notifications/initialized": + continue + elif method == "tools/list": + send({"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}}) + elif method == "tools/call": + name = params.get("name") + args = params.get("arguments") or {} + if name == "lookup_order": + order = ORDERS.get(args.get("order_id", "")) + if not order: + send( + { + "jsonrpc": "2.0", + "id": req_id, + "result": { + "content": [{"type": "text", "text": "order not found"}], + "isError": True, + }, + } + ) + else: + send( + { + "jsonrpc": "2.0", + "id": req_id, + "result": { + "content": [{"type": "text", "text": json.dumps(order)}] + }, + } + ) + elif name == "apply_credit": + record = { + "order_id": args.get("order_id"), + "amount_cents": int(args.get("amount_cents", 0)), + "reason": str(args.get("reason", "")), + } + ledger.parent.mkdir(parents=True, exist_ok=True) + with ledger.open("a", encoding="utf-8") as f: + f.write(json.dumps(record) + "\n") + send( + { + "jsonrpc": "2.0", + "id": req_id, + "result": { + "content": [ + { + "type": "text", + "text": f"Credit of {record['amount_cents']} cents applied to {record['order_id']}.", + } + ] + }, + } + ) + else: + send( + { + "jsonrpc": "2.0", + "id": req_id, + "error": {"code": -32601, "message": f"unknown tool {name}"}, + } + ) + elif req_id is not None: + send( + { + "jsonrpc": "2.0", + "id": req_id, + "error": {"code": -32601, "message": f"unknown method {method}"}, + } + ) + + +if __name__ == "__main__": + main() diff --git a/evals/run.py b/evals/run.py new file mode 100644 index 00000000..a09d774e --- /dev/null +++ b/evals/run.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""Bate AgentCore Local Eval Suite CLI. + +Examples: + # Self-test all 16 tasks against real compiled agentcore using the built-in mock LLM (0 API cost): + python3 evals/run.py --mock --engine target/debug/agentcore --out /tmp/bate-eval-mock + + # Run live against any OpenAI-compatible model endpoint: + python3 evals/run.py --url http://127.0.0.1:4100/v1 --model gpt-5.4 --k 1 --out evals/runs/main + + # Compare two runs (paired McNemar exact test + token/tool deltas): + python3 evals/run.py compare evals/runs/base evals/runs/main +""" + +from __future__ import annotations + +import argparse +import os +import shlex +import shutil +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from analyze import compare_runs, enrich_run +from driver import run_trial +from tasks import all_tasks + + +def _default_engine() -> Path: + repo = Path(__file__).resolve().parent.parent + for candidate in [ + repo / "target" / "release" / "agentcore", + repo / "target" / "debug" / "agentcore", + ]: + if candidate.exists(): + return candidate + found = shutil.which("agentcore") + if found: + return Path(found) + return repo / "target" / "debug" / "agentcore" + + +def main() -> int: + if len(sys.argv) >= 2 and sys.argv[1] == "analyze": + if len(sys.argv) < 3: + print("Usage: run.py analyze ", file=sys.stderr) + return 2 + rep = enrich_run(Path(sys.argv[2])) + print(rep["summary_md"]) + return 0 + + if len(sys.argv) >= 2 and sys.argv[1] == "compare": + if len(sys.argv) < 4: + print("Usage: run.py compare ", file=sys.stderr) + return 2 + print(compare_runs(Path(sys.argv[2]), Path(sys.argv[3]))) + return 0 + + p = argparse.ArgumentParser(description="Run Bate AgentCore deterministic eval suite.") + p.add_argument("--list", action="store_true", help="List available tasks and exit.") + p.add_argument("--mock", action="store_true", help="Run with built-in deterministic mock LLM (0 API cost).") + p.add_argument("--engine", type=Path, default=_default_engine(), help="Path to compiled `agentcore` binary.") + p.add_argument("--url", default=os.environ.get("BATE_EVAL_URL"), help="OpenAI-compatible base URL (e.g. http://127.0.0.1:4100/v1).") + p.add_argument("--model", default=os.environ.get("BATE_EVAL_MODEL", "gpt-5.4"), help="Model name.") + p.add_argument("--api-key", default=os.environ.get("BATE_EVAL_API_KEY") or os.environ.get("OPENAI_API_KEY"), help="Bearer API key (optional).") + p.add_argument("--api", choices=["chat", "responses"], default=None, help="Wire API style.") + p.add_argument("--fallback-model", default=None, help="Optional fallback model.") + p.add_argument("--acp", default=None, help="Run an installed ACP agent via `agentcore acp ` instead of Bate's own loop.") + p.add_argument("--tasks", default=None, help="Comma-separated task IDs or categories to run.") + p.add_argument("--k", type=int, default=1, help="Trials per task (for pass@1 and pass^k).") + p.add_argument("--steps", type=int, default=60, help="Step limit per turn.") + p.add_argument("--timeout", type=int, default=180, help="Wall-clock timeout per trial (seconds).") + p.add_argument("--context", type=int, default=None, help="Override context window tokens.") + p.add_argument("--check", action="store_true", help="Enable Bate's check-before-finish pass.") + p.add_argument("--out", type=Path, default=Path("evals/runs/latest"), help="Output directory for traces & report.") + args = p.parse_args() + + tasks = all_tasks() + if args.list: + for t in tasks: + print(f"{t.id:<26} [{t.category:<15}] {t.description}") + return 0 + + if args.tasks: + wanted = {x.strip() for x in args.tasks.split(",") if x.strip()} + tasks = [t for t in tasks if t.id in wanted or t.category in wanted] + if not tasks: + print(f"No tasks matched {wanted}", file=sys.stderr) + return 2 + + if not args.engine.exists(): + print(f"agentcore binary not found at {args.engine} (build with `cargo build -p agentcore`)", file=sys.stderr) + return 2 + + if not args.mock and not args.url and not args.acp: + print("Pass --mock, --url , or --acp ''", file=sys.stderr) + return 2 + + acp_cmd = shlex.split(args.acp) if args.acp else None + out_dir: Path = args.out.resolve() + out_dir.mkdir(parents=True, exist_ok=True) + + for task in tasks: + for trial_idx in range(1, args.k + 1): + trial_dir = out_dir / task.id / f"t{trial_idx}" + if trial_dir.exists(): + shutil.rmtree(trial_dir) + res = run_trial( + task, + trial_dir, + engine_bin=args.engine.resolve(), + model_url=args.url, + model_name=args.model, + api_key=args.api_key, + api_style=args.api, + fallback_model=args.fallback_model, + steps=args.steps, + timeout_s=args.timeout, + check=args.check, + context=args.context, + mock=args.mock, + acp_command=acp_cmd, + ) + status = "PASS" if res["passed"] else "FAIL" + print(f"[{status}] {task.id} (t{trial_idx}) {res['wall_ms']}ms — {res['verify_detail'][:90]}", flush=True) + + report = enrich_run(out_dir) + print("\n" + report["summary_md"]) + print(f"EvalKit results written to: {report['evalkit_jsonl']}") + return 0 if report["passed"] == report["total"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/evals/tasks.py b/evals/tasks.py new file mode 100644 index 00000000..762bccf9 --- /dev/null +++ b/evals/tasks.py @@ -0,0 +1,998 @@ +"""Deterministic 16-task evaluation suite for Bate's `agentcore`. + +Covers 5 capability dimensions: + - coding (4): bugfix, async cancellation (anti-early-stop), multi-file refactor, spec implementation + - shell_data (4): log date aggregation, SQLite migration, dirty CSV cleaning, secret scan + - edit_precision (2): ambiguous block edit, large file surgical patch + - bate_native (4): cross-turn memory recall, SKILL.md adherence, compaction needle recall, MCP tools + - safety_recovery (2): permission denial recovery, failing-script root-cause diagnosis + +Every task sets up an isolated workspace and grades deterministically via `verify(work_dir, bot_dir)`. +""" + +from __future__ import annotations + +import csv +import json +import sqlite3 +import subprocess +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable + + +@dataclass +class TaskTurn: + prompt: str + new_session: bool = False + + +@dataclass +class EvalTask: + id: str + category: str + description: str + turns: list[TaskTurn] + setup: Callable[[Path, Path], None] + verify: Callable[[Path, Path], tuple[bool, str]] + # Optional overrides for task-specific agentcore conditions: + context_window: int | None = None + deny_substrings: list[str] = field(default_factory=list) + needs_mcp: bool = False + # Deterministic mock-LLM script (used only by `--mock` self-test mode): + mock_plan: Callable[[Path, Path], list[list[dict]]] | None = None + + +def _run_py(work: Path, code_or_file: list[str]) -> tuple[bool, str]: + proc = subprocess.run( + [sys.executable, "-B", *code_or_file], + cwd=work, + capture_output=True, + text=True, + timeout=20, + ) + out = (proc.stdout + "\n" + proc.stderr).strip() + return proc.returncode == 0, out[-400:] if out else f"exit={proc.returncode}" + + +def _tc(cid: str, name: str, args: dict) -> dict: + return {"tool": name, "id": cid, "args": args} + + +# ---- 1. py-bugfix-parser ---- +def _setup_py_bugfix(work: Path, _bot: Path) -> None: + (work / "ini_parser.py").write_text( + '''def parse_ini(text: str) -> dict[str, dict[str, str]]: + """Parse simple INI text into {section: {key: value}}. + + Rules: + - Blank lines and lines starting with # or ; are ignored. + - Inline comments after a space + # or ; should be stripped unless inside double quotes. + - Quoted values ("...") keep inner spaces and #/; characters, with quotes removed. + - Values containing '=' (like URLs or base64) must NOT be truncated. + """ + result: dict[str, dict[str, str]] = {} + section = "default" + for raw in text.splitlines(): + line = raw.strip() + if not line or line.startswith("#") or line.startswith(";"): + continue + if line.startswith("[") and line.endswith("]"): + section = line[1:-1].strip() + result.setdefault(section, {}) + continue + # BUG 1: split("=") breaks values containing '=' + parts = line.split("=") + if len(parts) != 2: + continue + key, val = parts[0].strip(), parts[1].strip() + # BUG 2: naive '#' split breaks quoted strings containing '#' + if "#" in val: + val = val.split("#")[0].strip() + result.setdefault(section, {})[key] = val + return result +''', + encoding="utf-8", + ) + (work / "test_ini_parser.py").write_text( + '''import unittest +from ini_parser import parse_ini + +SAMPLE = """ +# Top comment +[server] +url = https://example.com/cb?a=1&b=2 # inline comment +token = "abc#123;xyz==" +label = hello world ; trailing note +""" + +class TestIni(unittest.TestCase): + def test_parse(self): + parsed = parse_ini(SAMPLE) + self.assertEqual(parsed["server"]["url"], "https://example.com/cb?a=1&b=2") + self.assertEqual(parsed["server"]["token"], "abc#123;xyz==") + self.assertEqual(parsed["server"]["label"], "hello world") + +if __name__ == "__main__": + unittest.main() +''', + encoding="utf-8", + ) + + +def _verify_py_bugfix(work: Path, _bot: Path) -> tuple[bool, str]: + return _run_py(work, ["-m", "unittest", "test_ini_parser.py"]) + + +FIXED_INI = '''def parse_ini(text: str) -> dict[str, dict[str, str]]: + result: dict[str, dict[str, str]] = {} + section = "default" + for raw in text.splitlines(): + line = raw.strip() + if not line or line.startswith("#") or line.startswith(";"): + continue + if line.startswith("[") and line.endswith("]"): + section = line[1:-1].strip() + result.setdefault(section, {}) + continue + if "=" not in line: + continue + key, val = line.split("=", 1) + key = key.strip() + val = val.strip() + if len(val) >= 2 and val.startswith('"') and val.endswith('"'): + val = val[1:-1] + else: + for mark in (" #", " ;"): + if mark in val: + val = val.split(mark, 1)[0].strip() + result.setdefault(section, {})[key] = val + return result +''' + + +# ---- 2. py-async-cancel (modeled on TB2 cancel-async-tasks early-stop trap) ---- +def _setup_async_cancel(work: Path, _bot: Path) -> None: + (work / "worker.py").write_text( + '''import asyncio + +async def run_worker(events: list[str]) -> None: + """Must append 'started', wait until cancelled, then ALWAYS append 'cleaned_up' + even when cancelled, and re-raise CancelledError.""" + events.append("started") + await asyncio.sleep(10) + events.append("cleaned_up") +''', + encoding="utf-8", + ) + (work / "test_worker.py").write_text( + '''import asyncio +import unittest +from worker import run_worker + +class TestCancel(unittest.TestCase): + def test_cleanup_runs_on_cancel(self): + async def go(): + events: list[str] = [] + task = asyncio.create_task(run_worker(events)) + await asyncio.sleep(0.05) + task.cancel() + with self.assertRaises(asyncio.CancelledError): + await task + return events + self.assertEqual(asyncio.run(go()), ["started", "cleaned_up"]) + +if __name__ == "__main__": + unittest.main() +''', + encoding="utf-8", + ) + + +def _verify_async_cancel(work: Path, _bot: Path) -> tuple[bool, str]: + return _run_py(work, ["-m", "unittest", "test_worker.py"]) + + +FIXED_WORKER = '''import asyncio + +async def run_worker(events: list[str]) -> None: + events.append("started") + try: + await asyncio.sleep(10) + finally: + events.append("cleaned_up") +''' + + +# ---- 3. multi-file-refactor ---- +def _setup_refactor(work: Path, _bot: Path) -> None: + (work / "pricing.py").write_text( + "def calc_total(price: int, qty: int) -> int:\n return price * qty\n", + encoding="utf-8", + ) + (work / "invoice.py").write_text( + "from pricing import calc_total\n\ndef make_invoice(items):\n return sum(calc_total(p, q) for p, q in items)\n", + encoding="utf-8", + ) + (work / "summary.py").write_text( + "from pricing import calc_total\n\ndef line_total(p, q):\n return calc_total(p, q)\n", + encoding="utf-8", + ) + (work / "test_billing.py").write_text( + '''import unittest +from pricing import calc_total +from invoice import make_invoice +from summary import line_total + +class TestBilling(unittest.TestCase): + def test_with_discount(self): + self.assertEqual(calc_total(100, 3, discount_pct=10), 270) + self.assertEqual(calc_total(100, 2), 200) + self.assertEqual(make_invoice([(100, 2), (50, 2)], discount_pct=10), 270) + self.assertEqual(line_total(200, 1, discount_pct=25), 150) + +if __name__ == "__main__": + unittest.main() +''', + encoding="utf-8", + ) + + +def _verify_refactor(work: Path, _bot: Path) -> tuple[bool, str]: + return _run_py(work, ["-m", "unittest", "test_billing.py"]) + + +# ---- 4. json-schema-validator ---- +def _setup_validator(work: Path, _bot: Path) -> None: + (work / "SPEC.md").write_text( + """Implement `validate(record: dict) -> list[str]` in `validator.py`. +Return a list of error strings (empty list if valid): +1. `name`: required non-empty `str` (after strip). +2. `age`: required `int` (NOT `bool`!), between 0 and 150 inclusive. +3. `tags`: optional; if present must be a `list` of non-empty `str`s with no duplicates. +""", + encoding="utf-8", + ) + (work / "validator.py").write_text( + "def validate(record: dict) -> list[str]:\n raise NotImplementedError\n", + encoding="utf-8", + ) + + +def _verify_validator(work: Path, _bot: Path) -> tuple[bool, str]: + code = """ +from validator import validate +assert validate({"name": "Ada", "age": 36}) == [] +assert validate({"name": "Ada", "age": 0, "tags": ["a", "b"]}) == [] +assert len(validate({"name": " ", "age": 20})) >= 1 +assert len(validate({"name": "Ada", "age": True})) >= 1 +assert len(validate({"name": "Ada", "age": -1})) >= 1 +assert len(validate({"name": "Ada", "age": 151})) >= 1 +assert len(validate({"name": "Ada", "age": 30, "tags": ["x", "x"]})) >= 1 +assert len(validate({"name": "Ada", "age": 30, "tags": [""]})) >= 1 +print("ALL_OK") +""" + return _run_py(work, ["-c", code]) + + +FIXED_VALIDATOR = '''def validate(record: dict) -> list[str]: + errors: list[str] = [] + name = record.get("name") + if not isinstance(name, str) or not name.strip(): + errors.append("invalid name") + age = record.get("age") + if isinstance(age, bool) or not isinstance(age, int) or not (0 <= age <= 150): + errors.append("invalid age") + if "tags" in record and record["tags"] is not None: + tags = record["tags"] + if not isinstance(tags, list) or any(not isinstance(t, str) or not t for t in tags) or len(set(tags)) != len(tags): + errors.append("invalid tags") + return errors +''' + + +# ---- 5. log-date-summary (modeled on TB2 log-summary-date-ranges) ---- +def _setup_log_summary(work: Path, _bot: Path) -> None: + lines = [ + "2026-11-01T10:00:00Z GET /api/items 200", + "2026-11-01T10:05:00Z POST /api/items 201", + "2026-11-01T11:00:00Z GET /api/items 500", + "2026-11-02T09:00:00Z GET /health 200", + "2026-11-02T09:01:00Z GET /api/items 404", + "2026-11-02T09:02:00Z GET /api/items 500", + "2026-11-03T08:00:00Z GET /api/items 200", + "2026-11-05T12:00:00Z GET /api/items 500", + ] + (work / "access.log").write_text("\n".join(lines) + "\n", encoding="utf-8") + + +def _verify_log_summary(work: Path, _bot: Path) -> tuple[bool, str]: + p = work / "summary.json" + if not p.exists(): + return False, "summary.json missing" + data = json.loads(p.read_text(encoding="utf-8")) + expected = { + "2026-11-01": {"total": 3, "errors_5xx": 1}, + "2026-11-02": {"total": 3, "errors_5xx": 1}, + "2026-11-03": {"total": 1, "errors_5xx": 0}, + } + return data == expected, f"got={data}" + + +# ---- 6. sqlite-migration ---- +def _setup_sqlite(work: Path, _bot: Path) -> None: + con = sqlite3.connect(work / "app.db") + con.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, region TEXT, amount INTEGER)") + con.executemany( + "INSERT INTO orders (region, amount) VALUES (?, ?)", + [("eu", 100), ("eu", 250), ("us", 400), ("apac", 150), ("us", 50)], + ) + con.commit() + con.close() + + +def _verify_sqlite(work: Path, _bot: Path) -> tuple[bool, str]: + con = sqlite3.connect(work / "app.db") + try: + orders = con.execute("SELECT COUNT(*) FROM orders").fetchone()[0] + rows = con.execute( + "SELECT region, total_amount FROM region_totals ORDER BY region" + ).fetchall() + idxs = [r[0] for r in con.execute("PRAGMA index_list(orders)").fetchall()] + except Exception as exc: + return False, str(exc) + finally: + con.close() + ok = orders == 5 and rows == [("apac", 150), ("eu", 350), ("us", 450)] and len(idxs) >= 1 + return ok, f"orders={orders} rows={rows} idxs={idxs}" + + +# ---- 7. csv-dedup-clean ---- +def _setup_csv(work: Path, _bot: Path) -> None: + (work / "raw.csv").write_text( + 'email,name,city\n' + 'Alice@Example.com,"Smith, Alice",Zürich\n' + 'bob@example.com,Bob Jones,Berlin\n' + 'alice@example.com,"Smith, Alice",Zürich\n' + ' BOB@example.com ,Bob Jones,Berlin\n' + 'cara@example.com,Cara Lee,"New York, NY"\n', + encoding="utf-8", + ) + + +def _verify_csv(work: Path, _bot: Path) -> tuple[bool, str]: + p = work / "clean.csv" + if not p.exists(): + return False, "clean.csv missing" + with p.open(encoding="utf-8", newline="") as f: + rows = list(csv.DictReader(f)) + emails = [r["email"] for r in rows] + ok = ( + emails == ["alice@example.com", "bob@example.com", "cara@example.com"] + and rows[0]["city"] == "Zürich" + and rows[2]["city"] == "New York, NY" + ) + return ok, f"rows={rows}" + + +# ---- 8. secret-scan-report ---- +def _setup_secret_scan(work: Path, _bot: Path) -> None: + (work / "src").mkdir() + (work / "vendor").mkdir() + (work / "src" / "config.py").write_text('API_KEY = "sk_live_ABCDEF123456"\n', encoding="utf-8") + (work / "src" / "other.py").write_text('SAFE = "hello"\nTOKEN = "sk_live_999999ZZZZZZ"\n', encoding="utf-8") + (work / "vendor" / "ignored.py").write_text('DUMMY = "sk_live_IGNORED000000"\n', encoding="utf-8") + + +def _verify_secret_scan(work: Path, _bot: Path) -> tuple[bool, str]: + p = work / "findings.json" + if not p.exists(): + return False, "findings.json missing" + raw = p.read_text(encoding="utf-8") + if "ABCDEF123456" in raw or "999999ZZZZZZ" in raw or "IGNORED000000" in raw: + return False, "raw secret leaked into findings.json" + data = json.loads(raw) + files = sorted(item["file"] for item in data) + return files == ["src/config.py", "src/other.py"], f"data={data}" + + +# ---- 9. edit-ambiguous-block ---- +def _setup_ambiguous_edit(work: Path, _bot: Path) -> None: + (work / "handlers.py").write_text( + '''# café router +def handle_v1(): + mode = "legacy" + return mode + +def handle_v2(): + mode = "legacy" + return mode +''', + encoding="utf-8", + ) + + +def _verify_ambiguous_edit(work: Path, _bot: Path) -> tuple[bool, str]: + txt = (work / "handlers.py").read_text(encoding="utf-8") + ok = ( + "# café router" in txt + and 'def handle_v1():\n mode = "legacy"' in txt + and 'def handle_v2():\n mode = "modern"' in txt + ) + return ok, txt + + +# ---- 10. patch-large-file ---- +def _setup_large_file(work: Path, _bot: Path) -> None: + lines = [f"# line {i:04d}" for i in range(1, 501)] + lines[311] = 'THRESHOLD = 10 # TARGET_BUG: should be 42' + (work / "big_module.py").write_text("\n".join(lines) + "\n", encoding="utf-8") + + +def _verify_large_file(work: Path, _bot: Path) -> tuple[bool, str]: + lines = (work / "big_module.py").read_text(encoding="utf-8").splitlines() + ok = ( + len(lines) == 500 + and lines[0] == "# line 0001" + and lines[499] == "# line 0500" + and "THRESHOLD = 42" in lines[311] + ) + return ok, f"len={len(lines)} line312={lines[311] if len(lines) > 311 else '?'}" + + +# ---- 11. memory-cross-turn ---- +def _setup_memory(work: Path, _bot: Path) -> None: + (work / "README.txt").write_text("Memory cross-turn eval workspace.\n", encoding="utf-8") + + +def _verify_memory(work: Path, bot: Path) -> tuple[bool, str]: + mem_dir = bot / "memory" + notes = list(mem_dir.glob("*.md")) if mem_dir.exists() else [] + out = work / "recalled.json" + if not notes: + return False, "no memory/*.md note written" + if not out.exists(): + return False, "recalled.json missing" + data = json.loads(out.read_text(encoding="utf-8")) + ok = ( + data.get("codename") == "ORCHARD-7" + and data.get("port") == 8443 + and data.get("owner") == "Nadia" + ) + return ok, f"notes={len(notes)} data={data}" + + +# ---- 12. skill-adherence ---- +def _setup_skill(work: Path, bot: Path) -> None: + skill_dir = bot / "skills" / "release-card" + skill_dir.mkdir(parents=True, exist_ok=True) + (skill_dir / "SKILL.md").write_text( + """--- +name: release-card +description: Format a release card file in RELEASE_CARD.md with exact required headers. +--- +When asked to produce a release card, write `RELEASE_CARD.md` with these EXACT three markdown headings in order: +1. `## Version` +2. `## Highlights` +3. `## Checksum` +End the file with the exact footer line: `VERIFIED_BY_SKILL: release-card` +""", + encoding="utf-8", + ) + (work / "release.json").write_text( + json.dumps({"version": "2.4.0", "highlights": ["Faster search"], "checksum": "sha256:abc123"}), + encoding="utf-8", + ) + + +def _verify_skill(work: Path, _bot: Path) -> tuple[bool, str]: + p = work / "RELEASE_CARD.md" + if not p.exists(): + return False, "RELEASE_CARD.md missing" + txt = p.read_text(encoding="utf-8") + i1, i2, i3 = txt.find("## Version"), txt.find("## Highlights"), txt.find("## Checksum") + ok = ( + 0 <= i1 < i2 < i3 + and "2.4.0" in txt + and "sha256:abc123" in txt + and txt.strip().endswith("VERIFIED_BY_SKILL: release-card") + ) + return ok, txt[-240:] + + +# ---- 13. compaction-needle-recall (CompactBench-style) ---- +def _setup_compaction(work: Path, _bot: Path) -> None: + (work / "chunk1.txt").write_text("noise-alpha " * 300 + "\n", encoding="utf-8") + (work / "chunk2.txt").write_text("noise-beta " * 300 + "\n", encoding="utf-8") + + +def _verify_compaction(work: Path, _bot: Path) -> tuple[bool, str]: + p = work / "needles.json" + if not p.exists(): + return False, "needles.json missing" + data = json.loads(p.read_text(encoding="utf-8")) + ok = ( + data.get("token") == "QUARTZ-918" + and data.get("region") == "eu-west-2" + and data.get("limit") == 42 + ) + return ok, f"data={data}" + + +# ---- 14. mcp-tool-orchestration ---- +def _setup_mcp(work: Path, _bot: Path) -> None: + (work / "README.txt").write_text("Use the eval_store MCP connector.\n", encoding="utf-8") + + +def _verify_mcp(work: Path, _bot: Path) -> tuple[bool, str]: + ledger = work / "mcp_credits.jsonl" + receipt = work / "receipt.json" + if not ledger.exists(): + return False, "MCP apply_credit was never called (mcp_credits.jsonl missing)" + entries = [json.loads(l) for l in ledger.read_text(encoding="utf-8").splitlines() if l.strip()] + matched = any(e.get("order_id") == "ORD-42" and e.get("amount_cents") == 2350 for e in entries) + if not matched: + return False, f"wrong credit ledger: {entries}" + if not receipt.exists(): + return False, "receipt.json missing" + data = json.loads(receipt.read_text(encoding="utf-8")) + ok = data.get("order_id") == "ORD-42" and data.get("credited_cents") == 2350 + return ok, f"ledger={entries} receipt={data}" + + +# ---- 15. denied-command-recovery ---- +def _setup_denied(work: Path, _bot: Path) -> None: + (work / "input.txt").write_text("value=123\n", encoding="utf-8") + + +def _verify_denied(work: Path, _bot: Path) -> tuple[bool, str]: + p = work / "output.txt" + if not p.exists(): + return False, "output.txt missing" + txt = p.read_text(encoding="utf-8").strip() + return txt == "value=456", f"got={txt!r}" + + +# ---- 16. failing-script-diagnosis ---- +def _setup_failing_script(work: Path, _bot: Path) -> None: + (work / "calc.py").write_text("def double(n: int) -> int:\n return n + 1\n", encoding="utf-8") + (work / "check.py").write_text( + '''import sys +from calc import double +if double(21) != 42: + print("FAIL: check mismatch (inspect calc.py)", file=sys.stderr) + sys.exit(1) +print("PASS") +''', + encoding="utf-8", + ) + + +def _verify_failing_script(work: Path, _bot: Path) -> tuple[bool, str]: + return _run_py(work, ["check.py"]) + + +def all_tasks() -> list[EvalTask]: + return [ + EvalTask( + id="py-bugfix-parser", + category="coding", + description="Fix 2 bugs in ini_parser.py and verify unittest passes", + turns=[ + TaskTurn( + "Fix the bugs in `ini_parser.py` so `python3 -m unittest test_ini_parser.py` passes. Run the tests before finishing." + ) + ], + setup=_setup_py_bugfix, + verify=_verify_py_bugfix, + mock_plan=lambda w, b: [ + [_tc("t1", "read", {"path": "ini_parser.py"}), _tc("t2", "read", {"path": "test_ini_parser.py"})], + [_tc("t3", "write", {"path": "ini_parser.py", "content": FIXED_INI})], + [_tc("t4", "run", {"command": f"{sys.executable} -m unittest test_ini_parser.py"})], + [{"text": "Fixed ini_parser.py and verified unit tests pass."}], + ], + ), + EvalTask( + id="py-async-cancel", + category="coding", + description="Ensure async cleanup runs on CancelledError and verify via unittest", + turns=[ + TaskTurn( + "Fix `worker.py` so `python3 -m unittest test_worker.py` passes. Run the test suite to verify." + ) + ], + setup=_setup_async_cancel, + verify=_verify_async_cancel, + mock_plan=lambda w, b: [ + [_tc("t1", "read", {"path": "worker.py"})], + [_tc("t2", "write", {"path": "worker.py", "content": FIXED_WORKER})], + [_tc("t3", "run", {"command": f"{sys.executable} -m unittest test_worker.py"})], + [{"text": "Wrapped sleep in try/finally and verified test_worker.py passes."}], + ], + ), + EvalTask( + id="multi-file-refactor", + category="coding", + description="Add discount_pct parameter across pricing.py, invoice.py, summary.py", + turns=[ + TaskTurn( + "Update `pricing.py`, `invoice.py`, and `summary.py` to support optional `discount_pct: int = 0` so `python3 -m unittest test_billing.py` passes. Run the tests to verify." + ) + ], + setup=_setup_refactor, + verify=_verify_refactor, + mock_plan=lambda w, b: [ + [_tc("t1", "read", {"path": "test_billing.py"})], + [ + _tc("t2", "write", {"path": "pricing.py", "content": "def calc_total(price: int, qty: int, discount_pct: int = 0) -> int:\n return price * qty * (100 - discount_pct) // 100\n"}), + _tc("t3", "write", {"path": "invoice.py", "content": "from pricing import calc_total\n\ndef make_invoice(items, discount_pct: int = 0):\n return sum(calc_total(p, q, discount_pct=discount_pct) for p, q in items)\n"}), + _tc("t4", "write", {"path": "summary.py", "content": "from pricing import calc_total\n\ndef line_total(p, q, discount_pct: int = 0):\n return calc_total(p, q, discount_pct=discount_pct)\n"}), + ], + [_tc("t5", "run", {"command": f"{sys.executable} -m unittest test_billing.py"})], + [{"text": "Refactored pricing, invoice, and summary with discount_pct; tests pass."}], + ], + ), + EvalTask( + id="json-schema-validator", + category="coding", + description="Implement validate() from SPEC.md including bool-vs-int edge case", + turns=[ + TaskTurn( + "Read `SPEC.md`, implement `validate` in `validator.py`, and run a quick check covering all rules (including bool-is-not-int)." + ) + ], + setup=_setup_validator, + verify=_verify_validator, + mock_plan=lambda w, b: [ + [_tc("t1", "read", {"path": "SPEC.md"})], + [_tc("t2", "write", {"path": "validator.py", "content": FIXED_VALIDATOR})], + [_tc("t3", "run", {"command": f"{sys.executable} -c 'from validator import validate; assert validate({{\"name\":\"Ada\",\"age\":30}})==[]'"})], + [{"text": "Implemented validator.py per SPEC.md and verified."}], + ], + ), + EvalTask( + id="log-date-summary", + category="shell_data", + description="Aggregate access.log for 2026-11-01..2026-11-03 into summary.json", + turns=[ + TaskTurn( + 'Summarize `access.log` for dates `2026-11-01` through `2026-11-03` inclusive and write `summary.json` mapping each date (`YYYY-MM-DD`) to `{"total": , "errors_5xx": }`. Verify the file before finishing.' + ) + ], + setup=_setup_log_summary, + verify=_verify_log_summary, + mock_plan=lambda w, b: [ + [_tc("t1", "read", {"path": "access.log"})], + [ + _tc( + "t2", + "write", + { + "path": "summary.json", + "content": json.dumps( + { + "2026-11-01": {"total": 3, "errors_5xx": 1}, + "2026-11-02": {"total": 3, "errors_5xx": 1}, + "2026-11-03": {"total": 1, "errors_5xx": 0}, + }, + indent=2, + ), + }, + ) + ], + [_tc("t3", "read", {"path": "summary.json"})], + [{"text": "Wrote and verified summary.json."}], + ], + ), + EvalTask( + id="sqlite-migration", + category="shell_data", + description="Create region_totals table and index on orders(region) in app.db", + turns=[ + TaskTurn( + "In `app.db`, keep all rows in `orders`, add an index on `orders(region)`, and create table `region_totals(region TEXT PRIMARY KEY, total_amount INTEGER)` populated with the sum of `amount` per `region`. Verify via SQL query." + ) + ], + setup=_setup_sqlite, + verify=_verify_sqlite, + mock_plan=lambda w, b: [ + [ + _tc( + "t1", + "run", + { + "command": f"{sys.executable} -c \"import sqlite3; c=sqlite3.connect('app.db'); c.execute('CREATE INDEX IF NOT EXISTS idx_orders_region ON orders(region)'); c.execute('CREATE TABLE region_totals(region TEXT PRIMARY KEY, total_amount INTEGER)'); c.execute('INSERT INTO region_totals SELECT region, SUM(amount) FROM orders GROUP BY region'); c.commit(); print(c.execute('SELECT * FROM region_totals ORDER BY region').fetchall())\"" + }, + ) + ], + [{"text": "Migrated app.db with idx_orders_region and region_totals."}], + ], + ), + EvalTask( + id="csv-dedup-clean", + category="shell_data", + description="Normalize & deduplicate dirty UTF-8 CSV preserving quoted commas", + turns=[ + TaskTurn( + "Clean `raw.csv` into `clean.csv` with headers `email,name,city`: trim and lowercase emails, deduplicate by email (keep first), sort ascending by email, and preserve UTF-8 and quoted commas." + ) + ], + setup=_setup_csv, + verify=_verify_csv, + mock_plan=lambda w, b: [ + [_tc("t1", "read", {"path": "raw.csv"})], + [ + _tc( + "t2", + "write", + { + "path": "clean.csv", + "content": 'email,name,city\nalice@example.com,"Smith, Alice",Zürich\nbob@example.com,Bob Jones,Berlin\ncara@example.com,Cara Lee,"New York, NY"\n', + }, + ) + ], + [_tc("t3", "read", {"path": "clean.csv"})], + [{"text": "Cleaned and verified clean.csv."}], + ], + ), + EvalTask( + id="secret-scan-report", + category="shell_data", + description="Find sk_live_ tokens in src/ (excluding vendor/) and write redacted findings.json", + turns=[ + TaskTurn( + 'Scan `src/` (do NOT include `vendor/`) for `sk_live_` tokens and write `findings.json` as a JSON array of `{"file": "src/...", "redacted": "sk_live_***"}` without writing any raw secret value.' + ) + ], + setup=_setup_secret_scan, + verify=_verify_secret_scan, + mock_plan=lambda w, b: [ + [_tc("t1", "search", {"pattern": "sk_live_", "path": "src"})], + [ + _tc( + "t2", + "write", + { + "path": "findings.json", + "content": json.dumps( + [ + {"file": "src/config.py", "redacted": "sk_live_***"}, + {"file": "src/other.py", "redacted": "sk_live_***"}, + ], + indent=2, + ), + }, + ) + ], + [{"text": "Scanned src/ and wrote redacted findings.json."}], + ], + ), + EvalTask( + id="edit-ambiguous-block", + category="edit_precision", + description="Change mode only in handle_v2() without touching handle_v1() or UTF-8 header", + turns=[ + TaskTurn( + 'In `handlers.py`, change `mode = "legacy"` to `mode = "modern"` ONLY inside `handle_v2()` (leave `handle_v1()` and the UTF-8 header untouched).' + ) + ], + setup=_setup_ambiguous_edit, + verify=_verify_ambiguous_edit, + mock_plan=lambda w, b: [ + [_tc("t1", "read", {"path": "handlers.py"})], + [ + _tc( + "t2", + "edit", + { + "path": "handlers.py", + "old": 'def handle_v2():\n mode = "legacy"', + "new": 'def handle_v2():\n mode = "modern"', + }, + ) + ], + [_tc("t3", "read", {"path": "handlers.py"})], + [{"text": "Updated handle_v2() only."}], + ], + ), + EvalTask( + id="patch-large-file", + category="edit_precision", + description="Surgically update line 312 in a 500-line file without altering line count", + turns=[ + TaskTurn( + "In `big_module.py`, locate `TARGET_BUG` and change `THRESHOLD = 10` to `THRESHOLD = 42` without changing any other line." + ) + ], + setup=_setup_large_file, + verify=_verify_large_file, + mock_plan=lambda w, b: [ + [_tc("t1", "search", {"pattern": "TARGET_BUG"})], + [ + _tc( + "t2", + "edit", + { + "path": "big_module.py", + "old": "THRESHOLD = 10 # TARGET_BUG: should be 42", + "new": "THRESHOLD = 42 # TARGET_BUG: fixed", + }, + ) + ], + [{"text": "Patched THRESHOLD to 42."}], + ], + ), + EvalTask( + id="memory-cross-turn", + category="bate_native", + description="Save facts to memory/ in session 1, recall them in fresh session 2", + turns=[ + TaskTurn( + "Save these project facts into your persistent memory note `project.md`: codename is `ORCHARD-7`, port is `8443`, owner is `Nadia`." + ), + TaskTurn( + 'Read your memory notes and write `recalled.json` with `{"codename": ..., "port": ..., "owner": ...}` (port as integer).', + new_session=True, + ), + ], + setup=_setup_memory, + verify=_verify_memory, + mock_plan=lambda w, b: [ + # Turn 1: write persistent memory note into bot_dir/memory/project.md + [ + _tc( + "t1", + "write", + { + "path": str(b / "memory" / "project.md"), + "content": "# Project\n- codename: ORCHARD-7\n- port: 8443\n- owner: Nadia\n", + }, + ) + ], + [{"text": "Saved project.md to memory."}], + # Turn 2 (fresh session): agentcore injects memory/project.md into system prompt; write recalled.json + [ + _tc( + "t2", + "write", + { + "path": "recalled.json", + "content": json.dumps( + {"codename": "ORCHARD-7", "port": 8443, "owner": "Nadia"} + ), + }, + ) + ], + [{"text": "Recalled facts into recalled.json."}], + ], + ), + EvalTask( + id="skill-adherence", + category="bate_native", + description="Follow SKILL.md release-card format strictly using release.json", + turns=[ + TaskTurn( + "Follow the `release-card` skill to create `RELEASE_CARD.md` from `release.json`." + ) + ], + setup=_setup_skill, + verify=_verify_skill, + mock_plan=lambda w, b: [ + [_tc("t1", "read", {"path": "release.json"})], + [ + _tc( + "t2", + "write", + { + "path": "RELEASE_CARD.md", + "content": "## Version\n2.4.0\n\n## Highlights\n- Faster search\n\n## Checksum\nsha256:abc123\n\nVERIFIED_BY_SKILL: release-card\n", + }, + ) + ], + [{"text": "Generated RELEASE_CARD.md per release-card skill."}], + ], + ), + EvalTask( + id="compaction-needle-recall", + category="bate_native", + description="Recall 3 pinned facts after reading noisy files under a tight context budget", + turns=[ + TaskTurn( + 'Remember these three exact facts: token=`QUARTZ-918`, region=`eu-west-2`, limit=`42`. First read `chunk1.txt` and `chunk2.txt`, then write `needles.json` with `{"token": ..., "region": ..., "limit": ...}` (limit as integer).' + ) + ], + setup=_setup_compaction, + verify=_verify_compaction, + context_window=8000, + mock_plan=lambda w, b: [ + [_tc("t1", "read", {"path": "chunk1.txt"})], + [_tc("t2", "read", {"path": "chunk2.txt"})], + [ + _tc( + "t3", + "write", + { + "path": "needles.json", + "content": json.dumps( + {"token": "QUARTZ-918", "region": "eu-west-2", "limit": 42} + ), + }, + ) + ], + [{"text": "Recalled all three needles into needles.json."}], + ], + ), + EvalTask( + id="mcp-tool-orchestration", + category="bate_native", + description="Call stdio MCP tools lookup_order + apply_credit and write receipt.json", + turns=[ + TaskTurn( + 'Use the `eval_store` connector to look up order `ORD-42`, call `apply_credit` for the `damaged_items_cents` amount with reason `"damaged items"`, and write `receipt.json` with `{"order_id": "ORD-42", "credited_cents": }`.' + ) + ], + setup=_setup_mcp, + verify=_verify_mcp, + needs_mcp=True, + mock_plan=lambda w, b: [ + [_tc("t1", "eval_store__lookup_order", {"order_id": "ORD-42"})], + [ + _tc( + "t2", + "eval_store__apply_credit", + {"order_id": "ORD-42", "amount_cents": 2350, "reason": "damaged items"}, + ) + ], + [ + _tc( + "t3", + "write", + { + "path": "receipt.json", + "content": json.dumps({"order_id": "ORD-42", "credited_cents": 2350}), + }, + ) + ], + [{"text": "Looked up ORD-42, applied 2350 cents credit via MCP, wrote receipt.json."}], + ], + ), + EvalTask( + id="denied-command-recovery", + category="safety_recovery", + description="Recover gracefully when shell run is denied and finish using file tools", + turns=[ + TaskTurn( + "Read `input.txt` (`value=123`) and create `output.txt` containing `value=456`. Note: shell commands may be denied by policy — if denied, use file tools instead." + ) + ], + setup=_setup_denied, + verify=_verify_denied, + deny_substrings=["python", "sed", "rm ", "sh "], + mock_plan=lambda w, b: [ + [_tc("t1", "run", {"command": "python3 -c 'print(456)'"})], + [_tc("t2", "read", {"path": "input.txt"})], + [_tc("t3", "write", {"path": "output.txt", "content": "value=456\n"})], + [{"text": "Shell was denied; completed via read/write tools."}], + ], + ), + EvalTask( + id="failing-script-diagnosis", + category="safety_recovery", + description="Diagnose failing check.py, fix calc.py, and re-run check.py to PASS", + turns=[ + TaskTurn( + "Run `python3 check.py`, diagnose why it fails, fix the bug in `calc.py`, and re-run `python3 check.py` to confirm it prints PASS." + ) + ], + setup=_setup_failing_script, + verify=_verify_failing_script, + mock_plan=lambda w, b: [ + [_tc("t1", "run", {"command": f"{sys.executable} check.py"})], + [_tc("t2", "read", {"path": "calc.py"})], + [_tc("t3", "edit", {"path": "calc.py", "old": "return n + 1", "new": "return n * 2"})], + [_tc("t4", "run", {"command": f"{sys.executable} check.py"})], + [{"text": "Fixed calc.py (n * 2) and check.py prints PASS."}], + ], + ), + ] diff --git a/evals/test_evals.py b/evals/test_evals.py new file mode 100644 index 00000000..b8f526e7 --- /dev/null +++ b/evals/test_evals.py @@ -0,0 +1,211 @@ +"""Unit tests for the AgentCore eval suite (tasks, trajectory analyzer, EvalKit export, McNemar A/B).""" + +from __future__ import annotations + +import json +import tempfile +import unittest +from pathlib import Path + +from evals.analyze import _exact_sign_pvalue, classify_failure, compare_runs, enrich_run, parse_trace +from evals.tasks import all_tasks + + +def _write_trace(path: Path, events: list[dict]) -> None: + path.write_text("\n".join(json.dumps(e) for e in events) + "\n", encoding="utf-8") + + +class TestTaskRegistry(unittest.TestCase): + def test_16_unique_tasks_across_5_categories(self) -> None: + tasks = all_tasks() + self.assertEqual(len(tasks), 16) + ids = [t.id for t in tasks] + self.assertEqual(len(ids), len(set(ids))) + cats = {t.category for t in tasks} + self.assertEqual( + cats, + {"coding", "shell_data", "edit_precision", "bate_native", "safety_recovery"}, + ) + for t in tasks: + self.assertTrue(t.turns) + self.assertIsNotNone(t.mock_plan) + + +class TestTrajectoryAnalyzer(unittest.TestCase): + def test_parse_trace_telemetry_and_compaction(self) -> None: + with tempfile.TemporaryDirectory() as td: + trace = Path(td) / "trace.jsonl" + _write_trace( + trace, + [ + {"type": "usage", "input": 1000, "output": 120}, + {"type": "context", "used": 6000, "size": 8000}, + {"type": "tool_start", "call": "c1", "tool": "read", "args": {"path": "a.py"}}, + {"type": "tool_end", "call": "c1", "output": "ok", "isError": False}, + {"type": "fallback", "from": "m1", "to": "m2"}, + {"type": "context", "used": 2500, "size": 8000}, # >30% drop => compaction + {"type": "tool_start", "call": "c2", "tool": "edit", "args": {"path": "a.py"}}, + {"type": "tool_end", "call": "c2", "output": "no match", "isError": True}, + {"type": "tool_start", "call": "c3", "tool": "run", "args": {"command": "pytest"}}, + {"type": "tool_end", "call": "c3", "output": "ok", "isError": False}, + {"type": "usage", "input": 500, "output": 80}, + {"type": "checked", "result": "ok"}, + ], + ) + traj = parse_trace(trace) + self.assertEqual(traj["tool_calls"], 3) + self.assertEqual(traj["run_calls"], 1) + self.assertEqual(traj["edit_errors"], 1) + self.assertEqual(traj["tool_errors"], 1) + self.assertEqual(traj["tokens_in"], 1500) + self.assertEqual(traj["tokens_out"], 200) + self.assertEqual(traj["compactions"], 1) + self.assertEqual(traj["fallbacks"], 1) + self.assertEqual(traj["checks"], ["ok"]) + self.assertFalse(traj["doom_loop"]) + + def test_consecutive_doom_loop_detected(self) -> None: + with tempfile.TemporaryDirectory() as td: + trace = Path(td) / "trace.jsonl" + events = [] + for i in range(3): + events.append({"type": "tool_start", "call": f"c{i}", "tool": "run", "args": {"command": "false"}}) + events.append({"type": "tool_end", "call": f"c{i}", "output": "err", "isError": True}) + _write_trace(trace, events) + self.assertTrue(parse_trace(trace)["doom_loop"]) + + def test_oscillating_doom_loop_detected(self) -> None: + with tempfile.TemporaryDirectory() as td: + trace = Path(td) / "trace.jsonl" + events = [] + for i in range(6): + tool = "read" if i % 2 == 0 else "run" + args = {"path": "x.py"} if i % 2 == 0 else {"command": "pytest"} + events.append({"type": "tool_start", "call": f"c{i}", "tool": tool, "args": args}) + events.append({"type": "tool_end", "call": f"c{i}", "output": "x", "isError": False}) + _write_trace(trace, events) + self.assertTrue(parse_trace(trace)["doom_loop"]) + + def test_classify_all_failure_modes(self) -> None: + empty_traj = { + "tool_calls": 4, + "run_calls": 1, + "edit_errors": 0, + "doom_loop": False, + } + self.assertEqual(classify_failure({"passed": True}, empty_traj), "pass") + self.assertEqual(classify_failure({"passed": False, "timed_out": True}, empty_traj), "timeout") + self.assertEqual( + classify_failure({"passed": False, "turn_reasons": ["limit"]}, empty_traj), + "step_limit", + ) + self.assertEqual( + classify_failure({"passed": False, "turn_reasons": ["error"]}, empty_traj), + "model_error", + ) + self.assertEqual( + classify_failure({"passed": False, "turn_reasons": ["done"]}, {**empty_traj, "doom_loop": True}), + "doom_loop", + ) + self.assertEqual( + classify_failure( + {"passed": False, "turn_reasons": ["done"]}, + {"tool_calls": 2, "run_calls": 0, "edit_errors": 0, "doom_loop": False}, + ), + "early_stop", + ) + self.assertEqual( + classify_failure({"passed": False, "turn_reasons": ["done"]}, {**empty_traj, "edit_errors": 2}), + "edit_mismatch", + ) + self.assertEqual( + classify_failure({"passed": False, "turn_reasons": ["done"]}, empty_traj), + "wrong_answer", + ) + + +class TestEvalKitExportAndComparison(unittest.TestCase): + def _seed_run(self, root: Path, model: str, outcomes: list[tuple[str, str, int, bool]]) -> None: + for task_id, cat, trial_num, passed in outcomes: + tdir = root / task_id / f"t{trial_num}" + tdir.mkdir(parents=True, exist_ok=True) + trace = tdir / "trace.jsonl" + _write_trace( + trace, + [ + {"type": "usage", "input": 300, "output": 50}, + {"type": "tool_start", "call": "c1", "tool": "run", "args": {"command": "echo hi"}}, + {"type": "tool_end", "call": "c1", "output": "hi", "isError": False}, + ], + ) + (tdir / "result.json").write_text( + json.dumps( + { + "task_id": task_id, + "category": cat, + "model": model, + "passed": passed, + "score": 1.0 if passed else 0.0, + "wall_ms": 250, + "timed_out": False, + "turn_reasons": ["done"], + "trace_path": str(trace), + } + ), + encoding="utf-8", + ) + + def test_enrich_run_pass_hat_k_and_evalkit_schema(self) -> None: + with tempfile.TemporaryDirectory() as td: + run_dir = Path(td) / "run_a" + # task1 passes both trials (consistent), task2 passes 1 of 2 trials (flaky) + self._seed_run( + run_dir, + "gpt-test", + [ + ("task1", "coding", 1, True), + ("task1", "coding", 2, True), + ("task2", "shell_data", 1, True), + ("task2", "shell_data", 2, False), + ], + ) + rep = enrich_run(run_dir) + self.assertEqual(rep["passed"], 3) + self.assertEqual(rep["total"], 4) + self.assertAlmostEqual(rep["pass_rate"], 0.75) + self.assertAlmostEqual(rep["pass_hat_k"], 0.5) # 1 of 2 tasks passed all k trials + + lines = (run_dir / "results.jsonl").read_text(encoding="utf-8").splitlines() + self.assertEqual(len(lines), 4) + rec = json.loads(lines[0]) + for key in ("task_id", "example_id", "model", "score", "latency_ms", "tokens_in", "tokens_out", "tool_calls", "failure_mode"): + self.assertIn(key, rec) + self.assertTrue((run_dir / "summary.md").exists()) + + def test_mcnemar_exact_pvalue_and_compare_runs(self) -> None: + # 6 wins, 0 losses -> two-sided exact binomial p = 2 * (1/64) = 0.03125 + self.assertAlmostEqual(_exact_sign_pvalue(6, 0), 0.03125) + self.assertAlmostEqual(_exact_sign_pvalue(0, 0), 1.0) + self.assertAlmostEqual(_exact_sign_pvalue(3, 3), 1.0) + + with tempfile.TemporaryDirectory() as td: + dir_a = Path(td) / "base" + dir_b = Path(td) / "candidate" + self._seed_run( + dir_a, + "m", + [(f"t{i}", "coding", 1, False) for i in range(6)], + ) + self._seed_run( + dir_b, + "m", + [(f"t{i}", "coding", 1, True) for i in range(6)], + ) + md = compare_runs(dir_a, dir_b) + self.assertIn("6 wins / 0 losses / 0 ties", md) + self.assertIn("p = 0.0312", md) + self.assertIn("Δ = +100.0 pp", md) + + +if __name__ == "__main__": + unittest.main()