instinct-cli 0.3.10

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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
// generated by hxc 1.0.0-acgt-compiler from src/case_experiment.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::{
    case_learning::{boolean_facts, obj, strings, Casebook},
    Json,
};
// hlx:3
use std::collections::{BTreeMap, BTreeSet};
// hlx:5
const ASSUMPTION: &str = "The action is deterministic, has two outcomes, and depends on at most two declared Boolean checks. Predictions are conditional on this assumption; verify them on new cases.";
// hlx:8
#[derive(Clone, Copy, Debug)]
// hlx:9
struct Rule {
    // hlx:10
    first: u16,
    // hlx:11
    second: u16,
    // hlx:12
    table: u8,
    // hlx:13
}
// hlx:15
impl Rule {
    // hlx:16
    fn at(self, row: u16) -> bool {
        // hlx:17
        let index = u8::from(row & self.first != 0) | (u8::from(row & self.second != 0) << 1);
        // hlx:18
        self.table & (1 << index) != 0
        // hlx:19
    }
    // hlx:21
    fn possible(self, known: u16, row: u16) -> u8 {
        // hlx:22
        let relevant = self.first | self.second;
        // hlx:23
        let mut outcomes = 0;
        // hlx:24
        for completion in [0, self.first, self.second, relevant] {
            // hlx:25
            if (row ^ completion) & known & relevant == 0 {
                // hlx:26
                outcomes |= 1 << u8::from(self.at(completion));
                // hlx:27
            }
            // hlx:28
        }
        // hlx:29
        outcomes
        // hlx:30
    }
    // hlx:32
    fn explain(self, check_keys: &[&str], labels: &[&str]) -> Json {
        // hlx:33
        let keys = [self.first, self.second]
            .into_iter()
            .filter(|&bit| bit != 0)
            .map(|bit| check_keys[bit.trailing_zeros() as usize]);
        // hlx:34
        let inputs = [0, self.first, self.second, self.first | self.second];
        // hlx:35
        let entries = 1 << (u8::from(self.first != 0) + u8::from(self.second != 0));
        // hlx:36
        obj([
            ("checks", strings(keys)),
            (
                "outcomes",
                strings(
                    inputs[..entries]
                        .iter()
                        .map(|&row| labels[usize::from(self.at(row))]),
                ),
            ),
        ])
        // hlx:37
    }
    // hlx:38
}
// hlx:41
fn family(n: usize) -> Vec<Rule> {
    // hlx:42
    let mut rules = vec![
        Rule {
            first: 0,
            second: 0,
            table: 0,
        },
        Rule {
            first: 0,
            second: 0,
            table: 1,
        },
    ];
    // hlx:43
    for a in 0..n {
        // hlx:44
        let first = 1 << a;
        // hlx:45
        for table in [1, 2] {
            // hlx:46
            rules.push(Rule {
                first,
                second: 0,
                table,
            });
            // hlx:47
        }
        // hlx:48
        for b in a + 1..n {
            // hlx:49
            for table in [1, 2, 4, 6, 7, 8, 9, 11, 13, 14] {
                // hlx:50
                rules.push(Rule {
                    first,
                    second: 1 << b,
                    table,
                });
                // hlx:51
            }
            // hlx:52
        }
        // hlx:53
    }
    // hlx:54
    rules
    // hlx:55
}
// hlx:61
fn votes_on_cube(n: usize, rules: &[Rule]) -> Vec<i32> {
    // hlx:62
    let mut constant = 0;
    // hlx:63
    let mut linear = [0; 16];
    // hlx:64
    let mut pair = [[0; 16]; 16];
    // hlx:65
    for &rule in rules {
        // hlx:66
        let base = i32::from(rule.at(0));
        // hlx:67
        constant += base;
        // hlx:68
        if rule.first != 0 {
            // hlx:69
            let a = rule.first.trailing_zeros() as usize;
            // hlx:70
            let only_a = i32::from(rule.at(rule.first));
            // hlx:71
            linear[a] += only_a - base;
            // hlx:72
            if rule.second != 0 {
                // hlx:73
                let b = rule.second.trailing_zeros() as usize;
                // hlx:74
                let only_b = i32::from(rule.at(rule.second));
                // hlx:75
                linear[b] += only_b - base;
                // hlx:76
                pair[b][a] += i32::from(rule.at(rule.first | rule.second)) - only_a - only_b + base;
                // hlx:77
            }
            // hlx:78
        }
        // hlx:79
    }
    // hlx:80
    const LOW: usize = 6;
    // hlx:81
    const WIDTH: usize = 1 << LOW;
    // hlx:82
    let mut votes = vec![0; 1usize << n];
    // hlx:83
    votes[0] = constant;
    // hlx:84
    for i in 0..n.min(LOW) {
        // hlx:85
        let high = 1usize << i;
        // hlx:86
        votes[high] = votes[0] + linear[i];
        // hlx:87
        for row in 1..high {
            // hlx:88
            let rest = row & (row - 1);
            // hlx:89
            votes[high + row] = votes[high + rest] + votes[row] - votes[rest]
                + pair[i][row.trailing_zeros() as usize];
            // hlx:90
        }
        // hlx:91
    }
    // hlx:94
    for i in LOW..n {
        // hlx:95
        let mut low_effect = [linear[i]; WIDTH];
        // hlx:96
        for lane in 1usize..WIDTH {
            // hlx:97
            low_effect[lane] =
                low_effect[lane & (lane - 1)] + pair[i][lane.trailing_zeros() as usize];
            // hlx:98
        }
        // hlx:99
        let high = 1usize << i;
        // hlx:100
        let (lower, upper) = votes[..high * 2].split_at_mut(high);
        // hlx:101
        for (mask, (src, dst)) in lower
            .chunks_exact(WIDTH)
            .zip(upper.chunks_exact_mut(WIDTH))
            .enumerate()
        {
            // hlx:102
            let mut offset = 0;
            // hlx:103
            let mut bits = mask;
            // hlx:104
            while bits != 0 {
                // hlx:105
                offset += pair[i][LOW + bits.trailing_zeros() as usize];
                // hlx:106
                bits &= bits - 1;
                // hlx:107
            }
            // hlx:108
            for ((dest, &base), &effect) in dst.iter_mut().zip(src).zip(&low_effect) {
                // hlx:109
                *dest = base + effect + offset;
                // hlx:110
            }
            // hlx:111
        }
        // hlx:112
    }
    // hlx:113
    votes
    // hlx:114
}
// hlx:116
fn masks(keys: &[&str], facts: &Json, complete: bool) -> Result<(u16, u16), String> {
    // hlx:117
    let values = boolean_facts(facts)?;
    // hlx:118
    if complete && values.len() != keys.len() {
        // hlx:119
        return Err("every pool row must contain all declared checks".into());
        // hlx:120
    }
    // hlx:121
    let mut known = 0;
    // hlx:122
    let mut row = 0;
    // hlx:123
    for (key, value) in values {
        // hlx:124
        let index = keys
            .binary_search(&key)
            .map_err(|_| format!("unknown experiment check {key}"))?;
        // hlx:125
        known |= 1 << index;
        // hlx:126
        row |= u16::from(value) << index;
        // hlx:127
    }
    // hlx:128
    Ok((known, row))
    // hlx:129
}
// hlx:131
fn feasible_rows(keys: &[&str], pool: &Json) -> Result<BTreeSet<u16>, String> {
    // hlx:132
    let Json::Arr(rows) = pool else {
        return Err("experiment pool must be an array of complete fact objects".into());
    };
    // hlx:133
    if rows.len() > 512 {
        // hlx:134
        return Err("experiment pool accepts at most 512 cases".into());
        // hlx:135
    }
    // hlx:136
    rows.iter()
        .map(|r| masks(keys, r, true).map(|(_, row)| row))
        .collect()
    // hlx:137
}
// hlx:139
fn next_probe(
    keys: &[&str],
    rules: &[Rule],
    labels: &[&str],
    pool: Option<&BTreeSet<u16>>,
) -> Json {
    // hlx:140
    let mut best = None;
    // hlx:141
    let mut best_balance = 0;
    // hlx:142
    let mut consider = |row: u16, yes: usize| {
        // hlx:143
        let balance = yes.min(rules.len() - yes);
        // hlx:144
        if balance > best_balance {
            // hlx:145
            best = Some((row, yes));
            // hlx:146
            best_balance = balance;
            // hlx:147
        }
        // hlx:148
    };
    // hlx:149
    if let Some(rows) = pool {
        // hlx:150
        for &row in rows {
            // hlx:151
            consider(row, rules.iter().filter(|rule| rule.at(row)).count());
            // hlx:152
        }
        // hlx:153
    } else {
        // hlx:154
        for (row, votes) in votes_on_cube(keys.len(), rules).into_iter().enumerate() {
            // hlx:155
            consider(row as u16, votes as usize);
            // hlx:156
        }
        // hlx:157
    }
    // hlx:158
    let Some((row, yes)) = best else {
        return Json::Null;
    };
    // hlx:159
    let facts = Json::Obj(
        keys.iter()
            .enumerate()
            .map(|(i, &key)| (key.into(), Json::Bool(row & (1 << i) != 0)))
            .collect(),
    );
    // hlx:160
    obj([
        ("facts", facts),
        ("guaranteed_eliminated", Json::Num(best_balance as f64)),
        // hlx:161
        (
            "votes",
            obj([
                (labels[0], Json::Num((rules.len() - yes) as f64)),
                (labels[1], Json::Num(yes as f64)),
            ]),
        ),
    ])
    // hlx:162
}
// hlx:164
fn fits(rows: &BTreeMap<u16, &str>, positive: &str, rule: Rule) -> bool {
    // hlx:165
    rows.iter()
        .all(|(&row, &action)| rule.at(row) == (action == positive))
    // hlx:166
}
// hlx:170
fn evidence_change(
    book: &Casebook,
    n: usize,
    reference: &str,
    labels: &[&str],
    with: usize,
) -> Result<Json, String> {
    // hlx:171
    if reference.trim().is_empty() {
        // hlx:172
        return Err("after_ref requires an evidence reference".into());
        // hlx:173
    }
    // hlx:174
    let mut rows = BTreeMap::new();
    // hlx:175
    let mut found = false;
    // hlx:176
    let mut conflict = false;
    // hlx:177
    for (id, row, action) in book.experiment_refs() {
        // hlx:178
        if id == reference {
            // hlx:179
            found = true;
            // hlx:180
        } else {
            // hlx:181
            conflict |= rows
                .insert(row, action)
                .is_some_and(|prior| prior != action);
            // hlx:182
        }
        // hlx:183
    }
    // hlx:184
    if !found {
        // hlx:185
        return Err(format!("unknown case evidence reference {reference}"));
        // hlx:186
    }
    // hlx:187
    let (status, without, with, eliminated) = if labels.len() == 2 {
        // hlx:188
        let before = if conflict {
            0
        } else {
            family(n)
                .into_iter()
                .filter(|&rule| fits(&rows, labels[1], rule))
                .count()
        };
        // hlx:189
        let (status, count) = if before == with {
            ("redundant", Json::Num(0.0))
        } else if with == 0 {
            ("falsified", Json::Null)
        } else {
            ("narrowed", Json::Num((before - with) as f64))
        };
        // hlx:190
        (
            status,
            Json::Num(before as f64),
            Json::Num(with as f64),
            count,
        )
    // hlx:191
    } else {
        // hlx:192
        ("unsupported", Json::Null, Json::Null, Json::Null)
        // hlx:193
    };
    // hlx:194
    Ok(obj([
        ("reference", Json::Str(reference.into())),
        ("status", Json::Str(status.into())),
        ("models_without", without),
        ("models_with", with),
        ("eliminated", eliminated),
    ]))
    // hlx:195
}
// hlx:197
pub(super) fn experiment(
    book: &Casebook,
    facts: Option<&Json>,
    pool: Option<&Json>,
    after_ref: Option<&str>,
) -> Result<Json, String> {
    // hlx:198
    let keys: Vec<_> = book.experiment_keys().collect();
    // hlx:199
    let query = facts.map(|v| masks(&keys, v, false)).transpose()?;
    // hlx:200
    let pool = pool.map(|p| feasible_rows(&keys, p)).transpose()?;
    // hlx:201
    let mut rows = BTreeMap::new();
    // hlx:202
    let mut labels = BTreeSet::new();
    // hlx:203
    let mut conflicting = false;
    // hlx:204
    for (_, row, action) in book.experiment_refs() {
        // hlx:205
        labels.insert(action);
        // hlx:206
        conflicting |= rows
            .insert(row, action)
            .is_some_and(|prior| prior != action);
        // hlx:207
    }
    // hlx:208
    let labels: Vec<_> = labels.into_iter().collect();
    // hlx:209
    let mut prediction = Json::Null;
    // hlx:210
    let mut probe = Json::Null;
    // hlx:211
    let mut rule = Json::Null;
    // hlx:212
    let mut survivors = Vec::new();
    // hlx:213
    let (status, reason) = if conflicting {
        // hlx:214
        (
            "falsified",
            "The same full facts have conflicting recorded actions.",
        )
    // hlx:215
    } else if labels.len() != 2 {
        // hlx:216
        (
            "unsupported",
            "This experiment needs exactly two distinct observed actions.",
        )
    // hlx:217
    } else {
        // hlx:218
        survivors = family(keys.len())
            .into_iter()
            .filter(|&rule| fits(&rows, labels[1], rule))
            .collect();
        // hlx:219
        if let Some((known, row)) = query {
            // hlx:220
            let possible = survivors
                .iter()
                .fold(0, |values, rule| values | rule.possible(known, row));
            // hlx:221
            if matches!(possible, 1 | 2) {
                prediction = Json::Str(labels[usize::from(possible == 2)].into());
            }
            // hlx:222
        }
        // hlx:223
        match survivors.as_slice() {
            // hlx:224
            [] => (
                "falsified",
                "No rule using at most two checks fits all recorded actions.",
            ),
            // hlx:225
            [only] => {
                rule = only.explain(&keys, &labels);
                (
                    "identified",
                    "One rule in the declared family fits the observations.",
                )
            }
            // hlx:226
            _ => {
                // hlx:227
                probe = next_probe(&keys, &survivors, &labels, pool.as_ref());
                // hlx:228
                if probe == Json::Null {
                    ("learning","The supplied pool contains no case that distinguishes the remaining rules.")
                } else {
                    ("learning","Observe the actual outcome of the proposed case to distinguish the remaining rules.")
                }
                // hlx:229
            } // hlx:230
        }
        // hlx:231
    };
    // hlx:232
    let mut report = obj([
        ("status", Json::Str(status.into())),
        ("reason", Json::Str(reason.into())),
        ("assumption", Json::Str(ASSUMPTION.into())),
        // hlx:233
        ("surviving_models", Json::Num(survivors.len() as f64)),
        ("prediction", prediction),
        ("next_case", probe),
        ("rule", rule),
    ]);
    // hlx:234
    if let (Some(reference), Json::Obj(fields)) = (after_ref, &mut report) {
        // hlx:235
        fields.push((
            "evidence_change".into(),
            evidence_change(book, keys.len(), reference, &labels, survivors.len())?,
        ));
        // hlx:236
    }
    // hlx:237
    Ok(report)
    // hlx:238
}
// hlx:240
#[cfg(test)]
// hlx:241
mod tests {
    // hlx:242
    use super::*;
    // hlx:243
    use crate::parse_json;
    // hlx:245
    fn report(book: &Casebook, facts: Option<&Json>, pool: Option<&Json>) -> Result<Json, String> {
        // hlx:246
        experiment(book, facts, pool, None)
        // hlx:247
    }
    // hlx:249
    fn facts(n: usize, bits: u16) -> Json {
        // hlx:250
        Json::Obj(
            (0..n)
                .map(|i| (format!("c{i:02}"), Json::Bool(bits & (1 << i) != 0)))
                .collect(),
        )
        // hlx:251
    }
    // hlx:253
    fn book(n: usize, rows: &[(u16, &str)]) -> Casebook {
        // hlx:254
        let checks = (0..n)
            .map(|i| {
                obj([
                    ("key", Json::Str(format!("c{i:02}"))),
                    ("question", Json::Str(format!("Check {i}?"))),
                    ("cost", Json::Num(1.0)),
                ])
            })
            .collect();
        // hlx:255
        let examples = rows
            .iter()
            .enumerate()
            .map(|(i, &(bits, label))| {
                obj([
                    ("ref", Json::Str(i.to_string())),
                    ("facts", facts(n, bits)),
                    ("action", Json::Str(label.into())),
                ])
            })
            .collect();
        // hlx:256
        Casebook::parse(&obj([
            ("checks", Json::Arr(checks)),
            ("examples", Json::Arr(examples)),
        ]))
        .unwrap()
        // hlx:257
    }
    // hlx:259
    #[test]
    // hlx:260
    fn enumerates_exactly_the_truth_tables_depending_on_at_most_two_inputs() {
        // hlx:261
        let rules = family(4);
        // hlx:262
        let actual: BTreeSet<u16> = rules
            .iter()
            .map(|r| (0..16).fold(0, |t, i| t | (u16::from(r.at(i)) << i)))
            .collect();
        // hlx:263
        let expected: BTreeSet<u16> = (0..=u16::MAX)
            .filter(|&t| {
                (0..4)
                    .filter(|i| (0..16).any(|x| (t >> x ^ t >> (x ^ (1 << i))) & 1 != 0))
                    .count()
                    <= 2
            })
            .collect();
        // hlx:264
        assert_eq!(actual, expected);
        // hlx:265
        assert_eq!(actual.len(), rules.len());
        // hlx:266
        assert_eq!(family(16).len(), 1234);
        // hlx:267
    }
    // hlx:269
    #[test]
    // hlx:270
    fn quadratic_votes_match_direct_votes_and_partial_predictions_match_all_completions() {
        // hlx:271
        let all = family(5);
        // hlx:272
        for seed in 0..11 {
            // hlx:273
            let rules: Vec<_> = all
                .iter()
                .enumerate()
                .filter(|(i, _)| (i * 7 + seed * 3) % 11 < 6)
                .map(|(_, r)| *r)
                .collect();
            // hlx:274
            let direct: Vec<_> = (0..32)
                .map(|x| rules.iter().filter(|r| r.at(x)).count() as i32)
                .collect();
            // hlx:275
            assert_eq!(votes_on_cube(5, &rules), direct);
            // hlx:276
        }
        // hlx:277
        for rule in all {
            // hlx:278
            for known in 0..32u16 {
                // hlx:279
                for partial in 0..32u16 {
                    // hlx:280
                    let oracle = (0..32u16)
                        .filter(|&row| (row ^ partial) & known == 0)
                        .fold(0, |o, row| o | (1 << u8::from(rule.at(row))));
                    // hlx:281
                    assert_eq!(rule.possible(known, partial), oracle);
                    // hlx:282
                }
                // hlx:283
            }
            // hlx:284
        }
        // hlx:285
    }
    // hlx:287
    #[test]
    // hlx:288
    fn cube_matches_direct_votes_across_block_boundaries() {
        // hlx:289
        for n in [1, 5, 6, 7, 9, 16] {
            // hlx:290
            let rules: Vec<_> = family(n)
                .into_iter()
                .enumerate()
                .filter(|(i, _)| i % 3 != 1)
                .map(|(_, r)| r)
                .collect();
            // hlx:291
            let votes = votes_on_cube(n, &rules);
            // hlx:292
            assert_eq!(votes.len(), 1usize << n);
            // hlx:293
            let step = if n == 16 { 127 } else { 1 };
            // hlx:294
            for row in (0..votes.len())
                .step_by(step)
                .chain([votes.len() / 2, votes.len() - 1])
            {
                // hlx:295
                assert_eq!(
                    votes[row],
                    rules.iter().filter(|r| r.at(row as u16)).count() as i32
                );
                // hlx:296
            }
            // hlx:297
        }
        // hlx:298
    }
    // hlx:300
    #[test]
    // hlx:301
    fn proposes_an_optimal_unseen_case_and_honours_the_restricted_pool() {
        // hlx:302
        let b = book(3, &[(0, "low"), (7, "high")]);
        // hlx:303
        let r = report(&b, Some(&facts(3, 0)), None).unwrap();
        // hlx:304
        assert_eq!(r.get("status").and_then(Json::as_str), Some("learning"));
        // hlx:305
        assert_eq!(r.get("prediction").and_then(Json::as_str), Some("low"));
        // hlx:306
        let probe = r.get("next_case").unwrap();
        // hlx:307
        let low = probe
            .get("votes")
            .unwrap()
            .get("low")
            .unwrap()
            .as_f64()
            .unwrap();
        // hlx:308
        let high = probe
            .get("votes")
            .unwrap()
            .get("high")
            .unwrap()
            .as_f64()
            .unwrap();
        // hlx:309
        assert_eq!(
            low + high,
            r.get("surviving_models").unwrap().as_f64().unwrap()
        );
        // hlx:310
        assert_eq!(
            probe.get("guaranteed_eliminated"),
            Some(&Json::Num(low.min(high)))
        );
        // hlx:311
        let full = Json::Arr((0..8).rev().map(|row| facts(3, row)).collect());
        // hlx:312
        assert_eq!(report(&b, Some(&facts(3, 0)), Some(&full)).unwrap(), r);
        // hlx:313
        let options = Json::Arr(vec![facts(3, 7), facts(3, 2), facts(3, 2)]);
        // hlx:314
        let selected = report(&b, None, Some(&options)).unwrap();
        // hlx:315
        assert_eq!(
            selected.get("next_case").unwrap().get("facts"),
            Some(&facts(3, 2))
        );
        // hlx:316
        for pool in [Json::Arr(vec![]), Json::Arr(vec![facts(3, 7), facts(3, 0)])] {
            // hlx:317
            let result = report(&b, None, Some(&pool)).unwrap();
            // hlx:318
            assert_eq!(result.get("next_case"), Some(&Json::Null));
            // hlx:319
            assert_eq!(
                result.get("status").and_then(Json::as_str),
                Some("learning")
            );
            // hlx:320
        }
        // hlx:321
        let repeated = book(3, &[(7, "high"), (0, "low"), (7, "high"), (0, "low")]);
        // hlx:322
        assert_eq!(report(&repeated, Some(&facts(3, 0)), None).unwrap(), r);
        // hlx:323
    }
    // hlx:325
    #[test]
    // hlx:326
    fn generalizes_only_on_agreement_and_exposes_the_identified_rule() {
        // hlx:327
        let rows = [
            (0, "skip"),
            (1, "ship"),
            (2, "ship"),
            (3, "skip"),
            (4, "skip"),
            (5, "ship"),
        ];
        // hlx:328
        let b = book(3, &rows);
        // hlx:329
        let r = report(&b, Some(&facts(3, 6)), None).unwrap();
        // hlx:330
        assert_eq!(r.get("status").and_then(Json::as_str), Some("identified"));
        // hlx:331
        assert_eq!(r.get("prediction").and_then(Json::as_str), Some("ship"));
        // hlx:332
        let rule = r.get("rule").unwrap();
        // hlx:333
        assert_eq!(rule.get("checks"), Some(&strings(["c00", "c01"])));
        // hlx:334
        assert_eq!(
            rule.get("outcomes"),
            Some(&strings(["skip", "ship", "ship", "skip"]))
        );
        // hlx:335
        let partial = parse_json(r#"{"c00":false,"c02":true}"#).unwrap();
        // hlx:336
        assert_eq!(
            report(&b, Some(&partial), None).unwrap().get("prediction"),
            Some(&Json::Null)
        );
        // hlx:337
        let sufficient = parse_json(r#"{"c00":true,"c01":true}"#).unwrap();
        // hlx:338
        assert_eq!(
            report(&b, Some(&sufficient), None)
                .unwrap()
                .get("prediction")
                .and_then(Json::as_str),
            Some("skip")
        );
        // hlx:339
    }
    // hlx:341
    #[test]
    // hlx:342
    fn falsifies_contradictions_and_three_way_parity_and_validates_inputs() {
        // hlx:343
        let rows: Vec<_> = (0..8u16)
            .map(|x| (x, if x.count_ones() % 2 == 1 { "on" } else { "off" }))
            .collect();
        // hlx:344
        for b in [book(3, &rows), book(3, &[(1, "off"), (1, "on")])] {
            // hlx:345
            let r = report(&b, Some(&facts(3, 0)), None).unwrap();
            // hlx:346
            assert_eq!(r.get("status").and_then(Json::as_str), Some("falsified"));
            // hlx:347
            assert_eq!(r.get("surviving_models"), Some(&Json::Num(0.0)));
            // hlx:348
            assert_eq!(r.get("prediction"), Some(&Json::Null));
            // hlx:349
            assert_eq!(r.get("next_case"), Some(&Json::Null));
            // hlx:350
        }
        // hlx:351
        for b in [
            book(3, &[(0, "a")]),
            book(3, &[(0, "a"), (1, "b"), (2, "c")]),
        ] {
            // hlx:352
            assert_eq!(
                report(&b, None, None)
                    .unwrap()
                    .get("status")
                    .and_then(Json::as_str),
                Some("unsupported")
            );
            // hlx:353
        }
        // hlx:354
        let b = book(2, &[(0, "on"), (3, "off")]);
        // hlx:355
        for raw in [
            r#"{"unknown":true}"#,
            r#"{"c00":1}"#,
            r#"{"c00":true,"c00":false}"#,
        ] {
            // hlx:356
            assert!(report(&b, Some(&parse_json(raw).unwrap()), None).is_err());
            // hlx:357
        }
        // hlx:358
        for raw in [
            r#"{}"#,
            r#"[{"c00":true}]"#,
            r#"[{"c00":true,"extra":false}]"#,
        ] {
            // hlx:359
            assert!(report(&b, None, Some(&parse_json(raw).unwrap())).is_err());
            // hlx:360
        }
        // hlx:361
        assert!(report(&b, None, Some(&Json::Arr(vec![facts(2, 0); 513]))).is_err());
        // hlx:362
    }
    // hlx:364
    #[test]
    // hlx:365
    fn attributes_only_the_models_eliminated_by_unique_evidence() {
        // hlx:366
        let b = book(3, &[(0, "low"), (7, "high"), (2, "low"), (2, "low")]);
        // hlx:367
        let original = report(&b, None, None).unwrap();
        // hlx:368
        assert!(original.get("evidence_change").is_none());
        // hlx:369
        let r = experiment(&b, None, None, Some("3")).unwrap();
        // hlx:370
        let delta = r.get("evidence_change").unwrap();
        // hlx:371
        assert_eq!(
            delta.get("status").and_then(Json::as_str),
            Some("redundant")
        );
        // hlx:372
        assert_eq!(delta.get("eliminated"), Some(&Json::Num(0.0)));
        // hlx:373
        assert_eq!(delta.get("models_with"), original.get("surviving_models"));
        // hlx:374
        assert_eq!(delta.get("models_without"), delta.get("models_with"));
        // hlx:375
        assert_eq!(original.get("next_case"), r.get("next_case"));
        // hlx:376
        let r = experiment(&b, None, None, Some("1")).unwrap();
        // hlx:377
        let delta = r.get("evidence_change").unwrap();
        // hlx:378
        let count_without = family(3).into_iter().filter(|r| r.at(0) && r.at(2)).count();
        // hlx:379
        assert_eq!(
            delta.get("models_without"),
            Some(&Json::Num(count_without as f64))
        );
        // hlx:380
        assert_eq!(delta.get("status").and_then(Json::as_str), Some("narrowed"));
        // hlx:381
        assert!(delta.get("eliminated").unwrap().as_f64().unwrap() > 0.0);
        // hlx:382
        assert!(experiment(&b, None, None, Some("absent")).is_err());
        // hlx:383
        assert!(experiment(&b, None, None, Some(" ")).is_err());
        // hlx:384
        let b = book(2, &[(0, "a"), (1, "b"), (2, "c")]);
        // hlx:385
        let r = experiment(&b, None, None, Some("1")).unwrap();
        // hlx:386
        let delta = r.get("evidence_change").unwrap();
        // hlx:387
        assert_eq!(
            delta.get("status").and_then(Json::as_str),
            Some("unsupported")
        );
        // hlx:388
        assert_eq!(delta.get("models_with"), Some(&Json::Null));
        // hlx:389
        assert_eq!(delta.get("eliminated"), Some(&Json::Null));
        // hlx:390
    }
    // hlx:392
    #[test]
    // hlx:393
    fn a_verified_exception_can_falsify_an_identified_two_check_explanation() {
        // hlx:394
        let mut rows = vec![(0, "even"), (1, "odd"), (2, "odd"), (3, "even")];
        // hlx:395
        let before = book(3, &rows);
        // hlx:396
        let r = report(&before, Some(&facts(3, 4)), None).unwrap();
        // hlx:397
        assert_eq!(r.get("status").and_then(Json::as_str), Some("identified"));
        // hlx:398
        assert_eq!(r.get("prediction").and_then(Json::as_str), Some("even"));
        // hlx:399
        rows.push((4, "odd"));
        // hlx:400
        let wrong = experiment(&book(3, &rows), Some(&facts(3, 4)), None, Some("4")).unwrap();
        // hlx:401
        let delta = wrong.get("evidence_change").unwrap();
        // hlx:402
        assert_eq!(
            delta.get("status").and_then(Json::as_str),
            Some("falsified")
        );
        // hlx:403
        assert_eq!(delta.get("models_without"), Some(&Json::Num(1.0)));
        // hlx:404
        assert_eq!(delta.get("models_with"), Some(&Json::Num(0.0)));
        // hlx:405
        assert_eq!(delta.get("eliminated"), Some(&Json::Null));
        // hlx:406
        assert_eq!(wrong.get("prediction"), Some(&Json::Null));
        // hlx:407
    }
    // hlx:408
}