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