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
// generated by hxc 1.0.0-acgt-compiler from src/case_learning.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
#[derive(Clone, Debug, PartialEq)]
// hlx:6
struct Check {
    // hlx:7
    key: String,
    // hlx:8
    question: String,
    // hlx:9
    cost: f64,
    // hlx:10
}
// hlx:12
#[derive(Clone, Debug, PartialEq)]
// hlx:13
struct Example {
    // hlx:14
    truth: u16,
    // hlx:15
    action: String,
    // hlx:16
}
// hlx:18
#[derive(Clone, Debug, PartialEq)]
// hlx:19
pub(super) struct Casebook {
    // hlx:20
    checks: Vec<Check>,
    // hlx:21
    examples: BTreeMap<String, Example>,
    // hlx:22
}
// hlx:24
pub(super) fn obj<const N: usize>(fields: [(&str, Json); N]) -> Json {
    // hlx:25
    Json::Obj(
        fields
            .into_iter()
            .map(|(key, value)| (key.into(), value))
            .collect(),
    )
    // hlx:26
}
// hlx:28
pub(super) fn strings<'a>(values: impl IntoIterator<Item = &'a str>) -> Json {
    // hlx:29
    Json::Arr(values.into_iter().map(|s| Json::Str(s.into())).collect())
    // hlx:30
}
// hlx:33
fn shape(value: &Json, name: &str, required: &[&str]) -> Result<(), String> {
    // hlx:34
    let Json::Obj(fields) = value else {
        return Err(format!("{name} must be an object"));
    };
    // hlx:35
    if fields.len() != required.len() || required.iter().any(|k| value.get(k).is_none()) {
        // hlx:36
        return Err(format!(
            "{name} requires exactly these fields once each: {}",
            required.join(", ")
        ));
        // hlx:37
    }
    // hlx:38
    Ok(())
    // hlx:39
}
// hlx:41
fn bounded_array<'a>(value: &'a Json, field: &str, limit: usize) -> Result<&'a [Json], String> {
    // hlx:42
    match value.get(field) {
        // hlx:43
        Some(Json::Arr(rows)) if (1..=limit).contains(&rows.len()) => Ok(rows),
        // hlx:44
        _ => Err(format!("{field} must have between 1 and {limit} entries")),
        // hlx:45
    }
    // hlx:46
}
// hlx:48
fn bounded_text<'a>(value: &'a Json, field: &str, limit: usize) -> Result<&'a str, String> {
    // hlx:49
    value.get(field).and_then(Json::as_str)
    // hlx:50
    .filter(|s| !s.is_empty() && s.trim() == *s && s.len() <= limit && !s.chars().any(char::is_control))
    // hlx:51
    .ok_or_else(|| format!("{field} must be nonempty single-line text of at most {limit} bytes without surrounding whitespace"))
    // hlx:52
}
// hlx:54
fn valid_key(key: &str) -> bool {
    // hlx:55
    !key.is_empty()
        && key.len() <= 128
        && key
            .bytes()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'.' | b'-'))
    // hlx:56
}
// hlx:58
pub(super) fn boolean_facts(value: &Json) -> Result<BTreeMap<&str, bool>, String> {
    // hlx:59
    let Json::Obj(fields) = value else {
        return Err("facts must be a JSON object".into());
    };
    // hlx:60
    if fields.len() > 128 {
        // hlx:61
        return Err("facts accepts at most 128 keys".into());
        // hlx:62
    }
    // hlx:63
    let mut facts = BTreeMap::new();
    // hlx:64
    for (key, value) in fields {
        // hlx:65
        if !valid_key(key) {
            // hlx:66
            return Err(
                "fact keys must be 1..128 ASCII letters, digits, dots, underscores or hyphens"
                    .into(),
            );
            // hlx:67
        }
        // hlx:68
        let Json::Bool(b) = value else {
            return Err(format!("fact {key} must be a Boolean"));
        };
        // hlx:69
        if facts.insert(key.as_str(), *b).is_some() {
            // hlx:70
            return Err(format!("duplicate fact {key}"));
            // hlx:71
        }
        // hlx:72
    }
    // hlx:73
    Ok(facts)
    // hlx:74
}
// hlx:76
pub(super) fn validate_facts(value: &Json) -> Result<(), String> {
    // hlx:77
    boolean_facts(value).map(|_| ())
    // hlx:78
}
// hlx:80
impl Casebook {
    // hlx:81
    pub(super) fn experiment_keys(&self) -> impl ExactSizeIterator<Item = &str> {
        // hlx:82
        self.checks.iter().map(|check| check.key.as_str())
        // hlx:83
    }
    // hlx:85
    pub(super) fn experiment_refs(&self) -> impl Iterator<Item = (&str, u16, &str)> {
        // hlx:86
        self.examples
            .iter()
            .map(|(reference, row)| (reference.as_str(), row.truth, row.action.as_str()))
        // hlx:87
    }
    // hlx:89
    pub(super) fn parse(value: &Json) -> Result<Self, String> {
        // hlx:90
        shape(value, "casebook", &["checks", "examples"])?;
        // hlx:91
        let mut checks = Vec::new();
        // hlx:92
        for check in bounded_array(value, "checks", 16)? {
            // hlx:93
            shape(check, "check", &["key", "question", "cost"])?;
            // hlx:94
            let key = bounded_text(check, "key", 128)?;
            // hlx:95
            if !valid_key(key) {
                // hlx:96
                return Err(
                    "check keys accept ASCII letters, digits, dots, underscores and hyphens".into(),
                );
                // hlx:97
            }
            // hlx:98
            let question = bounded_text(check, "question", 512)?;
            // hlx:99
            let cost = check
                .get("cost")
                .and_then(Json::as_f64)
                .filter(|n| n.is_finite() && *n >= 1.0 && n.fract() == 0.0)
                // hlx:100
                .ok_or("check cost must be a positive finite integer")?;
            // hlx:101
            checks.push(Check {
                key: key.into(),
                question: question.into(),
                cost,
            });
            // hlx:102
        }
        // hlx:103
        checks.sort_by(|a, b| a.key.cmp(&b.key));
        // hlx:104
        if let Some(pair) = checks.windows(2).find(|p| p[0].key == p[1].key) {
            // hlx:105
            return Err(format!("duplicate check {}", pair[0].key));
            // hlx:106
        }
        // hlx:107
        let mut examples = BTreeMap::new();
        // hlx:108
        for row in bounded_array(value, "examples", 128)? {
            // hlx:109
            shape(row, "example", &["ref", "facts", "action"])?;
            // hlx:110
            let reference = bounded_text(row, "ref", 256)?;
            // hlx:111
            let action = bounded_text(row, "action", 512)?;
            // hlx:112
            let facts = boolean_facts(row.get("facts").unwrap())?;
            // hlx:113
            if facts.len() != checks.len() {
                // hlx:114
                return Err(format!(
                    "example {reference} must have exactly the declared check keys"
                ));
                // hlx:115
            }
            // hlx:116
            let mut truth = 0u16;
            // hlx:117
            for (idx, check) in checks.iter().enumerate() {
                // hlx:118
                let value = facts
                    .get(check.key.as_str())
                    .ok_or_else(|| format!("example {reference} is missing check {}", check.key))?;
                // hlx:119
                truth |= (*value as u16) << idx;
                // hlx:120
            }
            // hlx:121
            if examples
                .insert(
                    reference.into(),
                    Example {
                        truth,
                        action: action.into(),
                    },
                )
                .is_some()
            {
                // hlx:122
                return Err(format!("duplicate example ref {reference}"));
                // hlx:123
            }
            // hlx:124
        }
        // hlx:125
        Ok(Self { checks, examples })
        // hlx:126
    }
    // hlx:128
    pub(super) fn to_json(&self) -> Json {
        // hlx:129
        let checks = self
            .checks
            .iter()
            .map(|c| {
                obj([
                    // hlx:130
                    ("key", Json::Str(c.key.clone())),
                    ("question", Json::Str(c.question.clone())),
                    ("cost", Json::Num(c.cost)), // hlx:131
                ])
            })
            .collect();
        // hlx:132
        let examples = self
            .examples
            .iter()
            .map(|(reference, example)| {
                // hlx:133
                let facts = self
                    .checks
                    .iter()
                    .enumerate()
                    .map(|(i, c)| (c.key.clone(), Json::Bool(example.truth & (1 << i) != 0)))
                    .collect();
                // hlx:134
                obj([
                    ("ref", Json::Str(reference.clone())),
                    ("facts", Json::Obj(facts)),
                    ("action", Json::Str(example.action.clone())),
                ])
                // hlx:135
            })
            .collect();
        // hlx:136
        obj([
            ("checks", Json::Arr(checks)),
            ("examples", Json::Arr(examples)),
        ])
        // hlx:137
    }
    // hlx:139
    pub(super) fn merge(&self, other: &Self) -> Result<Self, String> {
        // hlx:140
        if self.checks != other.checks {
            // hlx:141
            return Err("casebook checks, questions and costs must agree".into());
            // hlx:142
        }
        // hlx:143
        let mut merged = self.clone();
        // hlx:144
        for (reference, row) in &other.examples {
            // hlx:145
            match merged.examples.get(reference) {
                // hlx:146
                Some(old) if old != row => {
                    return Err(format!("conflicting example ref {reference}"))
                }
                // hlx:147
                Some(_) => (),
                // hlx:148
                None => {
                    merged.examples.insert(reference.clone(), row.clone());
                } // hlx:149
            }
            // hlx:150
        }
        // hlx:151
        if merged.examples.len() > 128 {
            // hlx:152
            return Err("merged casebook exceeds 128 examples".into());
            // hlx:153
        }
        // hlx:154
        Ok(merged)
        // hlx:155
    }
    // hlx:157
    pub(super) fn advise(&self, facts: &Json) -> Result<Json, String> {
        // hlx:158
        Ok(self.decide(&boolean_facts(facts)?).json())
        // hlx:159
    }
    // hlx:161
    pub(super) fn guidance(&self, facts: &Json) -> Result<String, String> {
        // hlx:162
        Ok(self.decide(&boolean_facts(facts)?).text())
        // hlx:163
    }
    // hlx:165
    pub(super) fn first_guidance(&self) -> String {
        // hlx:166
        self.decide(&BTreeMap::new()).text()
        // hlx:167
    }
    // hlx:171
    fn decide<'a>(&'a self, facts: &BTreeMap<&'a str, bool>) -> Decision<'a> {
        // hlx:172
        let mut observed = 0u16;
        // hlx:173
        let mut truth = 0u16;
        // hlx:174
        let mut ignored = Vec::new();
        // hlx:175
        for (&key, &value) in facts {
            // hlx:176
            match self.checks.binary_search_by(|c| c.key.as_str().cmp(key)) {
                // hlx:177
                Ok(idx) => {
                    observed |= 1 << idx;
                    truth |= (value as u16) << idx;
                }
                // hlx:178
                Err(_) => ignored.push(key),
                // hlx:179
            }
            // hlx:180
        }
        // hlx:181
        let mut evidence = Decision {
            outcome: Outcome::Unseen,
            actions: BTreeSet::new(),
            refs: Vec::new(),
            conflicting_refs: Vec::new(),
            distinct: 0,
            ignored,
        };
        // hlx:182
        if observed == 0 && !facts.is_empty() {
            // hlx:183
            return evidence;
            // hlx:184
        }
        // hlx:185
        let mut signatures = Vec::new();
        // hlx:186
        for (reference, row) in &self.examples {
            // hlx:187
            if row.truth & observed == truth {
                // hlx:188
                evidence.refs.push(reference.as_str());
                // hlx:189
                evidence.actions.insert(row.action.as_str());
                // hlx:190
                signatures.push((row.truth, row.action.as_str()));
                // hlx:191
            }
            // hlx:192
        }
        // hlx:193
        signatures.sort_unstable();
        // hlx:194
        signatures.dedup();
        // hlx:195
        evidence.distinct = signatures.len();
        // hlx:196
        if evidence.actions.len() <= 1 {
            // hlx:197
            if let Some(&action) = evidence.actions.first() {
                // hlx:198
                evidence.outcome = Outcome::Candidate(action);
                // hlx:199
            }
            // hlx:200
            return evidence;
            // hlx:201
        }
        // hlx:204
        let conflicts: BTreeSet<_> = signatures
            .windows(2)
            .filter(|p| p[0].0 == p[1].0)
            .map(|p| p[0].0)
            .collect();
        // hlx:205
        signatures.sort_unstable_by_key(|&(_, action)| action);
        // hlx:206
        let mut total_true = [0usize; 16];
        // hlx:207
        let mut same_action_pairs = [0usize; 16];
        // hlx:208
        for group in signatures.chunk_by(|a, b| a.1 == b.1) {
            // hlx:209
            let mut group_true = [0usize; 16];
            // hlx:210
            for &(mut set_bits, _) in group {
                // hlx:211
                while set_bits != 0 {
                    // hlx:212
                    group_true[set_bits.trailing_zeros() as usize] += 1;
                    // hlx:213
                    set_bits &= set_bits - 1;
                    // hlx:214
                }
                // hlx:215
            }
            // hlx:216
            for (key, &n) in group_true[..self.checks.len()].iter().enumerate() {
                // hlx:217
                total_true[key] += n;
                // hlx:218
                same_action_pairs[key] += n * (group.len() - n);
                // hlx:219
            }
            // hlx:220
        }
        // hlx:222
        let scores: [usize; 16] = std::array::from_fn(|i| {
            total_true[i] * (evidence.distinct - total_true[i]) - same_action_pairs[i]
        });
        // hlx:223
        evidence.conflicting_refs = self
            .examples
            .iter()
            .filter(|(_, row)| conflicts.contains(&row.truth))
            .map(|(r, _)| r.as_str())
            .collect();
        // hlx:224
        let best = self
            .checks
            .iter()
            .zip(scores)
            .filter(|(_, count)| *count != 0)
            // hlx:225
            .max_by(|(a, ac), (b, bc)| {
                separation_score(*ac, b.cost)
                    .cmp(&separation_score(*bc, a.cost))
                    // hlx:226
                    .then_with(|| b.cost.total_cmp(&a.cost))
                    .then_with(|| b.key.cmp(&a.key))
            });
        // hlx:227
        evidence.outcome = match best {
            Some((check, count)) => Outcome::Ask(check, count),
            None => Outcome::Conflict,
        };
        // hlx:228
        evidence
        // hlx:229
    }
    // hlx:230
}
// hlx:235
fn separation_score(pairs: usize, opposite_cost: f64) -> (i32, u128) {
    // hlx:236
    let bits = opposite_cost.to_bits();
    // hlx:237
    let significand = (bits & ((1u64 << 52) - 1)) | (1u64 << 52);
    // hlx:238
    let product = (pairs as u128) * u128::from(significand);
    // hlx:239
    let shift = product.leading_zeros();
    // hlx:240
    ((bits >> 52) as i32 - shift as i32, product << shift)
    // hlx:241
}
// hlx:243
enum Outcome<'a> {
    // hlx:244
    Ask(&'a Check, usize),
    // hlx:245
    Candidate(&'a str),
    // hlx:246
    Unseen,
    // hlx:247
    Conflict,
    // hlx:248
}
// hlx:250
struct Decision<'a> {
    // hlx:251
    outcome: Outcome<'a>,
    // hlx:252
    actions: BTreeSet<&'a str>,
    // hlx:253
    refs: Vec<&'a str>,
    // hlx:254
    conflicting_refs: Vec<&'a str>,
    // hlx:255
    distinct: usize,
    // hlx:256
    ignored: Vec<&'a str>,
    // hlx:257
}
// hlx:259
impl Decision<'_> {
    // hlx:260
    fn json(&self) -> Json {
        // hlx:261
        let (status, mut extra) = match self.outcome {
            // hlx:262
            Outcome::Ask(c, pairs) => (
                "ask",
                vec![
                    ("key".into(), Json::Str(c.key.clone())),
                    ("question".into(), Json::Str(c.question.clone())),
                    ("cost".into(), Json::Num(c.cost)),
                    ("separated_pairs".into(), Json::Num(pairs as f64)),
                ],
            ),
            // hlx:263
            Outcome::Candidate(action) => (
                "candidate_action",
                vec![("candidate_action".into(), Json::Str(action.into()))],
            ),
            // hlx:264
            Outcome::Unseen => ("unseen", vec![]),
            // hlx:265
            Outcome::Conflict => ("conflict", vec![]),
            // hlx:266
        };
        // hlx:267
        let mut fields = vec![
            // hlx:268
            ("status".into(), Json::Str(status.into())),
            ("supporting_refs".into(), strings(self.refs.iter().copied())),
            // hlx:269
            ("distinct_cases".into(), Json::Num(self.distinct as f64)),
            ("actions".into(), strings(self.actions.iter().copied())),
            // hlx:270
            (
                "conflicting_refs".into(),
                strings(self.conflicting_refs.iter().copied()),
            ),
            ("ignored_keys".into(), strings(self.ignored.iter().copied())), // hlx:271
        ];
        // hlx:272
        fields.append(&mut extra);
        // hlx:273
        Json::Obj(fields)
        // hlx:274
    }
    // hlx:276
    fn text(&self) -> String {
        // hlx:277
        let mut text = match self.outcome {
        // hlx:278
        Outcome::Ask(c, n) => format!("Check {}. {} Its cost is {} and its answer separates {n} {} of cases with different actions.", c.key, c.question, c.cost, if n == 1 { "pair" } else { "pairs" }),
        // hlx:279
        Outcome::Candidate(action) => format!("Candidate action from matching examples is \"{action}\". Verify it in the current situation."),
        // hlx:280
        Outcome::Unseen => "No recorded example matches the supplied facts. Gather evidence before choosing an action.".into(),
        // hlx:281
        Outcome::Conflict => "Matching examples record different actions for identical facts. Review the conflicting examples before choosing an action.".into(),
        // hlx:282
        };
        // hlx:283
        if !self.refs.is_empty() {
            // hlx:284
            let label = if self.distinct == 1 {
                "distinct case"
            } else {
                "distinct cases"
            };
            // hlx:285
            text.push_str(&format!(
                " Evidence from {} {label} ({}).",
                self.distinct,
                short_list(&self.refs)
            ));
            // hlx:286
        }
        // hlx:287
        if !self.conflicting_refs.is_empty() && matches!(self.outcome, Outcome::Ask(_, _)) {
            // hlx:288
            text.push_str(&format!(
                " Conflicting examples include {}.",
                short_list(&self.conflicting_refs)
            ));
            // hlx:289
        }
        // hlx:290
        if !self.ignored.is_empty() {
            // hlx:291
            text.push_str(&format!(
                " This casebook ignores {}.",
                short_list(&self.ignored)
            ));
            // hlx:292
        }
        // hlx:293
        text
        // hlx:294
    }
    // hlx:295
}
// hlx:297
#[cfg(test)]
// hlx:298
mod tests {
    // hlx:299
    use super::*;
    // hlx:300
    use crate::parse_json;
    // hlx:302
    fn check(key: &str, cost: f64) -> Json {
        // hlx:303
        obj([
            ("key", Json::Str(key.into())),
            ("question", Json::Str(format!("Does {key} hold?"))),
            ("cost", Json::Num(cost)),
        ])
        // hlx:304
    }
    // hlx:306
    fn row(reference: &str, a: bool, b: bool, action: &str) -> Json {
        // hlx:307
        obj([
            ("ref", Json::Str(reference.into())),
            ("facts", obj([("a", Json::Bool(a)), ("b", Json::Bool(b))])),
            ("action", Json::Str(action.into())),
        ])
        // hlx:308
    }
    // hlx:310
    fn make_book(cost: f64, examples: Vec<Json>) -> Casebook {
        // hlx:311
        Casebook::parse(&obj([
            ("checks", Json::Arr(vec![check("b", 1.0), check("a", cost)])),
            ("examples", Json::Arr(examples)),
        ]))
        .unwrap()
        // hlx:312
    }
    // hlx:314
    fn advise(book: &Casebook, facts: &str) -> Json {
        // hlx:315
        book.advise(&parse_json(facts).unwrap()).unwrap()
        // hlx:316
    }
    // hlx:318
    #[test]
    // hlx:319
    fn chooses_by_conflicting_pairs_per_cost_without_counting_duplicate_observations() {
        // hlx:320
        let rows = vec![
            row("one", false, false, "inspect"),
            row("two", true, false, "replace"),
            row("three", false, true, "replace"),
            row("copy", false, true, "replace"),
        ];
        // hlx:321
        let book = make_book(1.0, rows.clone());
        // hlx:322
        let ask = advise(&book, "{}");
        // hlx:323
        assert_eq!(ask.get("key").and_then(Json::as_str), Some("a"));
        // hlx:324
        assert_eq!(ask.get("separated_pairs"), Some(&Json::Num(1.0)));
        // hlx:325
        assert_eq!(ask.get("distinct_cases"), Some(&Json::Num(3.0)));
        // hlx:326
        assert!(book.first_guidance().contains("Does a hold?"));
        // hlx:327
        let costlier = make_book(2.0, rows);
        // hlx:328
        assert_eq!(
            advise(&costlier, "{}").get("key").and_then(Json::as_str),
            Some("b")
        );
        // hlx:329
        let supported = advise(&book, r#"{"b":true,"other.domain":true}"#);
        // hlx:330
        assert_eq!(
            supported.get("candidate_action").and_then(Json::as_str),
            Some("replace")
        );
        // hlx:331
        assert_eq!(
            supported.get("supporting_refs"),
            Some(&strings(["copy", "three"]))
        );
        // hlx:332
        assert_eq!(
            supported.get("ignored_keys"),
            Some(&strings(["other.domain"]))
        );
        // hlx:333
        assert_eq!(supported.get("distinct_cases"), Some(&Json::Num(1.0)));
        // hlx:334
        assert_eq!(
            advise(&book, r#"{"a":true,"b":true}"#)
                .get("status")
                .and_then(Json::as_str),
            Some("unseen")
        );
        // hlx:335
    }
    // hlx:337
    #[test]
    // hlx:338
    fn selects_a_costlier_check_when_it_distinguishes_more_pairs_per_unit() {
        // hlx:339
        let rows = [
            (false, false, false, "stay"),
            (false, false, true, "stay"),
            (false, true, false, "stay"),
            (true, false, false, "move"),
        ];
        // hlx:340
        let examples = rows
            .into_iter()
            .enumerate()
            .map(|(i, (a, b, c, action))| {
                obj([
                    // hlx:341
                    ("ref", Json::Str(i.to_string())),
                    (
                        "facts",
                        obj([
                            ("a", Json::Bool(a)),
                            ("b", Json::Bool(b)),
                            ("c", Json::Bool(c)),
                        ]),
                    ),
                    ("action", Json::Str(action.into())), // hlx:342
                ])
            })
            .collect();
        // hlx:343
        let book = Casebook::parse(&obj([
            (
                "checks",
                Json::Arr(vec![check("a", 2.0), check("b", 1.0), check("c", 1.0)]),
            ),
            ("examples", Json::Arr(examples)),
        ]))
        .unwrap();
        // hlx:344
        let choice = advise(&book, "{}");
        // hlx:345
        assert_eq!(choice.get("key").and_then(Json::as_str), Some("a"));
        // hlx:346
        assert_eq!(choice.get("separated_pairs"), Some(&Json::Num(3.0)));
        // hlx:347
    }
    // hlx:349
    #[test]
    // hlx:350
    fn distinguishes_no_recognized_keys_from_empty_facts_and_returns_single_record_support() {
        // hlx:351
        let book = make_book(3.0, vec![row("one", false, true, "inspect")]);
        // hlx:352
        let single = advise(&book, "{}");
        // hlx:353
        assert_eq!(
            single.get("status").and_then(Json::as_str),
            Some("candidate_action")
        );
        // hlx:354
        assert_eq!(single.get("supporting_refs"), Some(&strings(["one"])));
        // hlx:355
        assert_eq!(single.get("distinct_cases"), Some(&Json::Num(1.0)));
        // hlx:356
        let unknown = advise(&book, r#"{"another":false}"#);
        // hlx:357
        assert_eq!(unknown.get("status").and_then(Json::as_str), Some("unseen"));
        // hlx:358
        assert_eq!(unknown.get("supporting_refs"), Some(&strings([])));
        // hlx:359
        assert_eq!(unknown.get("ignored_keys"), Some(&strings(["another"])));
        // hlx:360
    }
    // hlx:362
    #[test]
    // hlx:363
    fn discloses_contradictions_while_a_useful_question_remains_then_abstains() {
        // hlx:364
        let book = make_book(
            1.0,
            vec![
                row("one", false, false, "repair"),
                row("two", false, false, "replace"),
                row("copy", false, false, "repair"),
                row("third", true, false, "inspect"),
            ],
        );
        // hlx:365
        let first = advise(&book, "{}");
        // hlx:366
        assert_eq!(first.get("status").and_then(Json::as_str), Some("ask"));
        // hlx:367
        assert_eq!(
            first.get("conflicting_refs"),
            Some(&strings(["copy", "one", "two"]))
        );
        // hlx:368
        let conflict = advise(&book, r#"{"a":false}"#);
        // hlx:369
        assert_eq!(
            conflict.get("status").and_then(Json::as_str),
            Some("conflict")
        );
        // hlx:370
        assert_eq!(
            conflict.get("actions"),
            Some(&strings(["repair", "replace"]))
        );
        // hlx:371
        assert_eq!(conflict.get("candidate_action"), None);
        // hlx:372
        assert_eq!(conflict.get("distinct_cases"), Some(&Json::Num(2.0)));
        // hlx:373
    }
    // hlx:375
    #[test]
    // hlx:376
    fn canonical_merge_reuses_unchanged_refs_and_rejects_edits_or_overflow() {
        // hlx:377
        let rows = vec![
            row("z", true, false, "replace"),
            row("a", false, true, "inspect"),
        ];
        // hlx:378
        let book = make_book(2.0, rows.clone());
        // hlx:379
        let reordered = obj([
            ("examples", Json::Arr(rows.into_iter().rev().collect())),
            ("checks", Json::Arr(vec![check("a", 2.0), check("b", 1.0)])),
        ]);
        // hlx:380
        let canonical = Casebook::parse(&reordered).unwrap();
        // hlx:381
        assert_eq!(book.to_json(), canonical.to_json());
        // hlx:382
        assert_eq!(book.merge(&canonical).unwrap(), book);
        // hlx:383
        let new = make_book(2.0, vec![row("third", false, false, "other")]);
        // hlx:384
        assert_eq!(book.merge(&new).unwrap(), new.merge(&book).unwrap());
        // hlx:385
        assert!(book
            .merge(&make_book(2.0, vec![row("z", true, false, "other")]))
            .is_err());
        // hlx:386
        assert!(book
            .merge(&make_book(5.0, vec![row("z", true, false, "replace")]))
            .is_err());
        // hlx:387
        let full = make_book(
            2.0,
            (0..128)
                .map(|i| row(&i.to_string(), false, true, "inspect"))
                .collect(),
        );
        // hlx:388
        assert!(full.merge(&new).is_err());
        // hlx:389
    }
    // hlx:391
    #[test]
    // hlx:392
    fn validates_shapes_keys_boolean_values_and_costs() {
        // hlx:393
        for invalid in [
            r#"{"a":true,"a":false}"#,
            r#"{"a":"true"}"#,
            r#"{"bad key":false}"#,
            "[]",
            "false",
        ] {
            // hlx:394
            assert!(validate_facts(&parse_json(invalid).unwrap()).is_err());
            // hlx:395
        }
        // hlx:396
        assert!(validate_facts(&parse_json("{}").unwrap()).is_ok());
        // hlx:397
        let examples = Json::Arr(vec![row("ref", true, false, "act")]);
        // hlx:398
        for cost in [-1.0, 0.0, 0.5, 1.25, f64::NAN, f64::INFINITY] {
            // hlx:399
            assert!(Casebook::parse(&obj([
                ("checks", Json::Arr(vec![check("a", cost), check("b", 1.0)])),
                ("examples", examples.clone())
            ]))
            .is_err());
            // hlx:400
        }
        // hlx:401
        for checks in [
            vec![],
            vec![check("a", 1.0)],
            vec![check("a", 1.0), check("a", 1.0)],
            vec![check("x", 1.0), check("b", 1.0)],
        ] {
            // hlx:402
            assert!(Casebook::parse(&obj([
                ("checks", Json::Arr(checks)),
                ("examples", examples.clone())
            ]))
            .is_err());
            // hlx:403
        }
        // hlx:404
        let checks = Json::Arr(vec![check("a", 1.0), check("b", 1.0)]);
        // hlx:405
        let duplicated = Json::Arr(vec![
            row("ref", true, false, "act"),
            row("ref", true, false, "act"),
        ]);
        // hlx:406
        assert!(
            Casebook::parse(&obj([("checks", checks.clone()), ("examples", duplicated)])).is_err()
        );
        // hlx:407
        assert!(Casebook::parse(&obj([
            ("checks", checks),
            ("examples", Json::Arr(Vec::new()))
        ]))
        .is_err());
        // hlx:408
    }
    // hlx:410
    #[test]
    // hlx:411
    fn ranks_extreme_integer_costs_without_rounding_or_overflow() {
        // hlx:412
        let large = f64::MAX;
        // hlx:413
        let almost = f64::from_bits(large.to_bits() - 1);
        // hlx:414
        assert!(separation_score(8128, large) > separation_score(8128, almost));
        // hlx:415
        assert_eq!(separation_score(2, 1.0), separation_score(1, 2.0));
        // hlx:416
        assert!(separation_score(1, large) > separation_score(8128, 1.0));
        // hlx:417
    }
    // hlx:418
}
// hlx:420
fn short_list(entries: &[&str]) -> String {
    // hlx:421
    let shown = entries.len().min(3);
    // hlx:422
    let mut text = entries[..shown].join(", ");
    // hlx:423
    if entries.len() > shown {
        // hlx:424
        text.push_str(&format!(" (+{} more)", entries.len() - shown));
        // hlx:425
    }
    // hlx:426
    text
    // hlx:427
}