Skip to main content

trusty_code/bakeoff/
metadata.rs

1//! `metadata.json` — the retained-evidence schema every bake-off level must
2//! carry (#5441).
3//!
4//! Why: #5441's gate contract requires each retained L1-L3 level to state
5//! tokens, cache use, cost, turns, duration, status, and build provenance. The
6//! first independent qualification attempt failed on exactly that: the runner
7//! kept raw artifacts but recorded neither the candidate commit, the binary
8//! hash, the challenge/runner revision, nor the instruction/agent/skill source
9//! digests, so nobody could prove which binary produced the numbers. Declaring
10//! the schema HERE — in the crate under test, not in the external runner —
11//! makes the runner conform to the gate rather than the gate infer the
12//! runner's shape.
13//! What: [`LevelMetadata`] and its parts, plus [`LevelMetadata::provenance_gaps`],
14//! which names every field a run left empty, `"unknown"`, or zero. Deserialization
15//! fails CLOSED: an unrecognised `evidence_mode` string becomes
16//! [`EvidenceMode::Unknown`], which the preflight rejects exactly as it rejects
17//! a declared mock.
18//! Test: `bakeoff::tests::metadata_round_trips_the_documented_shape`,
19//! `bakeoff::tests::provenance_gaps_names_every_missing_field`,
20//! `bakeoff::tests::unknown_evidence_mode_is_not_real`.
21
22use serde::{Deserialize, Serialize};
23
24/// Whether a level's artifacts came from a real model run or a plumbing-only
25/// mock.
26///
27/// Why: #5441 permits offline/mock runs to validate plumbing but states they
28/// "do not satisfy the exit gate". A boolean would let an absent field default
29/// to the permissive value; an explicit enum with a catch-all makes an
30/// unrecognised or missing declaration fail closed.
31/// What: `real` and `mock` deserialize from those literals; anything else
32/// (including a typo or a future variant) becomes `Unknown`, which
33/// [`EvidenceMode::is_real`] reports as not-real.
34/// Test: `bakeoff::tests::unknown_evidence_mode_is_not_real`.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(rename_all = "snake_case")]
37#[non_exhaustive]
38pub enum EvidenceMode {
39    /// A real model/provider run against the pinned candidate build.
40    Real,
41    /// A mocked or offline run — plumbing validation only.
42    Mock,
43    /// Any value this build does not recognise.
44    #[serde(other)]
45    Unknown,
46}
47
48impl EvidenceMode {
49    /// Whether this evidence can satisfy the milestone exit gate.
50    ///
51    /// Why: single decision point so the preflight never re-spells the
52    /// "mock does not count" rule.
53    /// What: true only for [`EvidenceMode::Real`].
54    /// Test: `bakeoff::tests::unknown_evidence_mode_is_not_real`.
55    pub fn is_real(self) -> bool {
56        matches!(self, EvidenceMode::Real)
57    }
58}
59
60/// Which bake-off runner produced the level, and at what revision.
61///
62/// Why: #5441's preflight must reject "stale runner paths". A path alone
63/// cannot establish that: the same path holds a different runner after a pull.
64/// Recording path, revision, and whether that checkout was dirty makes the
65/// claim checkable — a dirty runner checkout means the recorded revision does
66/// not identify what actually ran, which is precisely how the first
67/// qualification attempt's evidence was disqualified.
68/// What: plain strings plus a `dirty` flag; no path is resolved or touched by
69/// this crate, which never runs the runner.
70/// Test: `bakeoff::tests::dirty_runner_checkout_is_rejected`.
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72#[non_exhaustive]
73pub struct RunnerProvenance {
74    /// Absolute path to the runner script that produced this level.
75    pub path: String,
76    /// The runner checkout's commit (or tag) at invocation time.
77    pub revision: String,
78    /// Whether that checkout had uncommitted changes.
79    #[serde(default)]
80    pub dirty: bool,
81}
82
83/// Model, provider, and timeout the level was invoked with.
84///
85/// Why: #5441 requires one reproducible invocation; a rerun that silently
86/// changed model or timeout is a different experiment, not a comparison.
87/// What: the three fields that change a run's outcome independently of the
88/// candidate build.
89/// Test: `bakeoff::tests::provenance_gaps_names_every_missing_field`.
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91#[non_exhaustive]
92pub struct Invocation {
93    /// Model identifier, e.g. `anthropic/claude-sonnet-4`.
94    pub model: String,
95    /// Provider identifier, e.g. `openrouter`.
96    pub provider: String,
97    /// Wall-clock deadline handed to `run-task`, in seconds.
98    pub timeout_secs: u64,
99}
100
101/// Which `tcode` binary produced the level.
102///
103/// Why: "results produced by a different Trusty Code build" is one of the five
104/// rejections #5441 names. `version`/`commit`/`commit_date` mirror
105/// [`crate::build_info::provenance_json`] so the metadata can be cross-checked
106/// against the level's own `tcode_report.json` rather than trusted; the binary
107/// hash is what survives when the source tree is gone.
108/// What: the three report fields plus a SHA-256 of the invoked binary and a
109/// `dirty` flag for the candidate checkout.
110/// Test: `bakeoff::tests::report_build_mismatch_is_rejected`.
111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
112#[non_exhaustive]
113pub struct BuildProvenance {
114    /// Crate semver, matching `tcode_report.json`'s `build.version`.
115    pub version: String,
116    /// Short git commit, matching `tcode_report.json`'s `build.commit`.
117    pub commit: String,
118    /// Commit date, matching `tcode_report.json`'s `build.commit_date`.
119    pub commit_date: String,
120    /// SHA-256 of the `tcode` binary that was invoked.
121    pub binary_sha256: String,
122    /// Whether the candidate checkout had uncommitted changes.
123    #[serde(default)]
124    pub dirty: bool,
125}
126
127/// Digests of the canonical instruction/agent/skill sources the run consumed.
128///
129/// Why: #5441's R1 note is explicit that the compatibility runner still writes
130/// `.claude/agents` and `.claude/skills`, and that R1 "must record the
131/// compatibility-source digests it actually used". Recording digests keeps the
132/// evidence honest across the #5425/#5426 source convergence without this gate
133/// having to know which layout was canonical on the day.
134/// What: three opaque digest strings; this crate compares them across levels
135/// and never interprets their algorithm.
136/// Test: `bakeoff::tests::source_digest_drift_across_levels_is_rejected`.
137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
138#[non_exhaustive]
139pub struct SourceDigests {
140    /// Digest of the instruction source (e.g. the composed `CLAUDE.md`).
141    pub instructions: String,
142    /// Digest of the agent catalog the run resolved.
143    pub agents: String,
144    /// Digest of the skill catalog the run resolved.
145    pub skills: String,
146}
147
148/// Token counts for one level, mirroring `tcode_report.json`'s `usage` block.
149///
150/// Why: #5441 asks for tokens AND cache use separately — a cost change driven
151/// by a collapsed cache read is a different finding from one driven by more
152/// completion tokens.
153/// What: the same four counters `run_task::report` renders.
154/// Test: `bakeoff::tests::token_regression_beyond_tolerance_needs_a_disposition`.
155#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
156#[non_exhaustive]
157pub struct Tokens {
158    /// Prompt tokens billed.
159    pub prompt: u64,
160    /// Completion tokens billed.
161    pub completion: u64,
162    /// Tokens served from the provider's prompt cache.
163    pub cache_read: u64,
164    /// Tokens written into the provider's prompt cache.
165    pub cache_creation: u64,
166}
167
168impl Tokens {
169    /// Total billed tokens across all four counters.
170    ///
171    /// Why: the baseline comparison needs one scalar per metric; four separate
172    /// tolerance verdicts on correlated counters produce noise, not signal.
173    /// What: saturating sum of the four fields.
174    /// Test: `bakeoff::tests::token_regression_beyond_tolerance_needs_a_disposition`.
175    pub fn total(self) -> u64 {
176        self.prompt
177            .saturating_add(self.completion)
178            .saturating_add(self.cache_read)
179            .saturating_add(self.cache_creation)
180    }
181}
182
183/// What the level's run actually did.
184///
185/// Why: #5441 requires terminal status, turns, duration, and cost retained per
186/// level so the next milestone can compare against them.
187/// What: `status` uses `run_task::report`'s own vocabulary (`success`,
188/// `partial`, `deadline_exceeded`, …) so it can be cross-checked against the
189/// level's `tcode_report.json` rather than trusted.
190/// Test: `bakeoff::tests::metadata_status_must_match_the_run_report`.
191#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
192#[non_exhaustive]
193pub struct RunTelemetry {
194    /// Terminal status string, matching `tcode_report.json`'s `status`.
195    pub status: String,
196    /// PM turns consumed.
197    pub turns: u64,
198    /// Wall-clock duration of the run.
199    pub duration_secs: f64,
200    /// Summed USD cost, or `null` when pricing was unavailable.
201    pub cost_usd: Option<f64>,
202    /// Token counters.
203    pub tokens: Tokens,
204}
205
206/// The verifier's verdict for one level.
207///
208/// Why: verifier pass rate is the first thing #5441's comparison names, and a
209/// correctness regression blocks milestone closure outright.
210/// What: two counters; `checks_total == 0` means the verifier produced no
211/// correctness evidence at all, which the preflight treats as mock evidence.
212/// Test: `bakeoff::tests::zero_verifier_checks_is_mock_evidence`.
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
214#[non_exhaustive]
215pub struct VerifierResult {
216    /// Total checks the verifier ran.
217    pub checks_total: u32,
218    /// Checks that passed.
219    pub checks_passed: u32,
220}
221
222/// One level's complete `metadata.json`.
223///
224/// Why: this is the retained-evidence contract #5441's gate reads. Everything
225/// the gate decides comes from this document plus the sibling raw artifacts;
226/// nothing is inferred from the filesystem or from a live process.
227/// What: level number, evidence mode, runner/challenge/build/source provenance,
228/// the invocation, run telemetry, and the verifier verdict.
229/// Test: `bakeoff::tests::metadata_round_trips_the_documented_shape`.
230#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
231#[non_exhaustive]
232pub struct LevelMetadata {
233    /// Bake-off level: 1, 2, or 3.
234    pub level: u8,
235    /// Whether this is real or mock evidence.
236    pub evidence_mode: EvidenceMode,
237    /// Which runner produced it.
238    pub runner: RunnerProvenance,
239    /// The challenge repository's revision.
240    pub challenge_revision: String,
241    /// Model, provider, timeout.
242    pub invocation: Invocation,
243    /// Which `tcode` binary ran.
244    pub build: BuildProvenance,
245    /// Digests of the behavior sources the run consumed.
246    pub source_digests: SourceDigests,
247    /// What the run did.
248    pub run: RunTelemetry,
249    /// What the verifier concluded.
250    pub verifier: VerifierResult,
251}
252
253impl LevelMetadata {
254    /// Name every provenance field this document left unusable.
255    ///
256    /// Why: "missing provenance" is one of #5441's five rejections, and a gate
257    /// that reports only "provenance incomplete" sends the operator back to
258    /// diff two JSON files by hand. Naming each gap makes one rerun enough.
259    /// What: returns the dotted field names that are empty, whitespace-only,
260    /// the literal `"unknown"` (what [`crate::build_info`] emits outside a git
261    /// checkout), or — for `timeout_secs` — zero. An empty vector means every
262    /// provenance field carries a usable value.
263    /// Test: `bakeoff::tests::provenance_gaps_names_every_missing_field`,
264    /// `bakeoff::tests::a_complete_bundle_passes_preflight`.
265    pub fn provenance_gaps(&self) -> Vec<String> {
266        let mut gaps = Vec::new();
267        let mut require = |name: &str, value: &str| {
268            if !is_usable(value) {
269                gaps.push(name.to_string());
270            }
271        };
272        require("runner.path", &self.runner.path);
273        require("runner.revision", &self.runner.revision);
274        require("challenge_revision", &self.challenge_revision);
275        require("invocation.model", &self.invocation.model);
276        require("invocation.provider", &self.invocation.provider);
277        require("build.version", &self.build.version);
278        require("build.commit", &self.build.commit);
279        require("build.commit_date", &self.build.commit_date);
280        require("build.binary_sha256", &self.build.binary_sha256);
281        require(
282            "source_digests.instructions",
283            &self.source_digests.instructions,
284        );
285        require("source_digests.agents", &self.source_digests.agents);
286        require("source_digests.skills", &self.source_digests.skills);
287        require("run.status", &self.run.status);
288        if self.invocation.timeout_secs == 0 {
289            gaps.push("invocation.timeout_secs".to_string());
290        }
291        gaps
292    }
293
294    /// The build identity other levels and the pins are compared against.
295    ///
296    /// Why: four fields compared field-by-field at three call sites drifts;
297    /// one canonical rendering does not.
298    /// What: `<version>/<commit>/<commit_date>/<binary_sha256>`.
299    /// Test: `bakeoff::tests::build_drift_across_levels_is_rejected`.
300    pub fn build_identity(&self) -> String {
301        format!(
302            "{}/{}/{}/{}",
303            self.build.version, self.build.commit, self.build.commit_date, self.build.binary_sha256
304        )
305    }
306}
307
308/// Whether a recorded provenance string actually identifies anything.
309///
310/// Why: `build_info` emits the literal `"unknown"` rather than an absent key
311/// outside a git checkout, so an emptiness test alone would accept it.
312/// What: false for empty, whitespace-only, and case-insensitive `"unknown"`.
313/// Test: `bakeoff::tests::provenance_gaps_names_every_missing_field`.
314fn is_usable(value: &str) -> bool {
315    let trimmed = value.trim();
316    !trimmed.is_empty() && !trimmed.eq_ignore_ascii_case("unknown")
317}