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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! Real Emacs task outcomes, separate from generated-program exact-match scores.
//!
//! Reviewed fixture programs must satisfy their state goals before model proposals
//! are scored. The adapter binds evidence to model, task, runner and runtime bytes;
//! native failures abort a report instead of becoming successful refusals.

mod io;
mod types;

pub use io::write_report;
pub use types::{
    RunnerOptions, TaskBenchmarkError, TaskCase, TaskComparison, TaskCounts, TaskPrediction,
    TaskReport, TaskResult, TaskStatus, TaskSuite,
};

use std::{
    collections::{BTreeMap, BTreeSet},
    path::{Path, PathBuf},
    sync::atomic::AtomicBool,
};

use serde::Serialize;
use serde_json::{Value, json};

use crate::{
    actions::{Action, ActionKind, Program, parse_command},
    engine::ModelEngine,
    evaluation::EvaluationCase,
};
use io::{check_cancelled, digest, executable, file_digest, read_document};
use types::RunnerReport;

/// Bound report size and arithmetic independently of user-provided task counts.
const MAX_TASKS: usize = 512;

/// Require a compact nonempty ASCII identity instead of arbitrary path syntax.
fn valid_identity(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= 80
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
}

/// Require actual digest-shaped evidence at report comparison boundaries.
fn valid_digest(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

/// Decode only the existing typed action JSON shape; executable source is never accepted.
fn expected_program(value: &Value) -> Result<Program, TaskBenchmarkError> {
    let object = value
        .as_object()
        .ok_or(TaskBenchmarkError::Invalid("program must be an object"))?;
    if object.len() != 1 {
        return Err(TaskBenchmarkError::Invalid("program has unknown fields"));
    }
    let actions = object
        .get("actions")
        .and_then(Value::as_array)
        .ok_or(TaskBenchmarkError::Invalid("program needs typed actions"))?;
    if !matches!(actions.len(), 1 | 2) {
        return Err(TaskBenchmarkError::Invalid(
            "program needs one or two actions",
        ));
    }
    let parsed = actions
        .iter()
        .map(|value| {
            let object = value
                .as_object()
                .ok_or(TaskBenchmarkError::Invalid("action must be an object"))?;
            let label = object
                .get("action")
                .and_then(Value::as_str)
                .ok_or(TaskBenchmarkError::Invalid("action label missing"))?;
            let kind = ActionKind::from_label(label)?;
            let argument = match kind.argument_name() {
                Some(field) if object.len() == 2 => Some(
                    object
                        .get(field)
                        .and_then(Value::as_str)
                        .ok_or(TaskBenchmarkError::Invalid("typed string argument missing"))?
                        .to_owned(),
                ),
                None if object.len() == 1 => None,
                _ => {
                    return Err(TaskBenchmarkError::Invalid(
                        "action has incompatible fields",
                    ));
                }
            };
            Ok(Action::new(kind, argument)?)
        })
        .collect::<Result<Vec<_>, TaskBenchmarkError>>()?;
    Ok(Program::new(parsed)?)
}

/// Strictly decode task descriptions without touching model weights or an Emacs process.
///
/// The standalone runner additionally validates registered scenario names and
/// proves each reference program reaches its specified fixture goal.
pub fn parse_tasks(bytes: &[u8]) -> Result<TaskSuite, TaskBenchmarkError> {
    if u64::try_from(bytes.len()).map_err(|_| TaskBenchmarkError::OutputLimit)?
        > io::MAX_DOCUMENT_BYTES
    {
        return Err(TaskBenchmarkError::OutputLimit);
    }
    let suite: TaskSuite = serde_json::from_slice(bytes)?;
    if suite.format_version != 1
        || suite.policy.trim().is_empty()
        || suite.tasks.is_empty()
        || suite.tasks.len() > MAX_TASKS
    {
        return Err(TaskBenchmarkError::Invalid(
            "invalid task suite version, policy or size",
        ));
    }
    let mut identities = BTreeSet::new();
    for task in &suite.tasks {
        if !valid_identity(&task.id)
            || !valid_identity(&task.scenario)
            || !identities.insert(&task.id)
            || !matches!(task.steps, 1 | 2)
            || task.instruction.len() > 4096
            || task.instruction.contains('\0')
        {
            return Err(TaskBenchmarkError::Invalid(
                "invalid task identity, instruction or steps",
            ));
        }
        let program = expected_program(&task.expected)?;
        if program.actions().len() != usize::from(task.steps)
            || parse_command(&task.instruction)?.len() != usize::from(task.steps)
            || program
                .actions()
                .iter()
                .any(|action| action.kind().label().starts_with("lispm-"))
        {
            return Err(TaskBenchmarkError::Invalid(
                "task reference must match supported core Emacs steps",
            ));
        }
    }
    Ok(suite)
}

/// Validate the portable task schema before freezing it into a training project.
pub fn validate_tasks_bytes(bytes: &[u8]) -> Result<(), TaskBenchmarkError> {
    parse_tasks(bytes).map(|_| ())
}

/// Materialize exact-match expectations so existing split checks reserve task clauses.
///
/// These rows supplement state-goal measurements; matching an expected program
/// remains a separate measure from achieving that goal when it executes.
pub fn evaluation_cases(bytes: &[u8]) -> Result<Vec<EvaluationCase>, TaskBenchmarkError> {
    parse_tasks(bytes)?
        .tasks
        .into_iter()
        .map(|task| {
            let program = expected_program(&task.expected)?;
            let labels: Vec<String> = program
                .actions()
                .iter()
                .map(|action| action.kind().label().to_owned())
                .collect();
            let (action, actions) = if labels.len() == 1 {
                (labels.first().cloned(), Vec::new())
            } else {
                (None, labels)
            };
            Ok(EvaluationCase {
                input: task.instruction,
                expected: Some(program.to_lisp()),
                split: "supported".into(),
                action,
                actions,
                group: None,
                novel_to_both: false,
            })
        })
        .collect()
}

/// One reviewed case plus the separately generated model proposal.
#[derive(Serialize)]
struct RunnerCase<'a> {
    /// Reviewed fixture definition, including its independent reference program.
    #[serde(flatten)]
    task: &'a TaskCase,
    /// Model-selected action data, never executable source.
    prediction: &'a Option<Value>,
    /// Explicit inference refusal, disjoint from a proposal.
    refusal: &'a Option<String>,
}

