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 stalled: bool,
84    #[serde(default)]
85    pub big_read_turns: u32,
86    pub tool_calls: u32,
87    pub gate_attempts: u32,
88    pub rollbacks: u32,
89    pub provider_retries: u32,
90    /// List-price cost in USD, when the model's price is known.
91    pub cost_usd: Option<f64>,
92    /// Spending cap in USD given with `--max-cost`, if any.
93    pub max_cost_usd: Option<f64>,
94    /// Whether the run stopped because spending reached `--max-cost`.
95    pub cost_capped: bool,
96    /// Fold budget given with `--fold-budget`, if any.
97    pub fold_budget: Option<usize>,
98    /// Per-call usage (see `blyte_agent::run::TurnUsage`).
99    pub turn_usage: Vec<blyte_agent::run::TurnUsage>,
100    pub usage: UsageRecord,
101    pub gate_ms: Vec<u64>,
102    #[serde(default)]
103    pub gate_turns: Vec<u32>,
104    pub gate_wait_ms: Vec<u64>,
105    pub gate_failures: Vec<String>,
106    pub tool_counts: BTreeMap<String, u32>,
107    pub model_seconds: f64,
108    pub tools_seconds: f64,
109    pub gate_seconds: f64,
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub quote_problems: Option<Vec<String>>,
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub claim_check: Option<blyte_agent::claim_check::ClaimCheck>,
114}
115
116impl RunRecord {
117    fn base(config: &TaskConfig, elapsed: Duration) -> Self {
118        let gated = config.gate.as_deref().is_some_and(|g| !g.trim().is_empty());
119        let sandboxed = config.container.is_none()
120            && config.sandbox == "on"
121            && blyte_agent::sandbox::available();
122        let withheld_env = if config.container.is_some() {
123            Vec::new()
124        } else {
125            blyte_agent::shell::withheld_env()
126        };
127        let gate_left_out = config
128            .report
129            .as_deref()
130            .and_then(read_gate_left_out_from_start)
131            .unwrap_or_default();
132        Self {
133            schema_version: SCHEMA_VERSION,
134            harness_build: env!("BLYTE_BUILD").into(),
135            outcome: "error".into(),
136            error: None,
137            final_message: None,
138            model_requested: config.model.clone(),
139            model_id: None,
140            effort: None,
141            context: config.context_strategy.clone(),
142            gated,
143            gate_source: if gated { "user" } else { "none" }.into(),
144            gate_left_out,
145            container: config.container.clone(),
146            container_workdir: config.container_workdir.clone(),
147            sandboxed,
148            sandbox: sandbox_kind(config),
149            network: config.network.clone(),
150            allow_read: config
151                .allow_read
152                .iter()
153                .map(|p| p.display().to_string())
154                .collect(),
155            pass_env: config.pass_env.clone(),
156            withheld_env,
157            duration_seconds: elapsed.as_secs_f64(),
158            turns: 0,
159            empty_turns: 0,
160            truncated_turns: 0,
161            read_loop: false,
162            peak_read_repeats: 0,
163            fold_thrash: false,
164            stalled: false,
165            big_read_turns: 0,
166            tool_calls: 0,
167            gate_attempts: 0,
168            rollbacks: 0,
169            provider_retries: 0,
170            cost_usd: None,
171            max_cost_usd: config.max_cost_usd,
172            cost_capped: false,
173            fold_budget: config.fold_budget,
174            turn_usage: Vec::new(),
175            usage: UsageRecord::default(),
176            gate_ms: Vec::new(),
177            gate_turns: Vec::new(),
178            gate_wait_ms: Vec::new(),
179            gate_failures: Vec::new(),
180            tool_counts: BTreeMap::new(),
181            model_seconds: 0.0,
182            tools_seconds: 0.0,
183            gate_seconds: 0.0,
184            quote_problems: None,
185            claim_check: None,
186        }
187    }
188
189    /// A run that never reached the loop, e.g. a missing API key.
190    pub fn from_error(config: &TaskConfig, error: &str, elapsed: Duration) -> Self {
191        Self {
192            error: Some(error.to_string()),
193            ..Self::base(config, elapsed)
194        }
195    }
196
197    /// A run the loop completed, whatever its outcome.
198    pub fn from_run(
199        config: &TaskConfig,
200        model_id: &str,
201        outcome: &Outcome,
202        report: &RunReport,
203        state: &State,
204        elapsed: Duration,
205    ) -> Self {
206        let (outcome_name, error) = outcome_name(outcome);
207        let model_ms: u64 = report.turn_usage.iter().map(|t| t.model_ms).sum();
208        let tools_ms: u64 = report.turn_usage.iter().map(|t| t.tools_ms).sum();
209        let gate_ms_sum: u64 = report.gate_ms.iter().sum();
210        Self {
211            outcome: outcome_name.into(),
212            error,
213            final_message: report.final_message.clone(),
214            model_id: Some(model_id.to_string()),
215            turns: report.outcome_turns,
216            empty_turns: report.empty_turns,
217            truncated_turns: report.truncated_turns,
218            read_loop: report.read_loop,
219            peak_read_repeats: report.peak_read_repeats,
220            fold_thrash: report.fold_thrash,
221            stalled: report.stalled,
222            big_read_turns: report.big_read_turns,
223            tool_calls: report.tool_calls,
224            gate_attempts: report.gate_attempts,
225            rollbacks: state.runtime.rollbacks,
226            provider_retries: report.provider_retries,
227            cost_usd: blyte_provider::pricing(model_id).map(|p| p.cost(&report.usage)),
228            cost_capped: report.cost_capped,
229            turn_usage: report.turn_usage.clone(),
230            usage: UsageRecord {
231                input: report.usage.input,
232                cached: report.usage.cached,
233                output: report.usage.output,
234                thinking: report.usage.thinking,
235            },
236            gate_ms: report.gate_ms.clone(),
237            gate_turns: report.gate_turns.clone(),
238            gate_wait_ms: report.gate_wait_ms.clone(),
239            gate_failures: report.gate_failures.clone(),
240            tool_counts: report.tool_counts.clone(),
241            model_seconds: model_ms as f64 / 1000.0,
242            tools_seconds: tools_ms as f64 / 1000.0,
243            gate_seconds: gate_ms_sum as f64 / 1000.0,
244            quote_problems: report.quote_problems.clone(),
245            claim_check: report.claim_check.clone(),
246            ..Self::base(config, elapsed)
247        }
248    }
249}
250
251pub fn write(path: &Path, record: &RunRecord) -> Result<(), String> {
252    let json = serde_json::to_string_pretty(record)
253        .map_err(|e| format!("report serialisation failed: {e}"))?;
254    std::fs::write(path, json + "\n")
255        .map_err(|e| format!("cannot write report {}: {e}", path.display()))
256}
257
258fn read_gate_left_out_from_start(report_path: &Path) -> Option<Vec<String>> {
259    let file_name = report_path.file_name()?.to_str()?;
260    let id = file_name.strip_suffix(".report.json")?;
261    let start_path = report_path.with_file_name(format!("{id}.start.json"));
262    let content = std::fs::read_to_string(start_path).ok()?;
263    let val: serde_json::Value = serde_json::from_str(&content).ok()?;
264    let arr = val.get("gate_left_out")?.as_array()?;
265    let mut out = Vec::new();
266    for item in arr {
267        if let (Some(cmd), Some(reason)) = (
268            item.get("command").and_then(|v| v.as_str()),
269            item.get("reason").and_then(|v| v.as_str()),
270        ) {
271            out.push(format!("{cmd} ({reason})"));
272        } else if let Some(s) = item.as_str() {
273            out.push(s.to_string());
274        }
275    }
276    Some(out)
277}
278
279/// Returns the name of the sandbox mechanism active for the task configuration.
280pub fn sandbox_kind(config: &TaskConfig) -> String {
281    if config.container.is_some() {
282        return "container".into();
283    }
284    if config.sandbox != "on" || !blyte_agent::sandbox::available() {
285        return "off".into();
286    }
287    match blyte_agent::sandbox::default_profile_net(
288        &config.root,
289        &config.allow_read,
290        config.network == "on",
291    ) {
292        Profile::Seatbelt(_) => "seatbelt".into(),
293        Profile::Landlock(_) => "landlock".into(),
294        Profile::LandlockOffline(_) => "landlock-offline".into(),
295        Profile::LandlockConfined { block_tcp, .. } => {
296            if block_tcp {
297                "landlock-offline".into()
298            } else {
299                "landlock".into()
300            }
301        }
302    }
303}