File size: 12,584 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
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
//! Deterministic two-action regression cohorts built from frozen single-action wording.
//!
//! The Cartesian product covers every ordered pair of distinct catalog actions.
//! Reusing source wording measures composition, not independently authored language
//! or successful execution in an editor. The original source cohorts are retained.

use crate::actions::{Action, ActionKind, InputError, Program, parse_command};
use crate::evaluation::{Corpus, EvaluationCase, EvaluationError, validate_data_bytes};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use thiserror::Error;

/// Stable names used by reports and the per-corpus nonregression gate.
const CORPORA: [&str; 3] = [
    "composition_emacs",
    "composition_lispm",
    "composition_cross_domain",
];

/// Failure to derive a complete, validated and reproducible composition benchmark.
#[derive(Debug, Error)]
pub enum CompositionError {
    /// Source bytes or reconstructed expectations violate the evaluator contract.
    #[error(transparent)]
    Evaluation(#[from] EvaluationError),
    /// A required historical corpus is absent.
    #[error("composition source corpus is missing: {0}")]
    MissingCorpus(&'static str),
    /// Every catalog action needs at least one single-action source phrase.
    #[error("composition source has no usable phrase for action: {0}")]
    MissingAction(&'static str),
    /// An existing derived corpus must not be silently overwritten.
    #[error("composition corpus already exists: {0}")]
    AlreadyExpanded(&'static str),
    /// A source row is not a single operation from its owning domain.
    #[error("composition source contains an invalid single-action row")]
    InvalidSource,
    /// Input language or typed argument construction failed.
    #[error(transparent)]
    Input(#[from] InputError),
    /// Canonical JSON serialization failed.
    #[error(transparent)]
    Json(#[from] serde_json::Error),
}

/// Literal roles are identity-free values, so copying preserves their meaning.
#[derive(Clone, Copy)]
enum Role {
    /// The literal belongs to the first operation.
    First,
    /// The literal belongs to the second operation.
    Second,
}

impl Role {
    /// Return a distinct readable marker for argument preservation checks.
    const fn marker(self) -> &'static str {
        match self {
            Self::First => "first",
            Self::Second => "second",
        }
    }
}

/// Borrow source rows grouped by the authoritative action labels.
type Sources<'a> = BTreeMap<&'a str, Vec<&'a EvaluationCase>>;

/// Classify an existing action's application domain without changing its meaning.
fn is_lispm(kind: ActionKind) -> bool {
    kind.label().starts_with("lispm-")
}

/// Collect one source domain and reject falsely labeled composite source rows.
fn collect_sources<'a>(corpus: &'a Corpus, lispm: bool) -> Result<Sources<'a>, CompositionError> {
    let mut sources = BTreeMap::<&str, Vec<&EvaluationCase>>::new();
    for case in &corpus.cases {
        if case.split != "supported" {
            continue;
        }
        let label = case
            .action
            .as_deref()
            .ok_or(CompositionError::InvalidSource)?;
        let kind = ActionKind::from_label(label)?;
        if !case.actions.is_empty() || is_lispm(kind) != lispm {
            return Err(CompositionError::InvalidSource);
        }
        sources.entry(label).or_default().push(case);
    }
    Ok(sources)
}

/// Select a deterministic representative while keeping source row order significant.
fn representative<'a>(
    sources: &Sources<'a>,
    kind: ActionKind,
    selection: usize,
) -> Result<&'a EvaluationCase, CompositionError> {
    let phrases = sources
        .get(kind.label())
        .filter(|rows| !rows.is_empty())
        .ok_or(CompositionError::MissingAction(kind.label()))?;
    phrases
        .get(selection % phrases.len())
        .copied()
        .ok_or(CompositionError::MissingAction(kind.label()))
}

/// Produce distinct legal literal data, respecting the URL and basename domains.
fn argument(kind: ActionKind, role: Role) -> Option<String> {
    kind.argument_name()?;
    let marker = role.marker();
    Some(match kind {
        ActionKind::BrowserUrl => format!("https://example.org/{marker}-argument"),
        ActionKind::OpenFile => format!("{marker}-file.el"),
        ActionKind::FinderDirectory => format!("~/{marker}-directory"),
        ActionKind::FinderNewFolder => format!("{marker} folder"),
        _ => format!("{marker} argument"),
    })
}

/// Materialize one original phrase with a role-specific quoted literal and typed action.
fn materialize(
    case: &EvaluationCase,
    kind: ActionKind,
    role: Role,
) -> Result<(String, Action), CompositionError> {
    let clauses = parse_command(&case.input)?;
    let [clause] = clauses.as_slice() else {
        return Err(CompositionError::InvalidSource);
    };
    let literal = argument(kind, role);
    let phrase = match &literal {
        Some(value) => clause.text.replace("NAME", &serde_json::to_string(value)?),
        None => clause.text.to_owned(),
    };
    Ok((phrase, Action::new(kind, literal)?))
}

/// Construct a complete expected program; no model prediction becomes a benchmark label.
fn compose(
    first: (&EvaluationCase, ActionKind),
    second: (&EvaluationCase, ActionKind),
) -> Result<EvaluationCase, CompositionError> {
    let (first_phrase, first_action) = materialize(first.0, first.1, Role::First)?;
    let (second_phrase, second_action) = materialize(second.0, second.1, Role::Second)?;
    let expected = Program::new(vec![first_action, second_action])?.to_lisp();
    Ok(EvaluationCase {
        input: format!("{first_phrase} then {second_phrase}"),
        expected: Some(expected),
        split: "supported".to_owned(),
        action: None,
        actions: vec![first.1.label().to_owned(), second.1.label().to_owned()],
        group: None,
        novel_to_both: first.0.novel_to_both || second.0.novel_to_both,
    })
}

/// Select the regression cohort determined by both action domains.
fn cohort_name(first: ActionKind, second: ActionKind) -> &'static str {
    match (is_lispm(first), is_lispm(second)) {
        (false, false) => "composition_emacs",
        (true, true) => "composition_lispm",
        _ => "composition_cross_domain",
    }
}