/// Complete bounded request to the standalone batch runner.
#[derive(Serialize)]
struct RunnerRequest<'a> {
    /// Version of the request contract.
    format_version: u32,
    /// Frozen task order with one inference outcome per task.
    tasks: Vec<RunnerCase<'a>>,
}

/// A file path and its immutable content identity during one evaluation.
struct Source {
    /// Original source to recheck before claiming a report is complete.
    path: PathBuf,
    /// Digest of the exact source bytes used by this run.
    digest: String,
}

impl Source {
    /// Capture a source identity without retaining a duplicate file image.
    fn read(path: PathBuf) -> Result<Self, TaskBenchmarkError> {
        Ok(Self {
            digest: file_digest(&path)?,
            path,
        })
    }

    /// Refuse attribution if another process changed the source during evaluation.
    fn verify(&self) -> Result<(), TaskBenchmarkError> {
        if file_digest(&self.path)? != self.digest {
            return Err(TaskBenchmarkError::Changed(self.path.to_path_buf()));
        }
        Ok(())
    }
}

/// Score all task requests once with one loaded engine, preserving semantic refusals.
fn predictions(
    engine: &ModelEngine,
    suite: &TaskSuite,
    cancelled: &AtomicBool,
    progress: &mut dyn FnMut(Value),
) -> Result<Vec<TaskPrediction>, TaskBenchmarkError> {
    suite
        .tasks
        .iter()
        .enumerate()
        .map(|(index, task)| {
            check_cancelled(cancelled)?;
            let (program, refusal) = match engine.predict(&task.instruction, None, None) {
                Ok(program) => (Some(program.to_json()), None),
                Err(error) if error.is_refusal() => (None, Some(error.to_string())),
                Err(error) => return Err(error.into()),
            };
            progress(
                json!({"phase":"task_inference", "completed":index + 1, "total":suite.tasks.len()}),
            );
            Ok(TaskPrediction {
                id: task.id.to_owned(),
                instruction: task.instruction.to_owned(),
                program,
                refusal,
            })
        })
        .collect()
}

/// Derive all outcome cohorts from individual results instead of trusting summaries.
fn summaries(
    results: &[TaskResult],
) -> (
    TaskCounts,
    BTreeMap<u8, TaskCounts>,
    BTreeMap<String, TaskCounts>,
) {
    let mut overall = TaskCounts::default();
    let mut steps = BTreeMap::<u8, TaskCounts>::new();
    let mut scenarios = BTreeMap::<String, TaskCounts>::new();
    for result in results {
        overall.observe(result.status);
        steps
            .entry(result.steps)
            .or_default()
            .observe(result.status);
        scenarios
            .entry(result.scenario.to_owned())
            .or_default()
            .observe(result.status);
    }
    (overall, steps, scenarios)
}

