instinct-cli 0.3.9

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
// generated by hxc 1.0.0-acgt-compiler from src/replay_lesson.hlx -- do not edit by hand

#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
    let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
    if !ok {
        eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
    }
    ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    c
}

// hlx:2
use super::Json;
// hlx:3
use std::collections::{BTreeMap, BTreeSet};
// hlx:5
fn field<'a>(obj: &'a Json, key: &str) -> Result<&'a Json, String> {
    // hlx:6
    obj.get(key)
        .ok_or_else(|| format!("missing GNOSIS field {key}"))
    // hlx:7
}
// hlx:8
fn text<'a>(obj: &'a Json, key: &str) -> Result<&'a str, String> {
    // hlx:9
    field(obj, key)?
        .as_str()
        .filter(|s| !s.trim().is_empty() && s.trim() == *s && !s.chars().any(char::is_control))
        // hlx:10
        .ok_or_else(|| format!("{key} must contain a nonempty single-line label"))
    // hlx:11
}
// hlx:12
fn rows<'a>(obj: &'a Json, key: &str) -> Result<&'a [Json], String> {
    // hlx:13
    match field(obj, key)? {
        Json::Arr(a) => Ok(a),
        _ => Err(format!("{key} must be an array")),
    }
    // hlx:14
}
// hlx:15
fn check_row_units(row: &Json) -> Result<(), String> {
    // hlx:16
    // v1 has report-level x/y units only. A row override has no defined conversion or association.
    // hlx:17
    if [
        "unit",
        "units",
        "x_unit",
        "y_unit",
        "observed_unit",
        "predicted_unit",
    ]
    .iter()
    .any(|key| row.get(key).is_some())
    {
        // hlx:18
        return Err("gnosis-1 requires uniform report-level units".into());
        // hlx:19
    }
    // hlx:20
    Ok(())
    // hlx:21
}
// hlx:22
fn positive(obj: &Json, key: &str) -> Result<f64, String> {
    // hlx:23
    field(obj, key)?
        .as_f64()
        .filter(|v| v.is_finite() && *v > 0.0)
        .ok_or_else(|| format!("{key} must be finite and positive"))
    // hlx:24
}
// hlx:25
fn same(a: f64, b: f64) -> bool {
    // hlx:26
    a.is_finite() && b.is_finite() && (a - b).abs() <= 32.0 * f64::EPSILON * a.abs().max(b.abs())
    // hlx:27
}
// hlx:28
fn verify_num(obj: &Json, key: &str, expected: f64) -> Result<(), String> {
    // hlx:29
    if field(obj, key)?.as_f64().is_some_and(|v| same(v, expected)) {
        // hlx:30
        Ok(())
        // hlx:31
    } else {
        // hlx:32
        Err(format!("reported {key} disagrees with the paired data"))
        // hlx:33
    }
    // hlx:34
}
// hlx:35
fn unique_fields(value: &Json) -> Result<(), String> {
    // hlx:36
    let mut pending = vec![value];
    // hlx:37
    while let Some(node) = pending.pop() {
        // hlx:38
        match node {
            // hlx:39
            Json::Obj(fields) => {
                // hlx:40
                let mut seen = BTreeSet::new();
                // hlx:41
                for (key, child) in fields {
                    // hlx:42
                    if !seen.insert(key) {
                        return Err(format!("duplicate GNOSIS field {key}"));
                    }
                    // hlx:43
                    pending.push(child);
                    // hlx:44
                }
                // hlx:45
            }
            // hlx:46
            Json::Arr(items) => pending.extend(items),
            // hlx:47
            _ => (),
            // hlx:48
        }
        // hlx:49
    }
    // hlx:50
    Ok(())
    // hlx:51
}
// hlx:53
fn axis(report: &Json, key: &str) -> Result<String, String> {
    // hlx:54
    let obj = field(report, key)?;
    // hlx:55
    let name = text(obj, "name")?;
    // hlx:56
    let unit = text(obj, "unit")?;
    // hlx:57
    // A v1 axis declares its own units. A label records the measurement convention; it does not authorize conversion.
    // hlx:58
    let placeholder = matches!(
        unit.to_ascii_lowercase().as_str(),
        "unknown"
            | "unspecified"
            | "not specified"
            | "not provided"
            | "not available"
            | "n/a"
            | "na"
            | "none"
            | "null"
            | "tbd"
            | "-"
    ) || unit.chars().all(|c| c == '?');
    // hlx:59
    if unit.len() > 256 || placeholder || unit.contains(['\u{2028}', '\u{2029}']) {
        return Err(format!(
            "{key} requires an explicit single-line unit label of at most 256 bytes"
        ));
    }
    // hlx:60
    Ok(format!("{name} [{unit}]"))
    // hlx:61
}
// hlx:63
#[derive(Default)]
// hlx:64
struct Errors {
    // hlx:65
    covered: usize,
    // hlx:66
    log: f64,
    // hlx:67
    percent: f64,
    // hlx:68
    worst_percent: f64,
    // hlx:69
    absolute: f64,
    // hlx:70
}
// hlx:71
impl Errors {
    // hlx:72
    fn add(&mut self, predicted: f64, observed: f64, n: usize) {
        // hlx:73
        let total = n as f64;
        // hlx:74
        let absolute = (predicted - observed).abs();
        // hlx:75
        let relative = absolute / observed;
        // hlx:76
        self.covered += 1;
        // hlx:77
        self.log += (predicted.ln() - observed.ln()).abs() / total;
        // hlx:78
        self.absolute += absolute / total;
        // hlx:79
        self.percent += relative * (100.0 / total);
        // hlx:80
        self.worst_percent = self.worst_percent.max(relative * 100.0);
        // hlx:81
    }
    // hlx:82
    fn verify(&self, summary: &Json, n: usize) -> Result<(), String> {
        // hlx:83
        verify_num(summary, "covered", self.covered as f64)?;
        // hlx:84
        for (key, val) in [
            ("mean_absolute_log_error", self.log),
            ("mae", self.absolute),
            ("mape_percent", self.percent),
            ("max_absolute_percent_error", self.worst_percent),
        ] {
            // hlx:85
            if self.covered == n {
                // hlx:86
                verify_num(summary, key, val)?;
                // hlx:87
            } else if !matches!(field(summary, key)?, Json::Null) {
                // hlx:88
                return Err(format!("partial forecast must have null {key}"));
                // hlx:89
            }
            // hlx:90
        }
        // hlx:91
        Ok(())
        // hlx:92
    }
    // hlx:93
}
// hlx:96
fn model_columns<'a>(
    report: &'a Json,
    summaries: &str,
    column: &str,
    paired: &[(&Json, f64)],
) -> Result<Vec<(&'a str, Option<f64>)>, String> {
    // hlx:97
    let summaries = rows(report, summaries)?;
    // hlx:98
    let mut errors = BTreeMap::new();
    // hlx:99
    for summary in summaries {
        // hlx:100
        if errors
            .insert(text(summary, "family")?, Errors::default())
            .is_some()
        {
            return Err("duplicate model summary".into());
        }
        // hlx:101
    }
    // hlx:102
    for &(row, observed) in paired {
        // hlx:103
        let Json::Obj(models) = field(row, column)? else {
            return Err(format!("{column} must be an object"));
        };
        // hlx:104
        if models.len() != errors.len() {
            return Err(format!("incomplete {column}"));
        }
        // hlx:105
        for (name, value) in models {
            // hlx:106
            let model = errors
                .get_mut(name.as_str())
                .ok_or_else(|| format!("unreported forecast {name}"))?;
            // hlx:107
            match value {
                // hlx:108
                Json::Null => (),
                // hlx:109
                Json::Num(p) if p.is_finite() && *p > 0.0 => model.add(*p, observed, paired.len()),
                // hlx:110
                _ => return Err(format!("invalid forecast for {name}")),
                // hlx:111
            }
            // hlx:112
        }
        // hlx:113
    }
    // hlx:114
    let mut scores = Vec::new();
    // hlx:115
    for summary in summaries {
        // hlx:116
        let name = text(summary, "family")?;
        // hlx:117
        let e = &errors[name];
        // hlx:118
        e.verify(summary, paired.len())?;
        // hlx:119
        scores.push((name, (e.covered == paired.len()).then_some(e.log)));
        // hlx:120
    }
    // hlx:121
    Ok(scores)
    // hlx:122
}
// hlx:124
pub(super) fn from_gnosis(report: &Json) -> Result<Json, String> {
    // hlx:125
    unique_fields(report)?;
    // hlx:126
    if text(report, "protocol")? != "gnosis-1"
        || text(report, "mode")? != "check"
        || text(report, "metric")? != "mean_absolute_log_error"
    {
        // hlx:127
        return Err("expected a scored gnosis-1 check using mean_absolute_log_error".into());
        // hlx:128
    }
    // hlx:129
    let case = text(report, "case_id")?;
    // hlx:130
    let title = text(report, "title")?;
    // hlx:131
    let source = field(report, "source")?;
    // hlx:132
    let citation = text(source, "title")?;
    // hlx:133
    let url = text(source, "url")?;
    // hlx:134
    let limits = match report.get("limits") {
        // hlx:135
        None => "Only the supplied source, units and held-out split were tested.",
        // hlx:136
        Some(_) => text(report, "limits")?,
        // hlx:137
    };
    // hlx:138
    let x = axis(report, "x")?;
    // hlx:139
    let y = axis(report, "y")?;
    // hlx:140
    let selected = text(report, "selected_family")?;
    // hlx:141
    let recommended = text(report, "recommended_model")?;
    // hlx:142
    let evaluation = field(report, "evaluation")?;
    // hlx:143
    let training = rows(report, "training")?;
    // hlx:144
    let forecasts = rows(report, "predictions")?;
    // hlx:145
    let observations = rows(evaluation, "observations")?;
    // hlx:146
    let n = forecasts.len();
    // hlx:147
    if !(4..=128).contains(&training.len()) || !(1..=512).contains(&n) || observations.len() != n {
        // hlx:148
        return Err("incomplete or out-of-range GNOSIS split".into());
        // hlx:149
    }
    // hlx:150
    verify_num(report, "n_train", training.len() as f64)?;
    // hlx:151
    verify_num(report, "n_test", n as f64)?;
    // hlx:152
    let mut ids = BTreeSet::new();
    // hlx:153
    for row in training {
        // hlx:154
        check_row_units(row)?;
        // hlx:155
        if !ids.insert(text(row, "id")?) {
            return Err("duplicate training ID".into());
        }
        // hlx:156
        positive(row, "x")?;
        // hlx:157
        positive(row, "y")?;
        // hlx:158
    }
    // hlx:159
    let mut outcomes = BTreeMap::new();
    // hlx:160
    for obs in observations {
        // hlx:161
        check_row_units(obs)?;
        // hlx:162
        if outcomes.insert(text(obs, "id")?, obs).is_some() {
            return Err("duplicate observed ID".into());
        }
        // hlx:163
    }
    // hlx:164
    let mut paired = Vec::with_capacity(n);
    // hlx:165
    let mut selected_errors = Errors::default();
    // hlx:166
    let mut recommended_errors = Errors::default();
    // hlx:167
    for row in forecasts {
        // hlx:168
        check_row_units(row)?;
        // hlx:169
        let id = text(row, "id")?;
        // hlx:170
        if !ids.insert(id) {
            return Err("duplicate forecast ID or overlap with training".into());
        }
        // hlx:171
        positive(row, "x")?;
        // hlx:172
        let obs = outcomes
            .remove(id)
            .ok_or("forecast has no matching observation")?;
        // hlx:173
        let observed = positive(obs, "observed")?;
        // hlx:174
        let forecast = positive(row, "predicted")?;
        // hlx:175
        let advice = positive(row, "recommended")?;
        // hlx:176
        let controls = field(row, "control_predictions")?;
        // hlx:177
        if let Some(value) = controls.get(selected) {
            if value.as_f64() != Some(forecast) {
                return Err("selected family disagrees with its control column".into());
            }
        }
        // hlx:178
        let advised_forecast = if selected == recommended {
            Some(forecast)
        } else {
            controls.get(recommended).and_then(Json::as_f64)
        };
        // hlx:179
        if advised_forecast != Some(advice) {
            return Err("recommended model disagrees with its forecast column".into());
        }
        // hlx:180
        verify_num(obs, "absolute_error", (forecast - observed).abs())?;
        // hlx:181
        selected_errors.add(forecast, observed, n);
        // hlx:182
        recommended_errors.add(advice, observed, n);
        // hlx:183
        paired.push((row, observed));
        // hlx:184
    }
    // hlx:185
    for (key, name, errors) in [
        ("selected", selected, &selected_errors),
        ("recommended", recommended, &recommended_errors),
    ] {
        // hlx:186
        let summary = field(evaluation, key)?;
        // hlx:187
        if text(summary, "family")? != name {
            return Err(format!("mismatched {key} family"));
        }
        // hlx:188
        errors.verify(summary, n)?;
        // hlx:189
    }
    // hlx:190
    let controls = model_columns(report, "controls", "control_predictions", &paired)?;
    // hlx:191
    // gnosis-1 always produces these controls, even when a particular fit yields only null predictions.
    // hlx:192
    for required in [
        "median",
        "linear",
        "local_linear",
        "local_log_log",
        "local_reciprocal_log",
    ] {
        // hlx:193
        if !controls.iter().any(|(name, _)| *name == required) {
            return Err(format!("missing gnosis-1 control {required}"));
        }
        // hlx:194
    }
    // hlx:195
    model_columns(report, "transfer_scores", "donor_predictions", &paired)?;
    // hlx:196
    let full: Vec<_> = controls
        .into_iter()
        .filter_map(|(name, score)| Some((name, score?)))
        .collect();
    // hlx:197
    let declared = text(evaluation, "strongest_observed_control")?;
    // hlx:198
    let best = full
        .iter()
        .min_by(|a, b| a.1.total_cmp(&b.1))
        .ok_or("no fully covered control")?;
    // hlx:199
    if !full
        .iter()
        .any(|(name, score)| *name == declared && *score == best.1)
    {
        return Err("strongest observed control disagrees with recomputed scores".into());
    }
    // hlx:200
    let margin = 0.001;
    // hlx:201
    verify_num(evaluation, "margin_log_units", margin)?;
    // hlx:202
    let verdict = |s: f64, c: f64| {
        if s + margin < c {
            "lower_error_on_this_split"
        } else if c + margin < s {
            "control_wins"
        } else {
            "within_margin"
        }
    };
    // hlx:203
    if text(evaluation, "verdict")? != verdict(selected_errors.log, best.1) {
        return Err("reported verdict disagrees with recomputed scores".into());
    }
    // hlx:204
    // The producer's controls can include the selected model itself. Use a distinct family for the lesson.
    // hlx:205
    let (rival, other) = full
        .iter()
        .filter(|(name, _)| *name != selected)
        .min_by(|a, b| a.1.total_cmp(&b.1))
        .ok_or("no distinct fully covered rival")?;
    // hlx:206
    let decision = match verdict(selected_errors.log, *other) {
        "control_wins" => format!("{rival} had lower error"),
        "lower_error_on_this_split" => format!("{selected} had lower error"),
        _ => "the difference was within the comparison margin".into(),
    };
    // hlx:207
    let observation_word = if n == 1 {
        "observation"
    } else {
        "observations"
    };
    // hlx:208
    let values = [
    // hlx:209
    ("title", format!("Compare held-out model errors for {title}")),
    // hlx:210
    ("when", format!("Comparing forecasts for {y} from {x} on the {case} case, or planning a paired held-out comparison in a new case.")),
    // hlx:211
    ("found", format!("On the {case} split, {decision}. Mean absolute log error was {:.8e} for {selected} and {:.8e} for {rival} across {n} paired {observation_word}.", selected_errors.log,other)),
    // hlx:212
    ("how", "Freeze competing forecasts before measuring outcomes. Match each forecast to its held-out observation by unique ID. Use the same positive observations and units for every model. Compute the mean absolute difference of their natural logs. Compare the selected family with the lowest-error, fully covered alternative and apply the declared margin.".into()),
    // hlx:213
    ("evidence", format!("GNOSIS check {case}. {citation} ({url}). Split size {} training and {n} held out. Input {x}. Output {y}. Units recorded as declared, without conversion. Comparison margin {margin} log units.",training.len())),
    // hlx:214
    ("reconsider",format!("{limits} Recompute the comparison on fresh observations when the source, units, range or competing models change.")),
    // hlx:215
    ("tags","gnosis;held-out prediction;model comparison".into())];
    // hlx:216
    Ok(Json::Obj(
        values
            .into_iter()
            .map(|(key, value)| (key.into(), Json::Str(value)))
            .collect(),
    ))
    // hlx:217
}
// hlx:219
#[cfg(test)]
// hlx:220
mod tests {
    // hlx:221
    use super::*;
    // hlx:222
    use crate::parse_json;
    // hlx:225
    fn paired_report() -> String {
        // hlx:226
        let good = r#"{"covered":2,"mean_absolute_log_error":0,"mae":0,"mape_percent":0,"max_absolute_percent_error":0}"#;
        // hlx:227
        let bad = r#"{"covered":2,"mean_absolute_log_error":0.6931471805599453,"mae":3,"mape_percent":100,"max_absolute_percent_error":100}"#;
        // hlx:228
        let partial = r#"{"covered":1,"mean_absolute_log_error":null,"mae":null,"mape_percent":null,"max_absolute_percent_error":null}"#;
        // hlx:229
        let summary = |name: &str, s: &str| format!(r#"{{"family":"{name}",{}"#, &s[1..]);
        // hlx:230
        let controls = [
            ("median", bad),
            ("linear", partial),
            ("local_linear", good),
            ("local_log_log", bad),
            ("local_reciprocal_log", bad),
        ]
        .map(|(name, data)| summary(name, data))
        .join(",");
        // hlx:231
        let forecasts = [("held-red",4,2,"null"),("held-blue",8,4,"5")].map(|(id,p,y,linear)|
        // hlx:232
        format!(r#"{{"id":"{id}","x":1,"predicted":{p},"recommended":{y},"control_predictions":{{"median":{p},"linear":{linear},"local_linear":{y},"local_log_log":{p},"local_reciprocal_log":{p}}},"donor_predictions":{{}}}}"#)).join(",");
        // hlx:233
        let training = (0..4)
            .map(|i| format!(r#"{{"id":"train-{i}","x":1,"y":1}}"#))
            .collect::<Vec<_>>()
            .join(",");
        // hlx:234
        format!(
            r#"{{"protocol":"gnosis-1","mode":"check","metric":"mean_absolute_log_error","title":"Synthetic instrument","case_id":"synth","source":{{"title":"Test records","url":"urn:instrument:S","notes":"Synthetic values"}},"limits":"This instrument only.","x":{{"name":"time","unit":"s"}},"y":{{"name":"length","unit":"m"}},"n_train":4,"n_test":2,"training":[{training}],"predictions":[{forecasts}],"selected_family":"power","recommended_model":"local_linear","controls":[{controls}],"transfer_scores":[],"evaluation":{{"selected":{},"recommended":{},"strongest_observed_control":"local_linear","margin_log_units":0.001,"verdict":"control_wins","observations":[{{"id":"held-blue","observed":4,"absolute_error":4}},{{"id":"held-red","observed":2,"absolute_error":2}}]}}}}"#,
            summary("power", bad),
            summary("local_linear", good)
        )
        // hlx:235
    }
    // hlx:237
    #[test]
    // hlx:238
    fn learns_only_a_scoped_method_from_identically_paired_rows() {
        // hlx:239
        let lesson = from_gnosis(&parse_json(&paired_report()).unwrap()).unwrap();
        // hlx:240
        assert!(text(&lesson, "found")
            .unwrap()
            .contains("local_linear had lower error"));
        // hlx:241
        assert!(text(&lesson, "evidence")
            .unwrap()
            .contains("urn:instrument:S"));
        // hlx:242
        assert!(text(&lesson, "reconsider")
            .unwrap()
            .contains("This instrument only."));
        // hlx:243
        let Json::Obj(fields) = lesson else {
            panic!("expected lesson object");
        };
        // hlx:244
        assert_eq!(fields.len(), 7);
        // hlx:245
        assert!(fields
            .iter()
            .all(|(_, v)| !v.as_str().unwrap().contains("held-red")));
        // hlx:246
    }
    // hlx:248
    #[test]
    // hlx:249
    fn absent_study_limits_fall_back_to_the_tested_split() {
        // hlx:250
        let study = paired_report().replace(r#""limits":"This instrument only.","#, "");
        // hlx:251
        let lesson = from_gnosis(&parse_json(&study).unwrap()).unwrap();
        // hlx:252
        assert!(text(&lesson, "reconsider")
            .unwrap()
            .contains("Only the supplied source, units and held-out split were tested."));
        // hlx:253
    }
    // hlx:255
    #[test]
    // hlx:256
    fn records_declared_compound_and_assay_units_verbatim() {
        // hlx:257
        let report = paired_report();
        // hlx:258
        for unit in [
            "cm\u{b2}",
            "ppm",
            "astronomical units",
            "A17 calibrated assay units",
        ] {
            // hlx:259
            let study = report.replace(r#""unit":"m""#, &format!(r#""unit":"{unit}""#));
            // hlx:260
            let lesson = from_gnosis(&parse_json(&study).unwrap()).unwrap();
            // hlx:261
            let evidence = text(&lesson, "evidence").unwrap();
            // hlx:262
            assert!(evidence.contains(&format!("length [{unit}]")));
            // hlx:263
            assert!(evidence.contains("without conversion"));
            // hlx:264
        }
        // hlx:265
        let overlong = report.replace(r#""unit":"m""#, &format!(r#""unit":"{}""#, "u".repeat(257)));
        // hlx:266
        assert!(from_gnosis(&parse_json(&overlong).unwrap()).is_err());
        // hlx:267
    }
    // hlx:269
    #[test]
    // hlx:270
    fn rejects_unscored_wrongly_paired_or_tampered_reports() {
        // hlx:271
        let report = paired_report();
        // hlx:272
        let mutations = [
            // hlx:273
            (r#""mode":"check""#, r#""mode":"predict""#),
            // hlx:274
            (r#""unit":"s""#, r#""unit":"unknown""#),
            // hlx:275
            (r#""unit":"s""#, r#""unit":"?""#),
            // hlx:276
            (r#""unit":"s""#, r#""unit":"""#),
            // hlx:277
            (r#","unit":"s""#, ""),
            // hlx:278
            (r#""unit":"s""#, r#""unit":"a\nb""#),
            // hlx:279
            (r#""unit":"s""#, r#""unit":"a\u2028b""#),
            // hlx:280
            (
                r#""id":"held-blue","observed""#,
                r#""id":"held-red","observed""#,
            ),
            // hlx:281
            (
                r#""id":"held-red","observed""#,
                r#""id":"no-match","observed""#,
            ),
            // hlx:282
            (r#""id":"held-blue","x""#, r#""id":"train-1","x""#),
            // hlx:283
            (r#""observed":2"#, r#""observed":0"#),
            // hlx:284
            (r#""observed":2"#, r#""observed":2,"unit":"km""#),
            // hlx:285
            (r#""n_test":2"#, r#""n_test":3"#),
            // hlx:286
            (r#""predicted":4"#, r#""predicted":null"#),
            // hlx:287
            (
                r#""control_predictions":{"median":4"#,
                r#""control_predictions":{"median":-4"#,
            ),
            // hlx:288
            (
                r#""strongest_observed_control":"local_linear""#,
                r#""strongest_observed_control":"median""#,
            ),
            // hlx:289
            (
                r#""verdict":"control_wins""#,
                r#""verdict":"within_margin""#,
            ),
            // hlx:290
            (
                r#""mean_absolute_log_error":0.6931471805599453"#,
                r#""mean_absolute_log_error":0.7"#,
            ),
            // hlx:291
            (
                r#""mean_absolute_log_error":null"#,
                r#""mean_absolute_log_error":0"#,
            ),
            // hlx:292
            (r#""margin_log_units":0.001"#, r#""margin_log_units":1"#),
            // hlx:293
            (r#""covered":1"#, r#""covered":2"#),
            // hlx:294
            (r#""mape_percent":100"#, r#""mape_percent":10"#),
            // hlx:295
            (r#""recommended":2"#, r#""recommended":4"#),
            // hlx:296
            (r#""limits":"This instrument only.""#, r#""limits":"""#),
            // hlx:297
            (r#""limits":"This instrument only.""#, r#""limits":null"#),
            // hlx:298
            (
                r#""case_id":"synth""#,
                r#""case_id":"synth","case_id":"other""#,
            ),
            // hlx:299
        ];
        // hlx:300
        for (old, new) in mutations {
            // hlx:301
            let tampered = report.replacen(old, new, 1);
            // hlx:302
            assert_ne!(report, tampered, "fixture mutation {old}");
            // hlx:303
            assert!(
                from_gnosis(&parse_json(&tampered).unwrap()).is_err(),
                "accepted {new}"
            );
            // hlx:304
        }
        // hlx:305
    }
    // hlx:306
}