From dca4aa45e0153a68a4ad79c52b26595247b43ea8 Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Tue, 1 Dec 2026 14:00:24 -0500 Subject: [PATCH 1/3] feat(claude): sync claude plugin eval suites to braintrust experiments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > 🤖 **This text was AI-generated.** `claude plugin eval` (https://code.claude.com/docs/en/plugin-evals) scores a plugin by running each case with and without it, but its results stay in a local `aggregate-result.json` and HTML report. Each run's agent session lives in a temporary sandbox that Claude Code deletes when the suite ends, so there was no way to look at those runs or compare suites over time in Braintrust. `bt trace eval claude` runs the suite and, when it finishes, syncs it the way the Braintrust Harbor integration syncs a Harbor job (https://docs.braintrust.dev/integrations/sdk-integrations/harbor): ```bash bt trace eval --project my-evals claude -- ./my-plugin --runs 3 bt trace eval claude --from evals/results/2026-12-01T17-02-11-482Z ``` ```text dataset "claude-plugin-eval · " one record per case experiment " · baseline · ..." no-plugin arm experiment " · with plugin · ..." base experiment = baseline eval (row per run) input = case prompt, output = final reply ├── Claude Code session turns, LLM calls, tool calls ├── [score] 1 or 0 per grader verdict └── run_score [score] the run's weighted score ``` - Because the baseline is the with-plugin experiment's comparison base, Braintrust shows the plugin's effect on every score. `--base-experiment` compares against another experiment instead. - To capture sessions, `bt` passes `--keep-temp`, imports each run's native transcript below its row through the same translator used for live Claude Code tracing, and then deletes the sandboxes it kept. It never passes `--trust-plugin`. - Dataset records, experiments, and rows have IDs derived from the result document, so syncing a result again updates it instead of duplicating it. `--from` backfills existing results. Sessions are included only if their sandboxes still exist. - `--tag` and `--additional-metadata` apply to the experiment rows and the imported traces, like the other `bt trace` commands. Transcript import gains a `find_in_config` lookup so a transcript can be found in a config directory other than the user's, such as an eval run's sandbox. Limitations: there is no `braintrust-sync.json` manifest, no verifier attachments, and no span-plugin flag yet. When `--output-dir` is not passed, results go to a temporary directory whose path is printed. `bt` must bump its pinned `bt-daemon` revision to expose the command. --- .../command_output/trace_command_output.rs | 7 + bt-daemon/src/ids.rs | 2 +- bt-daemon/src/lib.rs | 4 + bt-daemon/src/plugin_eval/claude_result.rs | 359 +++++++++++ bt-daemon/src/plugin_eval/launch.rs | 165 +++++ bt-daemon/src/plugin_eval/mod.rs | 200 ++++++ bt-daemon/src/plugin_eval/output.rs | 76 +++ bt-daemon/src/plugin_eval/plan.rs | 583 ++++++++++++++++++ bt-daemon/src/plugin_eval/sandbox.rs | 204 ++++++ bt-daemon/src/plugin_eval/sync.rs | 320 ++++++++++ bt-daemon/src/plugin_eval/tests.rs | 471 ++++++++++++++ bt-daemon/src/trace_command.rs | 4 +- bt-daemon/src/trace_runtime.rs | 36 ++ bt-daemon/src/transcript_import/claude.rs | 8 +- bt-daemon/src/transcript_import/mod.rs | 18 + .../aggregate-result-2.1.333.json | 244 ++++++++ src/plugins/claude/content/README.md | 45 ++ 17 files changed, 2742 insertions(+), 4 deletions(-) create mode 100644 bt-daemon/src/plugin_eval/claude_result.rs create mode 100644 bt-daemon/src/plugin_eval/launch.rs create mode 100644 bt-daemon/src/plugin_eval/mod.rs create mode 100644 bt-daemon/src/plugin_eval/output.rs create mode 100644 bt-daemon/src/plugin_eval/plan.rs create mode 100644 bt-daemon/src/plugin_eval/sandbox.rs create mode 100644 bt-daemon/src/plugin_eval/sync.rs create mode 100644 bt-daemon/src/plugin_eval/tests.rs create mode 100644 bt-daemon/tests/fixtures/claude-plugin-eval/aggregate-result-2.1.333.json diff --git a/bt-daemon/src/command_output/trace_command_output.rs b/bt-daemon/src/command_output/trace_command_output.rs index 7fd36b65..59440ec4 100644 --- a/bt-daemon/src/command_output/trace_command_output.rs +++ b/bt-daemon/src/command_output/trace_command_output.rs @@ -3,6 +3,7 @@ use super::{ StopCommandOutput, UpdateCommandOutput, }; use crate::wire::StatusResult; +use crate::EvalSyncSummary; use serde::Serialize; use std::path::PathBuf; @@ -21,6 +22,7 @@ pub enum TraceCommandOutput { /// Summaries for the imported sessions. summaries: Vec, }, + Eval(Box), } impl TraceCommandOutput { @@ -114,6 +116,10 @@ impl TraceCommandOutput { Self::Import { summaries } } + pub fn eval(summary: EvalSyncSummary) -> Self { + Self::Eval(Box::new(summary)) + } + pub fn disable( source: impl Into, display_name: impl Into, @@ -169,6 +175,7 @@ impl TraceCommandOutput { .map(ImportSummary::render_human) .collect::>() .join("\n")), + Self::Eval(summary) => Ok(summary.render_human()), } } } diff --git a/bt-daemon/src/ids.rs b/bt-daemon/src/ids.rs index 5bb0cc81..ec34dc21 100644 --- a/bt-daemon/src/ids.rs +++ b/bt-daemon/src/ids.rs @@ -12,7 +12,7 @@ use uuid::Uuid; /// a v4 uuid, pinned as a constant so it never changes across builds). const NAMESPACE: Uuid = Uuid::from_u128(0x8f2b_4e11_9c7a_4d3e_b6a1_5f0c_2d84_71ae); -const SEP: char = '\u{1f}'; // ASCII unit separator; will not appear in ids/keys. +pub(crate) const SEP: char = '\u{1f}'; // ASCII unit separator; will not appear in ids/keys. /// A stable namespace for one agent's native session. Source qualification /// prevents two agents that choose the same native session id from sharing diff --git a/bt-daemon/src/lib.rs b/bt-daemon/src/lib.rs index 10d080ae..6d234674 100644 --- a/bt-daemon/src/lib.rs +++ b/bt-daemon/src/lib.rs @@ -32,6 +32,7 @@ mod managed_run; mod muse; mod pipeline; mod plugin_diagnostics; +mod plugin_eval; pub(crate) mod process; mod route; mod server; @@ -78,6 +79,9 @@ pub use hook_executable::delegate_hook_executable; pub use journal::source_journal_path; pub use managed_run::{run_traced, run_traced_with_host}; pub use plugin_diagnostics::PluginDiagnostic; +pub use plugin_eval::{ + EvalArgs, EvalArm, EvalSource, EvalSyncSummary, SyncedDataset, SyncedExperiment, +}; pub use server::{ braintrust_serve_options, debug_serve_options, run_serve, AuthLease, AuthProvider, AuthResolveReason, ServeOptions, diff --git a/bt-daemon/src/plugin_eval/claude_result.rs b/bt-daemon/src/plugin_eval/claude_result.rs new file mode 100644 index 00000000..ceb18759 --- /dev/null +++ b/bt-daemon/src/plugin_eval/claude_result.rs @@ -0,0 +1,359 @@ +//! The result document written by `claude plugin eval`. +//! +//! `aggregate-result.json` (and `--json` output) is a versioned, camelCase +//! document owned by Claude Code. Only the fields the sync reads are modeled, +//! all optional, so new fields and omitted ones never fail decoding. Types +//! that are logged to Braintrust serialize with snake_case keys. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::io::BufRead; +use std::path::{Path, PathBuf}; + +/// The only result schema version this integration understands. +const SUPPORTED_SCHEMA_VERSION: u64 = 1; + +/// The file name Claude Code writes in its output directory. +pub(crate) const RESULT_FILE_NAME: &str = "aggregate-result.json"; + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct EvalResult { + pub schema_version: Option, + pub claude_version: Option, + pub started_at: Option, + pub duration_seconds: Option, + pub cost_usd: Option, + #[serde(default)] + pub partial: bool, + pub partial_reason: Option, + pub suite: Option, + #[serde(default)] + pub cases: Vec, + pub aggregates: Option, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct Suite { + pub root: Option, + pub ablation: Option, + pub model_override: Option, + pub judge_model: Option, + pub threshold: Option, + #[serde(default)] + pub plugins: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub(crate) struct SuitePlugin { + pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all(deserialize = "camelCase"))] +pub(crate) struct SuiteAggregates { + #[serde(skip_serializing_if = "Option::is_none")] + pub cases_total: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cases_passed: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub overall_score: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub overall_pass_rate: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub mean_delta: Option, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct Case { + pub name: String, + /// The case directory relative to the plugin, such as `evals/greets`. + pub dir: Option, + pub prompt_markdown: Option, + pub model: Option, + pub max_turns: Option, + pub timeout_seconds: Option, + #[serde(default)] + pub graders: Vec, + #[serde(default)] + pub arms: Arms, +} + +impl Case { + /// The stable identity of a case within its suite. Directory names are + /// unique; display names repeat across nested groups. + pub fn key(&self) -> &str { + self.dir.as_deref().unwrap_or(&self.name) + } + + pub fn grader(&self, name: &str) -> Option<&GraderDefinition> { + self.graders.iter().find(|grader| grader.name == name) + } +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub(crate) struct GraderDefinition { + pub name: String, + #[serde(rename = "type", skip_serializing_if = "Option::is_none")] + pub kind: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub weight: Option, + /// Grader options vary by grader type (`regex`, `llm`, `tool_used`, ...) + /// and gain new keys between Claude Code releases. They are logged + /// verbatim as the score span's input, so they stay open-ended. + #[serde(skip_serializing_if = "Option::is_none")] + pub config: Option, +} + +#[derive(Debug, Clone, Default, Deserialize)] +pub(crate) struct Arms { + #[serde(default)] + pub with: Vec, + #[serde(default)] + pub without: Vec, +} + +impl Arms { + pub fn runs(&self, arm: Arm) -> &[Run] { + match arm { + Arm::WithPlugin => &self.with, + Arm::Baseline => &self.without, + } + } +} + +/// One agent run of a case in one arm. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct Run { + pub score: Option, + pub passed: Option, + pub turns: Option, + pub cost_usd: Option, + pub judge_cost_usd: Option, + pub duration_seconds: Option, + pub started_at: Option, + pub error: Option, + /// The run's stream-json session, inside its sandbox. Claude Code deletes + /// the sandbox after the suite unless `--keep-temp` was passed. + pub trace_path: Option, + pub skipped_paid_graders: Option, + pub aborted: Option, + #[serde(default)] + pub graders: Vec, +} + +/// A mock that stopped the run. +#[derive(Debug, Clone, Deserialize)] +pub(crate) struct Aborted { + pub server: Option, + pub tool: Option, + pub reason: Option, +} + +impl Aborted { + pub fn describe(&self) -> String { + let target = [self.server.as_deref(), self.tool.as_deref()] + .into_iter() + .flatten() + .collect::>() + .join("/"); + match (target.is_empty(), self.reason.as_deref()) { + (false, Some(reason)) => format!("aborted by mock {target}: {reason}"), + (false, None) => format!("aborted by mock {target}"), + (true, Some(reason)) => format!("aborted by mock: {reason}"), + (true, None) => "aborted by mock".into(), + } + } +} + +/// One grader's verdict on a run; logged as its score span's output. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all(deserialize = "camelCase"))] +pub(crate) struct GraderResult { + #[serde(skip_serializing)] + pub name: String, + pub passed: Option, + /// Whether the verdict counts toward the run score. Claude Code excludes + /// plugin-fired indicators, such as `tool_used: Skill`, in two-arm runs. + #[serde(skip_serializing_if = "Option::is_none")] + pub scored: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub with_only: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub explanation: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub evidence: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub judge_votes: Option>, +} + +impl EvalResult { + pub fn parse(bytes: &[u8], path: &Path) -> anyhow::Result { + let result: Self = serde_json::from_slice(bytes).map_err(|error| { + anyhow::anyhow!( + "{} is not a claude plugin eval result: {error}", + path.display() + ) + })?; + match result.schema_version { + Some(SUPPORTED_SCHEMA_VERSION) => Ok(result), + Some(version) => anyhow::bail!( + "{} has unsupported claude plugin eval schemaVersion {version}; expected {SUPPORTED_SCHEMA_VERSION}", + path.display() + ), + None => anyhow::bail!( + "{} has no schemaVersion; is it a claude plugin eval result?", + path.display() + ), + } + } + + /// Read a result document, or the one inside a results directory, with + /// the file it came from and its bytes. + pub fn read(path: &Path) -> anyhow::Result<(Self, PathBuf, Vec)> { + let file = if path.is_dir() { + path.join(RESULT_FILE_NAME) + } else { + path.to_path_buf() + }; + let bytes = std::fs::read(&file) + .map_err(|error| anyhow::anyhow!("could not read {}: {error}", file.display()))?; + Ok((Self::parse(&bytes, &file)?, file, bytes)) + } + + /// The plugin under test, when the suite resolved one. + pub fn plugin(&self) -> Option<&SuitePlugin> { + self.suite.as_ref().and_then(|suite| suite.plugins.first()) + } + + pub fn model_override(&self) -> Option<&str> { + self.suite.as_ref()?.model_override.as_deref() + } + + pub fn threshold(&self) -> Option { + self.suite.as_ref()?.threshold + } + + /// One arm's runs with their case and index within the arm. + pub fn arm_runs(&self, arm: Arm) -> impl Iterator { + self.cases.iter().flat_map(move |case| { + case.arms + .runs(arm) + .iter() + .enumerate() + .map(move |(index, run)| (case, index, run)) + }) + } + + /// Every run with its case, arm, and index within that arm. + pub fn runs(&self) -> impl Iterator { + [Arm::WithPlugin, Arm::Baseline] + .into_iter() + .flat_map(move |arm| { + self.arm_runs(arm) + .map(move |(case, index, run)| (case, arm, index, run)) + }) + } + + pub fn has_arm(&self, arm: Arm) -> bool { + self.arm_runs(arm).next().is_some() + } +} + +/// The two arms of an ablation: the plugin loaded, and the no-plugin baseline. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Arm { + WithPlugin, + Baseline, +} + +impl Arm { + /// The arm's key in Claude Code's result document. + pub fn result_key(self) -> &'static str { + match self { + Self::WithPlugin => "with", + Self::Baseline => "without", + } + } + + pub fn label(self) -> &'static str { + match self { + Self::WithPlugin => "with plugin", + Self::Baseline => "baseline", + } + } +} + +impl Serialize for Arm { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.result_key()) + } +} + +/// The records of a run's stream-json session (`trace.jsonl`) that the sync +/// reads. Claude Code adds record types and fields between releases, so +/// everything else is skipped. +#[derive(Debug, Clone, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +enum StreamRecord { + System { + subtype: Option, + session_id: Option, + }, + Result { + session_id: Option, + result: Option, + }, + #[serde(other)] + Other, +} + +/// What a run's stream-json session says about it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct StreamSummary { + pub session_id: Option, + /// The agent's final response text. + pub final_message: Option, +} + +impl StreamSummary { + pub fn read(path: &Path) -> anyhow::Result { + let file = + std::fs::File::open(path).and_then(|file| Self::parse(std::io::BufReader::new(file))); + file.map_err(|error| anyhow::anyhow!("could not read {}: {error}", path.display())) + } + + /// Only `system` and `result` records are decoded; message records, the + /// bulk of a session, are skipped unparsed. Unparseable lines (such as a + /// final record cut off by a timeout) never carry the identity read here. + pub fn parse(reader: impl BufRead) -> std::io::Result { + let mut summary = Self::default(); + for line in reader.lines() { + let line = line?; + if !line.contains(r#""type":"system""#) && !line.contains(r#""type":"result""#) { + continue; + } + match serde_json::from_str::(&line) { + Ok(StreamRecord::System { + subtype, + session_id, + }) if subtype.as_deref() == Some("init") => { + summary.session_id = summary.session_id.or(session_id); + } + Ok(StreamRecord::Result { session_id, result }) => { + summary.session_id = summary.session_id.or(session_id); + if result.is_some() { + summary.final_message = result; + } + } + _ => {} + } + } + Ok(summary) + } +} diff --git a/bt-daemon/src/plugin_eval/launch.rs b/bt-daemon/src/plugin_eval/launch.rs new file mode 100644 index 00000000..e4450ad5 --- /dev/null +++ b/bt-daemon/src/plugin_eval/launch.rs @@ -0,0 +1,165 @@ +//! Launch `claude plugin eval` so its results and agent transcripts survive +//! long enough to sync. + +use super::claude_result::RESULT_FILE_NAME; +use crate::managed_run::ManagedRun; +use crate::{env, subprocess}; +use std::ffi::{OsStr, OsString}; +use std::path::PathBuf; + +/// How an eval invocation was adjusted, and where its results land. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct EvalInvocation { + /// Arguments after `claude plugin eval`. + pub args: Vec, + /// The result document Claude Code writes, when the invocation runs a suite. + pub result_file: Option, + /// Whether this command, not the user, asked Claude Code to keep the run + /// sandboxes, and therefore deletes them after syncing. + pub owns_sandboxes: bool, +} + +impl EvalInvocation { + /// Add `--keep-temp` so each run's native transcript survives the suite, + /// and `--output-dir` when the user did not choose where results go. + /// Authoring (`init`) and help invocations pass through unchanged. The + /// plugin trust prompt is never answered on the user's behalf. + pub fn new(user_args: Vec, default_output_dir: impl FnOnce() -> PathBuf) -> Self { + let passthrough = user_args.first().is_some_and(|arg| arg == "init") + || user_args.iter().any(|arg| arg == "--help" || arg == "-h"); + if passthrough { + return Self { + args: user_args, + result_file: None, + owns_sandboxes: false, + }; + } + let keep_temp = user_args.iter().any(|arg| arg == "--keep-temp"); + let output_dir = option_value(&user_args, "--output-dir").map(PathBuf::from); + let mut args = Vec::new(); + if !keep_temp { + args.push(OsString::from("--keep-temp")); + } + let result_file = match output_dir { + Some(dir) => dir.join(RESULT_FILE_NAME), + None => { + let dir = default_output_dir(); + args.push(OsString::from("--output-dir")); + args.push(dir.clone().into_os_string()); + dir.join(RESULT_FILE_NAME) + } + }; + args.extend(user_args); + Self { + args, + result_file: Some(result_file), + owns_sandboxes: !keep_temp, + } + } +} + +/// The value of `--name VALUE` or `--name=VALUE`. +fn option_value(args: &[OsString], name: &str) -> Option { + let prefix = format!("{name}="); + let mut args = args.iter(); + while let Some(arg) = args.next() { + if arg == name { + return args.next().cloned(); + } + if let Some(value) = arg.to_str().and_then(|arg| arg.strip_prefix(&prefix)) { + return Some(OsString::from(value)); + } + } + None +} + +/// A results directory for invocations that did not choose one. +pub(crate) fn default_output_dir() -> PathBuf { + let stamp = chrono::Utc::now().format("%Y-%m-%dT%H-%M-%S%.3fZ"); + std::env::temp_dir() + .join("bt-claude-plugin-eval") + .join(format!( + "{stamp}-{}", + &uuid::Uuid::new_v4().simple().to_string()[..8] + )) +} + +/// Run `claude plugin eval` in the foreground with inherited stdio. An +/// interrupt reaches Claude Code through the terminal; it writes partial +/// results before exiting, so this waits for it. A second interrupt stops it. +pub(crate) async fn run(invocation: &EvalInvocation) -> anyhow::Result { + // Honor the same executable override as `bt trace run claude`. + let (executable_env, default_executable) = ManagedRun::executable(&crate::agents::Claude); + let executable = + env::var_os(executable_env).unwrap_or_else(|| OsString::from(default_executable)); + let mut command: tokio::process::Command = subprocess::interactive_command(&executable).into(); + command + .args([OsStr::new("plugin"), OsStr::new("eval")]) + .args(&invocation.args); + let mut child = command.spawn().map_err(|error| { + anyhow::anyhow!("failed to launch {}: {error}", executable.to_string_lossy()) + })?; + let mut interrupts = 0; + loop { + tokio::select! { + status = child.wait() => return Ok(status?), + result = tokio::signal::ctrl_c() => { + result?; + interrupts += 1; + if interrupts > 1 { + child.start_kill()?; + return Ok(child.wait().await?); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(values: &[&str]) -> Vec { + values.iter().map(OsString::from).collect() + } + + #[test] + fn injects_keep_temp_and_an_output_directory() { + let invocation = EvalInvocation::new(args(&[".", "--runs", "1"]), || PathBuf::from("/out")); + assert_eq!( + invocation.args, + args(&["--keep-temp", "--output-dir", "/out", ".", "--runs", "1"]) + ); + assert_eq!( + invocation.result_file, + Some(PathBuf::from("/out").join(RESULT_FILE_NAME)) + ); + assert!(invocation.owns_sandboxes); + } + + #[test] + fn honors_user_output_directory_and_kept_sandboxes() { + for user in [ + args(&[".", "--keep-temp", "--output-dir", "results"]), + args(&[".", "--keep-temp", "--output-dir=results"]), + ] { + let invocation = EvalInvocation::new(user.clone(), || unreachable!()); + assert_eq!(invocation.args, user); + assert_eq!( + invocation.result_file, + Some(PathBuf::from("results").join(RESULT_FILE_NAME)) + ); + assert!(!invocation.owns_sandboxes); + } + } + + #[test] + fn authoring_and_help_pass_through() { + for user in [args(&["init", "--bare", "case"]), args(&["--help"])] { + let invocation = EvalInvocation::new(user.clone(), || unreachable!()); + assert_eq!(invocation.args, user); + assert_eq!(invocation.result_file, None); + assert!(!invocation.owns_sandboxes); + } + } +} diff --git a/bt-daemon/src/plugin_eval/mod.rs b/bt-daemon/src/plugin_eval/mod.rs new file mode 100644 index 00000000..2f75e1f2 --- /dev/null +++ b/bt-daemon/src/plugin_eval/mod.rs @@ -0,0 +1,200 @@ +//! Trace a coding agent's plugin eval suite to a Braintrust experiment. +//! +//! `bt trace eval claude` runs `claude plugin eval` and, when it finishes, +//! syncs the suite to Braintrust the way the Harbor integration syncs a job: +//! a dataset of cases, an experiment per ablation arm with one row per run, +//! a score per grader verdict, and each run's agent session imported below +//! its row through the live Claude Code translator. `--from` syncs a result +//! that already exists, and re-syncing a result updates the same rows. + +mod claude_result; +mod launch; +mod output; +mod plan; +mod sandbox; +mod sync; +#[cfg(test)] +mod tests; + +pub use claude_result::Arm as EvalArm; +pub use output::{EvalSyncSummary, SyncedDataset, SyncedExperiment}; + +use crate::args::ImportSource; +use crate::transcript_import::ImportTarget; +use crate::wire::{BackendAuth, SessionRoute}; +use clap::{Args, ValueEnum}; +use claude_result::EvalResult; +use std::ffi::OsString; +use std::path::PathBuf; + +/// Arguments for `bt trace eval`. +#[derive(Debug, Clone, Args)] +#[command(trailing_var_arg = true)] +pub struct EvalArgs { + /// Coding agent whose plugin eval suite to run and sync. + #[arg(value_enum)] + pub source: EvalSource, + /// Sync an existing result instead of running the suite: an + /// `aggregate-result.json`, a `--json` result file, or a results directory. + /// Agent traces are imported only if the suite ran with `--keep-temp`. + #[arg(long, value_name = "PATH")] + pub from: Option, + /// Experiment name prefix (default: the plugin name). + #[arg(long, value_name = "PREFIX")] + pub experiment_prefix: Option, + /// Dataset that receives one record per case (default: + /// `claude-plugin-eval · `). + #[arg(long, value_name = "NAME", conflicts_with = "no_dataset")] + pub dataset: Option, + /// Do not sync cases to a dataset. + #[arg(long)] + pub no_dataset: bool, + /// Experiment the with-plugin experiment is compared to (default: this + /// run's no-plugin baseline experiment). + #[arg(long, value_name = "NAME")] + pub base_experiment: Option, + /// JSON object merged into each experiment's metadata and each imported + /// agent trace's root span metadata. + #[arg(long, env = "BRAINTRUST_ADDITIONAL_METADATA")] + pub additional_metadata: Option, + /// Tag applied to each experiment row and imported agent trace. May be + /// repeated or comma-separated. + #[arg(long = "tag", env = "BRAINTRUST_TAGS", value_delimiter = ',')] + pub tags: Vec, + /// Socket path override for the daemon that imports agent traces. + #[arg(long)] + pub socket: Option, + /// Fail instead of spawning a daemon if none is running. + #[arg(long)] + pub no_spawn: bool, + /// Arguments forwarded to `claude plugin eval`, such as the plugin + /// directory and `--runs`. + #[arg(allow_hyphen_values = true)] + pub eval_args: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] +pub enum EvalSource { + #[value(name = "claude", alias = "claude-code")] + Claude, +} + +impl EvalArgs { + pub(crate) fn validate(&self) -> anyhow::Result<()> { + if self.from.is_some() && !self.eval_args.is_empty() { + anyhow::bail!( + "--from syncs an existing result; do not pass claude plugin eval arguments" + ); + } + Ok(()) + } + + fn plan_options(&self, route: &SessionRoute) -> plan::PlanOptions { + plan::PlanOptions { + experiment_prefix: self.experiment_prefix.clone(), + dataset_name: self.dataset.clone(), + no_dataset: self.no_dataset, + base_experiment: self.base_experiment.clone(), + tags: route.tags.iter().cloned().collect(), + additional_metadata: match &route.additional_metadata { + Some(serde_json::Value::Object(map)) => Some(map.clone()), + _ => None, + }, + } + } +} + +impl EvalSource { + /// The translator for the agent's native session transcripts. + fn transcript_source(self) -> ImportSource { + match self { + Self::Claude => ImportSource::Claude, + } + } +} + +/// The resolved Braintrust destination for an eval sync. The import route +/// carries the project, credentials selection, tags, and metadata. +pub(crate) struct EvalTarget { + pub auth: BackendAuth, + pub import: ImportTarget, +} + +/// The outcome of `bt trace eval`. +pub(crate) struct EvalOutcome { + pub summary: Option, + /// The eval runner's exit status, for runs this command launched. + pub status: Option, +} + +/// Run or read an eval suite and sync it. Arguments are validated by the +/// caller before it resolves credentials. +pub(crate) async fn run_eval(args: EvalArgs, target: EvalTarget) -> anyhow::Result { + let options = args.plan_options(&target.import.route); + let sync_target = sync::SyncTarget { + auth: target.auth, + project: sync::ProjectSelection::from_destination( + target.import.route.destination.as_ref(), + )?, + import: target.import, + transcript_source: args.source.transcript_source(), + }; + if let Some(from) = &args.from { + let document = EvalResult::read(from)?; + let summary = sync_document(args.source, &document, &options, sync_target).await?; + return Ok(EvalOutcome { + summary: Some(summary), + status: None, + }); + } + + let invocation = match args.source { + EvalSource::Claude => { + launch::EvalInvocation::new(args.eval_args, launch::default_output_dir) + } + }; + let status = launch::run(&invocation).await?; + let Some(result_file) = invocation.result_file.as_deref() else { + return Ok(EvalOutcome { + summary: None, + status: Some(status), + }); + }; + if !result_file.exists() { + if status.success() { + anyhow::bail!( + "claude plugin eval wrote no result at {}", + result_file.display() + ); + } + return Ok(EvalOutcome { + summary: None, + status: Some(status), + }); + } + let document = EvalResult::read(result_file)?; + let synced = sync_document(args.source, &document, &options, sync_target).await; + if invocation.owns_sandboxes { + for error in sandbox::remove_all(&sandbox::sandboxes(&document.0)) { + tracing::warn!(%error, "could not delete a claude plugin eval sandbox"); + eprintln!("warning: {error:#}"); + } + } + Ok(EvalOutcome { + summary: Some(synced?), + status: Some(status), + }) +} + +async fn sync_document( + source: EvalSource, + (result, file, bytes): &(EvalResult, PathBuf, Vec), + options: &plan::PlanOptions, + target: sync::SyncTarget, +) -> anyhow::Result { + let plan = plan::SyncPlan::new(result, options, bytes); + let artifacts = match source { + EvalSource::Claude => plan.artifacts(sandbox::run_artifacts), + }; + sync::sync_result(&plan, &artifacts, file, target).await +} diff --git a/bt-daemon/src/plugin_eval/output.rs b/bt-daemon/src/plugin_eval/output.rs new file mode 100644 index 00000000..a636f02d --- /dev/null +++ b/bt-daemon/src/plugin_eval/output.rs @@ -0,0 +1,76 @@ +use super::claude_result::Arm; +use serde::Serialize; +use std::path::PathBuf; + +/// What one eval result sync delivered. +#[derive(Debug, Clone, Serialize)] +pub struct EvalSyncSummary { + /// The result document that was synced. + pub results_path: PathBuf, + /// Whether Claude Code reported an unfinished suite. + pub partial: bool, + pub project_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub project_name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub dataset: Option, + pub experiments: Vec, + /// Experiment rows written: one root and its score spans per run. + pub rows: usize, + /// Runs whose agent transcript was imported below their row. + pub traces_imported: usize, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub warnings: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct SyncedDataset { + pub id: String, + pub name: String, +} + +#[derive(Debug, Clone, Serialize)] +pub struct SyncedExperiment { + /// Serialized as `with` for the plugin arm, `without` for the baseline. + pub arm: Arm, + pub id: String, + pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, +} + +impl EvalSyncSummary { + pub(crate) fn render_human(&self) -> String { + let project = self.project_name.as_deref().unwrap_or(&self.project_id); + let partial = if self.partial { " (partial run)" } else { "" }; + let mut lines = vec![format!( + "Synced claude plugin eval results{partial} from {} to project {project}.", + self.results_path.display() + )]; + if let Some(dataset) = &self.dataset { + lines.push(format!(" Dataset: {}", dataset.name)); + } + for experiment in &self.experiments { + let arm = experiment.arm.label(); + let location = experiment + .url + .as_deref() + .map(|url| format!(": {url}")) + .unwrap_or_default(); + lines.push(format!( + " Experiment ({arm}): {}{location}", + experiment.name + )); + } + lines.push(format!( + " {} rows, {} agent trace(s) imported.", + self.rows, self.traces_imported + )); + lines.extend( + self.warnings + .iter() + .map(|warning| format!("warning: {warning}")), + ); + lines.join("\n") + } +} diff --git a/bt-daemon/src/plugin_eval/plan.rs b/bt-daemon/src/plugin_eval/plan.rs new file mode 100644 index 00000000..69e2bf9b --- /dev/null +++ b/bt-daemon/src/plugin_eval/plan.rs @@ -0,0 +1,583 @@ +//! Deterministic Braintrust objects for one `claude plugin eval` result. +//! +//! Like Braintrust's Harbor integration, a suite run becomes a managed +//! dataset with one record per case, and one experiment row per agent run. +//! Each ablation arm is its own experiment, so the no-plugin baseline is the +//! with-plugin experiment's comparison base and Braintrust shows the delta. +//! Every identifier derives from the result document, so syncing the same +//! result again replaces the same rows instead of duplicating them. + +use super::claude_result::{ + Arm, Case, EvalResult, GraderDefinition, Run, SuiteAggregates, SuitePlugin, +}; +use crate::ids::SEP; +use serde::Serialize; +use serde_json::{Map, Value}; +use std::collections::BTreeMap; +use std::path::PathBuf; + +/// Root span name of every experiment row, matching Braintrust evals. +const ROOT_SPAN_NAME: &str = "eval"; +/// Score holding a run's weighted grader score, as Claude Code computes it. +pub(crate) const RUN_SCORE: &str = "run_score"; +/// Metadata key that namespaces everything this integration records. +const METADATA_KEY: &str = "claude_plugin_eval"; +const DEFAULT_PREFIX: &str = "claude-plugin-eval"; + +/// User choices that shape the synced objects. +#[derive(Debug, Clone, Default)] +pub(crate) struct PlanOptions { + pub experiment_prefix: Option, + /// `None` uses the default dataset name. + pub dataset_name: Option, + pub no_dataset: bool, + pub base_experiment: Option, + pub tags: Vec, + /// Merged into each experiment's metadata. + pub additional_metadata: Option>, +} + +/// What was found on disk for one run. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct RunArtifacts { + pub session_id: Option, + pub final_message: Option, + /// The native transcript to import as the run's agent trace, or why the + /// trace is unavailable. + pub transcript: Result, +} + +impl RunArtifacts { + pub fn unavailable(reason: impl Into) -> Self { + Self { + session_id: None, + final_message: None, + transcript: Err(reason.into()), + } + } +} + +/// The identity of one result document's sync. +#[derive(Debug, Clone)] +pub(crate) struct SyncPlan<'a> { + pub result: &'a EvalResult, + pub options: &'a PlanOptions, + /// A stable id of the suite run, shared by everything it syncs. + pub run_key: String, +} + +impl<'a> SyncPlan<'a> { + pub fn new(result: &'a EvalResult, options: &'a PlanOptions, document: &[u8]) -> Self { + let identity = match ( + result + .suite + .as_ref() + .and_then(|suite| suite.root.as_deref()), + result.started_at.as_deref(), + ) { + (Some(root), Some(started_at)) => format!("{root}{SEP}{started_at}"), + // Without its identity fields, the document's bytes identify it. + _ => String::from_utf8_lossy(document).into_owned(), + }; + Self { + result, + options, + run_key: crate::ids::span_id(DEFAULT_PREFIX, &identity), + } + } + + fn plugin_name(&self) -> &str { + self.result + .plugin() + .map(|plugin| plugin.name.as_str()) + .unwrap_or(DEFAULT_PREFIX) + } + + pub fn dataset_name(&self) -> Option { + if self.options.no_dataset { + return None; + } + Some( + self.options + .dataset_name + .clone() + .unwrap_or_else(|| format!("{DEFAULT_PREFIX} · {}", self.plugin_name())), + ) + } + + pub fn experiment_name(&self, arm: Arm) -> String { + let prefix = self + .options + .experiment_prefix + .as_deref() + .unwrap_or_else(|| self.plugin_name()); + format!( + "{prefix} · {} · {} · {}", + arm.label(), + self.result.model_override().unwrap_or("default"), + &self.run_key[..8] + ) + } + + /// The comparison base for an arm's experiment. + pub fn base_experiment(&self, arm: Arm) -> Option { + match arm { + Arm::WithPlugin => self.options.base_experiment.clone().or_else(|| { + self.result + .has_arm(Arm::Baseline) + .then(|| self.experiment_name(Arm::Baseline)) + }), + Arm::Baseline => None, + } + } + + /// Arms in registration order: a baseline exists before it is a base. + pub fn arms(&self) -> Vec { + [Arm::Baseline, Arm::WithPlugin] + .into_iter() + .filter(|arm| self.result.has_arm(*arm)) + .collect() + } + + pub fn dataset_metadata(&self) -> anyhow::Result> { + to_object(&Namespaced { + claude_plugin_eval: DatasetMetadata { + plugin: self.plugin_name(), + schema_version: 1, + }, + }) + } + + pub fn experiment_metadata(&self, arm: Arm) -> anyhow::Result> { + let result = self.result; + let suite = result.suite.as_ref(); + let metadata = ExperimentMetadata { + run_id: &self.run_key, + arm, + started_at: result.started_at.as_deref(), + claude_version: result.claude_version.as_deref(), + plugin: result.plugin(), + ablation: suite.and_then(|suite| suite.ablation.as_deref()), + model: result.model_override(), + judge_model: suite.and_then(|suite| suite.judge_model.as_deref()), + threshold: result.threshold(), + partial: result.partial, + partial_reason: result.partial_reason.as_deref(), + cost_usd: result.cost_usd, + duration_seconds: result.duration_seconds, + aggregates: result.aggregates.as_ref(), + }; + let mut map = self.options.additional_metadata.clone().unwrap_or_default(); + map.insert(METADATA_KEY.into(), serde_json::to_value(metadata)?); + Ok(map) + } + + fn case_record_id(&self, case: &Case) -> String { + crate::ids::span_id( + &format!("{DEFAULT_PREFIX}:dataset:{}", self.plugin_name()), + case.key(), + ) + } + + /// One dataset record per case. Re-syncing upserts the same records. + pub fn dataset_rows(&self, dataset_id: &str) -> anyhow::Result> { + let created = chrono::Utc::now().to_rfc3339(); + self.result + .cases + .iter() + .map(|case| { + serde_json::to_value(DatasetRow { + id: self.case_record_id(case), + dataset_id, + input: CaseInput::of(case), + metadata: Namespaced { + claude_plugin_eval: CaseMetadata { + case: &case.name, + case_dir: case.dir.as_deref(), + max_turns: case.max_turns, + timeout_seconds: case.timeout_seconds, + graders: &case.graders, + }, + }, + created: &created, + }) + .map_err(Into::into) + }) + .collect() + } + + pub fn root_span_id(&self, case: &Case, arm: Arm, index: usize) -> String { + crate::ids::span_id( + &format!("{DEFAULT_PREFIX}:{}", self.run_key), + &format!( + "run{SEP}{}{SEP}{}{SEP}{index}", + arm.result_key(), + case.key() + ), + ) + } + + /// One arm's runs with their index in the arm and root span id. + pub fn arm_runs( + &self, + arm: Arm, + ) -> impl Iterator + '_ { + self.result + .arm_runs(arm) + .map(move |(case, index, run)| (case, index, run, self.root_span_id(case, arm, index))) + } + + /// Every run's root span id with what was found on disk for it. + pub fn artifacts(&self, find: impl Fn(&Run) -> RunArtifacts) -> BTreeMap { + self.result + .runs() + .map(|(case, arm, index, run)| (self.root_span_id(case, arm, index), find(run))) + .collect() + } + + /// The experiment rows for one arm: a root `eval` span per run with one + /// `score` span per grader verdict and one for the run's weighted score. + pub fn experiment_rows( + &self, + arm: Arm, + experiment_id: &str, + dataset_id: Option<&str>, + artifacts: &BTreeMap, + ) -> anyhow::Result> { + let created = chrono::Utc::now().to_rfc3339(); + let mut rows = Vec::new(); + for (case, index, run, root_id) in self.arm_runs(arm) { + let found = artifacts.get(&root_id); + let (start, end) = run_times(run); + let mut metrics = BTreeMap::new(); + if let Some(start) = start { + metrics.insert("start", start); + } + if let Some(end) = end { + metrics.insert("end", end); + } + if let Some(turns) = run.turns { + metrics.insert("turns", turns as f64); + } + let aborted = run.aborted.as_ref().map(|aborted| aborted.describe()); + rows.push(serde_json::to_value(ExperimentRow { + ids: SpanIds::root(&root_id), + experiment_id, + input: Some(CaseInput::of(case)), + output: found.and_then(|found| found.final_message.as_deref()), + error: run.error.as_deref().or(aborted.as_deref()), + scores: BTreeMap::new(), + metadata: Some(Namespaced { + claude_plugin_eval: RunMetadata { + case: &case.name, + case_dir: case.dir.as_deref(), + run_index: index, + passed: run.passed, + cost_usd: run.cost_usd, + judge_cost_usd: run.judge_cost_usd, + skipped_paid_graders: run.skipped_paid_graders, + session_id: found.and_then(|found| found.session_id.as_deref()), + model: case.model.as_deref().or(self.result.model_override()), + agent_trace_unavailable: found + .and_then(|found| found.transcript.as_ref().err()) + .map(String::as_str), + }, + }), + metrics, + tags: &self.options.tags, + span_attributes: SpanAttributes { + name: ROOT_SPAN_NAME, + kind: "eval", + purpose: None, + }, + origin: dataset_id.map(|dataset_id| Origin { + object_type: "dataset", + object_id: dataset_id, + id: self.case_record_id(case), + }), + created: &created, + })?); + + let time = end.or(start); + let score = |key: &str, name: &str, input, output, value| { + score_row(ScoreSpan { + root_id: &root_id, + key, + name, + input, + output, + value, + time, + experiment_id, + created: &created, + }) + }; + if let Some(value) = run.score { + rows.push(score( + RUN_SCORE, + RUN_SCORE, + None, + serde_json::to_value(RunScoreOutput { + score: value, + passed: run.passed, + threshold: self.result.threshold(), + })?, + value, + )?); + } + for grader in &run.graders { + let Some(passed) = grader.passed else { + continue; + }; + rows.push(score( + &format!("grader{SEP}{}", grader.name), + &grader.name, + case.grader(&grader.name), + serde_json::to_value(grader)?, + f64::from(u8::from(passed)), + )?); + } + } + Ok(rows) + } +} + +/// A `score` span below a run's root, written like Braintrust eval scorers. +struct ScoreSpan<'a> { + root_id: &'a str, + /// Distinguishes the span among its root's score spans. + key: &'a str, + name: &'a str, + input: Option<&'a GraderDefinition>, + output: Value, + value: f64, + /// Score spans are instantaneous at the end of the run. + time: Option, + experiment_id: &'a str, + created: &'a str, +} + +fn score_row(span: ScoreSpan<'_>) -> anyhow::Result { + let id = crate::ids::span_id(span.root_id, span.key); + let row = ExperimentRow::<_, _, ()> { + ids: SpanIds { + id: &id, + span_id: &id, + root_span_id: span.root_id, + span_parents: vec![span.root_id], + }, + experiment_id: span.experiment_id, + input: span.input, + output: Some(span.output), + error: None, + scores: BTreeMap::from([(span.name, span.value)]), + metadata: None, + metrics: span + .time + .map(|time| BTreeMap::from([("start", time), ("end", time)])) + .unwrap_or_default(), + tags: &[], + span_attributes: SpanAttributes { + name: span.name, + kind: "score", + purpose: Some("scorer"), + }, + origin: None, + created: span.created, + }; + Ok(serde_json::to_value(row)?) +} + +/// Epoch seconds for a run's start and end. +fn run_times(run: &Run) -> (Option, Option) { + let start = run + .started_at + .as_deref() + .and_then(|started_at| chrono::DateTime::parse_from_rfc3339(started_at).ok()) + .map(|time| time.timestamp_millis() as f64 / 1000.0); + let end = start + .zip(run.duration_seconds) + .map(|(start, duration)| start + duration.max(0.0)); + (start, end) +} + +fn to_object(value: &impl Serialize) -> anyhow::Result> { + match serde_json::to_value(value)? { + Value::Object(map) => Ok(map), + _ => anyhow::bail!("metadata must serialize to an object"), + } +} + +/// Metadata under this integration's key. +#[derive(Serialize)] +struct Namespaced { + claude_plugin_eval: T, +} + +#[derive(Serialize)] +struct DatasetMetadata<'a> { + plugin: &'a str, + schema_version: u32, +} + +#[derive(Serialize)] +struct ExperimentMetadata<'a> { + run_id: &'a str, + arm: Arm, + #[serde(skip_serializing_if = "Option::is_none")] + started_at: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + claude_version: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + plugin: Option<&'a SuitePlugin>, + #[serde(skip_serializing_if = "Option::is_none")] + ablation: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + model: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + judge_model: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + threshold: Option, + partial: bool, + #[serde(skip_serializing_if = "Option::is_none")] + partial_reason: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + cost_usd: Option, + #[serde(skip_serializing_if = "Option::is_none")] + duration_seconds: Option, + #[serde(flatten, skip_serializing_if = "Option::is_none")] + aggregates: Option<&'a SuiteAggregates>, +} + +/// A case's input, shared by its dataset record and experiment rows. +#[derive(Serialize)] +struct CaseInput<'a> { + case: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + prompt: Option<&'a str>, +} + +impl<'a> CaseInput<'a> { + fn of(case: &'a Case) -> Self { + Self { + case: &case.name, + prompt: case.prompt_markdown.as_deref(), + } + } +} + +#[derive(Serialize)] +struct RunScoreOutput { + score: f64, + #[serde(skip_serializing_if = "Option::is_none")] + passed: Option, + #[serde(skip_serializing_if = "Option::is_none")] + threshold: Option, +} + +#[derive(Serialize)] +struct CaseMetadata<'a> { + case: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + case_dir: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + max_turns: Option, + #[serde(skip_serializing_if = "Option::is_none")] + timeout_seconds: Option, + graders: &'a [GraderDefinition], +} + +/// Per-run facts. Suite-wide facts, such as the arm and Claude Code +/// version, are on the experiment. +#[derive(Serialize)] +struct RunMetadata<'a> { + case: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + case_dir: Option<&'a str>, + run_index: usize, + #[serde(skip_serializing_if = "Option::is_none")] + passed: Option, + #[serde(skip_serializing_if = "Option::is_none")] + cost_usd: Option, + #[serde(skip_serializing_if = "Option::is_none")] + judge_cost_usd: Option, + #[serde(skip_serializing_if = "Option::is_none")] + skipped_paid_graders: Option, + #[serde(skip_serializing_if = "Option::is_none")] + session_id: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + model: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + agent_trace_unavailable: Option<&'a str>, +} + +#[derive(Serialize)] +struct SpanAttributes<'a> { + name: &'a str, + #[serde(rename = "type")] + kind: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + purpose: Option<&'static str>, +} + +#[derive(Serialize)] +struct Origin<'a> { + object_type: &'static str, + object_id: &'a str, + id: String, +} + +#[derive(Serialize)] +struct DatasetRow<'a> { + id: String, + dataset_id: &'a str, + input: CaseInput<'a>, + metadata: Namespaced>, + created: &'a str, +} + +/// A row's identity. Its row id is its span id, so re-syncs replace it. +#[derive(Serialize)] +struct SpanIds<'a> { + id: &'a str, + span_id: &'a str, + root_span_id: &'a str, + #[serde(skip_serializing_if = "Vec::is_empty")] + span_parents: Vec<&'a str>, +} + +impl<'a> SpanIds<'a> { + fn root(id: &'a str) -> Self { + Self { + id, + span_id: id, + root_span_id: id, + span_parents: Vec::new(), + } + } +} + +#[derive(Serialize)] +struct ExperimentRow<'a, I: Serialize, O: Serialize, M: Serialize> { + #[serde(flatten)] + ids: SpanIds<'a>, + experiment_id: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + input: Option, + #[serde(skip_serializing_if = "Option::is_none")] + output: Option, + #[serde(skip_serializing_if = "Option::is_none")] + error: Option<&'a str>, + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + scores: BTreeMap<&'a str, f64>, + #[serde(skip_serializing_if = "Option::is_none")] + metadata: Option, + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + metrics: BTreeMap<&'static str, f64>, + #[serde(skip_serializing_if = "<[String]>::is_empty")] + tags: &'a [String], + span_attributes: SpanAttributes<'a>, + #[serde(skip_serializing_if = "Option::is_none")] + origin: Option>, + created: &'a str, +} diff --git a/bt-daemon/src/plugin_eval/sandbox.rs b/bt-daemon/src/plugin_eval/sandbox.rs new file mode 100644 index 00000000..bd9267a6 --- /dev/null +++ b/bt-daemon/src/plugin_eval/sandbox.rs @@ -0,0 +1,204 @@ +//! The temporary directory `claude plugin eval` creates for each agent run. +//! +//! A run sandbox holds `out/trace.jsonl` (the stream-json session), +//! `config/` (the run's Claude config directory, including the native session +//! transcript under `config/projects/`), and `sealed/` (the home and temporary +//! directories the plugin under test could write). Claude Code removes it after +//! the suite unless `--keep-temp` is passed, in which case it makes the +//! sandbox read-only and `sealed/` inaccessible. + +use super::claude_result::{EvalResult, Run, StreamSummary}; +use super::plan::RunArtifacts; +use crate::args::ImportSource; +use std::path::{Path, PathBuf}; + +/// Prefix of the sandbox directories Claude Code creates in the temp root. +const SANDBOX_PREFIX: &str = "e-"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct RunSandbox { + root: PathBuf, +} + +impl RunSandbox { + /// The sandbox containing a run's `tracePath`, if it has the expected + /// `/out/trace.jsonl` shape. + pub fn from_trace_path(trace_path: &Path) -> Option { + let out = trace_path.parent()?; + if out.file_name()? != "out" { + return None; + } + Some(Self { + root: out.parent()?.to_path_buf(), + }) + } + + /// The run's native Claude Code transcript. + pub fn transcript(&self, session_id: &str) -> anyhow::Result { + crate::transcript_import::find_in_config( + ImportSource::Claude, + &self.root.join("config"), + session_id, + ) + } + + /// Delete a sandbox this command asked Claude Code to keep. Only + /// directories with Claude Code's sandbox name directly inside one of the + /// canonical `temp_roots` are removed. + fn remove(&self, temp_roots: &[PathBuf]) -> anyhow::Result<()> { + if !self.root.exists() { + return Ok(()); + } + let name_matches = self + .root + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with(SANDBOX_PREFIX)); + let parent = self + .root + .parent() + .and_then(|parent| parent.canonicalize().ok()); + let in_temp_root = parent.is_some_and(|parent| temp_roots.contains(&parent)); + if !name_matches || !in_temp_root { + anyhow::bail!( + "refusing to delete {}: it is not a claude plugin eval sandbox", + self.root.display() + ); + } + make_removable(&self.root)?; + std::fs::remove_dir_all(&self.root) + .map_err(|error| anyhow::anyhow!("could not delete {}: {error}", self.root.display())) + } +} + +/// What a run's kept sandbox holds: its session identity, final response, +/// and native transcript. +pub(crate) fn run_artifacts(run: &Run) -> RunArtifacts { + let Some(trace_path) = run.trace_path.as_deref() else { + return RunArtifacts::unavailable("the result does not record the run's trace"); + }; + let Some(sandbox) = RunSandbox::from_trace_path(trace_path) else { + return RunArtifacts::unavailable(format!( + "unrecognized trace location {}", + trace_path.display() + )); + }; + if !sandbox.root.is_dir() { + return RunArtifacts::unavailable( + "the run's sandbox was deleted; rerun with --keep-temp to import agent traces", + ); + } + let summary = match StreamSummary::read(trace_path) { + Ok(summary) => summary, + Err(error) => return RunArtifacts::unavailable(error.to_string()), + }; + let transcript = match summary.session_id.as_deref() { + Some(session_id) => sandbox + .transcript(session_id) + .map_err(|error| error.to_string()), + None => Err("the run's trace names no session".into()), + }; + RunArtifacts { + session_id: summary.session_id, + final_message: summary.final_message, + transcript, + } +} + +/// Every sandbox the result refers to. +pub(crate) fn sandboxes(result: &EvalResult) -> Vec { + let mut sandboxes = result + .runs() + .filter_map(|(_, _, _, run)| run.trace_path.as_deref()) + .filter_map(RunSandbox::from_trace_path) + .collect::>(); + sandboxes.sort_by(|left, right| left.root.cmp(&right.root)); + sandboxes.dedup(); + sandboxes +} + +/// Delete the sandboxes kept only so their transcripts could be imported, +/// reporting each one that cannot be deleted. +pub(crate) fn remove_all(sandboxes: &[RunSandbox]) -> Vec { + let roots = temp_roots(); + sandboxes + .iter() + .filter_map(|sandbox| sandbox.remove(&roots).err()) + .collect() +} + +fn temp_roots() -> Vec { + let mut roots = vec![std::env::temp_dir()]; + if cfg!(unix) { + roots.push(PathBuf::from("/tmp")); + } + roots + .into_iter() + .filter_map(|root| root.canonicalize().ok()) + .collect() +} + +/// Restore owner access to every directory of a sealed, read-only sandbox so +/// it can be deleted. Symbolic links are never followed. +#[cfg(unix)] +fn make_removable(directory: &Path) -> anyhow::Result<()> { + use std::os::unix::fs::PermissionsExt; + + let metadata = std::fs::symlink_metadata(directory)?; + if !metadata.is_dir() { + return Ok(()); + } + std::fs::set_permissions(directory, std::fs::Permissions::from_mode(0o700)).map_err( + |error| anyhow::anyhow!("could not make {} removable: {error}", directory.display()), + )?; + for entry in std::fs::read_dir(directory)? { + let entry = entry?; + if entry.file_type()?.is_dir() { + make_removable(&entry.path())?; + } + } + Ok(()) +} + +#[cfg(not(unix))] +fn make_removable(_directory: &Path) -> anyhow::Result<()> { + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn removal_rejects_directories_that_are_not_sandboxes() { + let directory = tempfile::tempdir().unwrap(); + let other = directory.path().join("not-a-sandbox"); + std::fs::create_dir_all(other.join("out")).unwrap(); + let sandbox = RunSandbox::from_trace_path(&other.join("out/trace.jsonl")).unwrap(); + assert_eq!(remove_all(&[sandbox]).len(), 1); + assert!(other.exists()); + } + + #[cfg(unix)] + #[test] + fn removal_unseals_kept_sandboxes() { + use std::os::unix::fs::PermissionsExt; + + let root = tempfile::Builder::new() + .prefix(SANDBOX_PREFIX) + .tempdir_in(std::env::temp_dir()) + .unwrap() + .keep(); + let sealed = root.join("sealed/home"); + std::fs::create_dir_all(&sealed).unwrap(); + std::fs::write(sealed.join("file"), "x").unwrap(); + std::fs::create_dir_all(root.join("out")).unwrap(); + for directory in [root.join("sealed"), root.clone()] { + let mode = if directory == root { 0o500 } else { 0o000 }; + std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(mode)).unwrap(); + } + let sandbox = RunSandbox::from_trace_path(&root.join("out/trace.jsonl")).unwrap(); + assert!(remove_all(&[sandbox]).is_empty()); + assert!(!root.exists()); + } +} diff --git a/bt-daemon/src/plugin_eval/sync.rs b/bt-daemon/src/plugin_eval/sync.rs new file mode 100644 index 00000000..27c0f365 --- /dev/null +++ b/bt-daemon/src/plugin_eval/sync.rs @@ -0,0 +1,320 @@ +//! Deliver one eval result to Braintrust. + +use super::output::{EvalSyncSummary, SyncedDataset, SyncedExperiment}; +use super::plan::{RunArtifacts, SyncPlan}; +use crate::args::ImportSource; +use crate::transcript_import::{import_transcripts, ImportTarget}; +use crate::wire::{BackendAuth, TraceDestination}; +use braintrust_api_client::{Client, ProjectRegisterRequest, RegisteredProject}; +use braintrust_sdk_rust::{SpanComponents, SpanObjectType, DEFAULT_API_URL, DEFAULT_APP_URL}; +use futures::StreamExt; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// Rows per `/logs3` request. +const ROW_BATCH: usize = 100; +/// Matches `braintrust_sdk_rust`'s logs API version. +const LOGS_API_VERSION: u8 = 2; +/// Agent transcripts imported at once. Each import waits for the daemon to +/// deliver its spans, so they overlap instead of queueing. +const CONCURRENT_IMPORTS: usize = 8; + +/// Where the synced objects go and how to authenticate. +pub(crate) struct SyncTarget { + pub auth: BackendAuth, + pub project: ProjectSelection, + /// The daemon that imports each run's agent transcript. + pub import: ImportTarget, + /// The translator for the runs' native transcripts. + pub transcript_source: ImportSource, +} + +#[derive(Debug, Clone)] +pub(crate) enum ProjectSelection { + Id(String), + Name(String), +} + +impl ProjectSelection { + pub fn from_destination(destination: Option<&TraceDestination>) -> anyhow::Result { + match destination { + Some(TraceDestination::ProjectLogs { + project_id: Some(id), + .. + }) => Ok(Self::Id(id.clone())), + Some(TraceDestination::ProjectLogs { + project_name: Some(name), + .. + }) => Ok(Self::Name(name.clone())), + _ => anyhow::bail!( + "syncing plugin eval results requires a Braintrust project; pass --project " + ), + } + } +} + +pub(crate) async fn sync_result( + plan: &SyncPlan<'_>, + artifacts: &BTreeMap, + result_path: &Path, + target: SyncTarget, +) -> anyhow::Result { + if plan.result.cases.is_empty() { + anyhow::bail!("{} contains no eval cases", result_path.display()); + } + let backend = Backend::new(&target.auth)?; + let (project_id, project_name) = match &target.project { + ProjectSelection::Id(id) => (id.clone(), None), + ProjectSelection::Name(name) => { + let project = backend.register_project(name).await?; + ( + project.id, + Some(project.name.unwrap_or_else(|| name.clone())), + ) + } + }; + + let dataset = match plan.dataset_name() { + Some(name) => { + let dataset = backend + .register( + "dataset", + &RegisterDataset { + project_id: &project_id, + dataset_name: &name, + metadata: plan.dataset_metadata()?, + }, + ) + .await?; + backend.insert(&plan.dataset_rows(&dataset.id)?).await?; + Some(dataset) + } + None => None, + }; + let dataset_id = dataset.as_ref().map(|dataset| dataset.id.as_str()); + + let mut experiments = Vec::new(); + let mut rows = 0; + let mut traces = Vec::new(); + for arm in plan.arms() { + let experiment = backend + .register( + "experiment", + &RegisterExperiment { + project_id: &project_id, + experiment_name: &plan.experiment_name(arm), + update: true, + base_experiment: plan.base_experiment(arm).as_deref(), + dataset_id, + metadata: plan.experiment_metadata(arm)?, + }, + ) + .await?; + let arm_rows = plan.experiment_rows(arm, &experiment.id, dataset_id, artifacts)?; + rows += arm_rows.len(); + backend.insert(&arm_rows).await?; + for (_, _, _, root) in plan.arm_runs(arm) { + if let Some(Ok(transcript)) = artifacts.get(&root).map(|found| &found.transcript) { + traces.push((experiment.id.clone(), root, transcript.clone())); + } + } + experiments.push(SyncedExperiment { + arm, + url: backend.experiment_url(project_name.as_deref(), &experiment.name), + id: experiment.id, + name: experiment.name, + }); + } + + let mut warnings = Vec::new(); + let mut unavailable = artifacts + .values() + .filter_map(|found| found.transcript.as_ref().err()); + if let Some(reason) = unavailable.next() { + warnings.push(format!( + "{} run(s) have no agent trace: {reason}", + unavailable.count() + 1 + )); + } + + let imports = futures::stream::iter(&traces) + .map(|(experiment_id, root, transcript)| { + import_run_trace(&target, experiment_id, root, transcript) + }) + .buffer_unordered(CONCURRENT_IMPORTS) + .collect::>() + .await; + let mut imported = 0; + for result in imports { + match result { + Ok(()) => imported += 1, + Err(error) => warnings.push(format!("{error:#}")), + } + } + + Ok(EvalSyncSummary { + results_path: result_path.to_path_buf(), + partial: plan.result.partial, + project_id, + project_name, + dataset: dataset.map(|dataset| SyncedDataset { + id: dataset.id, + name: dataset.name, + }), + experiments, + rows, + traces_imported: imported, + warnings, + }) +} + +/// Import a run's native transcript below its experiment row, through the +/// same daemon translator that traces live sessions. +async fn import_run_trace( + target: &SyncTarget, + experiment_id: &str, + root_span_id: &str, + transcript: &PathBuf, +) -> anyhow::Result<()> { + let mut import = target.import.clone(); + import.route.destination = Some(TraceDestination::ParentSpan { + components: SpanComponents { + object_type: SpanObjectType::Experiment, + object_id: Some(experiment_id.to_owned()), + compute_object_metadata_args: None, + row_id: Some(root_span_id.to_owned()), + span_id: Some(root_span_id.to_owned()), + root_span_id: Some(root_span_id.to_owned()), + span_parents: None, + propagated_event: None, + }, + }); + import_transcripts( + std::slice::from_ref(transcript), + target.transcript_source, + import, + ) + .await + .map_err(|error| { + anyhow::anyhow!( + "could not import agent trace {}: {error:#}", + transcript.display() + ) + })?; + Ok(()) +} + +/// A registered dataset or experiment. +#[derive(Debug, Clone, Deserialize)] +struct Registered { + id: String, + name: String, +} + +/// Registration responses carry the object under its kind, next to its project. +#[derive(Deserialize)] +struct RegisterResponse { + #[serde(alias = "dataset", alias = "experiment")] + object: Registered, +} + +#[derive(Serialize)] +struct RegisterDataset<'a> { + project_id: &'a str, + dataset_name: &'a str, + metadata: Map, +} + +#[derive(Serialize)] +struct RegisterExperiment<'a> { + project_id: &'a str, + experiment_name: &'a str, + /// Reuse the experiment with this name, so re-syncs update it in place. + update: bool, + #[serde(skip_serializing_if = "Option::is_none")] + base_experiment: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + dataset_id: Option<&'a str>, + metadata: Map, +} + +#[derive(Serialize)] +struct Logs3Payload<'a> { + rows: &'a [Value], + api_version: u8, +} + +struct Backend { + client: Client, + app_url: String, + org_name: Option, +} + +impl Backend { + fn new(auth: &BackendAuth) -> anyhow::Result { + let api_url = auth.api_url.as_deref().unwrap_or(DEFAULT_API_URL); + let app_url = auth.app_url.as_deref().unwrap_or(DEFAULT_APP_URL); + let mut builder = Client::builder() + .api_key(auth.token.clone()) + .api_url(api_url) + .app_url(app_url); + if let Some(org_name) = &auth.org_name { + builder = builder.org_name(org_name.clone()); + } + Ok(Self { + client: builder.build()?, + app_url: app_url.trim_end_matches('/').to_owned(), + org_name: auth.org_name.clone(), + }) + } + + async fn register_project(&self, name: &str) -> anyhow::Result { + let mut request = ProjectRegisterRequest::new(name.to_owned()); + request.org_name = self.org_name.clone(); + Ok(self + .client + .register_project(&request) + .await + .map_err(|error| anyhow::anyhow!("could not register project {name:?}: {error}"))? + .into_inner() + .project) + } + + async fn register(&self, kind: &str, request: &impl Serialize) -> anyhow::Result { + let response = self + .client + .control_plane_json::<_, RegisterResponse>(kind, "register", request) + .await + .map_err(|error| anyhow::anyhow!("could not register {kind}: {error}"))?; + Ok(response.into_inner().object) + } + + async fn insert(&self, rows: &[Value]) -> anyhow::Result<()> { + for batch in rows.chunks(ROW_BATCH) { + self.client + .logs3(&Logs3Payload { + rows: batch, + api_version: LOGS_API_VERSION, + }) + .await + .map_err(|error| anyhow::anyhow!("could not write eval rows: {error}"))?; + } + Ok(()) + } + + fn experiment_url(&self, project: Option<&str>, experiment: &str) -> Option { + let org = self.org_name.as_deref()?; + let mut url = url::Url::parse(&self.app_url).ok()?; + url.path_segments_mut().ok()?.extend([ + "app", + org, + "p", + project?, + "experiments", + experiment, + ]); + Some(url.to_string()) + } +} diff --git a/bt-daemon/src/plugin_eval/tests.rs b/bt-daemon/src/plugin_eval/tests.rs new file mode 100644 index 00000000..113cae4b --- /dev/null +++ b/bt-daemon/src/plugin_eval/tests.rs @@ -0,0 +1,471 @@ +#![allow( + clippy::unwrap_used, + clippy::expect_used, + reason = "Test assertions and fixtures fail immediately on unexpected values." +)] + +use super::claude_result::{Arm, EvalResult}; +use super::plan::{PlanOptions, RunArtifacts, SyncPlan, RUN_SCORE}; +use super::{sandbox, sync}; +use serde_json::{json, Map, Value}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// A real `claude plugin eval` result (Claude Code 2.1.333): two cases, one +/// run per arm, with `llm`, `regex`, and `tool_used: Skill` graders. +const FIXTURE: &str = + include_str!("../../tests/fixtures/claude-plugin-eval/aggregate-result-2.1.333.json"); + +fn fixture() -> EvalResult { + EvalResult::parse(FIXTURE.as_bytes(), Path::new("fixture.json")).unwrap() +} + +fn rows_named<'a>(rows: &'a [Value], name: &str) -> Vec<&'a Value> { + rows.iter() + .filter(|row| row["span_attributes"]["name"] == name) + .collect() +} + +#[test] +fn rejects_other_schema_versions() { + let error = EvalResult::parse(br#"{"schemaVersion":2,"cases":[]}"#, Path::new("r.json")) + .unwrap_err() + .to_string(); + assert!(error.contains("unsupported"), "{error}"); + assert!(EvalResult::parse(br#"{"cases":[]}"#, Path::new("r.json")).is_err()); +} + +#[test] +fn baseline_is_registered_first_and_is_the_with_plugin_base() { + let result = fixture(); + let options = PlanOptions::default(); + let plan = SyncPlan::new(&result, &options, FIXTURE.as_bytes()); + assert_eq!(plan.arms(), vec![Arm::Baseline, Arm::WithPlugin]); + let key = &plan.run_key[..8]; + assert_eq!( + plan.experiment_name(Arm::WithPlugin), + format!("demo-plugin · with plugin · haiku · {key}") + ); + assert_eq!( + plan.base_experiment(Arm::WithPlugin), + Some(plan.experiment_name(Arm::Baseline)) + ); + assert_eq!(plan.base_experiment(Arm::Baseline), None); + assert_eq!( + plan.dataset_name().as_deref(), + Some("claude-plugin-eval · demo-plugin") + ); + + let options = PlanOptions { + base_experiment: Some("main".into()), + experiment_prefix: Some("ci".into()), + no_dataset: true, + ..PlanOptions::default() + }; + let plan = SyncPlan::new(&result, &options, FIXTURE.as_bytes()); + assert_eq!( + plan.base_experiment(Arm::WithPlugin).as_deref(), + Some("main") + ); + assert!(plan + .experiment_name(Arm::Baseline) + .starts_with("ci · baseline · ")); + assert_eq!(plan.dataset_name(), None); +} + +#[test] +fn identities_are_stable_for_a_result_and_distinct_across_runs() { + let result = fixture(); + let options = PlanOptions::default(); + let first = SyncPlan::new(&result, &options, FIXTURE.as_bytes()); + let again = SyncPlan::new(&result, &options, b"different bytes, same identity"); + assert_eq!(first.run_key, again.run_key); + assert_eq!( + first.dataset_rows("ds").unwrap()[0]["id"], + again.dataset_rows("ds").unwrap()[0]["id"] + ); + let case = &result.cases[0]; + assert_eq!( + first.root_span_id(case, Arm::WithPlugin, 0), + again.root_span_id(case, Arm::WithPlugin, 0) + ); + assert_ne!( + first.root_span_id(case, Arm::WithPlugin, 0), + first.root_span_id(case, Arm::Baseline, 0) + ); + + let mut later = fixture(); + later.started_at = Some("2026-12-02T00:00:00.000Z".into()); + let later = SyncPlan::new(&later, &options, FIXTURE.as_bytes()); + assert_ne!(first.run_key, later.run_key); + // Dataset records are per case, not per suite run: reruns upsert them. + assert_eq!( + first.dataset_rows("ds").unwrap()[0]["id"], + later.dataset_rows("ds").unwrap()[0]["id"] + ); +} + +#[test] +fn with_plugin_rows_are_eval_roots_with_one_score_span_per_verdict() { + let result = fixture(); + let options = PlanOptions { + tags: vec!["ci".into()], + ..PlanOptions::default() + }; + let plan = SyncPlan::new(&result, &options, FIXTURE.as_bytes()); + let case = &result.cases[0]; + let root_id = plan.root_span_id(case, Arm::WithPlugin, 0); + let artifacts = BTreeMap::from([( + root_id.clone(), + RunArtifacts { + session_id: Some("f47d3b30-74fb-4c9e-b178-6a2028a09fc7".into()), + final_message: Some("Ahoy, friend!".into()), + transcript: Ok(PathBuf::from("/t.jsonl")), + }, + )]); + let rows = plan + .experiment_rows(Arm::WithPlugin, "exp-1", Some("ds-1"), &artifacts) + .unwrap(); + // greets: root, run score, three graders; other: root, run score, one grader. + assert_eq!(rows.len(), 8); + assert!(rows.iter().all(|row| row["experiment_id"] == "exp-1")); + + let roots = rows_named(&rows, "eval"); + assert_eq!(roots.len(), 2); + let root = roots[0]; + assert_eq!(root["id"], root_id.as_str()); + assert_eq!(root["span_id"], root_id.as_str()); + assert_eq!(root["root_span_id"], root_id.as_str()); + assert!(root.get("span_parents").is_none()); + assert_eq!( + root["span_attributes"], + json!({"name": "eval", "type": "eval"}) + ); + assert_eq!(root["output"], "Ahoy, friend!"); + assert_eq!(root["tags"], json!(["ci"])); + assert_eq!(root["origin"]["object_type"], "dataset"); + assert_eq!(root["origin"]["object_id"], "ds-1"); + let records = plan.dataset_rows("ds-1").unwrap(); + assert_eq!(records.len(), 2); + assert_eq!(root["origin"]["id"], records[0]["id"]); + assert_eq!(records[0]["input"], root["input"]); + assert_eq!( + records[0]["input"], + json!({"case": "greets", "prompt": "Please greet me."}) + ); + let graders = &records[0]["metadata"]["claude_plugin_eval"]["graders"]; + assert_eq!(graders[1]["config"]["pattern"], "Ahoy"); + assert!(records[0].get("expected").is_none()); + assert!(root.get("scores").is_none()); + let metrics = &root["metrics"]; + assert_eq!( + metrics["end"].as_f64().unwrap() - metrics["start"].as_f64().unwrap(), + 5.0 + ); + assert_eq!(metrics["turns"], 3.0); + let metadata = &root["metadata"]["claude_plugin_eval"]; + assert_eq!(metadata["case_dir"], "evals/greets"); + assert_eq!(metadata["run_index"], 0); + assert_eq!( + metadata["session_id"], + "f47d3b30-74fb-4c9e-b178-6a2028a09fc7" + ); + assert!(metadata.get("agent_trace_unavailable").is_none()); + + let run_score = rows_named(&rows, RUN_SCORE)[0]; + assert_eq!(run_score["scores"], json!({RUN_SCORE: 1.0})); + assert_eq!(run_score["span_parents"], json!([root_id])); + assert_eq!(run_score["root_span_id"], root_id.as_str()); + assert_eq!( + run_score["span_attributes"], + json!({"name": RUN_SCORE, "type": "score", "purpose": "scorer"}) + ); + assert_eq!(run_score["metrics"]["start"], metrics["end"]); + + let judged = rows_named(&rows, "friendly")[0]; + assert_eq!(judged["scores"], json!({"friendly": 1.0})); + assert_eq!(judged["input"]["type"], "llm"); + assert_eq!(judged["output"]["judge_votes"], json!([true, true, true])); + assert_eq!(judged["output"]["evidence"], "Ahoy, friend!"); + + // Plugin-fired indicators are recorded, with Claude Code's exclusion. + let fired = rows_named(&rows, "skill-fired")[0]; + assert_eq!(fired["scores"], json!({"skill-fired": 1.0})); + assert_eq!(fired["output"]["scored"], false); + assert_eq!(fired["output"]["with_only"], true); + + let ids = rows + .iter() + .map(|row| row["id"].clone()) + .collect::>(); + assert_eq!(ids.len(), rows.len(), "row ids must be unique"); +} + +#[test] +fn baseline_rows_record_failed_verdicts_and_missing_traces() { + let result = fixture(); + let options = PlanOptions::default(); + let plan = SyncPlan::new(&result, &options, FIXTURE.as_bytes()); + let artifacts = plan.artifacts(sandbox::run_artifacts); + let rows = plan + .experiment_rows(Arm::Baseline, "exp-0", None, &artifacts) + .unwrap(); + // greets: root, run score, two graders; other: root, run score, one grader. + assert_eq!(rows.len(), 7); + let root = rows_named(&rows, "eval")[0]; + assert!(root.get("origin").is_none()); + assert!(root.get("output").is_none()); + assert!( + root["metadata"]["claude_plugin_eval"]["agent_trace_unavailable"] + .as_str() + .unwrap() + .contains("--keep-temp") + ); + assert_eq!( + rows_named(&rows, "says-ahoy")[0]["scores"], + json!({"says-ahoy": 0.0}) + ); + let run_score = rows_named(&rows, RUN_SCORE)[0]; + assert!((run_score["scores"][RUN_SCORE].as_f64().unwrap() - 2.0 / 3.0).abs() < 1e-9); + assert!(rows_named(&rows, "skill-fired").is_empty()); +} + +#[test] +fn errors_and_mock_aborts_become_row_errors() { + let mut result = fixture(); + result.cases[0].arms.with[0].error = Some("timed out after 300s".into()); + result.cases[1].arms.with[0].aborted = serde_json::from_value(json!({ + "server": "github", "tool": "create_issue", "reason": "priority must be low|medium|high" + })) + .unwrap(); + let options = PlanOptions::default(); + let plan = SyncPlan::new(&result, &options, FIXTURE.as_bytes()); + let rows = plan + .experiment_rows(Arm::WithPlugin, "exp", None, &BTreeMap::new()) + .unwrap(); + let roots = rows_named(&rows, "eval"); + assert_eq!(roots[0]["error"], "timed out after 300s"); + assert_eq!( + roots[1]["error"], + "aborted by mock github/create_issue: priority must be low|medium|high" + ); +} + +#[test] +fn artifacts_come_from_a_kept_sandbox() { + let temp = tempfile::tempdir().unwrap(); + let sandbox = temp.path().join("e-test"); + let session = "f47d3b30-74fb-4c9e-b178-6a2028a09fc7"; + std::fs::create_dir_all(sandbox.join("out")).unwrap(); + std::fs::write( + sandbox.join("out/trace.jsonl"), + // Message records are skipped and a record cut off by a timeout is + // ignored. + format!( + "{}\n{}\n{}\n{}", + json!({"type": "system", "subtype": "init", "session_id": session}), + json!({"type": "assistant", "message": {"content": []}, "session_id": session}), + json!({"type": "result", "result": "done", "session_id": session}), + r#"{"type":"result","subtype":"suc"# + ), + ) + .unwrap(); + let project = sandbox.join("config/projects/-tmp-e-test-home-cwd"); + std::fs::create_dir_all(&project).unwrap(); + let transcript = project.join(format!("{session}.jsonl")); + std::fs::write( + &transcript, + format!("{}\n", json!({"type": "user", "sessionId": session})), + ) + .unwrap(); + + let mut result = fixture(); + for case in &mut result.cases { + for run in case + .arms + .with + .iter_mut() + .chain(case.arms.without.iter_mut()) + { + run.trace_path = Some(sandbox.join("out/trace.jsonl")); + } + } + let options = PlanOptions::default(); + let plan = SyncPlan::new(&result, &options, FIXTURE.as_bytes()); + let artifacts = plan.artifacts(sandbox::run_artifacts); + let found = &artifacts[&plan.root_span_id(&result.cases[0], Arm::WithPlugin, 0)]; + assert_eq!(found.session_id.as_deref(), Some(session)); + assert_eq!(found.final_message.as_deref(), Some("done")); + assert_eq!(found.transcript.as_deref(), Ok(transcript.as_path())); + assert_eq!(sandbox::sandboxes(&result).len(), 1); +} + +mod backend { + use super::*; + use crate::client::HostInfo; + use crate::transcript_import::ImportTarget; + use crate::wire::{BackendAuth, SessionRoute}; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, Request, ResponseTemplate}; + + fn registered(kind: &str, id: &str, name: &str) -> Value { + json!({ "project": {"id": "project-1", "name": "Plugins"}, (kind): {"id": id, "name": name} }) + } + + #[tokio::test] + async fn sync_registers_objects_and_writes_rows() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/project/register")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(json!({"project": {"id": "project-1", "name": "Plugins"}})), + ) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/dataset/register")) + .respond_with(ResponseTemplate::new(200).set_body_json(registered( + "dataset", + "dataset-1", + "claude-plugin-eval · demo-plugin", + ))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/experiment/register")) + .respond_with(|request: &Request| { + let body: Value = serde_json::from_slice(&request.body).unwrap(); + let name = body["experiment_name"].as_str().unwrap().to_owned(); + let id = if name.contains("baseline") { + "exp-base" + } else { + "exp-with" + }; + ResponseTemplate::new(200).set_body_json(registered("experiment", id, &name)) + }) + .expect(2) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/logs3")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + + let result = fixture(); + let options = PlanOptions { + additional_metadata: Some(Map::from_iter([("commit".into(), json!("abc123"))])), + ..PlanOptions::default() + }; + let target = sync::SyncTarget { + auth: BackendAuth { + token: "token".into(), + api_url: Some(server.uri()), + app_url: Some(server.uri()), + org_name: Some("Acme".into()), + org_id: None, + }, + project: sync::ProjectSelection::Name("Plugins".into()), + import: ImportTarget { + socket: PathBuf::from("/nonexistent.sock"), + host: HostInfo { + serve_argv: Vec::new(), + version: "test".into(), + }, + route: SessionRoute::default(), + no_spawn: true, + }, + transcript_source: crate::args::ImportSource::Claude, + }; + let plan = SyncPlan::new(&result, &options, FIXTURE.as_bytes()); + let artifacts = plan.artifacts(sandbox::run_artifacts); + let summary = sync::sync_result( + &plan, + &artifacts, + Path::new("aggregate-result.json"), + target, + ) + .await + .unwrap(); + + assert_eq!(summary.project_name.as_deref(), Some("Plugins")); + assert_eq!(summary.dataset.as_ref().unwrap().id, "dataset-1"); + assert_eq!( + summary + .experiments + .iter() + .map(|experiment| experiment.arm) + .collect::>(), + vec![Arm::Baseline, Arm::WithPlugin] + ); + assert_eq!(summary.rows, 15); + assert_eq!(summary.traces_imported, 0); + assert_eq!(summary.warnings.len(), 1, "{:?}", summary.warnings); + let url = summary.experiments[1].url.as_deref().unwrap(); + assert!(url.starts_with(&format!( + "{}/app/Acme/p/Plugins/experiments/demo-plugin", + server.uri() + ))); + + let requests = server.received_requests().await.unwrap(); + let bodies = |route: &str| { + requests + .iter() + .filter(|request| request.url.path() == route) + .map(|request| serde_json::from_slice::(&request.body).unwrap()) + .collect::>() + }; + let experiments = bodies("/api/experiment/register"); + assert_eq!(experiments[0]["project_id"], "project-1"); + assert_eq!(experiments[0]["update"], true); + assert_eq!(experiments[0]["dataset_id"], "dataset-1"); + assert!(experiments[0].get("base_experiment").is_none()); + assert_eq!( + experiments[1]["base_experiment"], + experiments[0]["experiment_name"] + ); + let metadata = &experiments[1]["metadata"]; + assert_eq!(metadata["commit"], "abc123"); + let eval = &metadata["claude_plugin_eval"]; + assert_eq!(eval["arm"], "with"); + assert_eq!( + eval["plugin"], + json!({"name": "demo-plugin", "version": "0.0.1"}) + ); + assert_eq!(eval["cases_passed"], 2); + assert_eq!(eval["run_id"], plan.run_key.as_str()); + + let rows = bodies("/logs3") + .into_iter() + .flat_map(|body| { + assert_eq!(body["api_version"], 2); + body["rows"].as_array().unwrap().clone() + }) + .collect::>(); + assert_eq!( + rows.iter() + .filter(|row| row.get("dataset_id").is_some()) + .count(), + 2 + ); + assert_eq!( + rows.iter() + .filter(|row| row["experiment_id"] == "exp-base") + .count(), + 7 + ); + assert_eq!( + rows.iter() + .filter(|row| row["experiment_id"] == "exp-with") + .count(), + 8 + ); + assert!(requests + .iter() + .filter(|request| request.url.path() == "/logs3") + .all(|request| request.headers.get("x-bt-org-name").unwrap() == "Acme")); + } +} diff --git a/bt-daemon/src/trace_command.rs b/bt-daemon/src/trace_command.rs index f60915e4..877425ff 100644 --- a/bt-daemon/src/trace_command.rs +++ b/bt-daemon/src/trace_command.rs @@ -5,7 +5,7 @@ //! dispatch these commands without duplicating agent-specific CLI knowledge. use crate::agents::{self, Agent, Identity}; -use crate::{HookArgs, ImportArgs, RunArgs, ServeArgs, StatusArgs}; +use crate::{EvalArgs, HookArgs, ImportArgs, RunArgs, ServeArgs, StatusArgs}; use clap::{Args, Subcommand, ValueEnum}; use std::path::PathBuf; @@ -49,6 +49,8 @@ pub enum TraceCommand { Import(ImportArgs), /// Launch a coding agent with tracing enabled for this invocation. Run(RunArgs), + /// Run a coding agent's plugin eval suite and sync it to a Braintrust experiment. + Eval(EvalArgs), } #[derive(Debug, Clone, Args)] diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index d54137a5..f9dd0c34 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -918,6 +918,42 @@ pub async fn run_trace_with_matches( let summaries = run_import(import_args, target).await?; print_output(TraceCommandOutput::import(summaries), host.output_format) } + TraceCommand::Eval(eval_args) => { + eval_args.validate()?; + // Resolve the project and credentials before the suite runs, so a + // login prompt never waits until after a long eval. + let mut route = resolve_host_route( + &host, + RouteRequirements { + destination_required: true, + interactive_auth: true, + persistent_auth: false, + }, + ) + .await?; + route.apply_additional_metadata(eval_args.additional_metadata.as_deref())?; + route.apply_tags(&eval_args.tags)?; + let config = session_config(&host, &route).await?; + let target = crate::plugin_eval::EvalTarget { + auth: config.auth, + import: ImportTarget { + socket: paths::socket_path(eval_args.socket.as_deref()), + host: host_info(&host), + route, + no_spawn: eval_args.no_spawn, + }, + }; + let outcome = crate::plugin_eval::run_eval(eval_args, target).await?; + if let Some(summary) = outcome.summary { + print_output(TraceCommandOutput::eval(summary), host.output_format)?; + } + match outcome.status { + Some(status) if !status.success() => { + anyhow::bail!("plugin eval exited with {status}") + } + _ => Ok(()), + } + } TraceCommand::Run(run_args) => { run_args.validate_parent()?; let requirements = RouteRequirements { diff --git a/bt-daemon/src/transcript_import/claude.rs b/bt-daemon/src/transcript_import/claude.rs index 7c3477da..8a9a62a9 100644 --- a/bt-daemon/src/transcript_import/claude.rs +++ b/bt-daemon/src/transcript_import/claude.rs @@ -28,6 +28,10 @@ impl TranscriptImport for crate::agents::Claude { fn tail(&self) -> Box { Box::new(Tail::default()) } + + fn find_in_config(&self, config_dir: &Path, session_id: &str) -> anyhow::Result { + layout(vec![config_dir.join("projects")]).find(session_id) + } } #[derive(Default)] @@ -175,10 +179,10 @@ pub(super) fn layout(roots: Vec) -> TranscriptLayout { } fn roots(home: &Path) -> Vec { - let claude_home = std::env::var_os("CLAUDE_CONFIG_DIR") + let config_dir = std::env::var_os("CLAUDE_CONFIG_DIR") .map(PathBuf::from) .unwrap_or_else(|| home.join(".claude")); - vec![claude_home.join("projects")] + vec![config_dir.join("projects")] } fn filename_matches(path: &Path, session_id: &str) -> bool { diff --git a/bt-daemon/src/transcript_import/mod.rs b/bt-daemon/src/transcript_import/mod.rs index 4f406d2b..d7245d38 100644 --- a/bt-daemon/src/transcript_import/mod.rs +++ b/bt-daemon/src/transcript_import/mod.rs @@ -25,6 +25,14 @@ pub(crate) trait TranscriptImport: Agent { fn find(&self, home: &Path, session_id: &str) -> anyhow::Result; /// State for following one growing transcript. fn tail(&self) -> Box; + /// The saved transcript for one session in an agent config directory + /// other than the user's, such as an eval run's sandbox. + fn find_in_config(&self, _config_dir: &Path, _session_id: &str) -> anyhow::Result { + bail!( + "{} transcripts cannot be found in a separate config directory", + self.identity().display_name + ) + } } /// Where an agent saves its transcripts and how they are named. Each agent @@ -75,6 +83,16 @@ pub(crate) trait TailSession: Send { } } +/// An agent's transcript for `session_id` in a config directory other than +/// the user's. +pub(crate) fn find_in_config( + source: ImportSource, + config_dir: &Path, + session_id: &str, +) -> anyhow::Result { + importer(source).find_in_config(config_dir, session_id) +} + fn importer(source: ImportSource) -> &'static dyn TranscriptImport { let name = source.identity().id; registrar() diff --git a/bt-daemon/tests/fixtures/claude-plugin-eval/aggregate-result-2.1.333.json b/bt-daemon/tests/fixtures/claude-plugin-eval/aggregate-result-2.1.333.json new file mode 100644 index 00000000..3d4fc3e3 --- /dev/null +++ b/bt-daemon/tests/fixtures/claude-plugin-eval/aggregate-result-2.1.333.json @@ -0,0 +1,244 @@ +{ + "schemaVersion": 1, + "claudeVersion": "2.1.333", + "startedAt": "2026-12-01T17:46:28.972Z", + "durationSeconds": 11, + "costUsd": 0.005454540000000001, + "partial": false, + "suite": { + "root": "/home/user/demo-plugin", + "ablation": "with-without", + "modelOverride": "haiku", + "threshold": 0, + "concurrency": 1, + "plugins": [ + { + "name": "demo-plugin", + "version": "0.0.1", + "path": "/home/user/demo-plugin" + } + ] + }, + "cases": [ + { + "name": "greets", + "dir": "evals/greets", + "source": "prose", + "promptMarkdown": "Please greet me.", + "runsPerCase": 3, + "timeoutSeconds": 300, + "maxTurns": 4, + "graders": [ + { + "name": "friendly", + "type": "llm", + "weight": 2, + "graderMarkdown": "PASS if the response is a friendly greeting. FAIL otherwise.", + "config": { + "criteria": "PASS if the response is a friendly greeting. FAIL otherwise.", + "focus": "last_message" + } + }, + { + "name": "says-ahoy", + "type": "regex", + "weight": 1, + "config": { + "target": "last_message", + "pattern": "Ahoy", + "flags": "i", + "match": "contains" + } + }, + { + "name": "skill-fired", + "type": "tool_used", + "weight": 1, + "config": { + "tool": "Skill", + "input_match": "greet" + } + } + ], + "arms": { + "with": [ + { + "score": 1, + "passed": true, + "turns": 3, + "costUsd": 0.0015687299999999997, + "judgeCostUsd": 5.19e-05, + "durationSeconds": 5, + "startedAt": "2026-12-01T17:46:29.027Z", + "error": null, + "tracePath": "/nonexistent/claude-plugin-eval-fixture/e-WfkboS/out/trace.jsonl", + "skippedPaidGraders": false, + "graders": [ + { + "name": "friendly", + "passed": true, + "weight": 2, + "explanation": "judge votes: PASS PASS PASS", + "withOnly": false, + "scored": true, + "judgeVotes": [ + true, + true, + true + ], + "evidence": "Ahoy, friend!" + }, + { + "name": "says-ahoy", + "passed": true, + "weight": 1, + "explanation": "matched Ahoy", + "withOnly": false, + "scored": true + }, + { + "name": "skill-fired", + "passed": true, + "weight": 1, + "explanation": "Skill called 1x (expected 1..∞)", + "withOnly": true, + "scored": false + } + ] + } + ], + "without": [ + { + "score": 0.6666666666666666, + "passed": false, + "turns": 1, + "costUsd": 0.00136567, + "judgeCostUsd": 7.32e-05, + "durationSeconds": 3, + "startedAt": "2026-12-01T17:46:33.608Z", + "error": null, + "tracePath": "/nonexistent/claude-plugin-eval-fixture/e-akARtv/out/trace.jsonl", + "skippedPaidGraders": false, + "graders": [ + { + "name": "friendly", + "passed": true, + "weight": 2, + "explanation": "judge votes: PASS PASS PASS", + "withOnly": false, + "scored": true, + "judgeVotes": [ + true, + true, + true + ], + "evidence": "Hello! I'm Claude. What would you like to work on today?" + }, + { + "name": "says-ahoy", + "passed": false, + "weight": 1, + "explanation": "pattern not found in last_message", + "withOnly": false, + "scored": true + } + ] + } + ] + }, + "aggregates": { + "score": 1, + "passRate": 1, + "scoreWithout": 0.6666666666666666, + "passRateWithout": 0, + "delta": 0.33333333333333337 + } + }, + { + "name": "other", + "dir": "evals/nested/other", + "source": "prose", + "promptMarkdown": "What is 2+2? Answer with a single number.", + "runsPerCase": 3, + "timeoutSeconds": 300, + "maxTurns": 2, + "graders": [ + { + "name": "four", + "type": "regex", + "weight": 1, + "config": { + "target": "last_message", + "pattern": "\\b4\\b", + "flags": "", + "match": "contains" + } + } + ], + "arms": { + "with": [ + { + "score": 1, + "passed": true, + "turns": 1, + "costUsd": 0.0012647700000000001, + "judgeCostUsd": 0, + "durationSeconds": 2, + "startedAt": "2026-12-01T17:46:37.082Z", + "error": null, + "tracePath": "/nonexistent/claude-plugin-eval-fixture/e-nXpV5T/out/trace.jsonl", + "skippedPaidGraders": false, + "graders": [ + { + "name": "four", + "passed": true, + "weight": 1, + "explanation": "matched \\b4\\b", + "withOnly": false, + "scored": true + } + ] + } + ], + "without": [ + { + "score": 1, + "passed": true, + "turns": 1, + "costUsd": 0.00125537, + "judgeCostUsd": 0, + "durationSeconds": 1, + "startedAt": "2026-12-01T17:46:38.590Z", + "error": null, + "tracePath": "/nonexistent/claude-plugin-eval-fixture/e-tVYso6/out/trace.jsonl", + "skippedPaidGraders": false, + "graders": [ + { + "name": "four", + "passed": true, + "weight": 1, + "explanation": "matched \\b4\\b", + "withOnly": false, + "scored": true + } + ] + } + ] + }, + "aggregates": { + "score": 1, + "passRate": 1, + "scoreWithout": 1, + "passRateWithout": 1, + "delta": 0 + } + } + ], + "aggregates": { + "casesTotal": 2, + "casesPassed": 2, + "overallScore": 1, + "overallPassRate": 1, + "meanDelta": 0.16666666666666669 + } +} diff --git a/src/plugins/claude/content/README.md b/src/plugins/claude/content/README.md index 6e6d8414..96c996a7 100644 --- a/src/plugins/claude/content/README.md +++ b/src/plugins/claude/content/README.md @@ -105,6 +105,51 @@ bt trace import claude SESSION_ID --attach `run` leaves your saved settings alone. `import` reads a saved transcript; `--attach` follows it until Ctrl-C. Imports include only what the agent recorded. +## Plugin evals + +`bt trace eval claude` runs a +[`claude plugin eval`](https://code.claude.com/docs/en/plugin-evals) suite and +syncs it to Braintrust when it finishes. Arguments after `--` go to +`claude plugin eval` unchanged: + +```bash +bt trace eval --project my-plugin-evals claude -- ./my-plugin --runs 3 +bt trace eval claude --tag ci --base-experiment main-baseline -- . --trust-plugin --model claude-sonnet-5-5 +``` + +Each sync writes: + +- A dataset named `claude-plugin-eval · `, with one record per case + (the case prompt and its grader definitions). Use `--dataset NAME` to choose + another name, or `--no-dataset` to skip it. +- One experiment per ablation arm: `with plugin` and, when the suite runs a + no-plugin baseline, `baseline`. The with-plugin experiment uses the baseline + as its comparison base, so Braintrust shows the delta for every score. + `--base-experiment NAME` compares against a different experiment instead. +- One `eval` row per agent run. Its children are a score span for each grader + verdict (`1` or `0`), a `run_score` span with the run's weighted score, and + the run's Claude Code session (turns, LLM calls with token usage, and tool + calls), traced with the same translator as live sessions. + +To capture each run's session, `bt` passes `--keep-temp` to `claude plugin eval` +and deletes the kept sandboxes after syncing. If you pass `--keep-temp` +yourself, they are left in place. Results go to the `--output-dir` you pass, or +to a temporary directory whose path appears in the output. `bt` never passes +`--trust-plugin` for you. + +To sync a result that already exists, such as one produced in CI, use `--from` +with an `aggregate-result.json`, a `--json` result file, or a results +directory: + +```bash +bt trace eval claude --from evals/results/2026-12-01T17-02-11-482Z +``` + +Agent sessions are imported only when the suite ran with `--keep-temp` and its +sandboxes still exist. Otherwise the rows and scores are synced without them. +Syncing the same result again updates the same dataset records, experiments, +and rows instead of duplicating them. + ## Manage tracing ```bash From d15607faa972ef3fbed9dab0a5e88de9b732a5dc Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Tue, 1 Dec 2026 14:22:12 -0500 Subject: [PATCH 2/3] fix(claude): keep eval sandboxes and refresh login when syncing fails MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > 🤖 **This text was AI-generated.** Review of `bt trace eval claude` found five ways a sync could lose data or upload the wrong thing: ```text suite finishes ──▶ sync fails ──▶ sandboxes deleted ──▶ traces gone for good long suite ──────▶ token captured at launch has expired ──▶ upload fails reused --output-dir + failed rerun ──▶ previous result synced again bt trace eval claude -- --help ──▶ asks for a Braintrust login result entry without a `name` ──▶ whole result rejected ``` Now: - Sandboxes are deleted only when the sync succeeds and their transcript was imported. The ones that are kept are reported with the command to retry: ```text warning: kept 1 run sandbox(es) whose agent traces were not imported; retry with `bt trace eval claude --from /aggregate-result.json` ``` - Credentials are still checked before the suite runs, so a login prompt never waits for a long eval. They are resolved again through the host when syncing starts, which refreshes an expiring OAuth token. - A result is synced only if `aggregate-result.json` was written by this invocation, judged by its modification time. - `init` and `--help` invocations run `claude plugin eval` directly, without resolving a project or login. - Case, plugin, and grader `name` fields are optional, as AGENTS.md requires for agent-owned data. Cases with neither a name nor a directory are skipped with a warning. Verdicts without a name are not scored. Transcript imports still run concurrently, but are collected in order so each failure maps back to its sandbox. --- bt-daemon/src/plugin_eval/claude_result.rs | 53 ++++++++-- bt-daemon/src/plugin_eval/launch.rs | 27 ++++- bt-daemon/src/plugin_eval/mod.rs | 109 +++++++++++++++++---- bt-daemon/src/plugin_eval/output.rs | 3 + bt-daemon/src/plugin_eval/plan.rs | 19 ++-- bt-daemon/src/plugin_eval/sandbox.rs | 4 + bt-daemon/src/plugin_eval/sync.rs | 17 +++- bt-daemon/src/plugin_eval/tests.rs | 80 +++++++++++++++ bt-daemon/src/trace_runtime.rs | 17 +++- 9 files changed, 280 insertions(+), 49 deletions(-) diff --git a/bt-daemon/src/plugin_eval/claude_result.rs b/bt-daemon/src/plugin_eval/claude_result.rs index ceb18759..8d8cebce 100644 --- a/bt-daemon/src/plugin_eval/claude_result.rs +++ b/bt-daemon/src/plugin_eval/claude_result.rs @@ -31,6 +31,10 @@ pub(crate) struct EvalResult { #[serde(default)] pub cases: Vec, pub aggregates: Option, + /// Cases dropped while parsing because they have neither a name nor a + /// directory to identify them. + #[serde(skip)] + pub skipped_cases: usize, } #[derive(Debug, Clone, Deserialize)] @@ -47,7 +51,8 @@ pub(crate) struct Suite { #[derive(Debug, Clone, Deserialize, Serialize)] pub(crate) struct SuitePlugin { - pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, #[serde(skip_serializing_if = "Option::is_none")] pub version: Option, } @@ -70,7 +75,7 @@ pub(crate) struct SuiteAggregates { #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct Case { - pub name: String, + name: Option, /// The case directory relative to the plugin, such as `evals/greets`. pub dir: Option, pub prompt_markdown: Option, @@ -85,19 +90,37 @@ pub(crate) struct Case { impl Case { /// The stable identity of a case within its suite. Directory names are - /// unique; display names repeat across nested groups. + /// unique; display names repeat across nested groups. Parsing drops cases + /// that have neither. pub fn key(&self) -> &str { - self.dir.as_deref().unwrap_or(&self.name) + self.dir + .as_deref() + .or(self.name.as_deref()) + .unwrap_or_default() + } + + pub fn name(&self) -> &str { + self.name + .as_deref() + .or(self.dir.as_deref()) + .unwrap_or_default() + } + + fn is_identified(&self) -> bool { + self.dir.is_some() || self.name.is_some() } pub fn grader(&self, name: &str) -> Option<&GraderDefinition> { - self.graders.iter().find(|grader| grader.name == name) + self.graders + .iter() + .find(|grader| grader.name.as_deref() == Some(name)) } } #[derive(Debug, Clone, Deserialize, Serialize)] pub(crate) struct GraderDefinition { - pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, #[serde(rename = "type", skip_serializing_if = "Option::is_none")] pub kind: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -175,8 +198,9 @@ impl Aborted { #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all(deserialize = "camelCase"))] pub(crate) struct GraderResult { + /// Verdicts without a name cannot be matched to a score and are skipped. #[serde(skip_serializing)] - pub name: String, + pub name: Option, pub passed: Option, /// Whether the verdict counts toward the run score. Claude Code excludes /// plugin-fired indicators, such as `tool_used: Skill`, in two-arm runs. @@ -194,14 +218,19 @@ pub(crate) struct GraderResult { impl EvalResult { pub fn parse(bytes: &[u8], path: &Path) -> anyhow::Result { - let result: Self = serde_json::from_slice(bytes).map_err(|error| { + let mut result: Self = serde_json::from_slice(bytes).map_err(|error| { anyhow::anyhow!( "{} is not a claude plugin eval result: {error}", path.display() ) })?; match result.schema_version { - Some(SUPPORTED_SCHEMA_VERSION) => Ok(result), + Some(SUPPORTED_SCHEMA_VERSION) => { + let total = result.cases.len(); + result.cases.retain(Case::is_identified); + result.skipped_cases = total - result.cases.len(); + Ok(result) + } Some(version) => anyhow::bail!( "{} has unsupported claude plugin eval schemaVersion {version}; expected {SUPPORTED_SCHEMA_VERSION}", path.display() @@ -228,7 +257,11 @@ impl EvalResult { /// The plugin under test, when the suite resolved one. pub fn plugin(&self) -> Option<&SuitePlugin> { - self.suite.as_ref().and_then(|suite| suite.plugins.first()) + self.suite.as_ref()?.plugins.first() + } + + pub fn plugin_name(&self) -> Option<&str> { + self.plugin()?.name.as_deref() } pub fn model_override(&self) -> Option<&str> { diff --git a/bt-daemon/src/plugin_eval/launch.rs b/bt-daemon/src/plugin_eval/launch.rs index e4450ad5..cbb49d14 100644 --- a/bt-daemon/src/plugin_eval/launch.rs +++ b/bt-daemon/src/plugin_eval/launch.rs @@ -5,7 +5,8 @@ use super::claude_result::RESULT_FILE_NAME; use crate::managed_run::ManagedRun; use crate::{env, subprocess}; use std::ffi::{OsStr, OsString}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; /// How an eval invocation was adjusted, and where its results land. #[derive(Debug, Clone, PartialEq, Eq)] @@ -19,15 +20,29 @@ pub(crate) struct EvalInvocation { pub owns_sandboxes: bool, } +/// Whether `claude plugin eval` arguments run a suite that produces results. +/// Authoring (`init`) and help invocations do not. +pub(crate) fn runs_suite(args: &[OsString]) -> bool { + !(args.first().is_some_and(|arg| arg == "init") + || args.iter().any(|arg| arg == "--help" || arg == "-h")) +} + +/// A result file's modification time, if it exists. A result is new only if +/// this changed across the invocation, so a stale result left in a reused +/// `--output-dir` is never synced. +pub(crate) fn result_stamp(path: &Path) -> Option { + std::fs::metadata(path) + .and_then(|metadata| metadata.modified()) + .ok() +} + impl EvalInvocation { /// Add `--keep-temp` so each run's native transcript survives the suite, /// and `--output-dir` when the user did not choose where results go. /// Authoring (`init`) and help invocations pass through unchanged. The /// plugin trust prompt is never answered on the user's behalf. pub fn new(user_args: Vec, default_output_dir: impl FnOnce() -> PathBuf) -> Self { - let passthrough = user_args.first().is_some_and(|arg| arg == "init") - || user_args.iter().any(|arg| arg == "--help" || arg == "-h"); - if passthrough { + if !runs_suite(&user_args) { return Self { args: user_args, result_file: None, @@ -156,6 +171,10 @@ mod tests { #[test] fn authoring_and_help_pass_through() { for user in [args(&["init", "--bare", "case"]), args(&["--help"])] { + assert!( + !runs_suite(&user), + "{user:?} needs no Braintrust destination" + ); let invocation = EvalInvocation::new(user.clone(), || unreachable!()); assert_eq!(invocation.args, user); assert_eq!(invocation.result_file, None); diff --git a/bt-daemon/src/plugin_eval/mod.rs b/bt-daemon/src/plugin_eval/mod.rs index 2f75e1f2..002aa7e8 100644 --- a/bt-daemon/src/plugin_eval/mod.rs +++ b/bt-daemon/src/plugin_eval/mod.rs @@ -21,11 +21,13 @@ pub use output::{EvalSyncSummary, SyncedDataset, SyncedExperiment}; use crate::args::ImportSource; use crate::transcript_import::ImportTarget; -use crate::wire::{BackendAuth, SessionRoute}; +use crate::wire::SessionRoute; +use crate::{AuthResolveReason, TraceHostServices}; use clap::{Args, ValueEnum}; use claude_result::EvalResult; use std::ffi::OsString; use std::path::PathBuf; +use std::sync::Arc; /// Arguments for `bt trace eval`. #[derive(Debug, Clone, Args)] @@ -116,10 +118,29 @@ impl EvalSource { /// The resolved Braintrust destination for an eval sync. The import route /// carries the project, credentials selection, tags, and metadata. pub(crate) struct EvalTarget { - pub auth: BackendAuth, + /// Resolves the route's credentials when syncing starts, which may be long + /// after a suite was launched. + pub services: Arc, pub import: ImportTarget, } +impl EvalTarget { + async fn sync_target(self, source: EvalSource) -> anyhow::Result { + let lease = self + .services + .resolve_auth(&self.import.route.auth, AuthResolveReason::Initial) + .await?; + Ok(sync::SyncTarget { + auth: lease.auth, + project: sync::ProjectSelection::from_destination( + self.import.route.destination.as_ref(), + )?, + import: self.import, + transcript_source: source.transcript_source(), + }) + } +} + /// The outcome of `bt trace eval`. pub(crate) struct EvalOutcome { pub summary: Option, @@ -127,20 +148,31 @@ pub(crate) struct EvalOutcome { pub status: Option, } +impl EvalArgs { + /// Whether this invocation produces a result to sync. Authoring and help + /// invocations run without a Braintrust destination. + pub(crate) fn syncs(&self) -> bool { + self.from.is_some() || launch::runs_suite(&self.eval_args) + } +} + +/// Run an eval invocation that produces nothing to sync, such as `--help`. +pub(crate) async fn run_unsynced(args: EvalArgs) -> anyhow::Result { + let invocation = match args.source { + EvalSource::Claude => { + launch::EvalInvocation::new(args.eval_args, launch::default_output_dir) + } + }; + launch::run(&invocation).await +} + /// Run or read an eval suite and sync it. Arguments are validated by the /// caller before it resolves credentials. pub(crate) async fn run_eval(args: EvalArgs, target: EvalTarget) -> anyhow::Result { let options = args.plan_options(&target.import.route); - let sync_target = sync::SyncTarget { - auth: target.auth, - project: sync::ProjectSelection::from_destination( - target.import.route.destination.as_ref(), - )?, - import: target.import, - transcript_source: args.source.transcript_source(), - }; if let Some(from) = &args.from { let document = EvalResult::read(from)?; + let sync_target = target.sync_target(args.source).await?; let summary = sync_document(args.source, &document, &options, sync_target).await?; return Ok(EvalOutcome { summary: Some(summary), @@ -153,6 +185,10 @@ pub(crate) async fn run_eval(args: EvalArgs, target: EvalTarget) -> anyhow::Resu launch::EvalInvocation::new(args.eval_args, launch::default_output_dir) } }; + let previous = invocation + .result_file + .as_deref() + .and_then(launch::result_stamp); let status = launch::run(&invocation).await?; let Some(result_file) = invocation.result_file.as_deref() else { return Ok(EvalOutcome { @@ -160,10 +196,11 @@ pub(crate) async fn run_eval(args: EvalArgs, target: EvalTarget) -> anyhow::Resu status: Some(status), }); }; - if !result_file.exists() { + let written = launch::result_stamp(result_file); + if written.is_none() || written == previous { if status.success() { anyhow::bail!( - "claude plugin eval wrote no result at {}", + "claude plugin eval wrote no new result at {}", result_file.display() ); } @@ -173,12 +210,12 @@ pub(crate) async fn run_eval(args: EvalArgs, target: EvalTarget) -> anyhow::Resu }); } let document = EvalResult::read(result_file)?; - let synced = sync_document(args.source, &document, &options, sync_target).await; + let mut synced = match target.sync_target(args.source).await { + Ok(sync_target) => sync_document(args.source, &document, &options, sync_target).await, + Err(error) => Err(error), + }; if invocation.owns_sandboxes { - for error in sandbox::remove_all(&sandbox::sandboxes(&document.0)) { - tracing::warn!(%error, "could not delete a claude plugin eval sandbox"); - eprintln!("warning: {error:#}"); - } + clean_up_sandboxes(&document, &mut synced); } Ok(EvalOutcome { summary: Some(synced?), @@ -198,3 +235,41 @@ async fn sync_document( }; sync::sync_result(&plan, &artifacts, file, target).await } + +/// Delete the sandboxes kept only so their transcripts could be imported. +/// Sandboxes whose transcripts were not imported, including every sandbox +/// when the sync failed, are kept so `--from` can retry them. +fn clean_up_sandboxes( + (result, file, _): &(EvalResult, PathBuf, Vec), + synced: &mut anyhow::Result, +) { + let (keep, remove): (Vec<_>, Vec<_>) = + sandbox::sandboxes(result) + .into_iter() + .partition(|sandbox| match synced { + Ok(summary) => summary + .failed_transcripts + .iter() + .any(|transcript| transcript.starts_with(sandbox.root())), + Err(_) => true, + }); + for error in sandbox::remove_all(&remove) { + tracing::warn!(%error, "could not delete a claude plugin eval sandbox"); + eprintln!("warning: {error:#}"); + } + let kept = keep + .iter() + .filter(|sandbox| sandbox.root().exists()) + .count(); + if kept == 0 { + return; + } + let warning = format!( + "kept {kept} run sandbox(es) whose agent traces were not imported; retry with `bt trace eval claude --from {}`", + file.display() + ); + match synced { + Ok(summary) => summary.warnings.push(warning), + Err(_) => eprintln!("warning: {warning}"), + } +} diff --git a/bt-daemon/src/plugin_eval/output.rs b/bt-daemon/src/plugin_eval/output.rs index a636f02d..c6389338 100644 --- a/bt-daemon/src/plugin_eval/output.rs +++ b/bt-daemon/src/plugin_eval/output.rs @@ -21,6 +21,9 @@ pub struct EvalSyncSummary { pub traces_imported: usize, #[serde(skip_serializing_if = "Vec::is_empty")] pub warnings: Vec, + /// Transcripts whose import failed; their sandboxes are kept for a retry. + #[serde(skip)] + pub(crate) failed_transcripts: Vec, } #[derive(Debug, Clone, Serialize)] diff --git a/bt-daemon/src/plugin_eval/plan.rs b/bt-daemon/src/plugin_eval/plan.rs index 69e2bf9b..6800847e 100644 --- a/bt-daemon/src/plugin_eval/plan.rs +++ b/bt-daemon/src/plugin_eval/plan.rs @@ -87,10 +87,7 @@ impl<'a> SyncPlan<'a> { } fn plugin_name(&self) -> &str { - self.result - .plugin() - .map(|plugin| plugin.name.as_str()) - .unwrap_or(DEFAULT_PREFIX) + self.result.plugin_name().unwrap_or(DEFAULT_PREFIX) } pub fn dataset_name(&self) -> Option { @@ -192,7 +189,7 @@ impl<'a> SyncPlan<'a> { input: CaseInput::of(case), metadata: Namespaced { claude_plugin_eval: CaseMetadata { - case: &case.name, + case: case.name(), case_dir: case.dir.as_deref(), max_turns: case.max_turns, timeout_seconds: case.timeout_seconds, @@ -269,7 +266,7 @@ impl<'a> SyncPlan<'a> { scores: BTreeMap::new(), metadata: Some(Namespaced { claude_plugin_eval: RunMetadata { - case: &case.name, + case: case.name(), case_dir: case.dir.as_deref(), run_index: index, passed: run.passed, @@ -326,13 +323,13 @@ impl<'a> SyncPlan<'a> { )?); } for grader in &run.graders { - let Some(passed) = grader.passed else { + let (Some(name), Some(passed)) = (grader.name.as_deref(), grader.passed) else { continue; }; rows.push(score( - &format!("grader{SEP}{}", grader.name), - &grader.name, - case.grader(&grader.name), + &format!("grader{SEP}{name}"), + name, + case.grader(name), serde_json::to_value(grader)?, f64::from(u8::from(passed)), )?); @@ -460,7 +457,7 @@ struct CaseInput<'a> { impl<'a> CaseInput<'a> { fn of(case: &'a Case) -> Self { Self { - case: &case.name, + case: case.name(), prompt: case.prompt_markdown.as_deref(), } } diff --git a/bt-daemon/src/plugin_eval/sandbox.rs b/bt-daemon/src/plugin_eval/sandbox.rs index bd9267a6..53d149fe 100644 --- a/bt-daemon/src/plugin_eval/sandbox.rs +++ b/bt-daemon/src/plugin_eval/sandbox.rs @@ -33,6 +33,10 @@ impl RunSandbox { }) } + pub fn root(&self) -> &Path { + &self.root + } + /// The run's native Claude Code transcript. pub fn transcript(&self, session_id: &str) -> anyhow::Result { crate::transcript_import::find_in_config( diff --git a/bt-daemon/src/plugin_eval/sync.rs b/bt-daemon/src/plugin_eval/sync.rs index 27c0f365..3b944b45 100644 --- a/bt-daemon/src/plugin_eval/sync.rs +++ b/bt-daemon/src/plugin_eval/sync.rs @@ -129,6 +129,12 @@ pub(crate) async fn sync_result( } let mut warnings = Vec::new(); + if plan.result.skipped_cases > 0 { + warnings.push(format!( + "skipped {} case(s) without a name or directory", + plan.result.skipped_cases + )); + } let mut unavailable = artifacts .values() .filter_map(|found| found.transcript.as_ref().err()); @@ -143,14 +149,18 @@ pub(crate) async fn sync_result( .map(|(experiment_id, root, transcript)| { import_run_trace(&target, experiment_id, root, transcript) }) - .buffer_unordered(CONCURRENT_IMPORTS) + .buffered(CONCURRENT_IMPORTS) .collect::>() .await; let mut imported = 0; - for result in imports { + let mut failed_transcripts = Vec::new(); + for ((_, _, transcript), result) in traces.iter().zip(imports) { match result { Ok(()) => imported += 1, - Err(error) => warnings.push(format!("{error:#}")), + Err(error) => { + warnings.push(format!("{error:#}")); + failed_transcripts.push(transcript.clone()); + } } } @@ -167,6 +177,7 @@ pub(crate) async fn sync_result( rows, traces_imported: imported, warnings, + failed_transcripts, }) } diff --git a/bt-daemon/src/plugin_eval/tests.rs b/bt-daemon/src/plugin_eval/tests.rs index 113cae4b..bd50141d 100644 --- a/bt-daemon/src/plugin_eval/tests.rs +++ b/bt-daemon/src/plugin_eval/tests.rs @@ -5,6 +5,7 @@ )] use super::claude_result::{Arm, EvalResult}; +use super::output::EvalSyncSummary; use super::plan::{PlanOptions, RunArtifacts, SyncPlan, RUN_SCORE}; use super::{sandbox, sync}; use serde_json::{json, Map, Value}; @@ -35,6 +36,85 @@ fn rejects_other_schema_versions() { assert!(EvalResult::parse(br#"{"cases":[]}"#, Path::new("r.json")).is_err()); } +#[test] +fn entries_without_names_are_skipped_instead_of_rejecting_the_result() { + let document = json!({ + "schemaVersion": 1, + "suite": {"plugins": [{"version": "1.0.0"}]}, + "cases": [ + {"graders": []}, + {"dir": "evals/only-dir", "arms": {"with": [{"score": 1, "graders": [ + {"passed": true}, + {"name": "named", "passed": true} + ]}]}} + ] + }); + let bytes = serde_json::to_vec(&document).unwrap(); + let result = EvalResult::parse(&bytes, Path::new("r.json")).unwrap(); + assert_eq!(result.skipped_cases, 1); + assert_eq!(result.cases[0].name(), "evals/only-dir"); + let options = PlanOptions::default(); + let plan = SyncPlan::new(&result, &options, &bytes); + assert!(plan + .experiment_name(Arm::WithPlugin) + .starts_with("claude-plugin-eval · ")); + let rows = plan + .experiment_rows(Arm::WithPlugin, "exp", None, &BTreeMap::new()) + .unwrap(); + // The root, its run score, and the one named verdict. + assert_eq!(rows.len(), 3); + assert_eq!(rows_named(&rows, "named").len(), 1); +} + +#[test] +fn sandboxes_are_kept_when_their_traces_were_not_imported() { + // Both sit directly in a temp root, so either could be deleted. + let sandbox = || { + let root = tempfile::Builder::new() + .prefix("e-") + .tempdir_in(std::env::temp_dir()) + .unwrap() + .keep(); + std::fs::create_dir_all(root.join("out")).unwrap(); + root + }; + let imported = sandbox(); + let failed = sandbox(); + let mut result = fixture(); + result.cases[0].arms.with[0].trace_path = Some(imported.join("out/trace.jsonl")); + result.cases[1].arms.with[0].trace_path = Some(failed.join("out/trace.jsonl")); + let document = (result, PathBuf::from("aggregate-result.json"), Vec::new()); + let summary = || EvalSyncSummary { + results_path: PathBuf::new(), + partial: false, + project_id: String::new(), + project_name: None, + dataset: None, + experiments: Vec::new(), + rows: 0, + traces_imported: 1, + warnings: Vec::new(), + failed_transcripts: vec![failed.join("config/projects/p/s.jsonl")], + }; + + let mut failed_sync: anyhow::Result = Err(anyhow::anyhow!("offline")); + super::clean_up_sandboxes(&document, &mut failed_sync); + assert!( + imported.exists() && failed.exists(), + "a failed sync keeps every sandbox" + ); + + let mut synced = Ok(summary()); + super::clean_up_sandboxes(&document, &mut synced); + assert!(!imported.exists()); + assert!(failed.exists()); + let warnings = synced.unwrap().warnings; + assert!( + warnings[0].contains("--from aggregate-result.json"), + "{warnings:?}" + ); +} + #[test] fn baseline_is_registered_first_and_is_the_with_plugin_base() { let result = fixture(); diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index f9dd0c34..f389bafe 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -920,8 +920,17 @@ pub async fn run_trace_with_matches( } TraceCommand::Eval(eval_args) => { eval_args.validate()?; - // Resolve the project and credentials before the suite runs, so a - // login prompt never waits until after a long eval. + if !eval_args.syncs() { + let status = crate::plugin_eval::run_unsynced(eval_args).await?; + return if status.success() { + Ok(()) + } else { + anyhow::bail!("plugin eval exited with {status}") + }; + } + // Check the project and credentials before the suite runs, so a + // login prompt never waits until after a long eval. Credentials + // are resolved again when syncing starts. let mut route = resolve_host_route( &host, RouteRequirements { @@ -933,9 +942,9 @@ pub async fn run_trace_with_matches( .await?; route.apply_additional_metadata(eval_args.additional_metadata.as_deref())?; route.apply_tags(&eval_args.tags)?; - let config = session_config(&host, &route).await?; + session_config(&host, &route).await?; let target = crate::plugin_eval::EvalTarget { - auth: config.auth, + services: host.services.clone(), import: ImportTarget { socket: paths::socket_path(eval_args.socket.as_deref()), host: host_info(&host), From 4aa8df39381a1842a575148a876232a7444ab84c Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Tue, 1 Dec 2026 14:37:39 -0500 Subject: [PATCH 3/3] fix(claude): keep stored eval outputs when re-syncing without sandboxes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > 🤖 **This text was AI-generated.** A successful `bt trace eval claude` run deletes the run sandboxes it kept, because their transcripts are already in Braintrust. Each run's final reply and session ID are read from those sandboxes. Syncing the same result again with `--from` could no longer read them, and experiment rows were written as full replacements, so the re-sync erased the stored values: ```text first sync eval row: output = "Ahoy, friend!", session_id = f47d… sandboxes deleted --from again eval row: output = (none), session_id = (none), agent_trace_unavailable = "sandbox was deleted" ``` This also hit runs whose traces were imported when retrying a suite where only some imports failed. Root `eval` rows are now written with `_is_merge`, so fields a sync cannot read from disk keep their stored values. Score rows are still replaced, since every score is fully known from the result document. A deleted sandbox no longer records `agent_trace_unavailable` on the row, because an earlier sync may have imported that trace. The reason is now typed (`TraceUnavailable`). Only a trace that exists but cannot be read is recorded on its row. The command still warns when runs have no agent trace. --- bt-daemon/src/plugin_eval/plan.rs | 47 +++++++++++++++++++++++++--- bt-daemon/src/plugin_eval/sandbox.rs | 24 ++++++++------ bt-daemon/src/plugin_eval/tests.rs | 32 ++++++++++++------- 3 files changed, 78 insertions(+), 25 deletions(-) diff --git a/bt-daemon/src/plugin_eval/plan.rs b/bt-daemon/src/plugin_eval/plan.rs index 6800847e..205182de 100644 --- a/bt-daemon/src/plugin_eval/plan.rs +++ b/bt-daemon/src/plugin_eval/plan.rs @@ -44,15 +44,47 @@ pub(crate) struct RunArtifacts { pub final_message: Option, /// The native transcript to import as the run's agent trace, or why the /// trace is unavailable. - pub transcript: Result, + pub transcript: Result, } impl RunArtifacts { - pub fn unavailable(reason: impl Into) -> Self { + pub fn unavailable(reason: TraceUnavailable) -> Self { Self { session_id: None, final_message: None, - transcript: Err(reason.into()), + transcript: Err(reason), + } + } +} + +/// Why a run's agent trace cannot be imported. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum TraceUnavailable { + /// The sandbox is gone: the suite ran without `--keep-temp`, or an + /// earlier sync already imported the trace and deleted it. + SandboxDeleted, + /// The sandbox exists, but its trace cannot be read. + Unreadable(String), +} + +impl TraceUnavailable { + /// The reason to record on the run's row. A deleted sandbox records + /// nothing, so a re-sync never marks a trace an earlier sync imported. + fn recorded(&self) -> Option<&str> { + match self { + Self::SandboxDeleted => None, + Self::Unreadable(reason) => Some(reason), + } + } +} + +impl std::fmt::Display for TraceUnavailable { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::SandboxDeleted => f.write_str( + "the run's sandbox no longer exists; rerun with --keep-temp to import agent traces", + ), + Self::Unreadable(reason) => f.write_str(reason), } } } @@ -258,6 +290,9 @@ impl<'a> SyncPlan<'a> { } let aborted = run.aborted.as_ref().map(|aborted| aborted.describe()); rows.push(serde_json::to_value(ExperimentRow { + // A re-sync may lack the sandbox the first sync read the final + // reply and session from. Merging keeps those stored values. + is_merge: true, ids: SpanIds::root(&root_id), experiment_id, input: Some(CaseInput::of(case)), @@ -277,7 +312,7 @@ impl<'a> SyncPlan<'a> { model: case.model.as_deref().or(self.result.model_override()), agent_trace_unavailable: found .and_then(|found| found.transcript.as_ref().err()) - .map(String::as_str), + .and_then(TraceUnavailable::recorded), }, }), metrics, @@ -357,6 +392,7 @@ struct ScoreSpan<'a> { fn score_row(span: ScoreSpan<'_>) -> anyhow::Result { let id = crate::ids::span_id(span.root_id, span.key); let row = ExperimentRow::<_, _, ()> { + is_merge: false, ids: SpanIds { id: &id, span_id: &id, @@ -556,6 +592,9 @@ impl<'a> SpanIds<'a> { #[derive(Serialize)] struct ExperimentRow<'a, I: Serialize, O: Serialize, M: Serialize> { + /// Merge into an existing row, keeping fields this sync omits. + #[serde(rename = "_is_merge", skip_serializing_if = "std::ops::Not::not")] + is_merge: bool, #[serde(flatten)] ids: SpanIds<'a>, experiment_id: &'a str, diff --git a/bt-daemon/src/plugin_eval/sandbox.rs b/bt-daemon/src/plugin_eval/sandbox.rs index 53d149fe..3800cdaf 100644 --- a/bt-daemon/src/plugin_eval/sandbox.rs +++ b/bt-daemon/src/plugin_eval/sandbox.rs @@ -8,7 +8,7 @@ //! sandbox read-only and `sealed/` inaccessible. use super::claude_result::{EvalResult, Run, StreamSummary}; -use super::plan::RunArtifacts; +use super::plan::{RunArtifacts, TraceUnavailable}; use crate::args::ImportSource; use std::path::{Path, PathBuf}; @@ -79,28 +79,32 @@ impl RunSandbox { /// and native transcript. pub(crate) fn run_artifacts(run: &Run) -> RunArtifacts { let Some(trace_path) = run.trace_path.as_deref() else { - return RunArtifacts::unavailable("the result does not record the run's trace"); + return RunArtifacts::unavailable(TraceUnavailable::Unreadable( + "the result does not record the run's trace".into(), + )); }; let Some(sandbox) = RunSandbox::from_trace_path(trace_path) else { - return RunArtifacts::unavailable(format!( + return RunArtifacts::unavailable(TraceUnavailable::Unreadable(format!( "unrecognized trace location {}", trace_path.display() - )); + ))); }; if !sandbox.root.is_dir() { - return RunArtifacts::unavailable( - "the run's sandbox was deleted; rerun with --keep-temp to import agent traces", - ); + return RunArtifacts::unavailable(TraceUnavailable::SandboxDeleted); } let summary = match StreamSummary::read(trace_path) { Ok(summary) => summary, - Err(error) => return RunArtifacts::unavailable(error.to_string()), + Err(error) => { + return RunArtifacts::unavailable(TraceUnavailable::Unreadable(error.to_string())) + } }; let transcript = match summary.session_id.as_deref() { Some(session_id) => sandbox .transcript(session_id) - .map_err(|error| error.to_string()), - None => Err("the run's trace names no session".into()), + .map_err(|error| TraceUnavailable::Unreadable(error.to_string())), + None => Err(TraceUnavailable::Unreadable( + "the run's trace names no session".into(), + )), }; RunArtifacts { session_id: summary.session_id, diff --git a/bt-daemon/src/plugin_eval/tests.rs b/bt-daemon/src/plugin_eval/tests.rs index bd50141d..800fa4af 100644 --- a/bt-daemon/src/plugin_eval/tests.rs +++ b/bt-daemon/src/plugin_eval/tests.rs @@ -6,7 +6,7 @@ use super::claude_result::{Arm, EvalResult}; use super::output::EvalSyncSummary; -use super::plan::{PlanOptions, RunArtifacts, SyncPlan, RUN_SCORE}; +use super::plan::{PlanOptions, RunArtifacts, SyncPlan, TraceUnavailable, RUN_SCORE}; use super::{sandbox, sync}; use serde_json::{json, Map, Value}; use std::collections::BTreeMap; @@ -286,25 +286,35 @@ fn baseline_rows_record_failed_verdicts_and_missing_traces() { let result = fixture(); let options = PlanOptions::default(); let plan = SyncPlan::new(&result, &options, FIXTURE.as_bytes()); - let artifacts = plan.artifacts(sandbox::run_artifacts); + // The fixture's sandboxes no longer exist; one run's trace is unreadable. + let mut artifacts = plan.artifacts(sandbox::run_artifacts); + let unreadable = plan.root_span_id(&result.cases[1], Arm::Baseline, 0); + artifacts.insert( + unreadable, + RunArtifacts::unavailable(TraceUnavailable::Unreadable("truncated trace".into())), + ); let rows = plan .experiment_rows(Arm::Baseline, "exp-0", None, &artifacts) .unwrap(); // greets: root, run score, two graders; other: root, run score, one grader. assert_eq!(rows.len(), 7); - let root = rows_named(&rows, "eval")[0]; + let roots = rows_named(&rows, "eval"); + let root = roots[0]; assert!(root.get("origin").is_none()); + // Root rows merge, so a re-sync without the sandbox keeps the output and + // session an earlier sync stored, and does not mark its trace missing. + assert_eq!(root["_is_merge"], true); assert!(root.get("output").is_none()); - assert!( - root["metadata"]["claude_plugin_eval"]["agent_trace_unavailable"] - .as_str() - .unwrap() - .contains("--keep-temp") - ); + assert!(root["metadata"]["claude_plugin_eval"] + .get("agent_trace_unavailable") + .is_none()); assert_eq!( - rows_named(&rows, "says-ahoy")[0]["scores"], - json!({"says-ahoy": 0.0}) + roots[1]["metadata"]["claude_plugin_eval"]["agent_trace_unavailable"], + "truncated trace" ); + let verdict = rows_named(&rows, "says-ahoy")[0]; + assert_eq!(verdict["scores"], json!({"says-ahoy": 0.0})); + assert!(verdict.get("_is_merge").is_none()); let run_score = rows_named(&rows, RUN_SCORE)[0]; assert!((run_score["scores"][RUN_SCORE].as_f64().unwrap() - 2.0 / 3.0).abs() < 1e-9); assert!(rows_named(&rows, "skill-fired").is_empty());