/// Reject mismatched or contradictory subprocess outcomes before constructing evidence.
fn validate_runner(
    report: &RunnerReport,
    suite: &TaskSuite,
    predictions: &[TaskPrediction],
) -> Result<(), TaskBenchmarkError> {
    let task_count =
        u32::try_from(suite.tasks.len()).map_err(|_| TaskBenchmarkError::OutputLimit)?;
    if report.format_version != 1
        || report.emacs_version.trim().is_empty()
        || report.emacs_version.len() > 200
        || report.oracle_checked != task_count
        || report.results.len() != suite.tasks.len()
        || predictions.len() != suite.tasks.len()
    {
        return Err(TaskBenchmarkError::Invalid(
            "runner task/version/oracle identity mismatch",
        ));
    }
    for ((result, task), prediction) in report.results.iter().zip(&suite.tasks).zip(predictions) {
        if result.id != task.id || result.scenario != task.scenario || result.steps != task.steps {
            return Err(TaskBenchmarkError::Invalid(
                "runner changed task order or identity",
            ));
        }
        validate_outcome(result, prediction)?;
    }
    if summaries(&report.results).0 != report.counts {
        return Err(TaskBenchmarkError::Invalid(
            "runner outcome counts disagree with cases",
        ));
    }
    Ok(())
}

/// Ensure a recorded task outcome agrees with its proposal or explicit refusal.
fn validate_outcome(
    result: &TaskResult,
    prediction: &TaskPrediction,
) -> Result<(), TaskBenchmarkError> {
    let count = match (&prediction.program, &prediction.refusal) {
        (Some(program), None) => expected_program(program)?.actions().len(),
        (None, Some(reason)) if !reason.is_empty() => 0,
        _ => {
            return Err(TaskBenchmarkError::Invalid(
                "proposal and refusal must be disjoint",
            ));
        }
    };
    let complete = usize::from(result.completed_actions);
    let consistent = match result.status {
        TaskStatus::Rejected => count == 0 && complete == 0,
        TaskStatus::BlockedAction => count > 0 && complete == 0,
        TaskStatus::ExecutionError => count > 0 && complete < count,
        TaskStatus::Success | TaskStatus::WrongState => count > 0 && complete == count,
    };
    if !consistent || result.id != prediction.id {
        return Err(TaskBenchmarkError::Invalid(
            "task outcome contradicts model proposal",
        ));
    }
    Ok(())
}

/// Evaluate one unchanged model in an isolated, bounded Emacs batch process.
///
/// The caller owns LibTorch runtime coordination and thread configuration, as
/// with `evaluation::evaluate`. No host Emacs APIs are called by this function.
pub fn evaluate(
    model: &Path,
    tasks: &Path,
    options: &RunnerOptions,
    cancelled: &AtomicBool,
    progress: &mut dyn FnMut(Value),
) -> Result<TaskReport, TaskBenchmarkError> {
    check_cancelled(cancelled)?;
    if options.timeout_seconds == 0 || options.timeout_seconds > 3600 {
        return Err(TaskBenchmarkError::Invalid(
            "runner timeout must be 1..=3600 seconds",
        ));
    }
    let task_bytes = read_document(tasks)?;
    let suite = parse_tasks(&task_bytes)?;
    let runner_bytes = read_document(&options.runner)?;
    let executable = executable(&options.emacs)?;
    let weights = Source::read(model.join("model.safetensors"))?;
    let config = Source::read(model.join("config.json"))?;
    let task_source = Source {
        path: tasks.to_path_buf(),
        digest: digest(&task_bytes),
    };
    let runner_source = Source {
        path: options.runner.to_path_buf(),
        digest: digest(&runner_bytes),
    };
    let executable_source = Source::read(executable.to_path_buf())?;
    let engine = ModelEngine::load(model)?;
    weights.verify()?;
    config.verify()?;
    let predictions = predictions(&engine, &suite, cancelled, progress)?;
    let request = RunnerRequest {
        format_version: 1,
        tasks: suite
            .tasks
            .iter()
            .zip(&predictions)
            .map(|(task, prediction)| RunnerCase {
                task,
                prediction: &prediction.program,
                refusal: &prediction.refusal,
            })
            .collect(),
    };
    let request_bytes = serde_json::to_vec(&request)?;
    if u64::try_from(request_bytes.len()).map_err(|_| TaskBenchmarkError::OutputLimit)?
        > io::MAX_DOCUMENT_BYTES
    {
        return Err(TaskBenchmarkError::OutputLimit);
    }
    progress(json!({"phase":"task_execution", "tasks":suite.tasks.len()}));
    let response = io::run(
        &executable,
        &runner_bytes,
        &request_bytes,
        options,
        cancelled,
    )?;
    let execution: RunnerReport = serde_json::from_slice(&response)?;
    validate_runner(&execution, &suite, &predictions)?;
    for source in [
        &weights,
        &config,
        &task_source,
        &runner_source,
        &executable_source,
    ] {
        source.verify()?;
    }
    check_cancelled(cancelled)?;
    let (counts, by_steps, by_scenario) = summaries(&execution.results);
    let report = TaskReport {
        format_version: 1,
        weights_sha256: weights.digest,
        config_sha256: config.digest,
        tasks_sha256: task_source.digest,
        runner_sha256: runner_source.digest,
        emacs_executable_sha256: executable_source.digest,
        emacs_version: execution.emacs_version,
        policy: suite.policy,
        oracle_checked: execution.oracle_checked,
        success_rate: counts.success_rate(),
        counts,
        by_steps,
        by_scenario,
        results: execution.results,
        predictions,
    };
    progress(
        json!({"phase":"task_completed", "counts":report.counts, "success_rate":report.success_rate}),
    );
    Ok(report)
}

