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    pub container: Option<String>,
56    pub container_workdir: String,
57    /// Whether local shell commands ran under macOS seatbelt sandbox isolation.
58    pub sandboxed: bool,
59    /// The sandbox mechanism active for the run (`container`, `seatbelt`, `landlock`, `landlock-offline`, `off`).
60    pub sandbox: String,
61    /// Outbound network mode for commands (`on` or `off`).
62    pub network: String,
63    /// Filesystem paths permitted for reading despite credential deny-lists.
64    pub allow_read: Vec<String>,
65    /// Environment variables permitted to pass to commands despite looking like credentials.
66    pub pass_env: Vec<String>,
67    /// Names of environment variables withheld from commands by the credential filter.
68    pub withheld_env: Vec<String>,
69    pub duration_seconds: f64,
70    pub turns: u32,
71    pub empty_turns: u32,
72    #[serde(default)]
73    pub truncated_turns: u32,
74    #[serde(default)]
75    pub read_loop: bool,
76    #[serde(default)]
77    pub peak_read_repeats: u32,
78    #[serde(default)]
79    pub fold_thrash: bool,
80    #[serde(default)]
81    pub big_read_turns: u32,
82    pub tool_calls: u32,
83    pub gate_attempts: u32,
84    pub rollbacks: u32,
85    pub provider_retries: u32,
86    /// List-price cost in USD, when the model's price is known.
87    pub cost_usd: Option<f64>,
88    /// Spending cap in USD given with `--max-cost`, if any.
89    pub max_cost_usd: Option<f64>,
90    /// Whether the run stopped because spending reached `--max-cost`.
91    pub cost_capped: bool,
92    /// Fold budget given with `--fold-budget`, if any.
93    pub fold_budget: Option<usize>,
94    /// Per-call usage (see `blyte_agent::run::TurnUsage`).
95    pub turn_usage: Vec<blyte_agent::run::TurnUsage>,
96    pub usage: UsageRecord,
97    pub gate_ms: Vec<u64>,
98    #[serde(default)]
99    pub gate_turns: Vec<u32>,
100    pub gate_wait_ms: Vec<u64>,
101    pub gate_failures: Vec<String>,
102    pub tool_counts: BTreeMap<String, u32>,
103    pub model_seconds: f64,
104    pub tools_seconds: f64,
105    pub gate_seconds: f64,
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub quote_problems: Option<Vec<String>>,
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub claim_check: Option<blyte_agent::claim_check::ClaimCheck>,
110}
111
112impl RunRecord {
113    fn base(config: &TaskConfig, elapsed: Duration) -> Self {
114        let gated = config.gate.as_deref().is_some_and(|g| !g.trim().is_empty());
115        let sandboxed = config.container.is_none()
116            && config.sandbox == "on"
117            && blyte_agent::sandbox::available();
118        let withheld_env = if config.container.is_some() {
119            Vec::new()
120        } else {
121            blyte_agent::shell::withheld_env()
122        };
123        Self {
124            schema_version: SCHEMA_VERSION,
125            harness_build: env!("BLYTE_BUILD").into(),
126            outcome: "error".into(),
127            error: None,
128            final_message: None,
129            model_requested: config.model.clone(),
130            model_id: None,
131            effort: None,
132            context: config.context_strategy.clone(),
133            gated,
134            gate_source: if gated { "user" } else { "none" }.into(),
135            container: config.container.clone(),
136            container_workdir: config.container_workdir.clone(),
137            sandboxed,
138            sandbox: sandbox_kind(config),
139            network: config.network.clone(),
140            allow_read: config
141                .allow_read
142                .iter()
143                .map(|p| p.display().to_string())
144                .collect(),
145            pass_env: config.pass_env.clone(),
146            withheld_env,
147            duration_seconds: elapsed.as_secs_f64(),
148            turns: 0,
149            empty_turns: 0,
150            truncated_turns: 0,
151            read_loop: false,
152            peak_read_repeats: 0,
153            fold_thrash: false,
154            big_read_turns: 0,
155            tool_calls: 0,
156            gate_attempts: 0,
157            rollbacks: 0,
158            provider_retries: 0,
159            cost_usd: None,
160            max_cost_usd: config.max_cost_usd,
161            cost_capped: false,
162            fold_budget: config.fold_budget,
163            turn_usage: Vec::new(),
164            usage: UsageRecord::default(),
165            gate_ms: Vec::new(),
166            gate_turns: Vec::new(),
167            gate_wait_ms: Vec::new(),
168            gate_failures: Vec::new(),
169            tool_counts: BTreeMap::new(),
170            model_seconds: 0.0,
171            tools_seconds: 0.0,
172            gate_seconds: 0.0,
173            quote_problems: None,
174            claim_check: None,
175        }
176    }
177
178    /// A run that never reached the loop, e.g. a missing API key.
179    pub fn from_error(config: &TaskConfig, error: &str, elapsed: Duration) -> Self {
180        Self {
181            error: Some(error.to_string()),
182            ..Self::base(config, elapsed)
183        }
184    }
185
186    /// A run the loop completed, whatever its outcome.
187    pub fn from_run(
188        config: &TaskConfig,
189        model_id: &str,
190        outcome: &Outcome,
191        report: &RunReport,
192        state: &State,
193        elapsed: Duration,
194    ) -> Self {
195        let (outcome_name, error) = outcome_name(outcome);
196        let model_ms: u64 = report.turn_usage.iter().map(|t| t.model_ms).sum();
197        let tools_ms: u64 = report.turn_usage.iter().map(|t| t.tools_ms).sum();
198        let gate_ms_sum: u64 = report.gate_ms.iter().sum();
199        Self {
200            outcome: outcome_name.into(),
201            error,
202            final_message: report.final_message.clone(),
203            model_id: Some(model_id.to_string()),
204            turns: report.outcome_turns,
205            empty_turns: report.empty_turns,
206            truncated_turns: report.truncated_turns,
207            read_loop: report.read_loop,
208            peak_read_repeats: report.peak_read_repeats,
209            fold_thrash: report.fold_thrash,
210            big_read_turns: report.big_read_turns,
211            tool_calls: report.tool_calls,
212            gate_attempts: report.gate_attempts,
213            rollbacks: state.runtime.rollbacks,
214            provider_retries: report.provider_retries,
215            cost_usd: blyte_provider::pricing(model_id).map(|p| p.cost(&report.usage)),
216            cost_capped: report.cost_capped,
217            turn_usage: report.turn_usage.clone(),
218            usage: UsageRecord {
219                input: report.usage.input,
220                cached: report.usage.cached,
221                output: report.usage.output,
222                thinking: report.usage.thinking,
223            },
224            gate_ms: report.gate_ms.clone(),
225            gate_turns: report.gate_turns.clone(),
226            gate_wait_ms: report.gate_wait_ms.clone(),
227            gate_failures: report.gate_failures.clone(),
228            tool_counts: report.tool_counts.clone(),
229            model_seconds: model_ms as f64 / 1000.0,
230            tools_seconds: tools_ms as f64 / 1000.0,
231            gate_seconds: gate_ms_sum as f64 / 1000.0,
232            quote_problems: report.quote_problems.clone(),
233            claim_check: report.claim_check.clone(),
234            ..Self::base(config, elapsed)
235        }
236    }
237}
238
239pub fn write(path: &Path, record: &RunRecord) -> Result<(), String> {
240    let json = serde_json::to_string_pretty(record)
241        .map_err(|e| format!("report serialisation failed: {e}"))?;
242    std::fs::write(path, json + "\n")
243        .map_err(|e| format!("cannot write report {}: {e}", path.display()))
244}
245
246/// Returns the name of the sandbox mechanism active for the task configuration.
247pub fn sandbox_kind(config: &TaskConfig) -> String {
248    if config.container.is_some() {
249        return "container".into();
250    }
251    if config.sandbox != "on" || !blyte_agent::sandbox::available() {
252        return "off".into();
253    }
254    match blyte_agent::sandbox::default_profile_net(
255        &config.root,
256        &config.allow_read,
257        config.network == "on",
258    ) {
259        Profile::Seatbelt(_) => "seatbelt".into(),
260        Profile::Landlock(_) => "landlock".into(),
261        Profile::LandlockOffline(_) => "landlock-offline".into(),
262        Profile::LandlockConfined { block_tcp, .. } => {
263            if block_tcp {
264                "landlock-offline".into()
265            } else {
266                "landlock".into()
267            }
268        }
269    }
270}