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