/// Validate persisted outcomes and recompute all aggregate metrics before comparison.
fn validate_report(report: &TaskReport) -> Result<(), TaskBenchmarkError> {
    if report.format_version != 1
        || report.results.is_empty()
        || report.results.len() > MAX_TASKS
        || report.predictions.len() != report.results.len()
        || report.emacs_version.trim().is_empty()
        || report.policy.trim().is_empty()
        || ![
            &report.weights_sha256,
            &report.config_sha256,
            &report.tasks_sha256,
            &report.runner_sha256,
            &report.emacs_executable_sha256,
        ]
        .into_iter()
        .all(|hash| valid_digest(hash))
    {
        return Err(TaskBenchmarkError::Invalid(
            "incomplete task report identity",
        ));
    }
    let mut identities = BTreeSet::new();
    for (result, prediction) in report.results.iter().zip(&report.predictions) {
        if !valid_identity(&result.id)
            || !valid_identity(&result.scenario)
            || !identities.insert(&result.id)
            || !matches!(result.steps, 1 | 2)
        {
            return Err(TaskBenchmarkError::Invalid(
                "invalid persisted task identity",
            ));
        }
        validate_outcome(result, prediction)?;
    }
    let (counts, steps, scenarios) = summaries(&report.results);
    if counts != report.counts
        || steps != report.by_steps
        || scenarios != report.by_scenario
        || report.oracle_checked != counts.total
        || report.success_rate != counts.success_rate()
    {
        return Err(TaskBenchmarkError::Invalid(
            "persisted task aggregates disagree with outcomes",
        ));
    }
    Ok(())
}

/// Compare independently executed models only when all task/runtime identities agree.
///
/// This recomputes eligibility from case outcomes, including per-step and per-fixture
/// cohorts. A lower error count bought by more supported refusals cannot qualify.
pub fn compare(
    baseline: TaskReport,
    candidate: TaskReport,
) -> Result<TaskComparison, TaskBenchmarkError> {
    validate_report(&baseline)?;
    validate_report(&candidate)?;
    if baseline.tasks_sha256 != candidate.tasks_sha256
        || baseline.runner_sha256 != candidate.runner_sha256
        || baseline.emacs_executable_sha256 != candidate.emacs_executable_sha256
        || baseline.emacs_version != candidate.emacs_version
        || baseline.policy != candidate.policy
        || baseline.results.len() != candidate.results.len()
        || baseline
            .results
            .iter()
            .zip(&candidate.results)
            .any(|(left, right)| {
                left.id != right.id || left.scenario != right.scenario || left.steps != right.steps
            })
        || baseline
            .predictions
            .iter()
            .zip(&candidate.predictions)
            .any(|(left, right)| left.id != right.id || left.instruction != right.instruction)
    {
        return Err(TaskBenchmarkError::Invalid(
            "task comparison requires identical tasks and runtime",
        ));
    }
    let steps_preserved = baseline.by_steps.iter().all(|(steps, scores)| {
        candidate
            .by_steps
            .get(steps)
            .is_some_and(|candidate| candidate.preserves(scores))
    });
    let scenarios_preserved = baseline.by_scenario.iter().all(|(scenario, scores)| {
        candidate
            .by_scenario
            .get(scenario)
            .is_some_and(|candidate| candidate.preserves(scores))
    });
    let eligible =
        candidate.counts.preserves(&baseline.counts) && steps_preserved && scenarios_preserved;
    Ok(TaskComparison {
        baseline,
        candidate,
        eligible,
    })
}

#[cfg(test)]
mod tests;