File size: 10,613 Bytes
18de23f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
//! Typed task fixtures, subprocess results and artifact-bound comparison evidence.

use std::{collections::BTreeMap, path::PathBuf};

use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

/// Explicit failures of fixture validation, inference or the isolated task runner.
#[derive(Debug, Error)]
pub enum TaskBenchmarkError {
    /// Caller cancellation never produces a completed benchmark.
    #[error("Emacs task benchmark cancelled")]
    Cancelled,
    /// The reviewed task fixture or returned report violates its schema.
    #[error("invalid Emacs task benchmark: {0}")]
    Invalid(&'static str),
    /// A source changed after its exact bytes were recorded.
    #[error("task benchmark source changed: {0}")]
    Changed(PathBuf),
    /// No matching executable could be resolved from the explicit path or PATH.
    #[error("Emacs executable not found: {0}")]
    EmacsNotFound(PathBuf),
    /// The bounded child process exceeded the requested deadline.
    #[error("Emacs task runner exceeded its {0}-second deadline")]
    Timeout(u64),
    /// The child process failed rather than returning task outcomes.
    #[error("Emacs task runner failed: {0}")]
    RunnerFailed(String),
    /// The child exceeded its bounded report or diagnostic output size.
    #[error("Emacs task runner exceeded its output limit")]
    OutputLimit,
    /// An expected action is outside the bounded command algebra.
    #[error(transparent)]
    Action(#[from] crate::actions::InputError),
    /// Numerical infrastructure failed; this is never a model refusal.
    #[error(transparent)]
    Inference(#[from] crate::inference::InferenceError),
    /// Model loading failed before execution could be measured.
    #[error(transparent)]
    Model(#[from] crate::model::ModelError),
    /// File access or process management failed.
    #[error(transparent)]
    Io(#[from] std::io::Error),
    /// JSON input or output failed strict decoding.
    #[error(transparent)]
    Json(#[from] serde_json::Error),
}

impl TaskBenchmarkError {
    /// Recognize cooperative cancellation without comparing display strings.
    pub fn is_cancelled(&self) -> bool {
        matches!(self, Self::Cancelled)
    }
}

/// A reviewed fixture and its intended program, independent of model predictions.
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskCase {
    /// Stable unique identity used to correlate a prediction with a result.
    pub id: String,
    /// Original English request, with quoted literals preserved as data.
    pub instruction: String,
    /// Name of a fixed fixture and end-state predicate in the reviewed runner.
    pub scenario: String,
    /// Number of distinct actions required by the reviewed reference program.
    pub steps: u8,
    /// Typed reference program; the runner checks its goal before scoring predictions.
    pub expected: Value,
}

/// Strict portable description of a frozen real-Emacs task suite.
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskSuite {
    /// Version of the reviewed task schema.
    pub format_version: u32,
    /// Description of fixture provenance and benchmark exposure.
    pub policy: String,
    /// Ordered independently initialized task fixtures.
    pub tasks: Vec<TaskCase>,
}

/// Explicit executable and runner selection for one bounded child process.
#[derive(Debug)]
pub struct RunnerOptions {
    /// Absolute executable path, or a binary name resolved through PATH.
    pub emacs: PathBuf,
    /// Reviewed standalone Lisp runner copied to the isolated working directory.
    pub runner: PathBuf,
    /// Positive wall-clock limit for the complete Emacs child process.
    pub timeout_seconds: u64,
}

/// Mutually exclusive outcome of one supported task in its prepared environment.
/// Copying an outcome preserves this immutable classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaskStatus {
    /// The observed final state satisfied the task's goal predicate.
    Success,
    /// The proposed program executed but its resulting state missed the goal.
    WrongState,
    /// The model refused a supported request before any action was executed.
    Rejected,
    /// A permitted action raised a runtime error in the prepared fixture.
    ExecutionError,
    /// The complete proposal failed the runner's local effects boundary.
    BlockedAction,
}

/// Disjoint integer counts; accepted-program precision cannot hide refusals.
#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskCounts {
    /// Number of tasks in this cohort.
    pub total: u32,
    /// Tasks whose observed final state met the goal.
    pub success: u32,
    /// Executed programs with incorrect final states.
    pub wrong_state: u32,
    /// Supported requests refused before execution.
    pub rejected: u32,
    /// Permitted programs that raised execution errors.
    pub execution_error: u32,
    /// Proposals rejected by the runner's effects boundary.
    pub blocked_action: u32,
}

impl TaskCounts {
    /// Count one task outcome after the suite-size limit made overflow impossible.
    pub(super) fn observe(&mut self, status: TaskStatus) {
        self.total += 1;
        match status {
            TaskStatus::Success => self.success += 1,
            TaskStatus::WrongState => self.wrong_state += 1,
            TaskStatus::Rejected => self.rejected += 1,
            TaskStatus::ExecutionError => self.execution_error += 1,
            TaskStatus::BlockedAction => self.blocked_action += 1,
        }
    }

    /// Compute task success over all requests, including refusals and failures.
    pub fn success_rate(&self) -> f64 {
        if self.total == 0 {
            0.0
        } else {
            f64::from(self.success) / f64::from(self.total)
        }
    }

    /// Require every failure category and supported refusal count to not increase.
    pub(super) fn preserves(&self, baseline: &Self) -> bool {
        self.total == baseline.total
            && self.success >= baseline.success
            && self.wrong_state <= baseline.wrong_state
            && self.rejected <= baseline.rejected
            && self.execution_error <= baseline.execution_error
            && self.blocked_action <= baseline.blocked_action
    }
}

/// One task's measured outcome, retaining an inspectable final-state witness.
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskResult {
    /// Stable fixture identity from the frozen input.
    pub id: String,
    /// Reviewed state fixture and goal name.
    pub scenario: String,
    /// Required reference-program length, not a model-selected denominator.
    pub steps: u8,
    /// Exactly one measured result category.
    pub status: TaskStatus,
    /// Number of predicted actions completed before failure or goal inspection.
    pub completed_actions: u8,
    /// Human-readable refusal, effects-boundary or execution diagnostic.
    pub detail: Option<String>,
    /// Fixture-specific final state, or null when nothing was executed.
    pub state: Option<Value>,
}

/// The model's proposal or explicit refusal, retained separately from the oracle.
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskPrediction {
    /// Stable reviewed task identity.
    pub id: String,
    /// Exact input sent to the model.
    pub instruction: String,
    /// Typed action program, absent only when inference explicitly refused input.
    pub program: Option<Value>,
    /// Explicit semantic refusal reason, absent when a proposal was returned.
    pub refusal: Option<String>,
}

/// Exact report produced by the standalone Emacs runner.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct RunnerReport {
    /// Version of the task runner response schema.
    pub format_version: u32,
    /// Runtime version returned by the executing Emacs process.
    pub emacs_version: String,
    /// Number of reference programs whose goal predicates passed before inference scoring.
    pub oracle_checked: u32,
    /// Runner aggregate, independently recomputed by the Rust boundary.
    pub counts: TaskCounts,
    /// Results in frozen fixture order.
    pub results: Vec<TaskResult>,
}

/// Artifact-bound real-Emacs outcomes, separate from generated-code exact match.
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskReport {
    /// Version of the persisted task benchmark report.
    pub format_version: u32,
    /// Exact evaluated SafeTensors bytes.
    pub weights_sha256: String,
    /// Exact model vocabulary, labels and admission settings.
    pub config_sha256: String,
    /// Frozen task definitions, including fixture identities and reference programs.
    pub tasks_sha256: String,
    /// Exact standalone runner source executed in the isolated subprocess.
    pub runner_sha256: String,
    /// Selected executable bytes, including a launcher if that is the selected binary.
    pub emacs_executable_sha256: String,
    /// Runtime-reported Emacs version, identical for paired comparisons.
    pub emacs_version: String,
    /// Task provenance policy, not a claim of independent blind evaluation.
    pub policy: String,
    /// Every task's reference program passed its goal before scoring.
    pub oracle_checked: u32,
    /// All-request outcome counts.
    pub counts: TaskCounts,
    /// Success divided by all tasks; integer counts remain authoritative.
    pub success_rate: f64,
    /// Separate single-action and two-action cohorts.
    pub by_steps: BTreeMap<u8, TaskCounts>,
    /// Per-fixture outcomes expose regressions hidden by overall averages.
    pub by_scenario: BTreeMap<String, TaskCounts>,
    /// Every measured fixture outcome with its state witness.
    pub results: Vec<TaskResult>,
    /// Model proposals and refusals in the same frozen task order.
    pub predictions: Vec<TaskPrediction>,
}

/// Baseline/candidate evidence with a recomputed task nonregression decision.
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskComparison {
    /// Frozen baseline measured in the same runner and task environment.
    pub baseline: TaskReport,
    /// Candidate measured independently against identical task definitions.
    pub candidate: TaskReport,
    /// Overall, per-step and per-scenario task outcomes meet nonregression constraints.
    pub eligible: bool,
}