instinct-cli 0.3.9

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
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
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
// 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
#[path = "rational.rs"]
// hlx:6
mod rational;
// hlx:7
#[path = "graph.rs"]
// hlx:8
mod graph;
// hlx:9
use std::collections::{BTreeMap, BTreeSet};
// hlx:10
pub const MAX_CLAIM_DEPTH: usize = 32;
// hlx:11
pub const MAX_CLAIM_NODES: usize = 4096;
// hlx:12
pub const MAX_FACT_ENTRIES: usize = 10000;
// hlx:13
pub const MAX_STEPS: u64 = 100000;
// hlx:14
pub const MAX_OUTPUT_BYTES: usize = 65536;
// hlx:15
const MAX_LISTED: usize = 128;
// hlx:16
const MAX_CLAIM_TEXT: usize = 16384;
// hlx:17
const DIMS: [&str; 5] = ["project", "persona", "harness", "version", "machine"];
// hlx:18
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
// hlx:19
pub enum Mode {
    // hlx:20
    Validate,
    // hlx:21
    Run,
    // hlx:22
    Explain,
    // hlx:23
}
// hlx:24
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
// hlx:25
enum Ty {
    // hlx:26
    Str,
    // hlx:27
    Bool,
    // hlx:28
    Int,
    // hlx:29
    Rational,
    // hlx:30
    Graph,
    // hlx:31
    Set,
    // hlx:32
}
// hlx:33
impl Ty {
    // hlx:34
    fn name(self) -> &'static str {
        // hlx:35
        match self {
            // hlx:36
            Ty::Str => "string",
            // hlx:37
            Ty::Bool => "bool",
            // hlx:38
            Ty::Int => "int",
            // hlx:39
            Ty::Rational => "rational",
            // hlx:40
            Ty::Graph => "graph",
            // hlx:41
            Ty::Set => "set<string>",
            // hlx:42
        }
        // hlx:43
    }
    // hlx:44
}
// hlx:45
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
// hlx:46
enum Cmp {
    // hlx:47
    Subset,
    // hlx:48
    Disjoint,
    // hlx:49
    Contains,
    // hlx:50
    Eq,
    // hlx:51
    Lt,
    // hlx:52
    Lte,
    // hlx:53
}
// hlx:54
impl Cmp {
    // hlx:55
    fn name(self) -> &'static str {
        // hlx:56
        match self {
            // hlx:57
            Cmp::Subset => "subset",
            // hlx:58
            Cmp::Disjoint => "disjoint",
            // hlx:59
            Cmp::Contains => "contains",
            // hlx:60
            Cmp::Eq => "eq",
            // hlx:61
            Cmp::Lt => "lt",
            // hlx:62
            Cmp::Lte => "lte",
            // hlx:63
        }
        // hlx:64
    }
    // hlx:65
}
// hlx:66
#[derive(Debug)]
// hlx:67
enum Node {
    // hlx:68
    Cmp(Cmp, String, String),
    // hlx:69
    Reachable(String, String, String),
    // hlx:70
    All(Vec<Node>),
    // hlx:71
    Any(Vec<Node>),
    // hlx:72
    Not(Box<Node>),
    // hlx:73
}
// hlx:74
#[derive(Debug)]
// hlx:75
enum Val {
    // hlx:76
    S(String),
    // hlx:77
    B(bool),
    // hlx:78
    I(i128),
    // hlx:79
    Q(rational::Rational),
    // hlx:80
    G(graph::Graph),
    // hlx:81
    Set(Vec<String>),
    // hlx:82
}
// hlx:83
struct Def {
    // hlx:84
    id: String,
    // hlx:85
    revision: u32,
    // hlx:86
    inputs: BTreeMap<String, Ty>,
    // hlx:87
    claim: Node,
    // hlx:88
    conditions: Vec<String>,
    // hlx:89
    scope: Vec<(&'static str, String)>,
    // hlx:90
}
// hlx:91
type R<T> = Result<T, String>;
// hlx:92
fn clip(s: &str) -> String {
    // hlx:93
    let mut out = String::new();
    // hlx:94
    for ch in s.chars().take(48) {
        // hlx:95
        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:96
            out.push('?');
        // hlx:97
        } else {
            // hlx:98
            out.push(ch);
            // hlx:99
        }
        // hlx:100
    }
    // hlx:101
    if s.chars().count() > 48 {
        // hlx:102
        out.push_str("...");
        // hlx:103
    }
    // hlx:104
    out
    // hlx:105
}
// hlx:106
fn is_ident(s: &str) -> bool {
    // hlx:107
    let b = s.as_bytes();
    // hlx:108
    !b.is_empty()
// hlx:109
&& b.len() <= 128
// hlx:110
&& b[0].is_ascii_alphabetic()
// hlx:111
&& b.iter().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-'))
    // hlx:112
}
// hlx:113
fn obj<'a>(j: &'a J, what: &str) -> R<&'a [(String, J)]> {
    // hlx:114
    match j {
        // hlx:115
        J::Obj(o) => Ok(o),
        // hlx:116
        _ => Err(format!("malformed_definition: {what} must be an object")),
        // hlx:117
    }
    // hlx:118
}
// hlx:119
fn field<'a>(o: &'a [(String, J)], k: &str) -> Option<&'a J> {
    // hlx:120
    o.iter().find(|(key, _)| key == k).map(|(_, v)| v)
    // hlx:121
}
// hlx:122
fn only_keys(o: &[(String, J)], allowed: &[&str], what: &str) -> R<()> {
    // hlx:123
    for (k, _) in o {
        // hlx:124
        if !allowed.contains(&k.as_str()) {
            // hlx:125
            return Err(format!(
                "unknown_field: {what} has unknown key \"{}\"",
                clip(k)
            ));
            // hlx:126
        }
        // hlx:127
    }
    // hlx:128
    Ok(())
    // hlx:129
}
// hlx:130
fn need<'a>(o: &'a [(String, J)], k: &str, what: &str) -> R<&'a J> {
    // hlx:131
    field(o, k).ok_or_else(|| format!("malformed_definition: {what} requires \"{k}\""))
    // hlx:132
}
// hlx:133
fn text<'a>(j: &'a J, what: &str) -> R<&'a str> {
    // hlx:134
    match j {
        // hlx:135
        J::Str(s) => Ok(s),
        // hlx:136
        _ => Err(format!("malformed_definition: {what} must be a string")),
        // hlx:137
    }
    // hlx:138
}
// hlx:139
fn parse_scope(j: &J, what: &str) -> R<Vec<(&'static str, String)>> {
    // hlx:140
    let o = obj(j, what)?;
    // hlx:141
    only_keys(o, &DIMS, what)?;
    // hlx:142
    let mut out = Vec::new();
    // hlx:143
    for dim in DIMS {
        // hlx:144
        if let Some(v) = field(o, dim) {
            // hlx:145
            let s = text(v, what)?;
            // hlx:146
            if s.is_empty() || s == "*" {
                // hlx:147
                return Err(format!(
                    "invalid_scope: {what}.{dim} must be a nonempty literal, not \"*\""
                ));
                // hlx:148
            }
            // hlx:149
            out.push((dim, s.to_string()));
            // hlx:150
        }
        // hlx:151
    }
    // hlx:152
    Ok(out)
    // hlx:153
}
// hlx:154
fn canonical_int(s: &str) -> Option<i128> {
    // hlx:155
    let digits = s.strip_prefix('-').unwrap_or(s);
    // hlx:156
    if digits.is_empty() || !digits.bytes().all(|c| c.is_ascii_digit()) {
        // hlx:157
        return None;
        // hlx:158
    }
    // hlx:159
    if digits.len() > 1 && digits.starts_with('0') {
        // hlx:160
        return None;
        // hlx:161
    }
    // hlx:162
    if s.starts_with('-') && digits == "0" {
        // hlx:163
        return None;
        // hlx:164
    }
    // hlx:165
    s.parse::<i128>().ok()
    // hlx:166
}
// hlx:167
fn parse_ty(s: &str) -> R<Ty> {
    // hlx:168
    match s {
        // hlx:169
        "string" => Ok(Ty::Str),
        // hlx:170
        "bool" => Ok(Ty::Bool),
        // hlx:171
        "int" => Ok(Ty::Int),
        // hlx:172
        "set<string>" => Ok(Ty::Set),
        // hlx:173
        "rational" => Ok(Ty::Rational),
        // hlx:174
        "graph" => Ok(Ty::Graph),
        // hlx:175
        _ => Err(format!("invalid_type: unknown type \"{}\"", clip(s))),
        // hlx:176
    }
    // hlx:177
}
// hlx:178
fn operand(j: &J, inputs: &BTreeMap<String, Ty>, nodes: &mut usize) -> R<(String, Ty)> {
    // hlx:179
    *nodes += 1;
    // hlx:180
    if *nodes > MAX_CLAIM_NODES {
        // hlx:181
        return Err("limit_exceeded: claim has more than 4096 nodes".to_string());
        // hlx:182
    }
    // hlx:183
    let o = obj(j, "operand")?;
    // hlx:184
    only_keys(o, &["fact"], "operand")?;
    // hlx:185
    let name = text(need(o, "fact", "operand")?, "operand fact")?;
    // hlx:186
    match inputs.get(name) {
        // hlx:187
        Some(t) => Ok((name.to_string(), *t)),
        // hlx:188
        None => Err(format!(
            "unknown_reference: fact \"{}\" is not declared in inputs",
            clip(name)
        )),
        // hlx:189
    }
    // hlx:190
}
// hlx:191
fn compile(j: &J, depth: usize, inputs: &BTreeMap<String, Ty>, nodes: &mut usize) -> R<Node> {
    // hlx:192
    if depth > MAX_CLAIM_DEPTH {
        // hlx:193
        return Err("limit_exceeded: claim is nested deeper than 32".to_string());
        // hlx:194
    }
    // hlx:195
    *nodes += 1;
    // hlx:196
    if *nodes > MAX_CLAIM_NODES {
        // hlx:197
        return Err("limit_exceeded: claim has more than 4096 nodes".to_string());
        // hlx:198
    }
    // hlx:199
    let o = obj(j, "claim expression")?;
    // hlx:200
    let op = text(need(o, "op", "claim expression")?, "op")?;
    // hlx:201
    if op == "reachable" {
        // hlx:202
        only_keys(o, &["op", "graph", "from", "to"], op)?;
        // hlx:203
        let (g, gt) = operand(need(o, "graph", op)?, inputs, nodes)?;
        // hlx:204
        let (a, at) = operand(need(o, "from", op)?, inputs, nodes)?;
        // hlx:205
        let (b, bt) = operand(need(o, "to", op)?, inputs, nodes)?;
        // hlx:206
        if gt != Ty::Graph || at != Ty::Str || bt != Ty::Str {
            return Err("type_mismatch: reachable requires graph, string, string".into());
        }
        // hlx:207
        return Ok(Node::Reachable(g, a, b));
        // hlx:208
    }
    // hlx:209
    let cmp = match op {
        // hlx:210
        "subset" => Cmp::Subset,
        // hlx:211
        "disjoint" => Cmp::Disjoint,
        // hlx:212
        "contains" => Cmp::Contains,
        // hlx:213
        "eq" => Cmp::Eq,
        // hlx:214
        "lt" => Cmp::Lt,
        // hlx:215
        "lte" => Cmp::Lte,
        // hlx:216
        "all" | "any" => {
            // hlx:217
            only_keys(o, &["op", "args"], op)?;
            // hlx:218
            let args = match need(o, "args", op)? {
                // hlx:219
                J::Arr(a) if !a.is_empty() => a,
                // hlx:220
                _ => {
                    return Err(format!(
                        "malformed_definition: {op} args must be a nonempty array"
                    ))
                }
                // hlx:221
            };
            // hlx:222
            let mut kids = Vec::new();
            // hlx:223
            for a in args {
                // hlx:224
                kids.push(compile(a, depth + 1, inputs, nodes)?);
                // hlx:225
            }
            // hlx:226
            return Ok(if op == "all" {
                Node::All(kids)
            } else {
                Node::Any(kids)
            });
            // hlx:227
        }
        // hlx:228
        "implies" => {
            // hlx:229
            only_keys(o, &["op", "if", "then"], op)?;
            // hlx:230
            // Lower into existing three-valued primitives; count the generated not node.
            // hlx:231
            *nodes += 1;
            // hlx:232
            if *nodes > MAX_CLAIM_NODES {
                return Err("limit_exceeded: implication expansion exceeds 4096 nodes".into());
            }
            // hlx:233
            let premise = compile(need(o, "if", op)?, depth + 2, inputs, nodes)?;
            // hlx:234
            let conclusion = compile(need(o, "then", op)?, depth + 1, inputs, nodes)?;
            // hlx:235
            return Ok(Node::Any(vec![Node::Not(Box::new(premise)), conclusion]));
            // hlx:236
        }
        // hlx:237
        "not" => {
            // hlx:238
            only_keys(o, &["op", "arg"], op)?;
            // hlx:239
            return Ok(Node::Not(Box::new(compile(
                need(o, "arg", op)?,
                depth + 1,
                inputs,
                nodes,
            )?)));
            // hlx:240
        }
        // hlx:241
        _ => return Err(format!("unknown_operator: \"{}\"", clip(op))),
        // hlx:242
    };
    // hlx:243
    only_keys(o, &["op", "left", "right"], op)?;
    // hlx:244
    let (l, lt) = operand(need(o, "left", op)?, inputs, nodes)?;
    // hlx:245
    let (r, rt) = operand(need(o, "right", op)?, inputs, nodes)?;
    // hlx:246
    let ok = match cmp {
        // hlx:247
        Cmp::Subset | Cmp::Disjoint => lt == Ty::Set && rt == Ty::Set,
        // hlx:248
        Cmp::Contains => lt == Ty::Set && rt == Ty::Str,
        // hlx:249
        Cmp::Eq => lt == rt,
        // hlx:250
        Cmp::Lt | Cmp::Lte => lt == rt && matches!(lt, Ty::Int | Ty::Rational),
        // hlx:251
    };
    // hlx:252
    if !ok {
        // hlx:253
        return Err(format!(
            "type_mismatch: {} cannot compare {} with {}",
            op,
            lt.name(),
            rt.name()
        ));
        // hlx:254
    }
    // hlx:255
    Ok(Node::Cmp(cmp, l, r))
    // hlx:256
}
// hlx:257
fn compile_def(j: &J) -> R<Def> {
    // hlx:258
    let o = obj(j, "check")?;
    // hlx:259
    only_keys(
        o,
        &[
            "schema",
            "id",
            "revision",
            "inputs",
            "claim",
            "required_conditions",
            "scope",
        ],
        "check",
    )?;
    // hlx:260
    let schema = text(need(o, "schema", "check")?, "schema")?;
    // hlx:261
    if schema != "instinct.check/v1" {
        // hlx:262
        return Err(format!("unsupported_schema: \"{}\"", clip(schema)));
        // hlx:263
    }
    // hlx:264
    let id = text(need(o, "id", "check")?, "id")?;
    // hlx:265
    if !is_ident(id) {
        // hlx:266
        return Err("malformed_definition: id must be 1-128 ASCII letters, digits or ._- starting with a letter".to_string());
        // hlx:267
    }
    // hlx:268
    let revision = match need(o, "revision", "check")? {
        // hlx:269
        J::Num(n) => match n.parse::<u32>() {
            // hlx:270
            Ok(v)
                if (1..=2147483647).contains(&v)
                    && n.bytes().all(|c| c.is_ascii_digit())
                    && !n.starts_with('0') =>
            {
                v
            }
            // hlx:271
            _ => {
                return Err(
                    "invalid_number: revision must be an integer literal from 1 to 2147483647"
                        .to_string(),
                )
            }
            // hlx:272
        },
        // hlx:273
        _ => {
            return Err(
                "invalid_number: revision must be an integer literal, not a string".to_string(),
            )
        }
        // hlx:274
    };
    // hlx:275
    let mut inputs = BTreeMap::new();
    // hlx:276
    for (k, v) in obj(need(o, "inputs", "check")?, "inputs")? {
        // hlx:277
        if !is_ident(k) {
            // hlx:278
            return Err(format!(
                "malformed_definition: input name \"{}\" is not a valid name",
                clip(k)
            ));
            // hlx:279
        }
        // hlx:280
        inputs.insert(k.clone(), parse_ty(text(v, "input type")?)?);
        // hlx:281
    }
    // hlx:282
    let mut conditions = Vec::new();
    // hlx:283
    if let Some(rc) = field(o, "required_conditions") {
        // hlx:284
        match rc {
            // hlx:285
            J::Arr(a) => {
                // hlx:286
                for c in a {
                    // hlx:287
                    let name = text(c, "required condition")?;
                    // hlx:288
                    if !is_ident(name) {
                        // hlx:289
                        return Err(format!(
                            "malformed_definition: condition name \"{}\" is not a valid name",
                            clip(name)
                        ));
                        // hlx:290
                    }
                    // hlx:291
                    if conditions.iter().any(|x: &String| x == name) {
                        // hlx:292
                        return Err(format!(
                            "malformed_definition: duplicate required condition \"{}\"",
                            clip(name)
                        ));
                        // hlx:293
                    }
                    // hlx:294
                    conditions.push(name.to_string());
                    // hlx:295
                }
                // hlx:296
            }
            // hlx:297
            _ => {
                return Err("malformed_definition: required_conditions must be an array".to_string())
            }
            // hlx:298
        }
        // hlx:299
    }
    // hlx:300
    let scope = match field(o, "scope") {
        // hlx:301
        Some(s) => parse_scope(s, "check scope")?,
        // hlx:302
        None => Vec::new(),
        // hlx:303
    };
    // hlx:304
    let mut nodes = 0usize;
    // hlx:305
    let claim = compile(need(o, "claim", "check")?, 1, &inputs, &mut nodes)?;
    // hlx:306
    Ok(Def {
        id: id.to_string(),
        revision,
        inputs,
        claim,
        conditions,
        scope,
    })
    // hlx:307
}
// hlx:308
/// Everything the caller supplied, validated against the definition.
// hlx:309
struct Request {
    // hlx:310
    facts: BTreeMap<String, Val>,
    // hlx:311
    entries: usize,
    // hlx:312
    conditions: BTreeMap<String, bool>,
    // hlx:313
    scope: Vec<(&'static str, String)>,
    // hlx:314
}
// hlx:315
fn read_request(top: &[(String, J)], def: &Def) -> R<Request> {
    // hlx:316
    let mut facts = BTreeMap::new();
    // hlx:317
    let mut entries = 0usize;
    // hlx:318
    if let Some(f) = field(top, "facts") {
        // hlx:319
        for (k, v) in obj(f, "facts")? {
            // hlx:320
            let ty = match def.inputs.get(k) {
                // hlx:321
                Some(t) => *t,
                // hlx:322
                None => {
                    return Err(format!(
                        "unknown_fact: \"{}\" is not declared in inputs",
                        clip(k)
                    ))
                }
                // hlx:323
            };
            // hlx:324
            entries += 1;
            // hlx:325
            let val = match (ty, v) {
// hlx:326
(Ty::Str, J::Str(s)) => Val::S(s.clone()),
// hlx:327
(Ty::Bool, J::Bool(b)) => Val::B(*b),
// hlx:328
(Ty::Int, J::Str(s)) => match canonical_int(s) {
// hlx:329
Some(n) => Val::I(n),
// hlx:330
None => return Err(format!("invalid_number: fact \"{}\" is not a canonical decimal i128 string", clip(k))),
// hlx:331
},
// hlx:332
(Ty::Rational, J::Str(s)) => match rational::Rational::parse(s) {
// hlx:333
Some(q) => Val::Q(q),
// hlx:334
None => return Err(format!("invalid_number: fact \"{}\" must be numerator/denominator with canonical i128 components and positive denominator", clip(k))),
// hlx:335
},
// hlx:336
(Ty::Graph, value) => {
// hlx:337
let graph = graph::Graph::parse(value)?;
// hlx:338
entries += graph.entries();
// hlx:339
Val::G(graph)
// hlx:340
},
// hlx:341
(Ty::Set, J::Arr(items)) => {
// hlx:342
let mut members = Vec::new();
// hlx:343
for it in items {
// hlx:344
match it {
// hlx:345
J::Str(s) => members.push(s.clone()),
// hlx:346
_ => return Err(format!("type_mismatch: fact \"{}\" must be an array of strings", clip(k))),
// hlx:347
}
// hlx:348
}
// hlx:349
entries += members.len();
// hlx:350
members.sort();
// hlx:351
if members.windows(2).any(|w| w[0] == w[1]) {
// hlx:352
return Err(format!("duplicate_member: fact \"{}\" has a duplicate set member", clip(k)));
// hlx:353
}
// hlx:354
Val::Set(members)
// hlx:355
}
// hlx:356
_ => return Err(format!("type_mismatch: fact \"{}\" is not of declared type {}", clip(k), ty.name())),
// hlx:357
};
            // hlx:358
            facts.insert(k.clone(), val);
            // hlx:359
        }
        // hlx:360
    }
    // hlx:361
    let mut conditions = BTreeMap::new();
    // hlx:362
    if let Some(c) = field(top, "conditions") {
        // hlx:363
        for (k, v) in obj(c, "conditions")? {
            // hlx:364
            if !def.conditions.iter().any(|x| x == k) {
                // hlx:365
                return Err(format!(
                    "unknown_condition: \"{}\" is not a required condition",
                    clip(k)
                ));
                // hlx:366
            }
            // hlx:367
            match v {
                // hlx:368
                J::Bool(b) => {
                    // hlx:369
                    conditions.insert(k.clone(), *b);
                    // hlx:370
                }
                // hlx:371
                _ => {
                    return Err(format!(
                        "type_mismatch: condition \"{}\" must be a boolean",
                        clip(k)
                    ))
                }
                // hlx:372
            }
            // hlx:373
        }
        // hlx:374
    }
    // hlx:375
    let scope = match field(top, "scope") {
        // hlx:376
        Some(s) => parse_scope(s, "request scope")?,
        // hlx:377
        None => Vec::new(),
        // hlx:378
    };
    // hlx:379
    Ok(Request {
        facts,
        entries,
        conditions,
        scope,
    })
    // hlx:380
}
// hlx:381
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
// hlx:382
enum Tri {
    // hlx:383
    T,
    // hlx:384
    F,
    // hlx:385
    U,
    // hlx:386
}
// hlx:387
struct Exhausted;
// hlx:388
struct Ev<'a> {
    // hlx:389
    facts: &'a BTreeMap<String, Val>,
    // hlx:390
    steps: u64,
    // hlx:391
    missing: BTreeSet<String>,
    // hlx:392
}
// hlx:393
type Out = Result<(Tri, Option<String>), Exhausted>;
// hlx:394
fn tri(b: bool) -> Tri {
    // hlx:395
    if b {
        // hlx:396
        Tri::T
    // hlx:397
    } else {
        // hlx:398
        Tri::F
        // hlx:399
    }
    // hlx:400
}
// hlx:401
impl<'a> Ev<'a> {
    // hlx:402
    fn charge(&mut self, n: u64) -> Result<(), Exhausted> {
        // hlx:403
        self.steps = self.steps.saturating_add(n);
        // hlx:404
        if self.steps > MAX_STEPS {
            // hlx:405
            self.steps = MAX_STEPS;
            // hlx:406
            return Err(Exhausted);
            // hlx:407
        }
        // hlx:408
        Ok(())
        // hlx:409
    }
    // hlx:410
    fn contains(&mut self, set: &[String], x: &str) -> Result<bool, Exhausted> {
        // hlx:411
        let (mut lo, mut hi) = (0usize, set.len());
        // hlx:412
        while lo < hi {
            // hlx:413
            self.charge(1)?;
            // hlx:414
            let mid = lo + (hi - lo) / 2;
            // hlx:415
            match set[mid].as_str().cmp(x) {
                // hlx:416
                std::cmp::Ordering::Equal => return Ok(true),
                // hlx:417
                std::cmp::Ordering::Less => lo = mid + 1,
                // hlx:418
                std::cmp::Ordering::Greater => hi = mid,
                // hlx:419
            }
            // hlx:420
        }
        // hlx:421
        Ok(false)
        // hlx:422
    }
    // hlx:423
    fn eval(&mut self, n: &Node) -> Out {
        // hlx:424
        self.charge(1)?;
        // hlx:425
        match n {
            // hlx:426
            Node::Cmp(c, l, r) => self.cmp(*c, l, r),
            // hlx:427
            Node::Reachable(g, a, b) => {
                // hlx:428
                let facts = self.facts;
                // hlx:429
                for name in [g, a, b] {
                    if !facts.contains_key(name) {
                        self.missing.insert(name.clone());
                    }
                }
                // hlx:430
                let (Some(Val::G(graph)), Some(Val::S(start)), Some(Val::S(end))) =
                    (facts.get(g), facts.get(a), facts.get(b))
                else {
                    return Ok((Tri::U, None));
                };
                // hlx:431
                match graph.reachable(start, end, |n| self.charge(n))? {
                    Some(found) => Ok((tri(found), None)),
                    None => {
                        self.missing.insert(format!("{g}:endpoint"));
                        Ok((Tri::U, None))
                    }
                }
                // hlx:432
            }
            // hlx:433
            Node::Not(inner) => {
                // hlx:434
                let (t, _) = self.eval(inner)?;
                // hlx:435
                Ok((
                    // hlx:436
                    match t {
                        // hlx:437
                        Tri::T => Tri::F,
                        // hlx:438
                        Tri::F => Tri::T,
                        // hlx:439
                        Tri::U => Tri::U,
                        // hlx:440
                    },
                    // hlx:441
                    None,
                    // hlx:442
                ))
                // hlx:443
            }
            // hlx:444
            Node::All(kids) => {
                // hlx:445
                let mut unknown = false;
                // hlx:446
                for k in kids {
                    // hlx:447
                    let (t, w) = self.eval(k)?;
                    // hlx:448
                    match t {
                        // hlx:449
                        Tri::F => return Ok((Tri::F, w)),
                        // hlx:450
                        Tri::U => unknown = true,
                        // hlx:451
                        Tri::T => {} // hlx:452
                    }
                    // hlx:453
                }
                // hlx:454
                Ok((if unknown { Tri::U } else { Tri::T }, None))
                // hlx:455
            }
            // hlx:456
            Node::Any(kids) => {
                // hlx:457
                let mut unknown = false;
                // hlx:458
                for k in kids {
                    // hlx:459
                    let (t, _) = self.eval(k)?;
                    // hlx:460
                    match t {
                        // hlx:461
                        Tri::T => return Ok((Tri::T, None)),
                        // hlx:462
                        Tri::U => unknown = true,
                        // hlx:463
                        Tri::F => {} // hlx:464
                    }
                    // hlx:465
                }
                // hlx:466
                Ok((if unknown { Tri::U } else { Tri::F }, None))
                // hlx:467
            } // hlx:468
        }
        // hlx:469
    }
    // hlx:470
    fn cmp(&mut self, c: Cmp, l: &str, r: &str) -> Out {
        // hlx:471
        let facts = self.facts;
        // hlx:472
        let (lv, rv) = (facts.get(l), facts.get(r));
        // hlx:473
        if lv.is_none() {
            // hlx:474
            self.missing.insert(l.to_string());
            // hlx:475
        }
        // hlx:476
        if rv.is_none() {
            // hlx:477
            self.missing.insert(r.to_string());
            // hlx:478
        }
        // hlx:479
        let (lv, rv) = match (lv, rv) {
            // hlx:480
            (Some(a), Some(b)) => (a, b),
            // hlx:481
            _ => return Ok((Tri::U, None)),
            // hlx:482
        };
        // hlx:483
        match (c, lv, rv) {
            // hlx:484
            (Cmp::Subset, Val::Set(a), Val::Set(b)) => {
                // hlx:485
                let (mut i, mut j) = (0usize, 0usize);
                // hlx:486
                while i < a.len() {
                    // hlx:487
                    self.charge(1)?;
                    // hlx:488
                    if j >= b.len() || a[i] < b[j] {
                        // hlx:489
                        return Ok((Tri::F, Some(a[i].clone())));
                        // hlx:490
                    }
                    // hlx:491
                    if a[i] == b[j] {
                        // hlx:492
                        i += 1;
                        // hlx:493
                    }
                    // hlx:494
                    j += 1;
                    // hlx:495
                }
                // hlx:496
                Ok((Tri::T, None))
                // hlx:497
            }
            // hlx:498
            (Cmp::Disjoint, Val::Set(a), Val::Set(b)) => {
                // hlx:499
                let (mut i, mut j) = (0usize, 0usize);
                // hlx:500
                while i < a.len() && j < b.len() {
                    // hlx:501
                    self.charge(1)?;
                    // hlx:502
                    match a[i].cmp(&b[j]) {
                        // hlx:503
                        std::cmp::Ordering::Equal => return Ok((Tri::F, Some(a[i].clone()))),
                        // hlx:504
                        std::cmp::Ordering::Less => i += 1,
                        // hlx:505
                        std::cmp::Ordering::Greater => j += 1,
                        // hlx:506
                    }
                    // hlx:507
                }
                // hlx:508
                Ok((Tri::T, None))
                // hlx:509
            }
            // hlx:510
            (Cmp::Contains, Val::Set(a), Val::S(x)) => {
                // hlx:511
                let found = self.contains(a, x)?;
                // hlx:512
                Ok((tri(found), None))
                // hlx:513
            }
            // hlx:514
            (Cmp::Eq, Val::Set(a), Val::Set(b)) => {
                // hlx:515
                self.charge(1)?;
                // hlx:516
                if a.len() != b.len() {
                    // hlx:517
                    return Ok((Tri::F, None));
                    // hlx:518
                }
                // hlx:519
                for k in 0..a.len() {
                    // hlx:520
                    self.charge(1)?;
                    // hlx:521
                    if a[k] != b[k] {
                        // hlx:522
                        return Ok((Tri::F, None));
                        // hlx:523
                    }
                    // hlx:524
                }
                // hlx:525
                Ok((Tri::T, None))
                // hlx:526
            }
            // hlx:527
            (Cmp::Eq | Cmp::Lt | Cmp::Lte, Val::Q(a), Val::Q(b)) => {
                // hlx:528
                let (order, steps) = a.compare(*b);
                // hlx:529
                self.charge(steps)?;
                // hlx:530
                let pass = match c {
                    Cmp::Eq => order.is_eq(),
                    Cmp::Lt => order.is_lt(),
                    Cmp::Lte => !order.is_gt(),
                    _ => unreachable!(),
                };
                // hlx:531
                Ok((tri(pass), None))
                // hlx:532
            }
            // hlx:533
            (Cmp::Eq, Val::G(a), Val::G(b)) => {
                self.charge((a.entries() + b.entries()) as u64)?;
                Ok((tri(a == b), None))
            }
            // hlx:534
            (Cmp::Eq, Val::S(a), Val::S(b)) => Ok((tri(a == b), None)),
            // hlx:535
            (Cmp::Eq, Val::B(a), Val::B(b)) => Ok((tri(a == b), None)),
            // hlx:536
            (Cmp::Eq, Val::I(a), Val::I(b)) => Ok((tri(a == b), None)),
            // hlx:537
            (Cmp::Lt, Val::I(a), Val::I(b)) => Ok((tri(a < b), None)),
            // hlx:538
            (Cmp::Lte, Val::I(a), Val::I(b)) => Ok((tri(a <= b), None)),
            // hlx:539
            _ => Ok((Tri::U, None)),
            // hlx:540
        }
        // hlx:541
    }
    // hlx:542
}
// hlx:543
fn render_claim(n: &Node, out: &mut String) {
    // hlx:544
    if out.len() > MAX_CLAIM_TEXT {
        // hlx:545
        return;
        // hlx:546
    }
    // hlx:547
    match n {
        // hlx:548
        Node::Cmp(c, l, r) => out.push_str(&format!("{}({}, {})", c.name(), l, r)),
        // hlx:549
        Node::Reachable(g, a, b) => out.push_str(&format!("reachable({g}, {a}, {b})")),
        // hlx:550
        Node::Not(k) => {
            // hlx:551
            out.push_str("not(");
            // hlx:552
            render_claim(k, out);
            // hlx:553
            out.push(')');
            // hlx:554
        }
        // hlx:555
        Node::All(kids) | Node::Any(kids) => {
            // hlx:556
            out.push_str(if matches!(n, Node::All(_)) {
                "all("
            } else {
                "any("
            });
            // hlx:557
            for (i, k) in kids.iter().enumerate() {
                // hlx:558
                if i > 0 {
                    // hlx:559
                    out.push_str(", ");
                    // hlx:560
                }
                // hlx:561
                render_claim(k, out);
                // hlx:562
            }
            // hlx:563
            out.push(')');
            // hlx:564
        } // hlx:565
    }
    // hlx:566
}
// hlx:567
fn jstr(s: &str) -> String {
    // hlx:568
    let mut o = String::with_capacity(s.len() + 2);
    // hlx:569
    o.push('"');
    // hlx:570
    for ch in s.chars() {
        // hlx:571
        match ch {
            // hlx:572
            '"' => o.push_str("\\\""),
            // hlx:573
            '\\' => o.push_str("\\\\"),
            // hlx:574
            '\n' => o.push_str("\\n"),
            // hlx:575
            '\r' => o.push_str("\\r"),
            // hlx:576
            '\t' => o.push_str("\\t"),
            // hlx:577
            c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)),
            // hlx:578
            c => o.push(c),
            // hlx:579
        }
        // hlx:580
    }
    // hlx:581
    o.push('"');
    // hlx:582
    o
    // hlx:583
}
// hlx:584
fn jlist(items: &[String]) -> String {
    // hlx:585
    let parts: Vec<String> = items.iter().map(|s| jstr(s)).collect();
    // hlx:586
    format!("[{}]", parts.join(","))
    // hlx:587
}
// hlx:588
fn jscope(scope: &[(&'static str, String)]) -> String {
    // hlx:589
    let parts: Vec<String> = scope
        .iter()
        .map(|(k, v)| format!("{}:{}", jstr(k), jstr(v)))
        .collect();
    // hlx:590
    format!("{{{}}}", parts.join(","))
    // hlx:591
}
// hlx:592
pub fn error_json(reason: &str) -> String {
    // hlx:593
    format!("{{\"schema\":\"instinct.check-error/v1\",\"verdict\":\"error\",\"reason\":{},\"authorization\":\"not_evaluated\"}}", jstr(reason))
    // hlx:594
}
// hlx:595
/// One pure entry point for CLI, MCP and WASM. Returns the JSON text and whether it is an error shape.
// hlx:596
pub fn evaluate(mode: Mode, input: &[u8]) -> (String, bool) {
    // hlx:597
    match evaluate_inner(mode, input) {
        // hlx:598
        Ok(s) => (s, false),
        // hlx:599
        Err(e) => (error_json(&e), true),
        // hlx:600
    }
    // hlx:601
}
// hlx:602
fn evaluate_inner(mode: Mode, input: &[u8]) -> R<String> {
    // hlx:603
    let tree = json::parse(input)?;
    // hlx:604
    let top = match &tree {
        // hlx:605
        J::Obj(o) => o,
        // hlx:606
        _ => return Err("malformed_definition: the request must be a JSON object".to_string()),
        // hlx:607
    };
    // hlx:608
    only_keys(top, &["check", "facts", "conditions", "scope"], "request")?;
    // hlx:609
    let def = compile_def(need(top, "check", "request")?)?;
    // hlx:610
    let req = read_request(top, &def)?;
    // hlx:611
    if mode == Mode::Validate {
        // hlx:612
        if req.entries > MAX_FACT_ENTRIES {
            // hlx:613
            return Err(
                "limit_exceeded: facts have more than 10000 entries and set members".to_string(),
            );
            // hlx:614
        }
        // hlx:615
        return Ok(format!(
// hlx:616
"{{\"schema\":\"instinct.check-validation/v1\",\"check_id\":{},\"revision\":{},\"valid\":true,\"authorization\":\"not_evaluated\"}}",
// hlx:617
jstr(&def.id),
// hlx:618
def.revision
// hlx:619
));
        // hlx:620
    }
    // hlx:621
    let mut missing: BTreeSet<String> = BTreeSet::new();
    // hlx:622
    let mut steps = 0u64;
    // hlx:623
    let mut witness: Option<String> = None;
    // hlx:624
    let (verdict, reason) = 'decide: {
        // hlx:625
        if req.entries > MAX_FACT_ENTRIES {
            // hlx:626
            break 'decide (
                "abstain",
                "resource_limit: facts exceed 10000 entries".to_string(),
            );
            // hlx:627
        }
        // hlx:628
        for (dim, want) in &def.scope {
            // hlx:629
            match req.scope.iter().find(|(d, _)| d == dim) {
                // hlx:630
                None => break 'decide ("abstain", format!("scope_missing: {dim}")),
                // hlx:631
                Some((_, have)) if have != want => {
                    break 'decide ("abstain", format!("scope_mismatch: {dim}"))
                }
                // hlx:632
                Some(_) => {} // hlx:633
            }
            // hlx:634
        }
        // hlx:635
        for c in &def.conditions {
            // hlx:636
            if req.conditions.get(c) != Some(&true) {
                // hlx:637
                missing.insert(c.clone());
                // hlx:638
            }
            // hlx:639
        }
        // hlx:640
        if !missing.is_empty() {
            // hlx:641
            break 'decide ("abstain", "required_condition_not_met".to_string());
            // hlx:642
        }
        // hlx:643
        let mut ev = Ev {
            facts: &req.facts,
            steps: 0,
            missing: BTreeSet::new(),
        };
        // hlx:644
        let res = ev.eval(&def.claim);
        // hlx:645
        steps = ev.steps;
        // hlx:646
        missing.extend(ev.missing);
        // hlx:647
        match res {
            // hlx:648
            Err(Exhausted) => (
                "abstain",
                "resource_limit: evaluation budget exhausted".to_string(),
            ),
            // hlx:649
            Ok((Tri::T, _)) => ("pass", "claim_holds".to_string()),
            // hlx:650
            Ok((Tri::F, w)) => {
                // hlx:651
                witness = w;
                // hlx:652
                ("fail", "claim_false".to_string())
                // hlx:653
            }
            // hlx:654
            Ok((Tri::U, _)) => ("abstain", "fact_missing".to_string()),
            // hlx:655
        }
        // hlx:656
    };
    // hlx:657
    let missing: Vec<String> = missing.into_iter().collect();
    // hlx:658
    let mut out = format!(
// hlx:659
"{{\"schema\":\"instinct.check-result/v1\",\"check_id\":{},\"revision\":{},\"verdict\":\"{}\",\"reason\":{},\"witness\":{},\"missing\":{},\"scope\":{},\"steps\":{}",
// hlx:660
jstr(&def.id),
// hlx:661
def.revision,
// hlx:662
verdict,
// hlx:663
jstr(&reason),
// hlx:664
match &witness {
// hlx:665
Some(w) => jstr(w),
// hlx:666
None => "null".to_string(),
// hlx:667
},
// hlx:668
jlist(&missing),
// hlx:669
jscope(&req.scope),
// hlx:670
steps
// hlx:671
);
    // hlx:672
    if mode == Mode::Explain {
        // hlx:673
        let mut claim = String::new();
        // hlx:674
        render_claim(&def.claim, &mut claim);
        // hlx:675
        let claim_truncated = claim.len() > MAX_CLAIM_TEXT;
        // hlx:676
        if claim_truncated {
            // hlx:677
            let mut end = MAX_CLAIM_TEXT;
            // hlx:678
            while !claim.is_char_boundary(end) {
                // hlx:679
                end -= 1;
                // hlx:680
            }
            // hlx:681
            claim.truncate(end);
            // hlx:682
            claim.push_str("...");
            // hlx:683
        }
        // hlx:684
        let inputs: Vec<String> = def
            .inputs
            .iter()
            .take(MAX_LISTED)
            .map(|(k, t)| format!("{}:{}", jstr(k), jstr(t.name())))
            .collect();
        // hlx:685
        let conds: Vec<String> = def.conditions.iter().take(MAX_LISTED).cloned().collect();
        // hlx:686
        out.push_str(&format!(
// hlx:687
",\"explanation\":{{\"claim\":{},\"claim_truncated\":{},\"inputs\":{{{}}},\"inputs_truncated\":{},\"required_conditions\":{},\"required_conditions_truncated\":{},\"required_scope\":{}}}",
// hlx:688
jstr(&claim),
// hlx:689
claim_truncated,
// hlx:690
inputs.join(","),
// hlx:691
def.inputs.len() > MAX_LISTED,
// hlx:692
jlist(&conds),
// hlx:693
def.conditions.len() > MAX_LISTED,
// hlx:694
jscope(&def.scope)
// hlx:695
));
        // hlx:696
    }
    // hlx:697
    out.push_str(",\"authorization\":\"not_evaluated\",\"evidence_origin\":\"caller_reported\"}");
    // hlx:698
    if out.len() > MAX_OUTPUT_BYTES {
        // hlx:699
        // Never echo an oversized request back and never truncate scope, missing or explanation: refuse instead.
        // hlx:700
        return Err(
            "limit_exceeded: result would exceed 64 KiB (scope, missing or explanation too large)"
                .to_string(),
        );
        // hlx:701
    }
    // hlx:702
    Ok(out)
    // hlx:703
}
// hlx:704
#[cfg(test)]
// hlx:705
mod tests {
    // hlx:706
    use super::*;
    // hlx:707
    fn subset_doc(member: &str) -> String {
        // hlx:708
        format!(
// hlx:709
"{{\"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:710
)
        // hlx:711
    }
    // hlx:712
    #[test]
    // hlx:713
    fn diagnostic_clip_removes_display_controls_without_changing_fact_strings() {
        // hlx:714
        assert_eq!(clip("bad\u{202e}name\u{2066}x\u{200d}"), "bad?name?x?");
        // hlx:715
        assert_eq!(clip("café日本語"), "café日本語");
        // hlx:716
        assert!(jstr("\u{202e}fact").contains('\u{202e}'));
        // hlx:717
    }
    // hlx:718
    #[test]
    // hlx:719
    fn explanation_declares_when_display_claim_is_incomplete() {
        // hlx:720
        let leaf =
            r#"{"op":"eq","left":{"fact":"long_fact_name"},"right":{"fact":"long_fact_name"}}"#;
        // hlx:721
        let claim = format!(
            "{{\"op\":\"all\",\"args\":[{}]}}",
            vec![leaf; 1000].join(",")
        );
        // hlx:722
        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:723
        let (out, error) = evaluate(Mode::Explain, input.as_bytes());
        // hlx:724
        assert!(!error, "{out}");
        // hlx:725
        assert!(out.contains("\"claim_truncated\":true"), "{out}");
        // hlx:726
        assert!(out.len() <= MAX_OUTPUT_BYTES);
        // hlx:727
    }
    // hlx:728
    #[test]
    // hlx:729
    fn long_witness_is_the_exact_member_when_the_result_fits() {
        // hlx:730
        let member = "z".repeat(5000);
        // hlx:731
        let (out, is_err) = evaluate(Mode::Run, subset_doc(&member).as_bytes());
        // hlx:732
        assert!(!is_err);
        // hlx:733
        assert!(out.contains(&format!("\"witness\":\"{member}\"")));
        // hlx:734
        assert!(!out.contains("truncated"));
        // hlx:735
    }
    // hlx:736
    #[test]
    // hlx:737
    fn a_witness_that_cannot_fit_is_an_error_never_a_fabricated_member() {
        // hlx:738
        let member = "z".repeat(70000);
        // hlx:739
        let (out, is_err) = evaluate(Mode::Run, subset_doc(&member).as_bytes());
        // hlx:740
        assert!(is_err);
        // hlx:741
        assert!(out.contains("limit_exceeded") && out.len() < 300);
        // hlx:742
    }
    // hlx:743
}