File size: 5,302 Bytes
18de23f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36fe364
 
 
18de23f
 
 
 
 
 
 
 
 
 
 
 
36fe364
 
 
18de23f
 
36fe364
 
 
18de23f
36fe364
 
 
 
 
 
18de23f
 
 
 
36fe364
 
 
 
18de23f
36fe364
 
18de23f
 
 
 
 
 
 
 
 
 
 
36fe364
 
 
18de23f
 
 
 
 
 
 
 
36fe364
 
 
 
 
18de23f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36fe364
 
 
 
18de23f
36fe364
 
 
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
//! Frozen real-Emacs task evidence participates in the same project quality gate.

use super::io::{atomic_bytes, digest, file_digest};
use super::types::{ArtifactIdentity, FrozenTaskSuite, Manifest, TaskSuiteOptions, WorkflowError};
use crate::task_benchmark::{self, RunnerOptions, TaskComparison, TaskReport};
use serde_json::{Value, json};
use std::{fs, path::Path, sync::atomic::AtomicBool};

/// Prepared immutable files; cloning is limited to the evidence-only suite identity.
pub(super) struct PreparedTasks {
    /// Exact authored suite bytes copied after project creation succeeds.
    data: Vec<u8>,
    /// Exact reviewed self-contained runner bytes.
    runner: Vec<u8>,
    /// Runtime settings and both frozen content hashes.
    pub(super) suite: FrozenTaskSuite,
}

impl PreparedTasks {
    /// Write the already validated inputs inside a newly created project.
    pub(super) fn write(&self, project: &Path) -> Result<(), WorkflowError> {
        atomic_bytes(&project.join("frozen/emacs-tasks.json"), &self.data)?;
        atomic_bytes(&project.join("frozen/emacs-task-runner.el"), &self.runner)
    }
}

/// Validate task inputs and reserve their instructions in the frozen benchmark.
pub(super) fn prepare(
    options: &TaskSuiteOptions,
    evaluation: &mut Vec<u8>,
) -> Result<PreparedTasks, WorkflowError> {
    if options.timeout_seconds == 0 || options.timeout_seconds > 3600 {
        return Err(WorkflowError::Invalid(
            "task timeout must be 1..=3600 seconds",
        ));
    }
    let emacs = fs::canonicalize(&options.emacs)?;
    if !emacs.is_file() {
        return Err(WorkflowError::Invalid("Emacs executable must be a file"));
    }
    let data = fs::read(&options.data)?;
    let runner = fs::read(&options.runner)?;
    if runner.is_empty() {
        return Err(WorkflowError::Invalid("task runner is empty"));
    }
    let cases = task_benchmark::evaluation_cases(&data)?;
    let mut expanded: Value = serde_json::from_slice(evaluation)?;
    let corpora = expanded
        .get_mut("corpora")
        .and_then(Value::as_object_mut)
        .ok_or(WorkflowError::Invalid("benchmark corpora missing"))?;
    if corpora.contains_key("emacs_state_instructions") {
        return Err(WorkflowError::Invalid(
            "task instruction corpus already exists",
        ));
    }
    corpora.insert(
        "emacs_state_instructions".into(),
        json!({
            "sha256":digest(&data), "cases":cases,
        }),
    );
    *evaluation = serde_json::to_vec_pretty(&expanded)?;
    crate::evaluation::validate_data_bytes(evaluation)?;
    Ok(PreparedTasks {
        suite: FrozenTaskSuite {
            tasks_sha256: digest(&data),
            runner_sha256: digest(&runner),
            emacs,
            timeout_seconds: options.timeout_seconds,
        },
        data,
        runner,
    })
}

/// Run both artifacts against the same frozen task suite and isolated runtime.
pub(super) fn benchmark(
    project: &Path,
    source: &Manifest,
    candidate: &Path,
    cancelled: &AtomicBool,
    progress: &mut dyn FnMut(Value),
) -> Result<Option<TaskComparison>, WorkflowError> {
    let Some(suite) = &source.task_suite else {
        return Ok(None);
    };
    let options = RunnerOptions {
        emacs: suite.emacs.to_path_buf(),
        runner: project.join("frozen/emacs-task-runner.el"),
        timeout_seconds: suite.timeout_seconds,
    };
    let data = project.join("frozen/emacs-tasks.json");
    progress(json!({"phase":"task_benchmark_baseline"}));
    let baseline = task_benchmark::evaluate(
        &project.join("baseline"),
        &data,
        &options,
        cancelled,
        progress,
    )?;
    progress(json!({"phase":"task_benchmark_candidate"}));
    let candidate = task_benchmark::evaluate(candidate, &data, &options, cancelled, progress)?;
    Ok(Some(task_benchmark::compare(baseline, candidate)?))
}

/// Tie one task report to the model, frozen suite and current Emacs executable.
fn verify_report(
    report: &TaskReport,
    artifact: &ArtifactIdentity,
    suite: &FrozenTaskSuite,
) -> Result<(), WorkflowError> {
    if report.weights_sha256 != artifact.weights_sha256
        || report.config_sha256 != artifact.config_sha256
        || report.tasks_sha256 != suite.tasks_sha256
        || report.runner_sha256 != suite.runner_sha256
        || report.emacs_executable_sha256 != file_digest(&suite.emacs)?
    {
        return Err(WorkflowError::Invalid("task report identity mismatch"));
    }
    Ok(())
}

/// Require task evidence exactly when configured, and recompute its eligibility.
pub(super) fn revalidate(
    source: &Manifest,
    artifact: &ArtifactIdentity,
    report: Option<TaskComparison>,
) -> Result<Option<TaskComparison>, WorkflowError> {
    match (&source.task_suite, report) {
        (None, None) => Ok(None),
        (Some(suite), Some(report)) => {
            verify_report(&report.baseline, &source.baseline, suite)?;
            verify_report(&report.candidate, artifact, suite)?;
            Ok(Some(task_benchmark::compare(
                report.baseline,
                report.candidate,
            )?))
        }
        _ => Err(WorkflowError::Invalid(
            "configured task benchmark evidence missing or unexpected",
        )),
    }
}