Skip to main content

blyte_cli/
report.rs

1//! The headless solver's machine-readable run report (`--report <path>`).
2//!
3//! This is the contract between the harness and anything that measures it: blyte-eval
4//! reads exactly this shape. Every field is always written, because a zero is a measurement and
5//! an absent key is a bug. Schema: docs/superpowers/specs/2026-09-23-native-harness-eval-surface-design.md
6
7use std::collections::BTreeMap;
8use std::path::Path;
9use std::time::Duration;
10
11use blyte_agent::run::{Outcome, RunReport};
12use blyte_agent::sandbox::Profile;
13use blyte_agent::state::State;
14use serde::Serialize;
15
16use crate::task_runner::TaskConfig;
17
18pub const SCHEMA_VERSION: u32 = 1;
19
20#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
21pub struct UsageRecord {
22    pub input: u64,
23    pub cached: u64,
24    pub output: u64,
25    pub thinking: u64,
26}
27
28/// The report's name for an outcome, and its error message if it carries one.
29fn outcome_name(outcome: &Outcome) -> (&'static str, Option<String>) {
30    match outcome {
31        Outcome::Verified => ("verified", None),
32        Outcome::Finished => ("finished", None),
33        Outcome::BudgetExhausted => ("budget_exhausted", None),
34        Outcome::GateFailed => ("gate_failed", None),
35        Outcome::Blocked(why) => ("blocked", Some(why.clone())),
36        Outcome::Error(e) => ("error", Some(e.clone())),
37    }
38}
39
40#[derive(Debug, Clone, Default, Serialize, PartialEq)]
41pub struct RunRecord {
42    pub schema_version: u32,
43    /// The commit this blyte was built from (`build.rs`), or `unknown`.
44    pub harness_build: String,
45    pub outcome: String,
46    pub error: Option<String>,
47    pub final_message: Option<String>,
48    pub model_requested: Option<String>,
49    pub model_id: Option<String>,
50    pub effort: Option<String>,
51    pub context: String,
52    pub gated: bool,
53    /// Where the gate came from: `none` (ungated) or `user` (`--gate`).
54    pub gate_source: String,
55    #[serde(default)]
56    pub gate_left_out: Vec<String>,
57    pub container: Option<String>,
58    pub container_workdir: String,
59    /// Whether local shell commands ran under macOS seatbelt sandbox isolation.
60    pub sandboxed: bool,
61    /// The sandbox mechanism active for the run (`container`, `seatbelt`, `landlock`, `landlock-offline`, `off`).
62    pub sandbox: String,
63    /// Outbound network mode for commands (`on` or `off`).
64    pub network: String,
65    /// Filesystem paths permitted for reading despite credential deny-lists.
66    pub allow_read: Vec<String>,
67    /// Environment variables permitted to pass to commands despite looking like credentials.
68    pub pass_env: Vec<String>,
69    /// Names of environment variables withheld from commands by the credential filter.
70    pub withheld_env: Vec<String>,
71    pub duration_seconds: f64,
72    pub turns: u32,
73    pub empty_turns: u32,
74    #[serde(default)]
75    pub truncated_turns: u32,
76    #[serde(default)]
77    pub read_loop: bool,
78    #[serde(default)]
79    pub peak_read_repeats: u32,
80    #[serde(default)]
81    pub fold_thrash: bool,
82    #[serde(default)]
83    pub big_read_turns: u32,
84    pub tool_calls: u32,
85    pub gate_attempts: u32,
86    pub rollbacks: u32,
87    pub provider_retries: u32,
88    /// List-price cost in USD, when the model's price is known.
89    pub cost_usd: Option<f64>,
90    /// Spending cap in USD given with `--max-cost`, if any.
91    pub max_cost_usd: Option<f64>,
92    /// Whether the run stopped because spending reached `--max-cost`.
93    pub cost_capped: bool,
94    /// Fold budget given with `--fold-budget`, if any.
95    pub fold_budget: Option<usize>,
96    /// Per-call usage (see `blyte_agent::run::TurnUsage`).
97    pub turn_usage: Vec<blyte_agent::run::TurnUsage>,
98    pub usage: UsageRecord,
99    pub gate_ms: Vec<u64>,
100    #[serde(default)]
101    pub gate_turns: Vec<u32>,
102    pub gate_wait_ms: Vec<u64>,
103    pub gate_failures: Vec<String>,
104    pub tool_counts: BTreeMap<String, u32>,
105    pub model_seconds: f64,
106    pub tools_seconds: f64,
107    pub gate_seconds: f64,
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub quote_problems: Option<Vec<String>>,
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub claim_check: Option<blyte_agent::claim_check::ClaimCheck>,
112}
113
114impl RunRecord {
115    fn base(config: &TaskConfig, elapsed: Duration) -> Self {
116        let gated = config.gate.as_deref().is_some_and(|g| !g.trim().is_empty());
117        let sandboxed = config.container.is_none()
118            && config.sandbox == "on"
119            && blyte_agent::sandbox::available();
120        let withheld_env = if config.container.is_some() {
121            Vec::new()
122        } else {
123            blyte_agent::shell::withheld_env()
124        };
125        let gate_left_out = config
126            .report
127            .as_deref()
128            .and_then(read_gate_left_out_from_start)
129            .unwrap_or_default();
130        Self {
131            schema_version: SCHEMA_VERSION,
132            harness_build: env!("BLYTE_BUILD").into(),
133            outcome: "error".into(),
134            error: None,
135            final_message: None,
136            model_requested: config.model.clone(),
137            model_id: None,
138            effort: None,
139            context: config.context_strategy.clone(),
140            gated,
141            gate_source: if gated { "user" } else { "none" }.into(),
142            gate_left_out,
143            container: config.container.clone(),
144            container_workdir: config.container_workdir.clone(),
145            sandboxed,
146            sandbox: sandbox_kind(config),
147            network: config.network.clone(),
148            allow_read: config
149                .allow_read
150                .iter()
151                .map(|p| p.display().to_string())
152                .collect(),
153            pass_env: config.pass_env.clone(),
154            withheld_env,
155            duration_seconds: elapsed.as_secs_f64(),
156            turns: 0,
157            empty_turns: 0,
158            truncated_turns: 0,
159            read_loop: false,
160            peak_read_repeats: 0,
161            fold_thrash: false,
162            big_read_turns: 0,
163            tool_calls: 0,
164            gate_attempts: 0,
165            rollbacks: 0,
166            provider_retries: 0,
167            cost_usd: None,
168            max_cost_usd: config.max_cost_usd,
169            cost_capped: false,
170            fold_budget: config.fold_budget,
171            turn_usage: Vec::new(),
172            usage: UsageRecord::default(),
173            gate_ms: Vec::new(),
174            gate_turns: Vec::new(),
175            gate_wait_ms: Vec::new(),
176            gate_failures: Vec::new(),
177            tool_counts: BTreeMap::new(),
178            model_seconds: 0.0,
179            tools_seconds: 0.0,
180            gate_seconds: 0.0,
181            quote_problems: None,
182            claim_check: None,
183        }
184    }
185
186    /// A run that never reached the loop, e.g. a missing API key.
187    pub fn from_error(config: &TaskConfig, error: &str, elapsed: Duration) -> Self {
188        Self {
189            error: Some(error.to_string()),
190            ..Self::base(config, elapsed)
191        }
192    }
193
194    /// A run the loop completed, whatever its outcome.
195    pub fn from_run(
196        config: &TaskConfig,
197        model_id: &str,
198        outcome: &Outcome,
199        report: &RunReport,
200        state: &State,
201        elapsed: Duration,
202    ) -> Self {
203        let (outcome_name, error) = outcome_name(outcome);
204        let model_ms: u64 = report.turn_usage.iter().map(|t| t.model_ms).sum();
205        let tools_ms: u64 = report.turn_usage.iter().map(|t| t.tools_ms).sum();
206        let gate_ms_sum: u64 = report.gate_ms.iter().sum();
207        Self {
208            outcome: outcome_name.into(),
209            error,
210            final_message: report.final_message.clone(),
211            model_id: Some(model_id.to_string()),
212            turns: report.outcome_turns,
213            empty_turns: report.empty_turns,
214            truncated_turns: report.truncated_turns,
215            read_loop: report.read_loop,
216            peak_read_repeats: report.peak_read_repeats,
217            fold_thrash: report.fold_thrash,
218            big_read_turns: report.big_read_turns,
219            tool_calls: report.tool_calls,
220            gate_attempts: report.gate_attempts,
221            rollbacks: state.runtime.rollbacks,
222            provider_retries: report.provider_retries,
223            cost_usd: blyte_provider::pricing(model_id).map(|p| p.cost(&report.usage)),
224            cost_capped: report.cost_capped,
225            turn_usage: report.turn_usage.clone(),
226            usage: UsageRecord {
227                input: report.usage.input,
228                cached: report.usage.cached,
229                output: report.usage.output,
230                thinking: report.usage.thinking,
231            },
232            gate_ms: report.gate_ms.clone(),
233            gate_turns: report.gate_turns.clone(),
234            gate_wait_ms: report.gate_wait_ms.clone(),
235            gate_failures: report.gate_failures.clone(),
236            tool_counts: report.tool_counts.clone(),
237            model_seconds: model_ms as f64 / 1000.0,
238            tools_seconds: tools_ms as f64 / 1000.0,
239            gate_seconds: gate_ms_sum as f64 / 1000.0,
240            quote_problems: report.quote_problems.clone(),
241            claim_check: report.claim_check.clone(),
242            ..Self::base(config, elapsed)
243        }
244    }
245}
246
247pub fn write(path: &Path, record: &RunRecord) -> Result<(), String> {
248    let json = serde_json::to_string_pretty(record)
249        .map_err(|e| format!("report serialisation failed: {e}"))?;
250    std::fs::write(path, json + "\n")
251        .map_err(|e| format!("cannot write report {}: {e}", path.display()))
252}
253
254fn read_gate_left_out_from_start(report_path: &Path) -> Option<Vec<String>> {
255    let file_name = report_path.file_name()?.to_str()?;
256    let id = file_name.strip_suffix(".report.json")?;
257    let start_path = report_path.with_file_name(format!("{id}.start.json"));
258    let content = std::fs::read_to_string(start_path).ok()?;
259    let val: serde_json::Value = serde_json::from_str(&content).ok()?;
260    let arr = val.get("gate_left_out")?.as_array()?;
261    let mut out = Vec::new();
262    for item in arr {
263        if let (Some(cmd), Some(reason)) = (
264            item.get("command").and_then(|v| v.as_str()),
265            item.get("reason").and_then(|v| v.as_str()),
266        ) {
267            out.push(format!("{cmd} ({reason})"));
268        } else if let Some(s) = item.as_str() {
269            out.push(s.to_string());
270        }
271    }
272    Some(out)
273}
274
275/// Returns the name of the sandbox mechanism active for the task configuration.
276pub fn sandbox_kind(config: &TaskConfig) -> String {
277    if config.container.is_some() {
278        return "container".into();
279    }
280    if config.sandbox != "on" || !blyte_agent::sandbox::available() {
281        return "off".into();
282    }
283    match blyte_agent::sandbox::default_profile_net(
284        &config.root,
285        &config.allow_read,
286        config.network == "on",
287    ) {
288        Profile::Seatbelt(_) => "seatbelt".into(),
289        Profile::Landlock(_) => "landlock".into(),
290        Profile::LandlockOffline(_) => "landlock-offline".into(),
291        Profile::LandlockConfined { block_tcp, .. } => {
292            if block_tcp {
293                "landlock-offline".into()
294            } else {
295                "landlock".into()
296            }
297        }
298    }
299}