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