instinct-cli 0.3.6

Local memory for AI coding agents: an MCP server and CLI that gives Claude Code, Codex, Cursor and any MCP client the one lesson that fits. Lessons that keep failing go quiet.
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
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
// generated by hxc 1.0.0-acgt-compiler from src/check/kernel.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
// Scoped deterministic checks, version one: compile the full definition, validate facts, evaluate within a budget.
// hlx:3
// Pure: bytes in, JSON text out. No I/O, no environment, no clock, no globals.
// hlx:4
use super::json::{self, J};
// hlx:5
use std::collections::{BTreeMap, BTreeSet};
// hlx:6
pub const MAX_CLAIM_DEPTH: usize = 32;
// hlx:7
pub const MAX_CLAIM_NODES: usize = 4096;
// hlx:8
pub const MAX_FACT_ENTRIES: usize = 10000;
// hlx:9
pub const MAX_STEPS: u64 = 100000;
// hlx:10
pub const MAX_OUTPUT_BYTES: usize = 65536;
// hlx:11
const MAX_LISTED: usize = 128;
// hlx:12
const MAX_CLAIM_TEXT: usize = 16384;
// hlx:13
const DIMS: [&str; 5] = ["project", "persona", "harness", "version", "machine"];
// hlx:14
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
// hlx:15
pub enum Mode {
    // hlx:16
    Validate,
    // hlx:17
    Run,
    // hlx:18
    Explain,
    // hlx:19
}
// hlx:20
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
// hlx:21
enum Ty {
    // hlx:22
    Str,
    // hlx:23
    Bool,
    // hlx:24
    Int,
    // hlx:25
    Set,
    // hlx:26
}
// hlx:27
impl Ty {
    // hlx:28
    fn name(self) -> &'static str {
        // hlx:29
        match self {
            // hlx:30
            Ty::Str => "string",
            // hlx:31
            Ty::Bool => "bool",
            // hlx:32
            Ty::Int => "int",
            // hlx:33
            Ty::Set => "set<string>",
            // hlx:34
        }
        // hlx:35
    }
    // hlx:36
}
// hlx:37
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
// hlx:38
enum Cmp {
    // hlx:39
    Subset,
    // hlx:40
    Disjoint,
    // hlx:41
    Contains,
    // hlx:42
    Eq,
    // hlx:43
    Lt,
    // hlx:44
    Lte,
    // hlx:45
}
// hlx:46
impl Cmp {
    // hlx:47
    fn name(self) -> &'static str {
        // hlx:48
        match self {
            // hlx:49
            Cmp::Subset => "subset",
            // hlx:50
            Cmp::Disjoint => "disjoint",
            // hlx:51
            Cmp::Contains => "contains",
            // hlx:52
            Cmp::Eq => "eq",
            // hlx:53
            Cmp::Lt => "lt",
            // hlx:54
            Cmp::Lte => "lte",
            // hlx:55
        }
        // hlx:56
    }
    // hlx:57
}
// hlx:58
#[derive(Debug)]
// hlx:59
enum Node {
    // hlx:60
    Cmp(Cmp, String, String),
    // hlx:61
    All(Vec<Node>),
    // hlx:62
    Any(Vec<Node>),
    // hlx:63
    Not(Box<Node>),
    // hlx:64
}
// hlx:65
#[derive(Debug)]
// hlx:66
enum Val {
    // hlx:67
    S(String),
    // hlx:68
    B(bool),
    // hlx:69
    I(i128),
    // hlx:70
    Set(Vec<String>),
    // hlx:71
}
// hlx:72
struct Def {
    // hlx:73
    id: String,
    // hlx:74
    revision: u32,
    // hlx:75
    inputs: BTreeMap<String, Ty>,
    // hlx:76
    claim: Node,
    // hlx:77
    conditions: Vec<String>,
    // hlx:78
    scope: Vec<(&'static str, String)>,
    // hlx:79
}
// hlx:80
type R<T> = Result<T, String>;
// hlx:81
fn clip(s: &str) -> String {
    // hlx:82
    let mut out = String::new();
    // hlx:83
    for ch in s.chars().take(48) {
        // hlx:84
        if ch.is_control()
            || matches!(ch as u32, 0x00ad | 0x061c | 0x180e | 0x200b..=0x200f | 0x2028..=0x202e | 0x2060..=0x206f | 0xfeff | 0xfff9..=0xfffb | 0x1bca0..=0x1bca3 | 0x1d173..=0x1d17a | 0xe0001 | 0xe0020..=0xe007f)
        {
            // hlx:85
            out.push('?');
        // hlx:86
        } else {
            // hlx:87
            out.push(ch);
            // hlx:88
        }
        // hlx:89
    }
    // hlx:90
    if s.chars().count() > 48 {
        // hlx:91
        out.push_str("...");
        // hlx:92
    }
    // hlx:93
    out
    // hlx:94
}
// hlx:95
fn is_ident(s: &str) -> bool {
    // hlx:96
    let b = s.as_bytes();
    // hlx:97
    !b.is_empty()
// hlx:98
&& b.len() <= 128
// hlx:99
&& b[0].is_ascii_alphabetic()
// hlx:100
&& b.iter().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-'))
    // hlx:101
}
// hlx:102
fn obj<'a>(j: &'a J, what: &str) -> R<&'a [(String, J)]> {
    // hlx:103
    match j {
        // hlx:104
        J::Obj(o) => Ok(o),
        // hlx:105
        _ => Err(format!("malformed_definition: {what} must be an object")),
        // hlx:106
    }
    // hlx:107
}
// hlx:108
fn field<'a>(o: &'a [(String, J)], k: &str) -> Option<&'a J> {
    // hlx:109
    o.iter().find(|(key, _)| key == k).map(|(_, v)| v)
    // hlx:110
}
// hlx:111
fn only_keys(o: &[(String, J)], allowed: &[&str], what: &str) -> R<()> {
    // hlx:112
    for (k, _) in o {
        // hlx:113
        if !allowed.contains(&k.as_str()) {
            // hlx:114
            return Err(format!(
                "unknown_field: {what} has unknown key \"{}\"",
                clip(k)
            ));
            // hlx:115
        }
        // hlx:116
    }
    // hlx:117
    Ok(())
    // hlx:118
}
// hlx:119
fn need<'a>(o: &'a [(String, J)], k: &str, what: &str) -> R<&'a J> {
    // hlx:120
    field(o, k).ok_or_else(|| format!("malformed_definition: {what} requires \"{k}\""))
    // hlx:121
}
// hlx:122
fn text<'a>(j: &'a J, what: &str) -> R<&'a str> {
    // hlx:123
    match j {
        // hlx:124
        J::Str(s) => Ok(s),
        // hlx:125
        _ => Err(format!("malformed_definition: {what} must be a string")),
        // hlx:126
    }
    // hlx:127
}
// hlx:128
fn parse_scope(j: &J, what: &str) -> R<Vec<(&'static str, String)>> {
    // hlx:129
    let o = obj(j, what)?;
    // hlx:130
    only_keys(o, &DIMS, what)?;
    // hlx:131
    let mut out = Vec::new();
    // hlx:132
    for dim in DIMS {
        // hlx:133
        if let Some(v) = field(o, dim) {
            // hlx:134
            let s = text(v, what)?;
            // hlx:135
            if s.is_empty() || s == "*" {
                // hlx:136
                return Err(format!(
                    "invalid_scope: {what}.{dim} must be a nonempty literal, not \"*\""
                ));
                // hlx:137
            }
            // hlx:138
            out.push((dim, s.to_string()));
            // hlx:139
        }
        // hlx:140
    }
    // hlx:141
    Ok(out)
    // hlx:142
}
// hlx:143
fn canonical_int(s: &str) -> Option<i128> {
    // hlx:144
    let digits = s.strip_prefix('-').unwrap_or(s);
    // hlx:145
    if digits.is_empty() || !digits.bytes().all(|c| c.is_ascii_digit()) {
        // hlx:146
        return None;
        // hlx:147
    }
    // hlx:148
    if digits.len() > 1 && digits.starts_with('0') {
        // hlx:149
        return None;
        // hlx:150
    }
    // hlx:151
    if s.starts_with('-') && digits == "0" {
        // hlx:152
        return None;
        // hlx:153
    }
    // hlx:154
    s.parse::<i128>().ok()
    // hlx:155
}
// hlx:156
fn parse_ty(s: &str) -> R<Ty> {
    // hlx:157
    match s {
        // hlx:158
        "string" => Ok(Ty::Str),
        // hlx:159
        "bool" => Ok(Ty::Bool),
        // hlx:160
        "int" => Ok(Ty::Int),
        // hlx:161
        "set<string>" => Ok(Ty::Set),
        // hlx:162
        "rational" | "graph" => Err(format!(
            "unsupported_feature: type \"{s}\" is not supported in this version"
        )),
        // hlx:163
        _ => Err(format!("invalid_type: unknown type \"{}\"", clip(s))),
        // hlx:164
    }
    // hlx:165
}
// hlx:166
fn operand(j: &J, inputs: &BTreeMap<String, Ty>, nodes: &mut usize) -> R<(String, Ty)> {
    // hlx:167
    *nodes += 1;
    // hlx:168
    if *nodes > MAX_CLAIM_NODES {
        // hlx:169
        return Err("limit_exceeded: claim has more than 4096 nodes".to_string());
        // hlx:170
    }
    // hlx:171
    let o = obj(j, "operand")?;
    // hlx:172
    only_keys(o, &["fact"], "operand")?;
    // hlx:173
    let name = text(need(o, "fact", "operand")?, "operand fact")?;
    // hlx:174
    match inputs.get(name) {
        // hlx:175
        Some(t) => Ok((name.to_string(), *t)),
        // hlx:176
        None => Err(format!(
            "unknown_reference: fact \"{}\" is not declared in inputs",
            clip(name)
        )),
        // hlx:177
    }
    // hlx:178
}
// hlx:179
fn compile(j: &J, depth: usize, inputs: &BTreeMap<String, Ty>, nodes: &mut usize) -> R<Node> {
    // hlx:180
    if depth > MAX_CLAIM_DEPTH {
        // hlx:181
        return Err("limit_exceeded: claim is nested deeper than 32".to_string());
        // hlx:182
    }
    // hlx:183
    *nodes += 1;
    // hlx:184
    if *nodes > MAX_CLAIM_NODES {
        // hlx:185
        return Err("limit_exceeded: claim has more than 4096 nodes".to_string());
        // hlx:186
    }
    // hlx:187
    let o = obj(j, "claim expression")?;
    // hlx:188
    let op = text(need(o, "op", "claim expression")?, "op")?;
    // hlx:189
    let cmp = match op {
        // hlx:190
        "subset" => Cmp::Subset,
        // hlx:191
        "disjoint" => Cmp::Disjoint,
        // hlx:192
        "contains" => Cmp::Contains,
        // hlx:193
        "eq" => Cmp::Eq,
        // hlx:194
        "lt" => Cmp::Lt,
        // hlx:195
        "lte" => Cmp::Lte,
        // hlx:196
        "all" | "any" => {
            // hlx:197
            only_keys(o, &["op", "args"], op)?;
            // hlx:198
            let args = match need(o, "args", op)? {
                // hlx:199
                J::Arr(a) if !a.is_empty() => a,
                // hlx:200
                _ => {
                    return Err(format!(
                        "malformed_definition: {op} args must be a nonempty array"
                    ))
                } // hlx:201
            };
            // hlx:202
            let mut kids = Vec::new();
            // hlx:203
            for a in args {
                // hlx:204
                kids.push(compile(a, depth + 1, inputs, nodes)?);
                // hlx:205
            }
            // hlx:206
            return Ok(if op == "all" {
                Node::All(kids)
            } else {
                Node::Any(kids)
            });
            // hlx:207
        }
        // hlx:208
        "not" => {
            // hlx:209
            only_keys(o, &["op", "arg"], op)?;
            // hlx:210
            return Ok(Node::Not(Box::new(compile(
                need(o, "arg", op)?,
                depth + 1,
                inputs,
                nodes,
            )?)));
            // hlx:211
        }
        // hlx:212
        _ => return Err(format!("unknown_operator: \"{}\"", clip(op))),
        // hlx:213
    };
    // hlx:214
    only_keys(o, &["op", "left", "right"], op)?;
    // hlx:215
    let (l, lt) = operand(need(o, "left", op)?, inputs, nodes)?;
    // hlx:216
    let (r, rt) = operand(need(o, "right", op)?, inputs, nodes)?;
    // hlx:217
    let ok = match cmp {
        // hlx:218
        Cmp::Subset | Cmp::Disjoint => lt == Ty::Set && rt == Ty::Set,
        // hlx:219
        Cmp::Contains => lt == Ty::Set && rt == Ty::Str,
        // hlx:220
        Cmp::Eq => lt == rt,
        // hlx:221
        Cmp::Lt | Cmp::Lte => lt == Ty::Int && rt == Ty::Int,
        // hlx:222
    };
    // hlx:223
    if !ok {
        // hlx:224
        return Err(format!(
            "type_mismatch: {} cannot compare {} with {}",
            op,
            lt.name(),
            rt.name()
        ));
        // hlx:225
    }
    // hlx:226
    Ok(Node::Cmp(cmp, l, r))
    // hlx:227
}
// hlx:228
fn compile_def(j: &J) -> R<Def> {
    // hlx:229
    let o = obj(j, "check")?;
    // hlx:230
    only_keys(
        o,
        &[
            "schema",
            "id",
            "revision",
            "inputs",
            "claim",
            "required_conditions",
            "scope",
        ],
        "check",
    )?;
    // hlx:231
    let schema = text(need(o, "schema", "check")?, "schema")?;
    // hlx:232
    if schema != "instinct.check/v1" {
        // hlx:233
        return Err(format!("unsupported_schema: \"{}\"", clip(schema)));
        // hlx:234
    }
    // hlx:235
    let id = text(need(o, "id", "check")?, "id")?;
    // hlx:236
    if !is_ident(id) {
        // hlx:237
        return Err("malformed_definition: id must be 1-128 ASCII letters, digits or ._- starting with a letter".to_string());
        // hlx:238
    }
    // hlx:239
    let revision = match need(o, "revision", "check")? {
        // hlx:240
        J::Num(n) => match n.parse::<u32>() {
            // hlx:241
            Ok(v)
                if (1..=2147483647).contains(&v)
                    && n.bytes().all(|c| c.is_ascii_digit())
                    && !n.starts_with('0') =>
            {
                v
            }
            // hlx:242
            _ => {
                return Err(
                    "invalid_number: revision must be an integer literal from 1 to 2147483647"
                        .to_string(),
                )
            } // hlx:243
        },
        // hlx:244
        _ => {
            return Err(
                "invalid_number: revision must be an integer literal, not a string".to_string(),
            )
        } // hlx:245
    };
    // hlx:246
    let mut inputs = BTreeMap::new();
    // hlx:247
    for (k, v) in obj(need(o, "inputs", "check")?, "inputs")? {
        // hlx:248
        if !is_ident(k) {
            // hlx:249
            return Err(format!(
                "malformed_definition: input name \"{}\" is not a valid name",
                clip(k)
            ));
            // hlx:250
        }
        // hlx:251
        inputs.insert(k.clone(), parse_ty(text(v, "input type")?)?);
        // hlx:252
    }
    // hlx:253
    let mut conditions = Vec::new();
    // hlx:254
    if let Some(rc) = field(o, "required_conditions") {
        // hlx:255
        match rc {
            // hlx:256
            J::Arr(a) => {
                // hlx:257
                for c in a {
                    // hlx:258
                    let name = text(c, "required condition")?;
                    // hlx:259
                    if !is_ident(name) {
                        // hlx:260
                        return Err(format!(
                            "malformed_definition: condition name \"{}\" is not a valid name",
                            clip(name)
                        ));
                        // hlx:261
                    }
                    // hlx:262
                    if conditions.iter().any(|x: &String| x == name) {
                        // hlx:263
                        return Err(format!(
                            "malformed_definition: duplicate required condition \"{}\"",
                            clip(name)
                        ));
                        // hlx:264
                    }
                    // hlx:265
                    conditions.push(name.to_string());
                    // hlx:266
                }
                // hlx:267
            }
            // hlx:268
            _ => {
                return Err("malformed_definition: required_conditions must be an array".to_string())
            } // hlx:269
        }
        // hlx:270
    }
    // hlx:271
    let scope = match field(o, "scope") {
        // hlx:272
        Some(s) => parse_scope(s, "check scope")?,
        // hlx:273
        None => Vec::new(),
        // hlx:274
    };
    // hlx:275
    let mut nodes = 0usize;
    // hlx:276
    let claim = compile(need(o, "claim", "check")?, 1, &inputs, &mut nodes)?;
    // hlx:277
    Ok(Def {
        id: id.to_string(),
        revision,
        inputs,
        claim,
        conditions,
        scope,
    })
    // hlx:278
}
// hlx:279
/// Everything the caller supplied, validated against the definition.
// hlx:280
struct Request {
    // hlx:281
    facts: BTreeMap<String, Val>,
    // hlx:282
    entries: usize,
    // hlx:283
    conditions: BTreeMap<String, bool>,
    // hlx:284
    scope: Vec<(&'static str, String)>,
    // hlx:285
}
// hlx:286
fn read_request(top: &[(String, J)], def: &Def) -> R<Request> {
    // hlx:287
    let mut facts = BTreeMap::new();
    // hlx:288
    let mut entries = 0usize;
    // hlx:289
    if let Some(f) = field(top, "facts") {
        // hlx:290
        for (k, v) in obj(f, "facts")? {
            // hlx:291
            let ty = match def.inputs.get(k) {
                // hlx:292
                Some(t) => *t,
                // hlx:293
                None => {
                    return Err(format!(
                        "unknown_fact: \"{}\" is not declared in inputs",
                        clip(k)
                    ))
                } // hlx:294
            };
            // hlx:295
            entries += 1;
            // hlx:296
            let val = match (ty, v) {
                // hlx:297
                (Ty::Str, J::Str(s)) => Val::S(s.clone()),
                // hlx:298
                (Ty::Bool, J::Bool(b)) => Val::B(*b),
                // hlx:299
                (Ty::Int, J::Str(s)) => match canonical_int(s) {
                    // hlx:300
                    Some(n) => Val::I(n),
                    // hlx:301
                    None => {
                        return Err(format!(
                            "invalid_number: fact \"{}\" is not a canonical decimal i128 string",
                            clip(k)
                        ))
                    } // hlx:302
                },
                // hlx:303
                (Ty::Set, J::Arr(items)) => {
                    // hlx:304
                    let mut members = Vec::new();
                    // hlx:305
                    for it in items {
                        // hlx:306
                        match it {
                            // hlx:307
                            J::Str(s) => members.push(s.clone()),
                            // hlx:308
                            _ => {
                                return Err(format!(
                                    "type_mismatch: fact \"{}\" must be an array of strings",
                                    clip(k)
                                ))
                            } // hlx:309
                        }
                        // hlx:310
                    }
                    // hlx:311
                    entries += members.len();
                    // hlx:312
                    members.sort();
                    // hlx:313
                    if members.windows(2).any(|w| w[0] == w[1]) {
                        // hlx:314
                        return Err(format!(
                            "duplicate_member: fact \"{}\" has a duplicate set member",
                            clip(k)
                        ));
                        // hlx:315
                    }
                    // hlx:316
                    Val::Set(members)
                    // hlx:317
                }
                // hlx:318
                _ => {
                    return Err(format!(
                        "type_mismatch: fact \"{}\" is not of declared type {}",
                        clip(k),
                        ty.name()
                    ))
                } // hlx:319
            };
            // hlx:320
            facts.insert(k.clone(), val);
            // hlx:321
        }
        // hlx:322
    }
    // hlx:323
    let mut conditions = BTreeMap::new();
    // hlx:324
    if let Some(c) = field(top, "conditions") {
        // hlx:325
        for (k, v) in obj(c, "conditions")? {
            // hlx:326
            if !def.conditions.iter().any(|x| x == k) {
                // hlx:327
                return Err(format!(
                    "unknown_condition: \"{}\" is not a required condition",
                    clip(k)
                ));
                // hlx:328
            }
            // hlx:329
            match v {
                // hlx:330
                J::Bool(b) => {
                    // hlx:331
                    conditions.insert(k.clone(), *b);
                    // hlx:332
                }
                // hlx:333
                _ => {
                    return Err(format!(
                        "type_mismatch: condition \"{}\" must be a boolean",
                        clip(k)
                    ))
                } // hlx:334
            }
            // hlx:335
        }
        // hlx:336
    }
    // hlx:337
    let scope = match field(top, "scope") {
        // hlx:338
        Some(s) => parse_scope(s, "request scope")?,
        // hlx:339
        None => Vec::new(),
        // hlx:340
    };
    // hlx:341
    Ok(Request {
        facts,
        entries,
        conditions,
        scope,
    })
    // hlx:342
}
// hlx:343
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
// hlx:344
enum Tri {
    // hlx:345
    T,
    // hlx:346
    F,
    // hlx:347
    U,
    // hlx:348
}
// hlx:349
struct Exhausted;
// hlx:350
struct Ev<'a> {
    // hlx:351
    facts: &'a BTreeMap<String, Val>,
    // hlx:352
    steps: u64,
    // hlx:353
    missing: BTreeSet<String>,
    // hlx:354
}
// hlx:355
type Out = Result<(Tri, Option<String>), Exhausted>;
// hlx:356
fn tri(b: bool) -> Tri {
    // hlx:357
    if b {
        // hlx:358
        Tri::T
    // hlx:359
    } else {
        // hlx:360
        Tri::F
        // hlx:361
    }
    // hlx:362
}
// hlx:363
impl<'a> Ev<'a> {
    // hlx:364
    fn charge(&mut self, n: u64) -> Result<(), Exhausted> {
        // hlx:365
        self.steps = self.steps.saturating_add(n);
        // hlx:366
        if self.steps > MAX_STEPS {
            // hlx:367
            self.steps = MAX_STEPS;
            // hlx:368
            return Err(Exhausted);
            // hlx:369
        }
        // hlx:370
        Ok(())
        // hlx:371
    }
    // hlx:372
    fn contains(&mut self, set: &[String], x: &str) -> Result<bool, Exhausted> {
        // hlx:373
        let (mut lo, mut hi) = (0usize, set.len());
        // hlx:374
        while lo < hi {
            // hlx:375
            self.charge(1)?;
            // hlx:376
            let mid = lo + (hi - lo) / 2;
            // hlx:377
            match set[mid].as_str().cmp(x) {
                // hlx:378
                std::cmp::Ordering::Equal => return Ok(true),
                // hlx:379
                std::cmp::Ordering::Less => lo = mid + 1,
                // hlx:380
                std::cmp::Ordering::Greater => hi = mid,
                // hlx:381
            }
            // hlx:382
        }
        // hlx:383
        Ok(false)
        // hlx:384
    }
    // hlx:385
    fn eval(&mut self, n: &Node) -> Out {
        // hlx:386
        self.charge(1)?;
        // hlx:387
        match n {
            // hlx:388
            Node::Cmp(c, l, r) => self.cmp(*c, l, r),
            // hlx:389
            Node::Not(inner) => {
                // hlx:390
                let (t, _) = self.eval(inner)?;
                // hlx:391
                Ok((
                    // hlx:392
                    match t {
                        // hlx:393
                        Tri::T => Tri::F,
                        // hlx:394
                        Tri::F => Tri::T,
                        // hlx:395
                        Tri::U => Tri::U,
                        // hlx:396
                    },
                    // hlx:397
                    None,
                    // hlx:398
                ))
                // hlx:399
            }
            // hlx:400
            Node::All(kids) => {
                // hlx:401
                let mut unknown = false;
                // hlx:402
                for k in kids {
                    // hlx:403
                    let (t, w) = self.eval(k)?;
                    // hlx:404
                    match t {
                        // hlx:405
                        Tri::F => return Ok((Tri::F, w)),
                        // hlx:406
                        Tri::U => unknown = true,
                        // hlx:407
                        Tri::T => {} // hlx:408
                    }
                    // hlx:409
                }
                // hlx:410
                Ok((if unknown { Tri::U } else { Tri::T }, None))
                // hlx:411
            }
            // hlx:412
            Node::Any(kids) => {
                // hlx:413
                let mut unknown = false;
                // hlx:414
                for k in kids {
                    // hlx:415
                    let (t, _) = self.eval(k)?;
                    // hlx:416
                    match t {
                        // hlx:417
                        Tri::T => return Ok((Tri::T, None)),
                        // hlx:418
                        Tri::U => unknown = true,
                        // hlx:419
                        Tri::F => {} // hlx:420
                    }
                    // hlx:421
                }
                // hlx:422
                Ok((if unknown { Tri::U } else { Tri::F }, None))
                // hlx:423
            } // hlx:424
        }
        // hlx:425
    }
    // hlx:426
    fn cmp(&mut self, c: Cmp, l: &str, r: &str) -> Out {
        // hlx:427
        let facts = self.facts;
        // hlx:428
        let (lv, rv) = (facts.get(l), facts.get(r));
        // hlx:429
        if lv.is_none() {
            // hlx:430
            self.missing.insert(l.to_string());
            // hlx:431
        }
        // hlx:432
        if rv.is_none() {
            // hlx:433
            self.missing.insert(r.to_string());
            // hlx:434
        }
        // hlx:435
        let (lv, rv) = match (lv, rv) {
            // hlx:436
            (Some(a), Some(b)) => (a, b),
            // hlx:437
            _ => return Ok((Tri::U, None)),
            // hlx:438
        };
        // hlx:439
        match (c, lv, rv) {
            // hlx:440
            (Cmp::Subset, Val::Set(a), Val::Set(b)) => {
                // hlx:441
                let (mut i, mut j) = (0usize, 0usize);
                // hlx:442
                while i < a.len() {
                    // hlx:443
                    self.charge(1)?;
                    // hlx:444
                    if j >= b.len() || a[i] < b[j] {
                        // hlx:445
                        return Ok((Tri::F, Some(a[i].clone())));
                        // hlx:446
                    }
                    // hlx:447
                    if a[i] == b[j] {
                        // hlx:448
                        i += 1;
                        // hlx:449
                    }
                    // hlx:450
                    j += 1;
                    // hlx:451
                }
                // hlx:452
                Ok((Tri::T, None))
                // hlx:453
            }
            // hlx:454
            (Cmp::Disjoint, Val::Set(a), Val::Set(b)) => {
                // hlx:455
                let (mut i, mut j) = (0usize, 0usize);
                // hlx:456
                while i < a.len() && j < b.len() {
                    // hlx:457
                    self.charge(1)?;
                    // hlx:458
                    match a[i].cmp(&b[j]) {
                        // hlx:459
                        std::cmp::Ordering::Equal => return Ok((Tri::F, Some(a[i].clone()))),
                        // hlx:460
                        std::cmp::Ordering::Less => i += 1,
                        // hlx:461
                        std::cmp::Ordering::Greater => j += 1,
                        // hlx:462
                    }
                    // hlx:463
                }
                // hlx:464
                Ok((Tri::T, None))
                // hlx:465
            }
            // hlx:466
            (Cmp::Contains, Val::Set(a), Val::S(x)) => {
                // hlx:467
                let found = self.contains(a, x)?;
                // hlx:468
                Ok((tri(found), None))
                // hlx:469
            }
            // hlx:470
            (Cmp::Eq, Val::Set(a), Val::Set(b)) => {
                // hlx:471
                self.charge(1)?;
                // hlx:472
                if a.len() != b.len() {
                    // hlx:473
                    return Ok((Tri::F, None));
                    // hlx:474
                }
                // hlx:475
                for k in 0..a.len() {
                    // hlx:476
                    self.charge(1)?;
                    // hlx:477
                    if a[k] != b[k] {
                        // hlx:478
                        return Ok((Tri::F, None));
                        // hlx:479
                    }
                    // hlx:480
                }
                // hlx:481
                Ok((Tri::T, None))
                // hlx:482
            }
            // hlx:483
            (Cmp::Eq, Val::S(a), Val::S(b)) => Ok((tri(a == b), None)),
            // hlx:484
            (Cmp::Eq, Val::B(a), Val::B(b)) => Ok((tri(a == b), None)),
            // hlx:485
            (Cmp::Eq, Val::I(a), Val::I(b)) => Ok((tri(a == b), None)),
            // hlx:486
            (Cmp::Lt, Val::I(a), Val::I(b)) => Ok((tri(a < b), None)),
            // hlx:487
            (Cmp::Lte, Val::I(a), Val::I(b)) => Ok((tri(a <= b), None)),
            // hlx:488
            _ => Ok((Tri::U, None)),
            // hlx:489
        }
        // hlx:490
    }
    // hlx:491
}
// hlx:492
fn render_claim(n: &Node, out: &mut String) {
    // hlx:493
    if out.len() > MAX_CLAIM_TEXT {
        // hlx:494
        return;
        // hlx:495
    }
    // hlx:496
    match n {
        // hlx:497
        Node::Cmp(c, l, r) => out.push_str(&format!("{}({}, {})", c.name(), l, r)),
        // hlx:498
        Node::Not(k) => {
            // hlx:499
            out.push_str("not(");
            // hlx:500
            render_claim(k, out);
            // hlx:501
            out.push(')');
            // hlx:502
        }
        // hlx:503
        Node::All(kids) | Node::Any(kids) => {
            // hlx:504
            out.push_str(if matches!(n, Node::All(_)) {
                "all("
            } else {
                "any("
            });
            // hlx:505
            for (i, k) in kids.iter().enumerate() {
                // hlx:506
                if i > 0 {
                    // hlx:507
                    out.push_str(", ");
                    // hlx:508
                }
                // hlx:509
                render_claim(k, out);
                // hlx:510
            }
            // hlx:511
            out.push(')');
            // hlx:512
        } // hlx:513
    }
    // hlx:514
}
// hlx:515
fn jstr(s: &str) -> String {
    // hlx:516
    let mut o = String::with_capacity(s.len() + 2);
    // hlx:517
    o.push('"');
    // hlx:518
    for ch in s.chars() {
        // hlx:519
        match ch {
            // hlx:520
            '"' => o.push_str("\\\""),
            // hlx:521
            '\\' => o.push_str("\\\\"),
            // hlx:522
            '\n' => o.push_str("\\n"),
            // hlx:523
            '\r' => o.push_str("\\r"),
            // hlx:524
            '\t' => o.push_str("\\t"),
            // hlx:525
            c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)),
            // hlx:526
            c => o.push(c),
            // hlx:527
        }
        // hlx:528
    }
    // hlx:529
    o.push('"');
    // hlx:530
    o
    // hlx:531
}
// hlx:532
fn jlist(items: &[String]) -> String {
    // hlx:533
    let parts: Vec<String> = items.iter().map(|s| jstr(s)).collect();
    // hlx:534
    format!("[{}]", parts.join(","))
    // hlx:535
}
// hlx:536
fn jscope(scope: &[(&'static str, String)]) -> String {
    // hlx:537
    let parts: Vec<String> = scope
        .iter()
        .map(|(k, v)| format!("{}:{}", jstr(k), jstr(v)))
        .collect();
    // hlx:538
    format!("{{{}}}", parts.join(","))
    // hlx:539
}
// hlx:540
pub fn error_json(reason: &str) -> String {
    // hlx:541
    format!("{{\"schema\":\"instinct.check-error/v1\",\"verdict\":\"error\",\"reason\":{},\"authorization\":\"not_evaluated\"}}", jstr(reason))
    // hlx:542
}
// hlx:543
/// One pure entry point for CLI, MCP and WASM. Returns the JSON text and whether it is an error shape.
// hlx:544
pub fn evaluate(mode: Mode, input: &[u8]) -> (String, bool) {
    // hlx:545
    match evaluate_inner(mode, input) {
        // hlx:546
        Ok(s) => (s, false),
        // hlx:547
        Err(e) => (error_json(&e), true),
        // hlx:548
    }
    // hlx:549
}
// hlx:550
fn evaluate_inner(mode: Mode, input: &[u8]) -> R<String> {
    // hlx:551
    let tree = json::parse(input)?;
    // hlx:552
    let top = match &tree {
        // hlx:553
        J::Obj(o) => o,
        // hlx:554
        _ => return Err("malformed_definition: the request must be a JSON object".to_string()),
        // hlx:555
    };
    // hlx:556
    only_keys(top, &["check", "facts", "conditions", "scope"], "request")?;
    // hlx:557
    let def = compile_def(need(top, "check", "request")?)?;
    // hlx:558
    let req = read_request(top, &def)?;
    // hlx:559
    if mode == Mode::Validate {
        // hlx:560
        if req.entries > MAX_FACT_ENTRIES {
            // hlx:561
            return Err(
                "limit_exceeded: facts have more than 10000 entries and set members".to_string(),
            );
            // hlx:562
        }
        // hlx:563
        return Ok(format!(
// hlx:564
"{{\"schema\":\"instinct.check-validation/v1\",\"check_id\":{},\"revision\":{},\"valid\":true,\"authorization\":\"not_evaluated\"}}",
// hlx:565
jstr(&def.id),
// hlx:566
def.revision
// hlx:567
));
        // hlx:568
    }
    // hlx:569
    let mut missing: BTreeSet<String> = BTreeSet::new();
    // hlx:570
    let mut steps = 0u64;
    // hlx:571
    let mut witness: Option<String> = None;
    // hlx:572
    let (verdict, reason) = 'decide: {
        // hlx:573
        if req.entries > MAX_FACT_ENTRIES {
            // hlx:574
            break 'decide (
                "abstain",
                "resource_limit: facts exceed 10000 entries".to_string(),
            );
            // hlx:575
        }
        // hlx:576
        for (dim, want) in &def.scope {
            // hlx:577
            match req.scope.iter().find(|(d, _)| d == dim) {
                // hlx:578
                None => break 'decide ("abstain", format!("scope_missing: {dim}")),
                // hlx:579
                Some((_, have)) if have != want => {
                    break 'decide ("abstain", format!("scope_mismatch: {dim}"))
                }
                // hlx:580
                Some(_) => {} // hlx:581
            }
            // hlx:582
        }
        // hlx:583
        for c in &def.conditions {
            // hlx:584
            if req.conditions.get(c) != Some(&true) {
                // hlx:585
                missing.insert(c.clone());
                // hlx:586
            }
            // hlx:587
        }
        // hlx:588
        if !missing.is_empty() {
            // hlx:589
            break 'decide ("abstain", "required_condition_not_met".to_string());
            // hlx:590
        }
        // hlx:591
        let mut ev = Ev {
            facts: &req.facts,
            steps: 0,
            missing: BTreeSet::new(),
        };
        // hlx:592
        let res = ev.eval(&def.claim);
        // hlx:593
        steps = ev.steps;
        // hlx:594
        missing.extend(ev.missing);
        // hlx:595
        match res {
            // hlx:596
            Err(Exhausted) => (
                "abstain",
                "resource_limit: evaluation budget exhausted".to_string(),
            ),
            // hlx:597
            Ok((Tri::T, _)) => ("pass", "claim_holds".to_string()),
            // hlx:598
            Ok((Tri::F, w)) => {
                // hlx:599
                witness = w;
                // hlx:600
                ("fail", "claim_false".to_string())
                // hlx:601
            }
            // hlx:602
            Ok((Tri::U, _)) => ("abstain", "fact_missing".to_string()),
            // hlx:603
        }
        // hlx:604
    };
    // hlx:605
    let missing: Vec<String> = missing.into_iter().collect();
    // hlx:606
    let mut out = format!(
// hlx:607
"{{\"schema\":\"instinct.check-result/v1\",\"check_id\":{},\"revision\":{},\"verdict\":\"{}\",\"reason\":{},\"witness\":{},\"missing\":{},\"scope\":{},\"steps\":{}",
// hlx:608
jstr(&def.id),
// hlx:609
def.revision,
// hlx:610
verdict,
// hlx:611
jstr(&reason),
// hlx:612
match &witness {
// hlx:613
Some(w) => jstr(w),
// hlx:614
None => "null".to_string(),
// hlx:615
},
// hlx:616
jlist(&missing),
// hlx:617
jscope(&req.scope),
// hlx:618
steps
// hlx:619
);
    // hlx:620
    if mode == Mode::Explain {
        // hlx:621
        let mut claim = String::new();
        // hlx:622
        render_claim(&def.claim, &mut claim);
        // hlx:623
        let claim_truncated = claim.len() > MAX_CLAIM_TEXT;
        // hlx:624
        if claim_truncated {
            // hlx:625
            let mut end = MAX_CLAIM_TEXT;
            // hlx:626
            while !claim.is_char_boundary(end) {
                // hlx:627
                end -= 1;
                // hlx:628
            }
            // hlx:629
            claim.truncate(end);
            // hlx:630
            claim.push_str("...");
            // hlx:631
        }
        // hlx:632
        let inputs: Vec<String> = def
            .inputs
            .iter()
            .take(MAX_LISTED)
            .map(|(k, t)| format!("{}:{}", jstr(k), jstr(t.name())))
            .collect();
        // hlx:633
        let conds: Vec<String> = def.conditions.iter().take(MAX_LISTED).cloned().collect();
        // hlx:634
        out.push_str(&format!(
// hlx:635
",\"explanation\":{{\"claim\":{},\"claim_truncated\":{},\"inputs\":{{{}}},\"inputs_truncated\":{},\"required_conditions\":{},\"required_conditions_truncated\":{},\"required_scope\":{}}}",
// hlx:636
jstr(&claim),
// hlx:637
claim_truncated,
// hlx:638
inputs.join(","),
// hlx:639
def.inputs.len() > MAX_LISTED,
// hlx:640
jlist(&conds),
// hlx:641
def.conditions.len() > MAX_LISTED,
// hlx:642
jscope(&def.scope)
// hlx:643
));
        // hlx:644
    }
    // hlx:645
    out.push_str(",\"authorization\":\"not_evaluated\",\"evidence_origin\":\"caller_reported\"}");
    // hlx:646
    if out.len() > MAX_OUTPUT_BYTES {
        // hlx:647
        // Never echo an oversized request back and never truncate scope, missing or explanation: refuse instead.
        // hlx:648
        return Err(
            "limit_exceeded: result would exceed 64 KiB (scope, missing or explanation too large)"
                .to_string(),
        );
        // hlx:649
    }
    // hlx:650
    Ok(out)
    // hlx:651
}
// hlx:652
#[cfg(test)]
// hlx:653
mod tests {
    // hlx:654
    use super::*;
    // hlx:655
    fn subset_doc(member: &str) -> String {
        // hlx:656
        format!(
// hlx:657
"{{\"check\":{{\"schema\":\"instinct.check/v1\",\"id\":\"a\",\"revision\":1,\"inputs\":{{\"x\":\"set<string>\",\"y\":\"set<string>\"}},\"claim\":{{\"op\":\"subset\",\"left\":{{\"fact\":\"x\"}},\"right\":{{\"fact\":\"y\"}}}}}},\"facts\":{{\"x\":[\"{member}\"],\"y\":[]}}}}"
// hlx:658
)
        // hlx:659
    }
    // hlx:660
    #[test]
    // hlx:661
    fn diagnostic_clip_removes_display_controls_without_changing_fact_strings() {
        // hlx:662
        assert_eq!(clip("bad\u{202e}name\u{2066}x\u{200d}"), "bad?name?x?");
        // hlx:663
        assert_eq!(clip("café日本語"), "café日本語");
        // hlx:664
        assert!(jstr("\u{202e}fact").contains('\u{202e}'));
        // hlx:665
    }
    // hlx:666
    #[test]
    // hlx:667
    fn explanation_declares_when_display_claim_is_incomplete() {
        // hlx:668
        let leaf =
            r#"{"op":"eq","left":{"fact":"long_fact_name"},"right":{"fact":"long_fact_name"}}"#;
        // hlx:669
        let claim = format!(
            "{{\"op\":\"all\",\"args\":[{}]}}",
            vec![leaf; 1000].join(",")
        );
        // hlx:670
        let input = format!("{{\"check\":{{\"schema\":\"instinct.check/v1\",\"id\":\"explain-limit\",\"revision\":1,\"inputs\":{{\"long_fact_name\":\"bool\"}},\"claim\":{claim}}},\"facts\":{{\"long_fact_name\":true}}}}");
        // hlx:671
        let (out, error) = evaluate(Mode::Explain, input.as_bytes());
        // hlx:672
        assert!(!error, "{out}");
        // hlx:673
        assert!(out.contains("\"claim_truncated\":true"), "{out}");
        // hlx:674
        assert!(out.len() <= MAX_OUTPUT_BYTES);
        // hlx:675
    }
    // hlx:676
    #[test]
    // hlx:677
    fn long_witness_is_the_exact_member_when_the_result_fits() {
        // hlx:678
        let member = "z".repeat(5000);
        // hlx:679
        let (out, is_err) = evaluate(Mode::Run, subset_doc(&member).as_bytes());
        // hlx:680
        assert!(!is_err);
        // hlx:681
        assert!(out.contains(&format!("\"witness\":\"{member}\"")));
        // hlx:682
        assert!(!out.contains("truncated"));
        // hlx:683
    }
    // hlx:684
    #[test]
    // hlx:685
    fn a_witness_that_cannot_fit_is_an_error_never_a_fabricated_member() {
        // hlx:686
        let member = "z".repeat(70000);
        // hlx:687
        let (out, is_err) = evaluate(Mode::Run, subset_doc(&member).as_bytes());
        // hlx:688
        assert!(is_err);
        // hlx:689
        assert!(out.contains("limit_exceeded") && out.len() < 300);
        // hlx:690
    }
    // hlx:691
}