/// Hash deterministic serialized cases, binding expected labels, literals and source wording.
fn derived_corpus(cases: Vec<EvaluationCase>) -> Result<Corpus, CompositionError> {
    let sha256 = format!("{:x}", Sha256::digest(serde_json::to_vec(&cases)?));
    Ok(Corpus { sha256, cases })
}

/// Append all 2,256 distinct ordered action pairs while preserving original cohort values.
///
/// Requires `historical_emacs` and `historical_lispm`, together covering all 48
/// actions. The result is a new version-one evaluation document, not an edit to
/// any existing project or frozen source. Repeated application is rejected.
/// Derived cohort hashes identify their compact serialized case arrays.
pub fn extend(bytes: &[u8]) -> Result<Vec<u8>, CompositionError> {
    let data = validate_data_bytes(bytes)?;
    for name in CORPORA {
        if data.corpora.contains_key(name) {
            return Err(CompositionError::AlreadyExpanded(name));
        }
    }
    let emacs = data
        .corpora
        .get("historical_emacs")
        .ok_or(CompositionError::MissingCorpus("historical_emacs"))?;
    let lispm = data
        .corpora
        .get("historical_lispm")
        .ok_or(CompositionError::MissingCorpus("historical_lispm"))?;
    let mut sources = collect_sources(emacs, false)?;
    sources.extend(collect_sources(lispm, true)?);
    let mut derived = BTreeMap::<&str, Vec<EvaluationCase>>::new();
    for (first_index, first) in ActionKind::ALL.into_iter().enumerate() {
        for (second_index, second) in ActionKind::ALL.into_iter().enumerate() {
            if first == second {
                continue;
            }
            // Both indices are below the fixed catalog size 48; these sums cannot overflow.
            let first_case = representative(&sources, first, first_index + second_index)?;
            let second_case = representative(&sources, second, first_index * 3 + second_index)?;
            derived
                .entry(cohort_name(first, second))
                .or_default()
                .push(compose((first_case, first), (second_case, second))?);
        }
    }
    let mut output: Value = serde_json::from_slice(bytes)?;
    let corpora = output
        .get_mut("corpora")
        .and_then(Value::as_object_mut)
        .ok_or(CompositionError::InvalidSource)?;
    for (name, cases) in derived {
        corpora.insert(
            name.to_owned(),
            serde_json::to_value(derived_corpus(cases)?)?,
        );
    }
    output
        .as_object_mut()
        .ok_or(CompositionError::InvalidSource)?
        .insert(
            "policy".to_owned(),
            Value::String(format!(
                "{} Added composition cohorts are deterministic two-action recombinations of historical wording, not independent language samples or execution tasks.",
                data.policy
            )),
        );
    let encoded = serde_json::to_vec_pretty(&output)?;
    validate_data_bytes(&encoded)?;
    Ok(encoded)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{collections::BTreeSet, fs, path::Path};

    /// Read the immutable source benchmark used by the packaged native evaluator.
    fn original() -> Result<Vec<u8>, std::io::Error> {
        fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("data/evaluation.json"))
    }

    #[test]
    fn complete_ordered_pairs_preserve_original_cohorts_and_distinct_literals()
    -> Result<(), CompositionError> {
        let bytes = original().map_err(EvaluationError::Io)?;
        let generated = extend(&bytes)?;
        assert_eq!(generated, extend(&bytes)?);
        let source: Value = serde_json::from_slice(&bytes)?;
        let output: Value = serde_json::from_slice(&generated)?;
        for name in ["historical_emacs", "historical_lispm", "fresh_robustness"] {
            assert_eq!(
                source.get("corpora").and_then(|c| c.get(name)),
                output.get("corpora").and_then(|c| c.get(name))
            );
        }
        let data = validate_data_bytes(&generated)?;
        let mut pairs = BTreeSet::new();
        for (name, size) in [
            ("composition_emacs", 552),
            ("composition_lispm", 552),
            ("composition_cross_domain", 1152),
        ] {
            let corpus = data
                .corpora
                .get(name)
                .ok_or(CompositionError::MissingCorpus(name))?;
            assert_eq!(corpus.cases.len(), size);
            assert_eq!(
                corpus.sha256,
                format!("{:x}", Sha256::digest(serde_json::to_vec(&corpus.cases)?))
            );
            for case in &corpus.cases {
                let [first, second] = case.actions.as_slice() else {
                    return Err(CompositionError::InvalidSource);
                };
                assert_ne!(first, second);
                assert!(pairs.insert((first.as_str(), second.as_str())));
                let clauses = parse_command(&case.input)?;
                if let [first, second] = clauses.as_slice()
                    && let (Some(first), Some(second)) = (&first.name, &second.name)
                {
                    assert_ne!(first, second);
                    assert!(first.contains("first"));
                    assert!(second.contains("second"));
                }
            }
        }
        assert_eq!(pairs.len(), 2256);
        assert!(matches!(
            extend(&generated),
            Err(CompositionError::AlreadyExpanded(_))
        ));
        Ok(())
    }

    #[test]
    fn incomplete_source_catalog_is_an_error_instead_of_partial_coverage()
    -> Result<(), CompositionError> {
        let bytes = original().map_err(EvaluationError::Io)?;
        let mut data = validate_data_bytes(&bytes)?;
        let corpus = data
            .corpora
            .get_mut("historical_emacs")
            .ok_or(CompositionError::MissingCorpus("historical_emacs"))?;
        corpus
            .cases
            .retain(|case| case.action.as_deref() != Some("save-buffer"));
        assert!(matches!(
            extend(&serde_json::to_vec(&data)?),
            Err(CompositionError::MissingAction("save-buffer"))
        ));
        Ok(())
    }
}