instinct-cli 0.3.8

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
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
# Independent acceptance tests for docs/checks.md (instinct check); every line is literal Rust via TAG.
# Source of truth for tests/check_contract.rs: regenerate with  hxc export-rust tests/check_contract.hlx
TAG # // Independent acceptance tests for `instinct check`, written from docs/checks.md only.
TAG # // Every case runs the real binary in a fresh HOME / XDG / store environment, and every command is wrapped by a
TAG # // before/after snapshot of that whole environment (and the working directory): nothing may be created or changed.
TAG # use std::io::Write;
TAG # use std::path::{Path, PathBuf};
TAG # use std::process::{Command, Stdio};
TAG # use std::sync::atomic::{AtomicUsize, Ordering};
TAG # use std::time::Duration;
TAG # fn bin() -> &'static str {
TAG #     env!("CARGO_BIN_EXE_instinct")
TAG # }
TAG # // ---------------------------------------------------------------- minimal JSON reader for the outputs
TAG # #[derive(Debug, Clone, PartialEq)]
TAG # enum J {
TAG #     Null,
TAG #     Bool(bool),
TAG #     Num(String),
TAG #     Str(String),
TAG #     Arr(Vec<J>),
TAG #     Obj(Vec<(String, J)>),
TAG # }
TAG # impl J {
TAG #     fn get(&self, k: &str) -> Option<&J> {
TAG #         match self {
TAG #             J::Obj(v) => v.iter().find(|(a, _)| a == k).map(|(_, b)| b),
TAG #             _ => None,
TAG #         }
TAG #     }
TAG #     fn as_str(&self) -> Option<&str> {
TAG #         match self {
TAG #             J::Str(s) => Some(s),
TAG #             _ => None,
TAG #         }
TAG #     }
TAG # }
TAG # struct P<'a> {
TAG #     b: &'a [u8],
TAG #     i: usize,
TAG # }
TAG # impl<'a> P<'a> {
TAG #     fn ws(&mut self) {
TAG #         while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\n' | b'\t' | b'\r') {
TAG #             self.i += 1;
TAG #         }
TAG #     }
TAG #     fn lit(&mut self, w: &str, v: J) -> Result<J, String> {
TAG #         if self.b[self.i..].starts_with(w.as_bytes()) {
TAG #             self.i += w.len();
TAG #             Ok(v)
TAG #         } else {
TAG #             Err(format!("bad literal at {}", self.i))
TAG #         }
TAG #     }
TAG #     fn hex4(&mut self) -> Result<u32, String> {
TAG #         let h = self.b.get(self.i..self.i + 4).ok_or("short \\u")?;
TAG #         let h = std::str::from_utf8(h).map_err(|e| e.to_string())?;
TAG #         self.i += 4;
TAG #         u32::from_str_radix(h, 16).map_err(|e| e.to_string())
TAG #     }
TAG #     fn string(&mut self) -> Result<String, String> {
TAG #         if self.b.get(self.i) != Some(&b'"') {
TAG #             return Err(format!("expected string at {}", self.i));
TAG #         }
TAG #         self.i += 1;
TAG #         let mut out: Vec<u8> = Vec::new();
TAG #         loop {
TAG #             let c = *self.b.get(self.i).ok_or("unterminated string")?;
TAG #             self.i += 1;
TAG #             match c {
TAG #                 b'"' => return String::from_utf8(out).map_err(|e| e.to_string()),
TAG #                 b'\\' => {
TAG #                     let e = *self.b.get(self.i).ok_or("bad escape")?;
TAG #                     self.i += 1;
TAG #                     let ch = match e {
TAG #                         b'"' => '"',
TAG #                         b'\\' => '\\',
TAG #                         b'/' => '/',
TAG #                         b'b' => '\u{8}',
TAG #                         b'f' => '\u{c}',
TAG #                         b'n' => '\n',
TAG #                         b'r' => '\r',
TAG #                         b't' => '\t',
TAG #                         b'u' => {
TAG #                             let hi = self.hex4()?;
TAG #                             if (0xD800..0xDC00).contains(&hi) {
TAG #                                 if self.b.get(self.i) != Some(&b'\\') || self.b.get(self.i + 1) != Some(&b'u') {
TAG #                                     return Err("lone surrogate".into());
TAG #                                 }
TAG #                                 self.i += 2;
TAG #                                 let lo = self.hex4()?;
TAG #                                 char::from_u32(0x10000 + ((hi - 0xD800) << 10) + (lo.wrapping_sub(0xDC00)))
TAG #                                     .ok_or("bad pair")?
TAG #                             } else {
TAG #                                 char::from_u32(hi).ok_or("lone surrogate")?
TAG #                             }
TAG #                         }
TAG #                         _ => return Err("bad escape".into()),
TAG #                     };
TAG #                     let mut buf = [0u8; 4];
TAG #                     out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
TAG #                 }
TAG #                 _ => out.push(c),
TAG #             }
TAG #         }
TAG #     }
TAG #     fn val(&mut self) -> Result<J, String> {
TAG #         self.ws();
TAG #         match self.b.get(self.i).copied() {
TAG #             None => Err("eof".into()),
TAG #             Some(b'{') => {
TAG #                 self.i += 1;
TAG #                 let mut v = Vec::new();
TAG #                 self.ws();
TAG #                 if self.b.get(self.i) == Some(&b'}') {
TAG #                     self.i += 1;
TAG #                     return Ok(J::Obj(v));
TAG #                 }
TAG #                 loop {
TAG #                     self.ws();
TAG #                     let k = self.string()?;
TAG #                     self.ws();
TAG #                     if self.b.get(self.i) != Some(&b':') {
TAG #                         return Err("expected colon".into());
TAG #                     }
TAG #                     self.i += 1;
TAG #                     let x = self.val()?;
TAG #                     v.push((k, x));
TAG #                     self.ws();
TAG #                     match self.b.get(self.i) {
TAG #                         Some(b',') => self.i += 1,
TAG #                         Some(b'}') => {
TAG #                             self.i += 1;
TAG #                             return Ok(J::Obj(v));
TAG #                         }
TAG #                         _ => return Err("bad object".into()),
TAG #                     }
TAG #                 }
TAG #             }
TAG #             Some(b'[') => {
TAG #                 self.i += 1;
TAG #                 let mut v = Vec::new();
TAG #                 self.ws();
TAG #                 if self.b.get(self.i) == Some(&b']') {
TAG #                     self.i += 1;
TAG #                     return Ok(J::Arr(v));
TAG #                 }
TAG #                 loop {
TAG #                     v.push(self.val()?);
TAG #                     self.ws();
TAG #                     match self.b.get(self.i) {
TAG #                         Some(b',') => self.i += 1,
TAG #                         Some(b']') => {
TAG #                             self.i += 1;
TAG #                             return Ok(J::Arr(v));
TAG #                         }
TAG #                         _ => return Err("bad array".into()),
TAG #                     }
TAG #                 }
TAG #             }
TAG #             Some(b'"') => Ok(J::Str(self.string()?)),
TAG #             Some(b't') => self.lit("true", J::Bool(true)),
TAG #             Some(b'f') => self.lit("false", J::Bool(false)),
TAG #             Some(b'n') => self.lit("null", J::Null),
TAG #             Some(_) => {
TAG #                 let st = self.i;
TAG #                 while self.i < self.b.len() && matches!(self.b[self.i], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') {
TAG #                     self.i += 1;
TAG #                 }
TAG #                 if st == self.i {
TAG #                     return Err(format!("unexpected byte at {st}"));
TAG #                 }
TAG #                 Ok(J::Num(String::from_utf8_lossy(&self.b[st..self.i]).into_owned()))
TAG #             }
TAG #         }
TAG #     }
TAG # }
TAG # fn parse_json(s: &str) -> Result<J, String> {
TAG #     let mut p = P { b: s.as_bytes(), i: 0 };
TAG #     let v = p.val()?;
TAG #     p.ws();
TAG #     if p.i != p.b.len() {
TAG #         return Err("trailing data".into());
TAG #     }
TAG #     Ok(v)
TAG # }
TAG # fn to_s(j: &J) -> String {
TAG #     match j {
TAG #         J::Null => "null".into(),
TAG #         J::Bool(b) => b.to_string(),
TAG #         J::Num(n) => n.clone(),
TAG #         J::Str(s) => format!("{s:?}"),
TAG #         J::Arr(v) => format!("[{}]", v.iter().map(to_s).collect::<Vec<_>>().join(",")),
TAG #         J::Obj(v) => format!("{{{}}}", v.iter().map(|(k, x)| format!("{k:?}:{}", to_s(x))).collect::<Vec<_>>().join(",")),
TAG #     }
TAG # }
TAG # // ---------------------------------------------------------------- isolated environment and process runner
TAG # struct Out {
TAG #     code: Option<i32>,
TAG #     out: Vec<u8>,
TAG #     err: Vec<u8>,
TAG # }
TAG # impl Out {
TAG #     fn text(&self) -> String {
TAG #         String::from_utf8_lossy(&self.out).into_owned()
TAG #     }
TAG # }
TAG # fn fnv(b: &[u8]) -> u64 {
TAG #     let mut h = 0xcbf29ce484222325u64;
TAG #     for x in b {
TAG #         h ^= *x as u64;
TAG #         h = h.wrapping_mul(0x100000001b3);
TAG #     }
TAG #     h
TAG # }
TAG # fn walk(base: &Path, dir: &Path, acc: &mut Vec<String>) {
TAG #     let mut ents: Vec<_> = match std::fs::read_dir(dir) {
TAG #         Ok(r) => r.filter_map(|e| e.ok()).collect(),
TAG #         Err(_) => return,
TAG #     };
TAG #     ents.sort_by_key(|e| e.file_name());
TAG #     for e in ents {
TAG #         let p = e.path();
TAG #         let rel = p.strip_prefix(base).unwrap().display().to_string();
TAG #         let md = match std::fs::symlink_metadata(&p) {
TAG #             Ok(m) => m,
TAG #             Err(_) => continue,
TAG #         };
TAG #         if md.is_dir() {
TAG #             acc.push(format!("d {rel}"));
TAG #             walk(base, &p, acc);
TAG #         } else {
TAG #             let b = std::fs::read(&p).unwrap_or_default();
TAG #             acc.push(format!("f {rel} {} {:x}", b.len(), fnv(&b)));
TAG #         }
TAG #     }
TAG # }
TAG # struct Env {
TAG #     root: PathBuf,
TAG # }
TAG # impl Env {
TAG #     fn new(name: &str) -> Env {
TAG #         static N: AtomicUsize = AtomicUsize::new(0);
TAG #         let root = std::env::temp_dir().join(format!(
TAG #             "instinct-check-contract-{}-{}-{name}",
TAG #             std::process::id(),
TAG #             N.fetch_add(1, Ordering::Relaxed)
TAG #         ));
TAG #         let _ = std::fs::remove_dir_all(&root);
TAG #         for d in ["home", "data", "local", "cfg", "state", "cache", "cwd", "in"] {
TAG #             std::fs::create_dir_all(root.join(d)).unwrap();
TAG #         }
TAG #         Env { root }
TAG #     }
TAG #     fn bank(&self) -> PathBuf {
TAG #         let base = if cfg!(windows) { "local" } else { "data" };
TAG #         self.root.join(base).join("instinct").join("bank.hxdb")
TAG #     }
TAG #     fn put(&self, name: &str, bytes: &[u8]) -> PathBuf {
TAG #         let p = self.root.join("in").join(name);
TAG #         std::fs::write(&p, bytes).unwrap();
TAG #         p
TAG #     }
TAG #     fn snapshot(&self) -> Vec<String> {
TAG #         let mut acc = Vec::new();
TAG #         walk(&self.root, &self.root, &mut acc);
TAG #         acc
TAG #     }
TAG #     fn exec_env(&self, args: &[&str], stdin: &[u8], envs: &[(&str, &str)]) -> Out {
TAG #         let before = self.snapshot();
TAG #         let mut c = Command::new(bin());
TAG #         c.args(args)
TAG #             .current_dir(self.root.join("cwd"))
TAG #             .env("HOME", self.root.join("home"))
TAG #             .env("XDG_DATA_HOME", self.root.join("data"))
TAG #             .env("XDG_CONFIG_HOME", self.root.join("cfg"))
TAG #             .env("XDG_STATE_HOME", self.root.join("state"))
TAG #             .env("XDG_CACHE_HOME", self.root.join("cache"))
TAG #             .env("LOCALAPPDATA", self.root.join("local"))
TAG #             .env("APPDATA", self.root.join("local"));
TAG #         for (k, _) in std::env::vars() {
TAG #             if k.starts_with("INSTINCT_") {
TAG #                 c.env_remove(k);
TAG #             }
TAG #         }
TAG #         for (k, v) in envs {
TAG #             c.env(k, v);
TAG #         }
TAG #         c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
TAG #         let mut child = c.spawn().unwrap();
TAG #         let mut si = child.stdin.take().unwrap();
TAG #         let data = stdin.to_vec();
TAG #         let w = std::thread::spawn(move || {
TAG #             let _ = si.write_all(&data);
TAG #         });
TAG #         let (tx, rx) = std::sync::mpsc::channel();
TAG #         std::thread::spawn(move || {
TAG #             let _ = tx.send(child.wait_with_output());
TAG #         });
TAG #         let o = rx.recv_timeout(Duration::from_secs(180)).expect("instinct check hung").unwrap();
TAG #         let _ = w.join();
TAG #         let after = self.snapshot();
TAG #         assert_eq!(before, after, "command changed the filesystem: {args:?}");
TAG #         if std::env::var_os("CHECK_CONTRACT_COUNT").is_some() {
TAG #             eprintln!("check_contract_exec");
TAG #         }
TAG #         Out { code: o.status.code(), out: o.stdout, err: o.stderr }
TAG #     }
TAG #     fn exec(&self, args: &[&str], stdin: &[u8]) -> Out {
TAG #         self.exec_env(args, stdin, &[])
TAG #     }
TAG #     fn run(&self, sub: &str, doc: &str) -> Out {
TAG #         self.exec(&["check", sub, "--input", "-"], doc.as_bytes())
TAG #     }
TAG #     fn run_bytes(&self, sub: &str, doc: &[u8]) -> Out {
TAG #         self.exec(&["check", sub, "--input", "-"], doc)
TAG #     }
TAG # }
TAG # impl Drop for Env {
TAG #     fn drop(&mut self) {
TAG #         let _ = std::fs::remove_dir_all(&self.root);
TAG #     }
TAG # }
TAG # // ---------------------------------------------------------------- output assertions
TAG # fn trunc(s: &str) -> String {
TAG #     s.chars().take(400).collect()
TAG # }
TAG # fn obj(o: &Out) -> J {
TAG #     let t = o.text();
TAG #     let j = parse_json(t.trim()).unwrap_or_else(|e| panic!("stdout is not one JSON value ({e}): {}", trunc(&t)));
TAG #     assert!(matches!(j, J::Obj(_)), "stdout must be one JSON object: {}", trunc(&t));
TAG #     j
TAG # }
TAG # fn sf<'a>(j: &'a J, k: &str) -> &'a str {
TAG #     j.get(k).and_then(J::as_str).unwrap_or_else(|| panic!("missing string field {k} in {}", trunc(&to_s(j))))
TAG # }
TAG # fn names(j: &J) -> Vec<String> {
TAG #     match j {
TAG #         J::Arr(v) => v.iter().map(|x| x.as_str().expect("array of strings").to_string()).collect(),
TAG #         other => panic!("expected an array, got {}", to_s(other)),
TAG #     }
TAG # }
TAG # fn pairs(j: &J) -> Vec<(String, String)> {
TAG #     match j {
TAG #         J::Obj(v) => {
TAG #             let mut r: Vec<(String, String)> =
TAG #                 v.iter().map(|(k, x)| (k.clone(), x.as_str().expect("string scope value").to_string())).collect();
TAG #             r.sort();
TAG #             r
TAG #         }
TAG #         other => panic!("expected an object, got {}", to_s(other)),
TAG #     }
TAG # }
TAG # fn result(o: &Out) -> J {
TAG #     assert_eq!(o.code, Some(0), "expected exit 0: {}", trunc(&o.text()));
TAG #     let j = obj(o);
TAG #     assert_eq!(sf(&j, "schema"), "instinct.check-result/v1", "{}", trunc(&o.text()));
TAG #     assert!(["pass", "fail", "abstain"].contains(&sf(&j, "verdict")), "{}", trunc(&o.text()));
TAG #     assert_eq!(sf(&j, "authorization"), "not_evaluated");
TAG #     assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
TAG #     assert!(!sf(&j, "reason").is_empty());
TAG #     assert!(!sf(&j, "check_id").is_empty());
TAG #     match j.get("revision") {
TAG #         Some(J::Num(n)) => assert!(n.parse::<u32>().is_ok(), "revision must be an integer: {n}"),
TAG #         other => panic!("revision must be a number: {other:?}"),
TAG #     }
TAG #     match j.get("steps") {
TAG #         Some(J::Num(n)) => assert!(n.parse::<u64>().is_ok(), "steps must be a non-negative integer: {n}"),
TAG #         other => panic!("steps must be a number: {other:?}"),
TAG #     }
TAG #     match j.get("witness") {
TAG #         Some(J::Null) | Some(J::Str(_)) => {}
TAG #         other => panic!("witness must be string or null: {other:?}"),
TAG #     }
TAG #     let m = names(j.get("missing").expect("missing field"));
TAG #     let mut sorted = m.clone();
TAG #     sorted.sort();
TAG #     sorted.dedup();
TAG #     assert_eq!(m, sorted, "missing must be sorted and unique");
TAG #     assert!(matches!(j.get("scope"), Some(J::Obj(_))), "scope must be an object");
TAG #     let verdict = sf(&j, "verdict");
TAG #     if verdict == "pass" || verdict == "abstain" {
TAG #         assert_eq!(j.get("witness"), Some(&J::Null), "only a failed check has a witness: {}", trunc(&o.text()));
TAG #     }
TAG #     j
TAG # }
TAG # fn verdict(o: &Out) -> String {
TAG #     sf(&result(o), "verdict").to_string()
TAG # }
TAG # fn err(o: &Out, ctx: &str) {
TAG #     assert_eq!(o.code, Some(2), "{ctx}: expected exit 2, stdout={}", trunc(&o.text()));
TAG #     let j = obj(o);
TAG #     assert_eq!(sf(&j, "schema"), "instinct.check-error/v1", "{ctx}: {}", trunc(&o.text()));
TAG #     assert_eq!(sf(&j, "verdict"), "error", "{ctx}");
TAG #     assert!(!sf(&j, "reason").is_empty(), "{ctx}");
TAG #     assert_eq!(sf(&j, "authorization"), "not_evaluated", "{ctx}");
TAG #     assert!(o.out.len() <= 65_537, "{ctx}: error output must be bounded, got {} bytes", o.out.len());
TAG # }
TAG # // run validate, run and explain: every one must reject the document
TAG # fn all_err(env: &Env, raw: &[u8], ctx: &str) {
TAG #     for sub in ["validate", "run", "explain"] {
TAG #         err(&env.run_bytes(sub, raw), &format!("{sub} {ctx}"));
TAG #     }
TAG # }
TAG # fn all_err_s(env: &Env, raw: &str, ctx: &str) {
TAG #     all_err(env, raw.as_bytes(), &format!("{ctx}: {}", trunc(raw)));
TAG # }
TAG # fn valid(env: &Env, raw: &str, ctx: &str) {
TAG #     let o = env.run("validate", raw);
TAG #     assert_eq!(o.code, Some(0), "{ctx}: {}", trunc(&o.text()));
TAG #     let j = obj(&o);
TAG #     assert_eq!(sf(&j, "schema"), "instinct.check-validation/v1", "{ctx}");
TAG #     assert_eq!(j.get("valid"), Some(&J::Bool(true)), "{ctx}");
TAG #     assert_eq!(sf(&j, "authorization"), "not_evaluated");
TAG # }
TAG # // ---------------------------------------------------------------- document builders
TAG # #[derive(Clone)]
TAG # struct D {
TAG #     schema: String,
TAG #     id: String,
TAG #     rev: String,
TAG #     inputs: String,
TAG #     claim: String,
TAG #     req: Option<String>,
TAG #     dscope: Option<String>,
TAG #     facts: Option<String>,
TAG #     conds: Option<String>,
TAG #     scope: Option<String>,
TAG # }
TAG # fn d(inputs: &str, claim: &str) -> D {
TAG #     D {
TAG #         schema: "\"instinct.check/v1\"".into(),
TAG #         id: "\"t1\"".into(),
TAG #         rev: "1".into(),
TAG #         inputs: inputs.into(),
TAG #         claim: claim.into(),
TAG #         req: None,
TAG #         dscope: None,
TAG #         facts: None,
TAG #         conds: None,
TAG #         scope: None,
TAG #     }
TAG # }
TAG # impl D {
TAG #     fn facts(mut self, s: &str) -> D {
TAG #         self.facts = Some(s.into());
TAG #         self
TAG #     }
TAG #     fn conds(mut self, s: &str) -> D {
TAG #         self.conds = Some(s.into());
TAG #         self
TAG #     }
TAG #     fn scope(mut self, s: &str) -> D {
TAG #         self.scope = Some(s.into());
TAG #         self
TAG #     }
TAG #     fn dscope(mut self, s: &str) -> D {
TAG #         self.dscope = Some(s.into());
TAG #         self
TAG #     }
TAG #     fn req(mut self, s: &str) -> D {
TAG #         self.req = Some(s.into());
TAG #         self
TAG #     }
TAG #     fn id(mut self, s: &str) -> D {
TAG #         self.id = s.into();
TAG #         self
TAG #     }
TAG #     fn rev(mut self, s: &str) -> D {
TAG #         self.rev = s.into();
TAG #         self
TAG #     }
TAG #     fn schema(mut self, s: &str) -> D {
TAG #         self.schema = s.into();
TAG #         self
TAG #     }
TAG #     fn json(&self) -> String {
TAG #         let mut c = format!(
TAG #             "{{\"schema\":{},\"id\":{},\"revision\":{},\"inputs\":{},\"claim\":{}",
TAG #             self.schema, self.id, self.rev, self.inputs, self.claim
TAG #         );
TAG #         if let Some(r) = &self.req {
TAG #             c.push_str(&format!(",\"required_conditions\":{r}"));
TAG #         }
TAG #         if let Some(s) = &self.dscope {
TAG #             c.push_str(&format!(",\"scope\":{s}"));
TAG #         }
TAG #         c.push('}');
TAG #         let mut t = format!("{{\"check\":{c}");
TAG #         if let Some(f) = &self.facts {
TAG #             t.push_str(&format!(",\"facts\":{f}"));
TAG #         }
TAG #         if let Some(f) = &self.conds {
TAG #             t.push_str(&format!(",\"conditions\":{f}"));
TAG #         }
TAG #         if let Some(f) = &self.scope {
TAG #             t.push_str(&format!(",\"scope\":{f}"));
TAG #         }
TAG #         t.push('}');
TAG #         t
TAG #     }
TAG # }
TAG # fn fact(n: &str) -> String {
TAG #     format!("{{\"fact\":\"{n}\"}}")
TAG # }
TAG # fn op2(op: &str, l: &str, r: &str) -> String {
TAG #     format!("{{\"op\":\"{op}\",\"left\":{},\"right\":{}}}", fact(l), fact(r))
TAG # }
TAG # fn all_of(a: &[String]) -> String {
TAG #     format!("{{\"op\":\"all\",\"args\":[{}]}}", a.join(","))
TAG # }
TAG # fn any_of(a: &[String]) -> String {
TAG #     format!("{{\"op\":\"any\",\"args\":[{}]}}", a.join(","))
TAG # }
TAG # fn not_of(a: &str) -> String {
TAG #     format!("{{\"op\":\"not\",\"arg\":{a}}}")
TAG # }
TAG # // the example from the contract, on one line
TAG # const BASE: &str = "{\"check\":{\"schema\":\"instinct.check/v1\",\"id\":\"artifact-membership\",\"revision\":1,\"inputs\":{\"actual\":\"set<string>\",\"allowed\":\"set<string>\"},\"claim\":{\"op\":\"subset\",\"left\":{\"fact\":\"actual\"},\"right\":{\"fact\":\"allowed\"}},\"required_conditions\":[\"complete-inventory\",\"explicit-policy\"],\"scope\":{\"project\":\"release-lab\"}},\"facts\":{\"actual\":[\"release.bin\",\"scratch.env\"],\"allowed\":[\"release.bin\"]},\"conditions\":{\"complete-inventory\":true,\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}";
TAG # const SET_IN: &str = "{\"actual\":\"set<string>\",\"allowed\":\"set<string>\"}";
TAG # fn mutate(from: &str, to: &str) -> String {
TAG #     assert_eq!(BASE.matches(from).count(), 1, "mutation anchor must be unique: {from}");
TAG #     BASE.replacen(from, to, 1)
TAG # }
TAG # fn set_doc(op: &str, l: &str, r: &str) -> String {
TAG #     d(SET_IN, &op2(op, "actual", "allowed")).facts(&format!("{{\"actual\":{l},\"allowed\":{r}}}")).json()
TAG # }
TAG # fn js(items: &[&str]) -> String {
TAG #     format!("[{}]", items.iter().map(|s| format!("\"{s}\"")).collect::<Vec<_>>().join(","))
TAG # }
TAG # fn many(n: usize, prefix: &str) -> String {
TAG #     format!("[{}]", (0..n).map(|i| format!("\"{prefix}{i:05}\"")).collect::<Vec<_>>().join(","))
TAG # }
TAG # // ---------------------------------------------------------------- wire and result basics
TAG # #[test]
TAG # fn contract_example_fails_with_the_first_unexpected_member() {
TAG #     let env = Env::new("example");
TAG #     let o = env.run("run", BASE);
TAG #     let j = result(&o);
TAG #     assert!(o.text().trim_start().starts_with('{'), "no logging before the JSON result");
TAG #     assert_eq!(sf(&j, "verdict"), "fail");
TAG #     assert_eq!(sf(&j, "check_id"), "artifact-membership");
TAG #     assert_eq!(j.get("revision"), Some(&J::Num("1".into())));
TAG #     assert_eq!(j.get("witness"), Some(&J::Str("scratch.env".into())));
TAG #     assert_eq!(names(j.get("missing").unwrap()), Vec::<String>::new());
TAG #     assert_eq!(pairs(j.get("scope").unwrap()), vec![("project".to_string(), "release-lab".to_string())]);
TAG # }
TAG # #[test]
TAG # fn contract_example_with_a_complete_allow_list_passes_without_a_witness() {
TAG #     let env = Env::new("example-pass");
TAG #     let doc = mutate("\"allowed\":[\"release.bin\"]", "\"allowed\":[\"scratch.env\",\"release.bin\"]");
TAG #     let j = result(&env.run("run", &doc));
TAG #     assert_eq!(sf(&j, "verdict"), "pass");
TAG #     assert_eq!(j.get("witness"), Some(&J::Null));
TAG #     assert_eq!(names(j.get("missing").unwrap()), Vec::<String>::new());
TAG # }
TAG # #[test]
TAG # fn validate_checks_the_definition_and_never_claims_a_predicate_pass() {
TAG #     let env = Env::new("validate");
TAG #     let o = env.run("validate", BASE);
TAG #     assert_eq!(o.code, Some(0));
TAG #     let j = obj(&o);
TAG #     assert_eq!(sf(&j, "schema"), "instinct.check-validation/v1");
TAG #     assert_eq!(sf(&j, "check_id"), "artifact-membership");
TAG #     assert_eq!(j.get("revision"), Some(&J::Num("1".into())));
TAG #     assert_eq!(j.get("valid"), Some(&J::Bool(true)));
TAG #     assert_eq!(sf(&j, "authorization"), "not_evaluated");
TAG #     assert!(j.get("verdict").is_none(), "validation is not a verdict: {}", o.text());
TAG #     assert!(j.get("witness").is_none());
TAG #     assert!(!o.text().contains("\"pass\""), "validation must not read as a PASS");
TAG #     // The predicate fails on these facts, yet the definition and the supplied evidence are valid.
TAG #     // Missing facts, missing conditions and a missing scope are not validation errors either.
TAG #     let bare = d(SET_IN, &op2("subset", "actual", "allowed")).req("[\"c1\"]").dscope("{\"project\":\"p\"}");
TAG #     for doc in [
TAG #         bare.clone().json(),
TAG #         bare.clone().facts("{}").conds("{}").scope("{}").json(),
TAG #         bare.clone().facts("{\"actual\":[\"x\"]}").json(),
TAG #         bare.clone().facts("{\"actual\":[\"x\"],\"allowed\":[]}").conds("{\"c1\":false}").scope("{\"project\":\"other\"}").json(),
TAG #     ] {
TAG #         valid(&env, &doc, &doc);
TAG #     }
TAG # }
TAG # #[test]
TAG # fn explain_repeats_the_result_and_adds_declared_types_conditions_and_scope() {
TAG #     let env = Env::new("explain");
TAG #     let run = result(&env.run("run", BASE));
TAG #     let o = env.run("explain", BASE);
TAG #     let ex = result(&o);
TAG #     for k in ["check_id", "revision", "verdict", "reason", "witness", "missing", "scope", "steps"] {
TAG #         assert_eq!(run.get(k), ex.get(k), "explain must carry the same {k}");
TAG #     }
TAG #     let e = ex.get("explanation").unwrap_or_else(|| panic!("explain needs an explanation: {}", trunc(&o.text())));
TAG #     assert_ne!(e, &J::Null);
TAG #     let t = to_s(e);
TAG #     for needle in ["set<string>", "actual", "allowed", "complete-inventory", "explicit-policy", "release-lab", "subset"] {
TAG #         assert!(t.contains(needle), "explanation should mention {needle}: {t}");
TAG #     }
TAG #     assert!(!t.contains("release.bin"), "explanation must not echo fact values: {t}");
TAG #     assert!(run.get("explanation").is_none(), "run has no explanation");
TAG # }
TAG # #[test]
TAG # fn explain_and_run_do_not_expose_unrelated_fact_values() {
TAG #     let env = Env::new("expose");
TAG #     let inputs = "{\"actual\":\"set<string>\",\"allowed\":\"set<string>\",\"note\":\"string\",\"other\":\"set<string>\"}";
TAG #     let doc = d(inputs, &op2("subset", "actual", "allowed"))
TAG #         .facts("{\"actual\":[\"a\"],\"allowed\":[\"a\",\"SECRET_MEMBER_77\"],\"note\":\"SECRET_NOTE_88\",\"other\":[\"SECRET_OTHER_99\"]}")
TAG #         .json();
TAG #     for sub in ["run", "explain"] {
TAG #         let o = env.run(sub, &doc);
TAG #         let t = o.text();
TAG #         assert_eq!(verdict(&o), "pass");
TAG #         for s in ["SECRET_MEMBER_77", "SECRET_NOTE_88", "SECRET_OTHER_99"] {
TAG #             assert!(!t.contains(s), "{sub} leaked {s}: {t}");
TAG #         }
TAG #     }
TAG #     let failing = d(inputs, &op2("subset", "actual", "allowed"))
TAG #         .facts("{\"actual\":[\"zz\"],\"allowed\":[],\"note\":\"SECRET_NOTE_88\",\"other\":[\"SECRET_OTHER_99\"]}")
TAG #         .json();
TAG #     for sub in ["run", "explain"] {
TAG #         let t = env.run(sub, &failing).text();
TAG #         assert!(!t.contains("SECRET_NOTE_88") && !t.contains("SECRET_OTHER_99"), "{sub} leaked: {t}");
TAG #     }
TAG # }
TAG # #[test]
TAG # fn omitted_facts_conditions_and_scope_default_to_empty_and_missing_evidence_abstains() {
TAG #     let env = Env::new("defaults");
TAG #     let doc = d(SET_IN, &op2("subset", "actual", "allowed")).json();
TAG #     let j = result(&env.run("run", &doc));
TAG #     assert_eq!(sf(&j, "verdict"), "abstain");
TAG #     assert_eq!(names(j.get("missing").unwrap()), vec!["actual", "allowed"]);
TAG #     assert_eq!(pairs(j.get("scope").unwrap()), vec![]);
TAG #     for explicit in ["{}"] {
TAG #         let same = d(SET_IN, &op2("subset", "actual", "allowed")).facts(explicit).conds(explicit).scope(explicit).json();
TAG #         let k = result(&env.run("run", &same));
TAG #         assert_eq!(k.get("verdict"), j.get("verdict"));
TAG #         assert_eq!(k.get("missing"), j.get("missing"));
TAG #     }
TAG # }
TAG # #[test]
TAG # fn results_are_deterministic_across_runs_and_machines() {
TAG #     let a = Env::new("det-a");
TAG #     let b = Env::new("det-b");
TAG #     for doc in [BASE.to_string(), set_doc("disjoint", "[\"b\",\"a\"]", "[\"a\",\"b\"]")] {
TAG #         for sub in ["run", "validate", "explain"] {
TAG #             let x = a.run(sub, &doc);
TAG #             assert_eq!(x.out, a.run(sub, &doc).out);
TAG #             assert_eq!(x.out, b.run(sub, &doc).out);
TAG #         }
TAG #     }
TAG # }
TAG # #[test]
TAG # fn file_and_stdin_input_are_identical_for_results_and_errors() {
TAG #     let env = Env::new("parity");
TAG #     let docs = [
TAG #         BASE.to_string(),
TAG #         mutate("\"revision\":1", "\"revision\":2"),
TAG #         mutate("\"complete-inventory\":true", "\"complete-inventory\":false"),
TAG #         "{\"check\":".to_string(),
TAG #         mutate("\"op\":\"subset\"", "\"op\":\"nope\""),
TAG #         String::new(),
TAG #     ];
TAG #     for (i, doc) in docs.iter().enumerate() {
TAG #         let path = env.put(&format!("doc{i}.json"), doc.as_bytes());
TAG #         let p = path.to_str().unwrap();
TAG #         for sub in ["run", "validate", "explain"] {
TAG #             let f = env.exec(&["check", sub, "--input", p], b"");
TAG #             let s = env.run(sub, doc);
TAG #             assert_eq!(f.code, s.code, "{sub} doc{i}");
TAG #             assert_eq!(f.out, s.out, "{sub} doc{i}");
TAG #             // the document is read from the file; stdin is ignored when a file is named
TAG #             let both = env.exec(&["check", sub, "--input", p], BASE.as_bytes());
TAG #             assert_eq!(f.out, both.out, "{sub} doc{i}: named file wins over stdin");
TAG #         }
TAG #     }
TAG # }
TAG # #[test]
TAG # fn input_io_errors_use_the_error_shape() {
TAG #     let env = Env::new("io");
TAG #     let missing = env.root.join("in").join("nope.json");
TAG #     err(&env.exec(&["check", "run", "--input", missing.to_str().unwrap()], b""), "missing file");
TAG #     err(&env.exec(&["check", "validate", "--input", env.root.join("in").to_str().unwrap()], b""), "directory");
TAG #     err(&env.exec(&["check", "explain", "--input", ""], b""), "empty path");
TAG #     err(&env.exec(&["check", "run", "--input", "-"], b""), "empty stdin");
TAG # }
TAG # // ---------------------------------------------------------------- top-level keys and definition keys
TAG # #[test]
TAG # fn top_level_shape_is_strict() {
TAG #     let env = Env::new("top");
TAG #     let check = "{\"schema\":\"instinct.check/v1\",\"id\":\"t1\",\"revision\":1,\"inputs\":{\"a\":\"bool\"},\"claim\":{\"op\":\"eq\",\"left\":{\"fact\":\"a\"},\"right\":{\"fact\":\"a\"}}}";
TAG #     let bad = [
TAG #         "{}".to_string(),
TAG #         "[]".to_string(),
TAG #         "null".to_string(),
TAG #         "\"check\"".to_string(),
TAG #         "7".to_string(),
TAG #         "true".to_string(),
TAG #         format!("{{\"facts\":{{}},\"check\":null}}"),
TAG #         format!("{{\"check\":[]}}"),
TAG #         format!("{{\"check\":{check},\"extra\":{{}}}}"),
TAG #         format!("{{\"check\":{check},\"Facts\":{{}}}}"),
TAG #         format!("{{\"check\":{check},\"facts\":null}}"),
TAG #         format!("{{\"check\":{check},\"conditions\":null}}"),
TAG #         format!("{{\"check\":{check},\"scope\":null}}"),
TAG #         format!("{{\"check\":{check},\"facts\":[]}}"),
TAG #         format!("{{\"check\":{check},\"conditions\":[]}}"),
TAG #         format!("{{\"check\":{check},\"scope\":[]}}"),
TAG #         format!("{{\"facts\":{{}},\"conditions\":{{}},\"scope\":{{}}}}"),
TAG #     ];
TAG #     for doc in &bad {
TAG #         all_err_s(&env, doc, "top level");
TAG #     }
TAG #     valid(&env, &format!("{{\"check\":{check}}}"), "check alone");
TAG #     valid(&env, &format!("{{\"scope\":{{}},\"conditions\":{{}},\"facts\":{{}},\"check\":{check}}}"), "order is free");
TAG # }
TAG # #[test]
TAG # fn definition_requires_its_five_keys_and_rejects_unknown_ones() {
TAG #     let env = Env::new("defkeys");
TAG #     let parts = [
TAG #         ("schema", "\"instinct.check/v1\""),
TAG #         ("id", "\"t1\""),
TAG #         ("revision", "1"),
TAG #         ("inputs", "{\"a\":\"bool\"}"),
TAG #         ("claim", "{\"op\":\"eq\",\"left\":{\"fact\":\"a\"},\"right\":{\"fact\":\"a\"}}"),
TAG #     ];
TAG #     let build = |skip: Option<&str>, extra: &str| {
TAG #         let body: Vec<String> =
TAG #             parts.iter().filter(|(k, _)| Some(*k) != skip).map(|(k, v)| format!("\"{k}\":{v}")).collect();
TAG #         format!("{{\"check\":{{{}{extra}}}}}", body.join(","))
TAG #     };
TAG #     valid(&env, &build(None, ""), "complete");
TAG #     valid(&env, &build(None, ",\"required_conditions\":[],\"scope\":{}"), "optional keys");
TAG #     for (k, _) in parts {
TAG #         all_err_s(&env, &build(Some(k), ""), &format!("missing {k}"));
TAG #     }
TAG #     for extra in [
TAG #         ",\"extra\":1",
TAG #         ",\"description\":\"x\"",
TAG #         ",\"Scope\":{}",
TAG #         ",\"required_conditions\":null",
TAG #         ",\"required_conditions\":\"c\"",
TAG #         ",\"required_conditions\":{}",
TAG #         ",\"required_conditions\":[1]",
TAG #         ",\"required_conditions\":[null]",
TAG #         ",\"required_conditions\":[[\"c\"]]",
TAG #         ",\"scope\":null",
TAG #         ",\"scope\":[]",
TAG #         ",\"inputs\":{}",
TAG #     ] {
TAG #         all_err_s(&env, &build(None, extra), extra);
TAG #     }
TAG # }
TAG # #[test]
TAG # fn schema_string_must_match_exactly() {
TAG #     let env = Env::new("schema");
TAG #     let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a"));
TAG #     valid(&env, &base.clone().json(), "v1");
TAG #     for s in [
TAG #         "\"instinct.check/v2\"",
TAG #         "\"instinct.check/v0\"",
TAG #         "\"instinct.check/V1\"",
TAG #         "\"Instinct.check/v1\"",
TAG #         "\"instinct.check/v1 \"",
TAG #         "\"instinct.check\"",
TAG #         "\"instinct.check-result/v1\"",
TAG #         "\"\"",
TAG #         "1",
TAG #         "null",
TAG #         "true",
TAG #         "[\"instinct.check/v1\"]",
TAG #     ] {
TAG #         all_err_s(&env, &base.clone().schema(s).json(), s);
TAG #     }
TAG # }
TAG # #[test]
TAG # fn ids_are_one_to_128_ascii_characters_starting_with_a_letter() {
TAG #     let env = Env::new("ids");
TAG #     let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}");
TAG #     let long_ok = format!("a{}", "b".repeat(127));
TAG #     let ok = ["a", "Z", "a1", "A_b-c.d", "x.y.z", "a-", "a.", "a_", "ab0", &long_ok, "artifact-membership"];
TAG #     for id in ok {
TAG #         let j = result(&env.run("run", &base.clone().id(&format!("\"{id}\"")).json()));
TAG #         assert_eq!(sf(&j, "check_id"), id);
TAG #         assert_eq!(sf(&j, "verdict"), "pass");
TAG #     }
TAG #     let too_long = format!("a{}", "b".repeat(128));
TAG #     let bad = [
TAG #         "".to_string(),
TAG #         "1a".to_string(),
TAG #         "0".to_string(),
TAG #         "_a".to_string(),
TAG #         "-a".to_string(),
TAG #         ".a".to_string(),
TAG #         "a b".to_string(),
TAG #         "a/b".to_string(),
TAG #         "a:b".to_string(),
TAG #         "a\\u00e9".to_string(),
TAG #         "\\u00e9a".to_string(),
TAG #         "a\\u0000".to_string(),
TAG #         "a\\n".to_string(),
TAG #         "a b".replace(' ', "\\t"),
TAG #         "a*".to_string(),
TAG #         "a@b".to_string(),
TAG #         "a\\u0430".to_string(),
TAG #         too_long,
TAG #     ];
TAG #     for id in &bad {
TAG #         all_err_s(&env, &base.clone().id(&format!("\"{id}\"")).json(), &format!("id {id:?}"));
TAG #     }
TAG #     for raw in ["null", "1", "true", "[]", "{}", "[\"a\"]"] {
TAG #         all_err_s(&env, &base.clone().id(raw).json(), raw);
TAG #     }
TAG # }
TAG # #[test]
TAG # fn revision_is_an_exact_integer_literal_between_1_and_2147483647() {
TAG #     let env = Env::new("rev");
TAG #     let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}");
TAG #     for r in ["1", "2", "10", "255", "65536", "2147483646", "2147483647"] {
TAG #         let j = result(&env.run("run", &base.clone().rev(r).json()));
TAG #         assert_eq!(j.get("revision"), Some(&J::Num(r.into())), "revision {r}");
TAG #     }
TAG #     for r in [
TAG #         "0", "-1", "2147483648", "2147483649", "4294967296", "99999999999999999999", "01", "001", "1.0", "1.", ".5", "1.5", "1e0",
TAG #         "1E0", "1e+0", "1e1", "10e-1", "0.1e1", "+1", "-0", "-", "--1", "0x1", "1_0", "Infinity", "NaN", "null", "true", "false",
TAG #         "\"1\"", "[1]", "{}", "1 2", "1.0000000000000001",
TAG #     ] {
TAG #         all_err_s(&env, &base.clone().rev(r).json(), &format!("revision {r}"));
TAG #     }
TAG # }
TAG # // ---------------------------------------------------------------- types
TAG # #[test]
TAG # fn input_type_names_are_exactly_the_six_supported_ones() {
TAG #     let env = Env::new("typenames");
TAG #     for t in ["string", "bool", "int", "rational", "graph", "set<string>"] {
TAG #         let doc = d(&format!("{{\"a\":\"{t}\"}}"), &op2("eq", "a", "a")).json();
TAG #         valid(&env, &doc, t);
TAG #     }
TAG #     for t in [
TAG #         "float", "number", "integer", "i64", "u32", "str", "boolean", "set<int>", "set<bool>", "set", "set<>", "set<string",
TAG #         "Set<string>", "set< string >", "set<String>", "SET<STRING>", "String", "Bool", "INT", "list<string>", "array<string>",
TAG #         "map<string,string>", "set<set<string>>", "node", "edge", "set<node>", "", " string", "string ", "null", "any",
TAG #         "string|int", "string?", "option<string>",
TAG #     ] {
TAG #         let doc = d(&format!("{{\"a\":\"{t}\"}}"), &op2("eq", "a", "a")).json();
TAG #         all_err_s(&env, &doc, &format!("type {t:?}"));
TAG #     }
TAG #     for raw in ["null", "1", "true", "[]", "[\"string\"]", "{\"type\":\"string\"}", "{}"] {
TAG #         all_err_s(&env, &d(&format!("{{\"a\":{raw}}}"), &op2("eq", "a", "a")).json(), raw);
TAG #     }
TAG #     for raw in ["[]", "null", "\"a\"", "1"] {
TAG #         all_err_s(&env, &d(raw, &op2("eq", "a", "a")).json(), raw);
TAG #     }
TAG #     // names differing only by case are different facts
TAG #     let two = d("{\"A\":\"string\",\"a\":\"string\"}", &op2("eq", "A", "a")).facts("{\"A\":\"x\",\"a\":\"x\"}").json();
TAG #     assert_eq!(verdict(&env.run("run", &two)), "pass");
TAG # }
TAG # #[test]
TAG # fn supplied_facts_must_be_declared_and_correctly_typed() {
TAG #     let env = Env::new("facttypes");
TAG #     let ins = "{\"s\":\"string\",\"b\":\"bool\",\"n\":\"int\",\"x\":\"set<string>\"}";
TAG #     let claim = all_of(&[op2("eq", "s", "s"), op2("eq", "b", "b"), op2("eq", "n", "n"), op2("eq", "x", "x")]);
TAG #     let mk = |facts: &str| d(ins, &claim).facts(facts).json();
TAG #     let good = "{\"s\":\"v\",\"b\":true,\"n\":\"7\",\"x\":[\"p\",\"q\"]}";
TAG #     assert_eq!(verdict(&env.run("run", &mk(good))), "pass");
TAG #     valid(&env, &mk(good), "good");
TAG #     valid(&env, &mk("{\"s\":\"\",\"b\":false,\"n\":\"0\",\"x\":[]}"), "empty values");
TAG #     valid(&env, &mk("{}"), "no facts");
TAG #     valid(&env, &mk("{\"x\":[\"p\"]}"), "some facts");
TAG #     for f in [
TAG #         "{\"s\":1}",
TAG #         "{\"s\":true}",
TAG #         "{\"s\":null}",
TAG #         "{\"s\":[\"a\"]}",
TAG #         "{\"s\":{}}",
TAG #         "{\"b\":\"true\"}",
TAG #         "{\"b\":1}",
TAG #         "{\"b\":0}",
TAG #         "{\"b\":null}",
TAG #         "{\"b\":\"false\"}",
TAG #         "{\"n\":7}",
TAG #         "{\"n\":0}",
TAG #         "{\"n\":7.0}",
TAG #         "{\"n\":true}",
TAG #         "{\"n\":null}",
TAG #         "{\"n\":[\"7\"]}",
TAG #         "{\"x\":\"p\"}",
TAG #         "{\"x\":null}",
TAG #         "{\"x\":{}}",
TAG #         "{\"x\":[1]}",
TAG #         "{\"x\":[null]}",
TAG #         "{\"x\":[true]}",
TAG #         "{\"x\":[[\"p\"]]}",
TAG #         "{\"x\":[{}]}",
TAG #         "{\"x\":[\"p\",\"p\"]}",
TAG #         "{\"x\":[\"p\",\"q\",\"p\"]}",
TAG #         "{\"unknown\":\"v\"}",
TAG #         "{\"S\":\"v\"}",
TAG #         "{\"s\":\"v\",\"zzz\":true}",
TAG #         "[]",
TAG #         "null",
TAG #         "\"s\"",
TAG #         "7",
TAG #     ] {
TAG #         all_err_s(&env, &mk(f), f);
TAG #     }
TAG # }
TAG # #[test]
TAG # fn supplied_facts_are_type_checked_even_when_short_circuit_would_skip_them() {
TAG #     let env = Env::new("shortcircuit-types");
TAG #     let ins = "{\"one\":\"bool\",\"zero\":\"bool\",\"s\":\"string\"}";
TAG #     let any_t = any_of(&[op2("eq", "one", "one"), op2("eq", "s", "s")]);
TAG #     let all_f = all_of(&[op2("eq", "one", "zero"), op2("eq", "s", "s")]);
TAG #     for claim in [any_t, all_f] {
TAG #         let ok = d(ins, &claim).facts("{\"one\":true,\"zero\":false,\"s\":\"x\"}").json();
TAG #         assert_ne!(verdict(&env.run("run", &ok)), "abstain");
TAG #         let bad = d(ins, &claim).facts("{\"one\":true,\"zero\":false,\"s\":5}").json();
TAG #         all_err_s(&env, &bad, "unread wrong-typed fact");
TAG #         let undeclared = d(ins, &claim).facts("{\"one\":true,\"zero\":false,\"s\":\"x\",\"ghost\":true}").json();
TAG #         all_err_s(&env, &undeclared, "unread undeclared fact");
TAG #     }
TAG # }
TAG # #[test]
TAG # fn int_facts_are_canonical_decimal_strings_within_i128() {
TAG #     let env = Env::new("ints");
TAG #     let mk = |v: &str| d("{\"n\":\"int\"}", &op2("eq", "n", "n")).facts(&format!("{{\"n\":\"{v}\"}}")).json();
TAG #     for v in [
TAG #         "0",
TAG #         "1",
TAG #         "-1",
TAG #         "9",
TAG #         "10",
TAG #         "-10",
TAG #         "123",
TAG #         "9007199254740992",
TAG #         "9007199254740993",
TAG #         "-9007199254740993",
TAG #         "9223372036854775807",
TAG #         "9223372036854775808",
TAG #         "-9223372036854775808",
TAG #         "-9223372036854775809",
TAG #         "18446744073709551615",
TAG #         "18446744073709551616",
TAG #         "170141183460469231731687303715884105727",
TAG #         "-170141183460469231731687303715884105728",
TAG #     ] {
TAG #         assert_eq!(verdict(&env.run("run", &mk(v))), "pass", "{v}");
TAG #         valid(&env, &mk(v), v);
TAG #     }
TAG #     for v in [
TAG #         "+1",
TAG #         "+0",
TAG #         "1e3",
TAG #         "1E3",
TAG #         "1.0",
TAG #         "1.",
TAG #         ".5",
TAG #         "01",
TAG #         "00",
TAG #         "-0",
TAG #         "-00",
TAG #         "-01",
TAG #         "",
TAG #         " ",
TAG #         "- 1",
TAG #         " 1",
TAG #         "1 ",
TAG #         "1\\n",
TAG #         "\\t1",
TAG #         "0x10",
TAG #         "0b1",
TAG #         "1_000",
TAG #         "1,000",
TAG #         "-",
TAG #         "--1",
TAG #         "+-1",
TAG #         "abc",
TAG #         "NaN",
TAG #         "Infinity",
TAG #         "null",
TAG #         "true",
TAG #         "170141183460469231731687303715884105728",
TAG #         "-170141183460469231731687303715884105729",
TAG #         "340282366920938463463374607431768211455",
TAG #         "99999999999999999999999999999999999999999999",
TAG #         "-99999999999999999999999999999999999999999999",
TAG #         "\\uff11\\uff12",
TAG #         "\\u0661",
TAG #         "\\u0663\\u0664",
TAG #         "1\\u0000",
TAG #         "\\u2212" ,
TAG #         "1\\u00a0",
TAG #     ] {
TAG #         all_err_s(&env, &mk(v), &format!("int {v:?}"));
TAG #     }
TAG # }
TAG # #[test]
TAG # fn int_comparisons_are_exact_beyond_f64_and_numeric_not_lexical() {
TAG #     let env = Env::new("intcmp");
TAG #     let max = "170141183460469231731687303715884105727";
TAG #     let min = "-170141183460469231731687303715884105728";
TAG #     // (a, b, lt, lte, eq)
TAG #     let rows: Vec<(&str, &str, &str, &str, &str)> = vec![
TAG #         ("9007199254740992", "9007199254740993", "pass", "pass", "fail"),
TAG #         ("9007199254740993", "9007199254740992", "fail", "fail", "fail"),
TAG #         ("9007199254740993", "9007199254740993", "fail", "pass", "pass"),
TAG #         ("9007199254740993", "9007199254740995", "pass", "pass", "fail"),
TAG #         ("-9007199254740993", "-9007199254740992", "pass", "pass", "fail"),
TAG #         ("-9007199254740992", "-9007199254740993", "fail", "fail", "fail"),
TAG #         ("-1", "0", "pass", "pass", "fail"),
TAG #         ("0", "-1", "fail", "fail", "fail"),
TAG #         ("-10", "-9", "pass", "pass", "fail"),
TAG #         ("-9", "-10", "fail", "fail", "fail"),
TAG #         ("9", "10", "pass", "pass", "fail"),
TAG #         ("10", "9", "fail", "fail", "fail"),
TAG #         ("2", "10", "pass", "pass", "fail"),
TAG #         ("0", "0", "fail", "pass", "pass"),
TAG #         ("-5", "-5", "fail", "pass", "pass"),
TAG #         ("9223372036854775807", "9223372036854775808", "pass", "pass", "fail"),
TAG #         ("-9223372036854775809", "-9223372036854775808", "pass", "pass", "fail"),
TAG #         ("18446744073709551615", "18446744073709551616", "pass", "pass", "fail"),
TAG #         ("18446744073709551616", "18446744073709551615", "fail", "fail", "fail"),
TAG #         (min, max, "pass", "pass", "fail"),
TAG #         (max, min, "fail", "fail", "fail"),
TAG #         (max, max, "fail", "pass", "pass"),
TAG #         (min, min, "fail", "pass", "pass"),
TAG #         ("170141183460469231731687303715884105726", max, "pass", "pass", "fail"),
TAG #         (max, "170141183460469231731687303715884105726", "fail", "fail", "fail"),
TAG #         (min, "-170141183460469231731687303715884105727", "pass", "pass", "fail"),
TAG #         ("-170141183460469231731687303715884105727", min, "fail", "fail", "fail"),
TAG #         (max, "0", "fail", "fail", "fail"),
TAG #         (min, "0", "pass", "pass", "fail"),
TAG #     ];
TAG #     for (a, b, lt, lte, eq) in rows {
TAG #         let facts = format!("{{\"a\":\"{a}\",\"b\":\"{b}\"}}");
TAG #         for (op, want) in [("lt", lt), ("lte", lte), ("eq", eq)] {
TAG #             let doc = d("{\"a\":\"int\",\"b\":\"int\"}", &op2(op, "a", "b")).facts(&facts).json();
TAG #             let j = result(&env.run("run", &doc));
TAG #             assert_eq!(sf(&j, "verdict"), want, "{op}({a}, {b})");
TAG #         }
TAG #     }
TAG # }
TAG # #[test]
TAG # fn operand_types_must_match_the_operator_even_with_no_facts_supplied() {
TAG #     let env = Env::new("opptypes");
TAG #     let ins = "{\"s\":\"string\",\"t\":\"string\",\"b\":\"bool\",\"c\":\"bool\",\"n\":\"int\",\"m\":\"int\",\"x\":\"set<string>\",\"y\":\"set<string>\"}";
TAG #     let good = [
TAG #         ("eq", "s", "t"),
TAG #         ("eq", "b", "c"),
TAG #         ("eq", "n", "m"),
TAG #         ("eq", "x", "y"),
TAG #         ("subset", "x", "y"),
TAG #         ("disjoint", "x", "y"),
TAG #         ("contains", "x", "s"),
TAG #         ("lt", "n", "m"),
TAG #         ("lte", "n", "m"),
TAG #     ];
TAG #     for (op, l, r) in good {
TAG #         valid(&env, &d(ins, &op2(op, l, r)).json(), &format!("{op} {l} {r}"));
TAG #     }
TAG #     let bad = [
TAG #         ("eq", "s", "n"),
TAG #         ("eq", "s", "b"),
TAG #         ("eq", "s", "x"),
TAG #         ("eq", "n", "b"),
TAG #         ("eq", "n", "x"),
TAG #         ("eq", "b", "x"),
TAG #         ("lt", "s", "t"),
TAG #         ("lt", "b", "c"),
TAG #         ("lt", "x", "y"),
TAG #         ("lt", "n", "s"),
TAG #         ("lt", "s", "n"),
TAG #         ("lte", "s", "t"),
TAG #         ("lte", "b", "c"),
TAG #         ("lte", "x", "y"),
TAG #         ("lte", "n", "x"),
TAG #         ("subset", "s", "t"),
TAG #         ("subset", "x", "s"),
TAG #         ("subset", "s", "y"),
TAG #         ("subset", "n", "m"),
TAG #         ("subset", "b", "c"),
TAG #         ("disjoint", "x", "s"),
TAG #         ("disjoint", "s", "y"),
TAG #         ("disjoint", "n", "m"),
TAG #         ("contains", "s", "t"),
TAG #         ("contains", "s", "x"),
TAG #         ("contains", "x", "y"),
TAG #         ("contains", "x", "n"),
TAG #         ("contains", "x", "b"),
TAG #         ("contains", "n", "s"),
TAG #     ];
TAG #     for (op, l, r) in bad {
TAG #         all_err_s(&env, &d(ins, &op2(op, l, r)).json(), &format!("{op}({l}, {r})"));
TAG #     }
TAG # }
TAG # // ---------------------------------------------------------------- set semantics, Unicode, witnesses
TAG # #[test]
TAG # fn subset_and_disjoint_ignore_order_and_name_a_deterministic_witness() {
TAG #     let env = Env::new("sets");
TAG #     // (op, left, right, verdict, witness)
TAG #     let rows: Vec<(&str, &str, &str, &str, Option<&str>)> = vec![
TAG #         ("subset", "[]", "[]", "pass", None),
TAG #         ("subset", "[]", "[\"x\"]", "pass", None),
TAG #         ("subset", "[\"x\"]", "[]", "fail", Some("x")),
TAG #         ("subset", "[\"a\",\"b\"]", "[\"b\",\"a\",\"c\"]", "pass", None),
TAG #         ("subset", "[\"b\",\"a\"]", "[\"a\",\"b\"]", "pass", None),
TAG #         ("subset", "[\"z\",\"b\",\"m\"]", "[\"m\"]", "fail", Some("b")),
TAG #         ("subset", "[\"m\",\"b\",\"z\"]", "[\"m\"]", "fail", Some("b")),
TAG #         ("subset", "[\"b\",\"m\",\"z\"]", "[\"m\"]", "fail", Some("b")),
TAG #         ("subset", "[\"a\",\"B\"]", "[]", "fail", Some("B")),
TAG #         ("subset", "[\"a\",\"A\"]", "[\"a\"]", "fail", Some("A")),
TAG #         ("subset", "[\"ab\",\"a\"]", "[]", "fail", Some("a")),
TAG #         ("subset", "[\"\"]", "[\"\"]", "pass", None),
TAG #         ("subset", "[\"\",\"a\"]", "[\"a\"]", "fail", Some("")),
TAG #         ("subset", "[\"A\"]", "[\"a\"]", "fail", Some("A")),
TAG #         ("subset", "[\"a \"]", "[\"a\"]", "fail", Some("a ")),
TAG #         ("subset", "[\"a\\nb\"]", "[]", "fail", Some("a\nb")),
TAG #         ("subset", "[\"q\\\"r\\\\s\"]", "[]", "fail", Some("q\"r\\s")),
TAG #         ("subset", "[\"a\\u0000b\"]", "[\"a\\u0000b\"]", "pass", None),
TAG #         ("disjoint", "[]", "[]", "pass", None),
TAG #         ("disjoint", "[]", "[\"a\"]", "pass", None),
TAG #         ("disjoint", "[\"a\"]", "[]", "pass", None),
TAG #         ("disjoint", "[\"a\"]", "[\"b\"]", "pass", None),
TAG #         ("disjoint", "[\"a\",\"b\"]", "[\"c\",\"d\"]", "pass", None),
TAG #         ("disjoint", "[\"a\"]", "[\"A\"]", "pass", None),
TAG #         ("disjoint", "[\"a\",\"b\"]", "[\"b\",\"c\"]", "fail", Some("b")),
TAG #         ("disjoint", "[\"m\",\"b\"]", "[\"b\",\"m\"]", "fail", Some("b")),
TAG #         ("disjoint", "[\"b\",\"m\"]", "[\"m\",\"b\"]", "fail", Some("b")),
TAG #         ("disjoint", "[\"z\",\"m\",\"b\"]", "[\"q\",\"m\",\"b\",\"z\"]", "fail", Some("b")),
TAG #     ];
TAG #     for (op, l, r, v, w) in rows {
TAG #         let j = result(&env.run("run", &set_doc(op, l, r)));
TAG #         assert_eq!(sf(&j, "verdict"), v, "{op} {l} {r}");
TAG #         match w {
TAG #             Some(w) => assert_eq!(j.get("witness"), Some(&J::Str(w.into())), "{op} {l} {r}"),
TAG #             None => assert_eq!(j.get("witness"), Some(&J::Null), "{op} {l} {r}"),
TAG #         }
TAG #     }
TAG # }
TAG # #[test]
TAG # fn witness_does_not_depend_on_input_order() {
TAG #     let env = Env::new("perm");
TAG #     let orders = [
TAG #         ["a", "b", "c", "d"],
TAG #         ["d", "c", "b", "a"],
TAG #         ["b", "d", "a", "c"],
TAG #         ["c", "a", "d", "b"],
TAG #     ];
TAG #     let mut seen = Vec::new();
TAG #     for l in orders {
TAG #         for r in orders {
TAG #             let ls = js(&l);
TAG #             let rs = js(&r[..2]);
TAG #             let sub = result(&env.run("run", &set_doc("subset", &ls, &rs)));
TAG #             let dis = result(&env.run("run", &set_doc("disjoint", &ls, &rs)));
TAG #             seen.push((sub.get("verdict").cloned(), sub.get("witness").cloned(), dis.get("verdict").cloned(), dis.get("witness").cloned()));
TAG #         }
TAG #     }
TAG #     // the right-hand set is {a,b} or {d,c} etc. depending on order, so group by the actual right set
TAG #     for l in orders {
TAG #         let mut by_set: Vec<(Vec<String>, J, J)> = Vec::new();
TAG #         for r in orders {
TAG #             let mut key: Vec<String> = r[..2].iter().map(|s| s.to_string()).collect();
TAG #             key.sort();
TAG #             let o = result(&env.run("run", &set_doc("subset", &js(&l), &js(&r[..2]))));
TAG #             let w = o.get("witness").cloned().unwrap();
TAG #             let v = o.get("verdict").cloned().unwrap();
TAG #             if let Some(prev) = by_set.iter().find(|(k, _, _)| *k == key) {
TAG #                 assert_eq!((prev.1.clone(), prev.2.clone()), (v, w), "order changed the outcome for {l:?} vs {r:?}");
TAG #             } else {
TAG #                 by_set.push((key, v, w));
TAG #             }
TAG #         }
TAG #     }
TAG #     assert!(!seen.is_empty());
TAG # }
TAG # #[test]
TAG # fn contains_is_exact_membership_without_case_folding_or_normalization() {
TAG #     let env = Env::new("contains");
TAG #     let ins = "{\"x\":\"set<string>\",\"s\":\"string\"}";
TAG #     let rows: Vec<(&str, &str, &str)> = vec![
TAG #         ("[\"a\",\"b\"]", "b", "pass"),
TAG #         ("[\"a\",\"b\"]", "c", "fail"),
TAG #         ("[\"a\",\"b\"]", "B", "fail"),
TAG #         ("[\"a\",\"b\"]", "ab", "fail"),
TAG #         ("[\"a\",\"b\"]", "", "fail"),
TAG #         ("[\"a\",\"\"]", "", "pass"),
TAG #         ("[]", "a", "fail"),
TAG #         ("[\"\\u00e9\"]", "\\u00e9", "pass"),
TAG #         ("[\"\\u00e9\"]", "e\\u0301", "fail"),
TAG #         ("[\"e\\u0301\"]", "\\u00e9", "fail"),
TAG #         ("[\"e\\u0301\"]", "e\\u0301", "pass"),
TAG #         ("[\"\\u00df\"]", "SS", "fail"),
TAG #         ("[\"\\u00df\"]", "ss", "fail"),
TAG #         ("[\"\\u0130\"]", "i", "fail"),
TAG #         ("[\"K\"]", "\\u212a", "fail"),
TAG #         ("[\"\\ud83d\\ude00\"]", "\\ud83d\\ude00", "pass"),
TAG #         ("[\"a\\u200bb\"]", "ab", "fail"),
TAG #         ("[\"a\\u0000b\"]", "a\\u0000b", "pass"),
TAG #         ("[\"a\\u0000b\"]", "a", "fail"),
TAG #         ("[\"Stra\\u00dfe\"]", "STRASSE", "fail"),
TAG #         ("[\"\\u0391\"]", "\\u0041", "fail"),
TAG #     ];
TAG #     for (x, s, want) in rows {
TAG #         let doc = d(ins, &op2("contains", "x", "s")).facts(&format!("{{\"x\":{x},\"s\":\"{s}\"}}")).json();
TAG #         assert_eq!(verdict(&env.run("run", &doc)), want, "contains {x} {s}");
TAG #     }
TAG #     // raw UTF-8 and the escaped spelling are the same scalar sequence
TAG #     let raw = d(ins, &op2("contains", "x", "s")).facts("{\"x\":[\"\\ud83d\\ude00\",\"\\u00e9\"],\"s\":\"\u{1F600}\"}").json();
TAG #     assert_eq!(verdict(&env.run("run", &raw)), "pass");
TAG #     let raw = d(ins, &op2("contains", "x", "s")).facts("{\"x\":[\"\u{1F600}\",\"\u{e9}\"],\"s\":\"\\u00e9\"}").json();
TAG #     assert_eq!(verdict(&env.run("run", &raw)), "pass");
TAG # }
TAG # #[test]
TAG # fn unicode_members_are_compared_as_exact_scalar_sequences_and_witnessed_verbatim() {
TAG #     let env = Env::new("unicode");
TAG #     let j = result(&env.run("run", &set_doc("subset", "[\"e\\u0301\"]", "[\"\\u00e9\"]")));
TAG #     assert_eq!(sf(&j, "verdict"), "fail");
TAG #     assert_eq!(j.get("witness"), Some(&J::Str("e\u{301}".into())));
TAG #     let j = result(&env.run("run", &set_doc("subset", "[\"\u{e9}\",\"\\ud83d\\ude00\"]", "[\"\\u00e9\",\"\u{1F600}\"]")));
TAG #     assert_eq!(sf(&j, "verdict"), "pass");
TAG #     let j = result(&env.run("run", &set_doc("disjoint", "[\"\u{e9}\"]", "[\"e\\u0301\"]")));
TAG #     assert_eq!(sf(&j, "verdict"), "pass");
TAG #     let j = result(&env.run("run", &set_doc("subset", "[\"\\u0434\\u0430\"]", "[]")));
TAG #     assert_eq!(j.get("witness"), Some(&J::Str("\u{434}\u{430}".into())));
TAG #     let j = result(&env.run("run", &set_doc("subset", "[\"\u{1F600}\"]", "[]")));
TAG #     assert_eq!(j.get("witness"), Some(&J::Str("\u{1F600}".into())));
TAG #     // code point order decides "first lexicographic"
TAG #     let j = result(&env.run("run", &set_doc("subset", "[\"\u{e9}\",\"z\",\"\u{1F600}\"]", "[]")));
TAG #     assert_eq!(j.get("witness"), Some(&J::Str("z".into())));
TAG #     // strings compare exactly in eq
TAG #     let eq = |a: &str, b: &str| {
TAG #         let doc = d("{\"a\":\"string\",\"b\":\"string\"}", &op2("eq", "a", "b")).facts(&format!("{{\"a\":\"{a}\",\"b\":\"{b}\"}}")).json();
TAG #         verdict(&env.run("run", &doc))
TAG #     };
TAG #     assert_eq!(eq("\\u00e9", "\u{e9}"), "pass");
TAG #     assert_eq!(eq("\\u00e9", "e\\u0301"), "fail");
TAG #     assert_eq!(eq("a", "A"), "fail");
TAG #     assert_eq!(eq("", ""), "pass");
TAG #     assert_eq!(eq("a", "a "), "fail");
TAG #     assert_eq!(eq("\\ud83d\\ude00", "\u{1F600}"), "pass");
TAG #     assert_eq!(eq("\\/", "/"), "pass");
TAG # }
TAG # #[test]
TAG # fn duplicate_set_members_are_rejected_including_escaped_spellings() {
TAG #     let env = Env::new("setdups");
TAG #     for l in [
TAG #         "[\"a\",\"a\"]",
TAG #         "[\"a\",\"b\",\"a\"]",
TAG #         "[\"\",\"\"]",
TAG #         "[\"\\u0061\",\"a\"]",
TAG #         "[\"a\",\"\\u0061\"]",
TAG #         "[\"\\u00e9\",\"\u{e9}\"]",
TAG #         "[\"\\u00E9\",\"\\u00e9\"]",
TAG #         "[\"\\ud83d\\ude00\",\"\u{1F600}\"]",
TAG #         "[\"a\\/b\",\"a/b\"]",
TAG #         "[\"a\\nb\",\"a\\u000ab\"]",
TAG #     ] {
TAG #         all_err_s(&env, &set_doc("subset", l, "[]"), l);
TAG #         all_err_s(&env, &set_doc("subset", "[]", l), l);
TAG #     }
TAG #     for l in [
TAG #         "[\"a\",\"A\"]",
TAG #         "[\"a\",\"a \"]",
TAG #         "[\"\\u00e9\",\"e\\u0301\"]",
TAG #         "[\"\",\"a\"]",
TAG #         "[\"a\\u0000\",\"a\"]",
TAG #     ] {
TAG #         valid(&env, &set_doc("subset", l, "[]"), l);
TAG #     }
TAG # }
TAG # #[test]
TAG # fn strings_must_be_unicode_scalar_sequences() {
TAG #     let env = Env::new("surrogates");
TAG #     for l in [
TAG #         "[\"\\ud800\"]",
TAG #         "[\"\\udc00\"]",
TAG #         "[\"\\udfff\"]",
TAG #         "[\"a\\ud800\"]",
TAG #         "[\"\\ud800a\"]",
TAG #         "[\"\\ud83d\\ud83d\"]",
TAG #         "[\"\\ude00\\ud83d\"]",
TAG #         "[\"\\ud83d\\u0061\"]",
TAG #     ] {
TAG #         all_err_s(&env, &set_doc("subset", l, "[]"), l);
TAG #         let doc = d("{\"s\":\"string\"}", &op2("eq", "s", "s")).facts(&format!("{{\"s\":{}}}", &l[1..l.len() - 1])).json();
TAG #         all_err_s(&env, &doc, l);
TAG #     }
TAG # }
TAG # #[test]
TAG # fn eq_compares_each_supported_type_and_sets_without_order() {
TAG #     let env = Env::new("eq");
TAG #     let ins = "{\"x\":\"set<string>\",\"y\":\"set<string>\"}";
TAG #     let cases = [
TAG #         ("[\"a\",\"b\"]", "[\"b\",\"a\"]", "pass"),
TAG #         ("[]", "[]", "pass"),
TAG #         ("[\"a\"]", "[\"a\",\"b\"]", "fail"),
TAG #         ("[\"a\",\"b\"]", "[\"a\"]", "fail"),
TAG #         ("[\"a\"]", "[\"A\"]", "fail"),
TAG #         ("[\"a\",\"b\",\"c\"]", "[\"c\",\"a\",\"b\"]", "pass"),
TAG #         ("[]", "[\"a\"]", "fail"),
TAG #     ];
TAG #     for (x, y, want) in cases {
TAG #         let doc = d(ins, &op2("eq", "x", "y")).facts(&format!("{{\"x\":{x},\"y\":{y}}}")).json();
TAG #         assert_eq!(verdict(&env.run("run", &doc)), want, "{x} == {y}");
TAG #     }
TAG #     for (a, b, want) in [("true", "true", "pass"), ("false", "false", "pass"), ("true", "false", "fail"), ("false", "true", "fail")] {
TAG #         let doc = d("{\"a\":\"bool\",\"b\":\"bool\"}", &op2("eq", "a", "b")).facts(&format!("{{\"a\":{a},\"b\":{b}}}")).json();
TAG #         assert_eq!(verdict(&env.run("run", &doc)), want, "{a} == {b}");
TAG #     }
TAG # }
TAG # // ---------------------------------------------------------------- missing evidence and three-valued logic
TAG # #[test]
TAG # fn missing_facts_abstain_and_are_listed_sorted_and_unique() {
TAG #     let env = Env::new("missing");
TAG #     let ins = "{\"z\":\"bool\",\"m\":\"bool\",\"a\":\"bool\"}";
TAG #     let claim = all_of(&[op2("eq", "z", "a"), op2("eq", "m", "a"), op2("eq", "z", "m")]);
TAG #     let j = result(&env.run("run", &d(ins, &claim).json()));
TAG #     assert_eq!(sf(&j, "verdict"), "abstain");
TAG #     assert_eq!(names(j.get("missing").unwrap()), vec!["a", "m", "z"]);
TAG #     // supplying one removes it from the list; the rest stay missing
TAG #     let j = result(&env.run("run", &d(ins, &claim).facts("{\"m\":true}").json()));
TAG #     assert_eq!(sf(&j, "verdict"), "abstain");
TAG #     let miss = names(j.get("missing").unwrap());
TAG #     assert!(!miss.contains(&"m".to_string()) && miss.contains(&"a".to_string()) && miss.contains(&"z".to_string()), "{miss:?}");
TAG #     // all supplied: nothing missing
TAG #     let j = result(&env.run("run", &d(ins, &claim).facts("{\"z\":true,\"m\":true,\"a\":true}").json()));
TAG #     assert_eq!(sf(&j, "verdict"), "pass");
TAG #     assert_eq!(names(j.get("missing").unwrap()), Vec::<String>::new());
TAG #     // each operator abstains when one operand is missing
TAG #     for (op, ins, facts) in [
TAG #         ("subset", SET_IN, "{\"actual\":[\"a\"]}"),
TAG #         ("subset", SET_IN, "{\"allowed\":[\"a\"]}"),
TAG #         ("disjoint", SET_IN, "{\"actual\":[\"a\"]}"),
TAG #         ("eq", "{\"actual\":\"string\",\"allowed\":\"string\"}", "{\"actual\":\"a\"}"),
TAG #         ("lt", "{\"actual\":\"int\",\"allowed\":\"int\"}", "{\"allowed\":\"3\"}"),
TAG #         ("lte", "{\"actual\":\"int\",\"allowed\":\"int\"}", "{}"),
TAG #     ] {
TAG #         let j = result(&env.run("run", &d(ins, &op2(op, "actual", "allowed")).facts(facts).json()));
TAG #         assert_eq!(sf(&j, "verdict"), "abstain", "{op} {facts}");
TAG #         assert_eq!(j.get("witness"), Some(&J::Null));
TAG #         assert!(!names(j.get("missing").unwrap()).is_empty());
TAG #     }
TAG #     let doc = d("{\"x\":\"set<string>\",\"s\":\"string\"}", &op2("contains", "x", "s")).facts("{\"x\":[\"a\"]}").json();
TAG #     assert_eq!(verdict(&env.run("run", &doc)), "abstain");
TAG # }
TAG # #[test]
TAG # fn three_valued_all_any_not_follow_the_documented_tables() {
TAG #     let env = Env::new("truth");
TAG #     let ins = "{\"one\":\"bool\",\"zero\":\"bool\",\"gone\":\"bool\"}";
TAG #     let facts = "{\"one\":true,\"zero\":false}";
TAG #     fn build(s: &[u8], i: &mut usize) -> (String, char) {
TAG #         let c = s[*i];
TAG #         *i += 1;
TAG #         match c {
TAG #             b'T' => (op2("eq", "one", "one"), 'T'),
TAG #             b'F' => (op2("eq", "one", "zero"), 'F'),
TAG #             b'U' => (op2("eq", "one", "gone"), 'U'),
TAG #             b'!' => {
TAG #                 let (e, v) = build(s, i);
TAG #                 (not_of(&e), match v { 'T' => 'F', 'F' => 'T', _ => 'U' })
TAG #             }
TAG #             b'A' | b'O' => {
TAG #                 assert_eq!(s[*i], b'(');
TAG #                 *i += 1;
TAG #                 let (mut es, mut vs) = (Vec::new(), Vec::new());
TAG #                 while s[*i] != b')' {
TAG #                     let (e, v) = build(s, i);
TAG #                     es.push(e);
TAG #                     vs.push(v);
TAG #                 }
TAG #                 *i += 1;
TAG #                 if c == b'A' {
TAG #                     let v = if vs.contains(&'F') { 'F' } else if vs.contains(&'U') { 'U' } else { 'T' };
TAG #                     (all_of(&es), v)
TAG #                 } else {
TAG #                     let v = if vs.contains(&'T') { 'T' } else if vs.contains(&'U') { 'U' } else { 'F' };
TAG #                     (any_of(&es), v)
TAG #                 }
TAG #             }
TAG #             other => panic!("bad dsl {}", other as char),
TAG #         }
TAG #     }
TAG #     let check = |expr: &str| {
TAG #         let mut i = 0;
TAG #         let (claim, v) = build(expr.as_bytes(), &mut i);
TAG #         assert_eq!(i, expr.len());
TAG #         let want = match v { 'T' => "pass", 'F' => "fail", _ => "abstain" };
TAG #         let j = result(&env.run("run", &d(ins, &claim).facts(facts).json()));
TAG #         assert_eq!(sf(&j, "verdict"), want, "{expr}");
TAG #         if want == "abstain" {
TAG #             assert!(names(j.get("missing").unwrap()).contains(&"gone".to_string()), "{expr}");
TAG #         }
TAG #     };
TAG #     let mut level1: Vec<String> = Vec::new();
TAG #     for l in ["T", "F", "U"] {
TAG #         level1.push(l.to_string());
TAG #         level1.push(format!("!{l}"));
TAG #     }
TAG #     for op in ["A", "O"] {
TAG #         for n in 1..=3usize {
TAG #             let mut combos: Vec<String> = vec![String::new()];
TAG #             for _ in 0..n {
TAG #                 combos = combos.iter().flat_map(|c| ["T", "F", "U"].map(|l| format!("{c}{l}"))).collect();
TAG #             }
TAG #             for c in combos {
TAG #                 level1.push(format!("{op}({c})"));
TAG #                 level1.push(format!("!{op}({c})"));
TAG #             }
TAG #         }
TAG #     }
TAG #     for e in &level1 {
TAG #         check(e);
TAG #     }
TAG #     let sample = ["T", "F", "U", "!U", "!A(TU)", "O(FU)", "A(UF)", "!O(FF)", "A(TTT)", "O(UU)"];
TAG #     for a in sample {
TAG #         for b in sample {
TAG #             check(&format!("A({a}{b})"));
TAG #             check(&format!("O({a}{b})"));
TAG #             check(&format!("!A({a}{b})"));
TAG #             check(&format!("!O({b}{a})"));
TAG #         }
TAG #     }
TAG #     for e in ["A(U!TO(UF)A(UT))", "O(A(UT)O(FF)!U)", "!!U", "!!!T", "A(!U!F)", "O(!F!U)", "!O(A(FU)A(TU))"] {
TAG #         check(e);
TAG #     }
TAG # }
TAG # #[test]
TAG # fn a_false_operand_decides_all_and_a_true_operand_decides_any_regardless_of_unknown_siblings() {
TAG #     let env = Env::new("decide");
TAG #     let ins = "{\"one\":\"bool\",\"zero\":\"bool\",\"gone\":\"bool\"}";
TAG #     let u = op2("eq", "one", "gone");
TAG #     let t = op2("eq", "one", "one");
TAG #     let f = op2("eq", "one", "zero");
TAG #     let facts = "{\"one\":true,\"zero\":false}";
TAG #     let run = |claim: String| verdict(&env.run("run", &d(ins, &claim).facts(facts).json()));
TAG #     assert_eq!(run(all_of(&[u.clone(), f.clone()])), "fail");
TAG #     assert_eq!(run(all_of(&[f.clone(), u.clone()])), "fail");
TAG #     assert_eq!(run(any_of(&[u.clone(), t.clone()])), "pass");
TAG #     assert_eq!(run(any_of(&[t.clone(), u.clone()])), "pass");
TAG #     assert_eq!(run(all_of(&[t.clone(), u.clone()])), "abstain");
TAG #     assert_eq!(run(any_of(&[f.clone(), u.clone()])), "abstain");
TAG #     assert_eq!(run(not_of(&u)), "abstain");
TAG #     let j = result(&env.run("run", &d(ins, &all_of(&[u.clone(), f.clone()])).facts(facts).json()));
TAG #     assert_eq!(j.get("verdict"), Some(&J::Str("fail".into())));
TAG # }
TAG # #[test]
TAG # fn a_missing_required_condition_or_scope_mismatch_abstains_whatever_the_claim_says() {
TAG #     let env = Env::new("gates");
TAG #     let ins = "{\"one\":\"bool\",\"zero\":\"bool\"}";
TAG #     let t = op2("eq", "one", "one");
TAG #     let f = op2("eq", "one", "zero");
TAG #     let facts = "{\"one\":true,\"zero\":false}";
TAG #     for (claim, open_verdict) in [(&t, "pass"), (&f, "fail")] {
TAG #         let base = d(ins, claim).facts(facts).req("[\"c1\",\"c2\"]").dscope("{\"project\":\"p\",\"persona\":\"q\"}");
TAG #         let open = base.clone().conds("{\"c1\":true,\"c2\":true}").scope("{\"project\":\"p\",\"persona\":\"q\"}");
TAG #         assert_eq!(verdict(&env.run("run", &open.json())), open_verdict);
TAG #         let gated = [
TAG #             ("no conditions", base.clone().scope("{\"project\":\"p\",\"persona\":\"q\"}")),
TAG #             ("one missing", open.clone().conds("{\"c1\":true}")),
TAG #             ("other missing", open.clone().conds("{\"c2\":true}")),
TAG #             ("one false", open.clone().conds("{\"c1\":false,\"c2\":true}")),
TAG #             ("other false", open.clone().conds("{\"c1\":true,\"c2\":false}")),
TAG #             ("both false", open.clone().conds("{\"c1\":false,\"c2\":false}")),
TAG #             ("no scope", open.clone().scope("{}")),
TAG #             ("scope omitted", base.clone().conds("{\"c1\":true,\"c2\":true}")),
TAG #             ("wrong project", open.clone().scope("{\"project\":\"x\",\"persona\":\"q\"}")),
TAG #             ("wrong persona", open.clone().scope("{\"project\":\"p\",\"persona\":\"x\"}")),
TAG #             ("one dimension", open.clone().scope("{\"project\":\"p\"}")),
TAG #         ];
TAG #         for (name, doc) in gated {
TAG #             for sub in ["run", "explain"] {
TAG #                 let j = result(&env.run(sub, &doc.json()));
TAG #                 assert_eq!(sf(&j, "verdict"), "abstain", "{sub} {name} claim={claim}");
TAG #                 assert_eq!(j.get("witness"), Some(&J::Null), "{name}");
TAG #             }
TAG #         }
TAG #     }
TAG # }
TAG # #[test]
TAG # fn missing_required_conditions_are_named_in_missing() {
TAG #     let env = Env::new("condmissing");
TAG #     let doc = d("{\"one\":\"bool\"}", &op2("eq", "one", "one")).facts("{\"one\":true}").req("[\"zeta\",\"alpha\"]");
TAG #     let j = result(&env.run("run", &doc.clone().json()));
TAG #     assert_eq!(sf(&j, "verdict"), "abstain");
TAG #     assert_eq!(names(j.get("missing").unwrap()), vec!["alpha", "zeta"]);
TAG #     let j = result(&env.run("run", &doc.clone().conds("{\"zeta\":true}").json()));
TAG #     assert_eq!(sf(&j, "verdict"), "abstain");
TAG #     assert_eq!(names(j.get("missing").unwrap()), vec!["alpha"]);
TAG #     let j = result(&env.run("run", &doc.clone().conds("{\"zeta\":true,\"alpha\":true}").json()));
TAG #     assert_eq!(sf(&j, "verdict"), "pass");
TAG #     assert_eq!(names(j.get("missing").unwrap()), Vec::<String>::new());
TAG # }
TAG # #[test]
TAG # fn conditions_are_declared_booleans_only() {
TAG #     let env = Env::new("conditions");
TAG #     let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}").req("[\"c1\",\"c2\"]");
TAG #     valid(&env, &base.clone().conds("{}").json(), "empty");
TAG #     valid(&env, &base.clone().conds("{\"c1\":true}").json(), "partial");
TAG #     valid(&env, &base.clone().conds("{\"c1\":false,\"c2\":true}").json(), "false is fine");
TAG #     for c in [
TAG #         "{\"c3\":true}",
TAG #         "{\"c1\":true,\"c3\":true}",
TAG #         "{\"C1\":true}",
TAG #         "{\"c1\":\"true\"}",
TAG #         "{\"c1\":1}",
TAG #         "{\"c1\":0}",
TAG #         "{\"c1\":null}",
TAG #         "{\"c1\":[true]}",
TAG #         "{\"c1\":{}}",
TAG #         "[\"c1\"]",
TAG #         "null",
TAG #         "true",
TAG #     ] {
TAG #         all_err_s(&env, &base.clone().conds(c).json(), c);
TAG #     }
TAG #     // conditions are rejected when the definition requires none
TAG #     let none = d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}");
TAG #     all_err_s(&env, &none.clone().conds("{\"c1\":true}").json(), "undeclared condition");
TAG #     valid(&env, &none.clone().conds("{}").json(), "no conditions");
TAG #     let empty_req = none.clone().req("[]");
TAG #     valid(&env, &empty_req.clone().conds("{}").json(), "empty required list");
TAG #     all_err_s(&env, &empty_req.conds("{\"c1\":false}").json(), "condition not in empty list");
TAG # }
TAG # // ---------------------------------------------------------------- scope
TAG # #[test]
TAG # fn scope_objects_accept_only_the_five_dimensions_with_nonempty_strings() {
TAG #     let env = Env::new("scopeshape");
TAG #     let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}");
TAG #     let good = [
TAG #         "{}",
TAG #         "{\"project\":\"p\"}",
TAG #         "{\"persona\":\"p\"}",
TAG #         "{\"harness\":\"h\"}",
TAG #         "{\"version\":\"1.2.3\"}",
TAG #         "{\"machine\":\"m\"}",
TAG #         "{\"project\":\"p\",\"persona\":\"q\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}",
TAG #         "{\"project\":\" \"}",
TAG #         "{\"project\":\"a*b\"}",
TAG #         "{\"project\":\"**\"}",
TAG #         "{\"project\":\"p*\"}",
TAG #         "{\"project\":\"\\u00e9\"}",
TAG #         "{\"project\":\"\\ud83d\\ude00\"}",
TAG #         "{\"project\":\"a b\"}",
TAG #     ];
TAG #     for s in good {
TAG #         valid(&env, &base.clone().dscope(s).json(), s);
TAG #         valid(&env, &base.clone().scope(s).json(), s);
TAG #         valid(&env, &base.clone().dscope(s).scope(s).json(), s);
TAG #     }
TAG #     let bad = [
TAG #         "{\"project\":\"\"}",
TAG #         "{\"project\":null}",
TAG #         "{\"project\":1}",
TAG #         "{\"project\":true}",
TAG #         "{\"project\":[\"p\"]}",
TAG #         "{\"project\":{}}",
TAG #         "{\"project\":\"*\"}",
TAG #         "{\"env\":\"x\"}",
TAG #         "{\"cwd\":\"/tmp\"}",
TAG #         "{\"user\":\"x\"}",
TAG #         "{\"Project\":\"p\"}",
TAG #         "{\"PROJECT\":\"p\"}",
TAG #         "{\"project \":\"p\"}",
TAG #         "{\"project\":\"p\",\"extra\":\"x\"}",
TAG #         "{\"*\":\"x\"}",
TAG #         "{\"project\":\"p\",\"persona\":\"\"}",
TAG #         "[]",
TAG #         "[\"project\"]",
TAG #         "\"project\"",
TAG #         "1",
TAG #         "true",
TAG #     ];
TAG #     for s in bad {
TAG #         all_err_s(&env, &base.clone().dscope(s).json(), &format!("definition scope {s}"));
TAG #         all_err_s(&env, &base.clone().scope(s).json(), &format!("request scope {s}"));
TAG #     }
TAG #     // a bad request scope is an error even when the definition scope is different
TAG #     all_err_s(&env, &base.clone().dscope("{\"project\":\"p\"}").scope("{\"env\":\"x\"}").json(), "bad request scope");
TAG #     all_err_s(&env, &base.clone().dscope("{\"env\":\"x\"}").scope("{\"project\":\"p\"}").json(), "bad definition scope");
TAG # }
TAG # #[test]
TAG # fn scope_matching_is_exact_per_required_dimension() {
TAG #     let env = Env::new("scopematch");
TAG #     let ins = "{\"one\":\"bool\",\"zero\":\"bool\"}";
TAG #     let facts = "{\"one\":true,\"zero\":false}";
TAG #     // the claim fails when evaluated, so "fail" proves the scope matched and "abstain" proves it did not
TAG #     let claim = op2("eq", "one", "zero");
TAG #     let rows: Vec<(Option<&str>, Option<&str>, &str)> = vec![
TAG #         (Some("{\"project\":\"p\"}"), Some("{\"project\":\"p\"}"), "fail"),
TAG #         (Some("{\"project\":\"p\"}"), Some("{\"project\":\"q\"}"), "abstain"),
TAG #         (Some("{\"project\":\"p\"}"), Some("{\"project\":\"P\"}"), "abstain"),
TAG #         (Some("{\"project\":\"p\"}"), Some("{\"project\":\"p \"}"), "abstain"),
TAG #         (Some("{\"project\":\"p\"}"), Some("{\"project\":\" p\"}"), "abstain"),
TAG #         (Some("{\"project\":\"p\"}"), Some("{\"project\":\"pp\"}"), "abstain"),
TAG #         (Some("{\"project\":\"pp\"}"), Some("{\"project\":\"p\"}"), "abstain"),
TAG #         (Some("{\"project\":\"p\"}"), None, "abstain"),
TAG #         (Some("{\"project\":\"p\"}"), Some("{}"), "abstain"),
TAG #         (Some("{\"project\":\"p\"}"), Some("{\"persona\":\"p\"}"), "abstain"),
TAG #         (Some("{\"project\":\"p\"}"), Some("{\"project\":\"p\",\"persona\":\"x\"}"), "fail"),
TAG #         (Some("{}"), Some("{\"project\":\"p\"}"), "fail"),
TAG #         (Some("{}"), Some("{}"), "fail"),
TAG #         (Some("{}"), None, "fail"),
TAG #         (None, Some("{\"project\":\"p\"}"), "fail"),
TAG #         (None, None, "fail"),
TAG #         (Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"project\":\"p\"}"), "abstain"),
TAG #         (Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"persona\":\"a\"}"), "abstain"),
TAG #         (Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"project\":\"p\",\"persona\":\"b\"}"), "abstain"),
TAG #         (Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"project\":\"q\",\"persona\":\"a\"}"), "abstain"),
TAG #         (Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"persona\":\"a\",\"project\":\"p\"}"), "fail"),
TAG #         (Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"project\":\"p\",\"persona\":\"a\",\"machine\":\"m\"}"), "fail"),
TAG #         (Some("{\"harness\":\"h\"}"), Some("{\"harness\":\"h\"}"), "fail"),
TAG #         (Some("{\"harness\":\"h\"}"), Some("{\"harness\":\"H\"}"), "abstain"),
TAG #         (Some("{\"version\":\"1.0\"}"), Some("{\"version\":\"1.0\"}"), "fail"),
TAG #         (Some("{\"version\":\"1.0\"}"), Some("{\"version\":\"1.00\"}"), "abstain"),
TAG #         (Some("{\"version\":\"1.0\"}"), Some("{\"version\":\"1\"}"), "abstain"),
TAG #         (Some("{\"machine\":\"m\"}"), Some("{\"machine\":\"m\"}"), "fail"),
TAG #         (Some("{\"machine\":\"m\"}"), Some("{\"machine\":\"n\"}"), "abstain"),
TAG #         (Some("{\"machine\":\"m\"}"), Some("{\"project\":\"m\"}"), "abstain"),
TAG #         (Some("{\"project\":\"a*b\"}"), Some("{\"project\":\"axxb\"}"), "abstain"),
TAG #         (Some("{\"project\":\"a*b\"}"), Some("{\"project\":\"a*b\"}"), "fail"),
TAG #         (Some("{\"project\":\"pr\\u00f3\"}"), Some("{\"project\":\"pr\\u00f3\"}"), "fail"),
TAG #         (Some("{\"project\":\"pr\\u00f3\"}"), Some("{\"project\":\"pr\u{f3}\"}"), "fail"),
TAG #         (Some("{\"project\":\"pr\\u00f3\"}"), Some("{\"project\":\"pro\\u0301\"}"), "abstain"),
TAG #         (Some("{\"project\":\"pro\\u0301\"}"), Some("{\"project\":\"pr\\u00f3\"}"), "abstain"),
TAG #         (Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}"),
TAG #          Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}"), "fail"),
TAG #         (Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}"),
TAG #          Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"x\"}"), "abstain"),
TAG #         (Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}"),
TAG #          Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\"}"), "abstain"),
TAG #     ];
TAG #     for (def, req, want) in rows {
TAG #         let mut doc = d(ins, &claim).facts(facts);
TAG #         if let Some(s) = def {
TAG #             doc = doc.dscope(s);
TAG #         }
TAG #         if let Some(s) = req {
TAG #             doc = doc.scope(s);
TAG #         }
TAG #         let j = result(&env.run("run", &doc.json()));
TAG #         assert_eq!(sf(&j, "verdict"), want, "definition {def:?} request {req:?}");
TAG #         // the result reports the explicit current scope, never an inferred one
TAG #         let want_scope = match req {
TAG #             Some(s) => pairs(&parse_json(s).unwrap()),
TAG #             None => vec![],
TAG #         };
TAG #         assert_eq!(pairs(j.get("scope").unwrap()), want_scope, "definition {def:?} request {req:?}");
TAG #     }
TAG # }
TAG # // ---------------------------------------------------------------- expression shape errors, even when unreachable
TAG # #[test]
TAG # fn malformed_predicates_are_rejected_even_in_unreachable_branches() {
TAG #     let env = Env::new("shape");
TAG #     let ins = "{\"one\":\"bool\",\"zero\":\"bool\",\"a\":\"string\",\"b\":\"string\",\"x\":\"set<string>\",\"n\":\"int\"}";
TAG #     let facts = "{\"one\":true,\"zero\":false}";
TAG #     let fa = fact("a");
TAG #     let fb = fact("b");
TAG #     let t = op2("eq", "one", "one");
TAG #     let f = op2("eq", "one", "zero");
TAG #     let bad: Vec<String> = vec![
TAG #         format!("{{\"op\":\"xor\",\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"neq\",\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"gt\",\"left\":{{\"fact\":\"n\"}},\"right\":{{\"fact\":\"n\"}}}}"),
TAG #         format!("{{\"op\":\"Eq\",\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"EQ\",\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"ALL\",\"args\":[{t}]}}"),
TAG #         format!("{{\"op\":\"Not\",\"arg\":{t}}}"),
TAG #         format!("{{\"op\":\"\",\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq \",\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"matches\",\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"exec\",\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":1,\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":null,\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":[\"eq\"],\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{fb},\"extra\":1}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{fb},\"args\":[]}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{fb},\"arg\":{t}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{fa}}}"),
TAG #         format!("{{\"op\":\"eq\",\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\"}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":null}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"nope\"}},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{{\"fact\":\"nope\"}}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"A\"}},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"\"}},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{{\"value\":\"lit\"}},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{{\"literal\":\"lit\"}},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{{\"const\":\"lit\"}},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":\"lit\",\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":\"a\",\"right\":\"b\"}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":1,\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":true,\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":[\"a\"],\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{{}},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{{\"fact\":1}},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{{\"fact\":null}},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{{\"fact\":[\"a\"]}},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"a\",\"extra\":1}},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"a\",\"fact\":\"b\"}},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{{\"Fact\":\"a\"}},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{t},\"right\":{f}}}"),
TAG #         format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{{\"fact\":\"one\"}}}}"),
TAG #         format!("{{\"op\":\"lt\",\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"subset\",\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"contains\",\"left\":{fa},\"right\":{fb}}}"),
TAG #         format!("{{\"op\":\"contains\",\"left\":{{\"fact\":\"x\"}},\"right\":{{\"fact\":\"x\"}}}}"),
TAG #         format!("{{\"op\":\"disjoint\",\"left\":{{\"fact\":\"x\"}},\"right\":{fb}}}"),
TAG #         "{\"op\":\"all\",\"args\":[]}".to_string(),
TAG #         "{\"op\":\"any\",\"args\":[]}".to_string(),
TAG #         "{\"op\":\"all\"}".to_string(),
TAG #         "{\"op\":\"any\"}".to_string(),
TAG #         "{\"op\":\"all\",\"args\":null}".to_string(),
TAG #         "{\"op\":\"all\",\"args\":\"x\"}".to_string(),
TAG #         format!("{{\"op\":\"all\",\"args\":{t}}}"),
TAG #         "{\"op\":\"any\",\"args\":[1]}".to_string(),
TAG #         "{\"op\":\"any\",\"args\":[null]}".to_string(),
TAG #         "{\"op\":\"any\",\"args\":[\"eq\"]}".to_string(),
TAG #         "{\"op\":\"any\",\"args\":[[]]}".to_string(),
TAG #         format!("{{\"op\":\"all\",\"arg\":{t}}}"),
TAG #         format!("{{\"op\":\"all\",\"args\":[{t}],\"arg\":{t}}}"),
TAG #         format!("{{\"op\":\"any\",\"args\":[{t}],\"extra\":true}}"),
TAG #         format!("{{\"op\":\"all\",\"args\":[{t}],\"left\":{fa}}}"),
TAG #         format!("{{\"op\":\"all\",\"args\":[{t},{{\"op\":\"eq\"}}]}}"),
TAG #         "{\"op\":\"not\"}".to_string(),
TAG #         "{\"op\":\"not\",\"arg\":null}".to_string(),
TAG #         "{\"op\":\"not\",\"arg\":1}".to_string(),
TAG #         "{\"op\":\"not\",\"arg\":\"x\"}".to_string(),
TAG #         "{\"op\":\"not\",\"arg\":{}}".to_string(),
TAG #         format!("{{\"op\":\"not\",\"arg\":[{t}]}}"),
TAG #         format!("{{\"op\":\"not\",\"args\":[{t}]}}"),
TAG #         format!("{{\"op\":\"not\",\"arg\":{t},\"args\":[{t}]}}"),
TAG #         format!("{{\"op\":\"not\",\"arg\":{t},\"extra\":1}}"),
TAG #         format!("{{\"op\":\"not\",\"arg\":{t},\"arg\":{f}}}"),
TAG #         format!("{{\"op\":\"not\",\"left\":{t}}}"),
TAG #         format!("{{\"op\":\"all\",\"args\":[{t}],\"args\":[{f}]}}"),
TAG #         "{}".to_string(),
TAG #         "[]".to_string(),
TAG #         "null".to_string(),
TAG #         "\"eq\"".to_string(),
TAG #         "1".to_string(),
TAG #         "true".to_string(),
TAG #         "{\"fact\":\"one\"}".to_string(),
TAG #         format!("[{t}]"),
TAG #     ];
TAG #     for b in &bad {
TAG #         let direct = d(ins, b).facts(facts).json();
TAG #         all_err_s(&env, &direct, &format!("direct {b}"));
TAG #         // behind a short circuit that would never read it
TAG #         for (wrapped, what) in [
TAG #             (any_of(&[t.clone(), b.clone()]), "any[T,bad]"),
TAG #             (all_of(&[f.clone(), b.clone()]), "all[F,bad]"),
TAG #             (not_of(b), "not[bad]"),
TAG #             (any_of(&[t.clone(), all_of(&[f.clone(), b.clone()])]), "any[T,all[F,bad]]"),
TAG #         ] {
TAG #             let doc = d(ins, &wrapped).facts(facts).json();
TAG #             all_err_s(&env, &doc, &format!("{what} {b}"));
TAG #         }
TAG #     }
TAG #     // the good forms of the same shapes still work
TAG #     for claim in [any_of(&[t.clone(), f.clone()]), all_of(&[t.clone()]), not_of(&f)] {
TAG #         assert_eq!(verdict(&env.run("run", &d(ins, &claim).facts(facts).json())), "pass");
TAG #     }
TAG #     // a bad reference or type in a branch the evaluator would skip is still an error
TAG #     for claim in [
TAG #         any_of(&[t.clone(), op2("eq", "a", "one")]),
TAG #         any_of(&[t.clone(), op2("lt", "a", "b")]),
TAG #         any_of(&[t.clone(), op2("eq", "ghost", "a")]),
TAG #         all_of(&[f.clone(), op2("subset", "a", "b")]),
TAG #         all_of(&[f.clone(), op2("contains", "x", "x")]),
TAG #     ] {
TAG #         all_err_s(&env, &d(ins, &claim).facts(facts).json(), &claim);
TAG #     }
TAG # }
TAG # // ---------------------------------------------------------------- wire format
TAG # #[test]
TAG # fn invalid_json_is_a_structured_error() {
TAG #     let env = Env::new("badjson");
TAG #     let inner = &BASE[1..BASE.len() - 1];
TAG #     let mut docs: Vec<String> = vec![
TAG #         "".into(),
TAG #         " ".into(),
TAG #         "\n".into(),
TAG #         "{".into(),
TAG #         "}".into(),
TAG #         "{{}}".into(),
TAG #         "{\"check\"".into(),
TAG #         "{\"check\":".into(),
TAG #         "{\"check\":}".into(),
TAG #         "{\"check\":{}".into(),
TAG #         "{\"check\" {}}".into(),
TAG #         "{check:{}}".into(),
TAG #         "{'check':{}}".into(),
TAG #         "{\"check\":{},}".into(),
TAG #         "{,\"check\":{}}".into(),
TAG #         "{\"check\":{}} x".into(),
TAG #         "{\"check\":{}}{}".into(),
TAG #         "x".into(),
TAG #         "nul".into(),
TAG #         "tru".into(),
TAG #         "NaN".into(),
TAG #         "undefined".into(),
TAG #         "{\"check\":NaN}".into(),
TAG #         "{\"check\":Infinity}".into(),
TAG #         "{\"check\":undefined}".into(),
TAG #         "{\"check\":[1,]}".into(),
TAG #         "{\"check\":[,1]}".into(),
TAG #         "{\"check\":[1 2]}".into(),
TAG #         "{\"check\":\"abc}".into(),
TAG #         "{\"check\":\"a\\qb\"}".into(),
TAG #         "{\"check\":\"a\\u12\"}".into(),
TAG #         "{\"check\":\"a\\u12G4\"}".into(),
TAG #         "{\"check\":\"a\\x41\"}".into(),
TAG #         "{\"check\":\"a\\'b\"}".into(),
TAG #         "{\"check\":\"a\\".into(),
TAG #         format!("{BASE} x"),
TAG #         format!("{BASE}{BASE}"),
TAG #         format!("{BASE},"),
TAG #         format!("{BASE}}}"),
TAG #         format!("{BASE}\n{BASE}"),
TAG #         format!("{BASE} // comment"),
TAG #         format!("/* c */ {BASE}"),
TAG #         format!("# c\n{BASE}"),
TAG #         format!("[{BASE}]"),
TAG #         BASE[..BASE.len() - 1].to_string(),
TAG #         BASE[..BASE.len() / 2].to_string(),
TAG #         BASE.replacen(":", " ", 1),
TAG #         BASE.replacen("{\"schema\"", "{schema", 1),
TAG #         BASE.replacen("\"id\":", "\"id\"=", 1),
TAG #         BASE.replacen("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",", 1),
TAG #         BASE.replacen("\"revision\":1,", "\"revision\":1,,", 1),
TAG #         BASE.replacen("\"project\":\"release-lab\"", "\"project\":'release-lab'", 1),
TAG #         BASE.replacen("true", "True", 1),
TAG #         BASE.replacen("true", "tru", 1),
TAG #         BASE.replacen("true", "TRUE", 1),
TAG #         format!("{{{inner},}}"),
TAG #         format!("{{\"a\":1 {inner}}}"),
TAG #     ];
TAG #     docs.push(format!("\u{feff}{BASE}"));
TAG #     docs.push(format!("\u{0}{BASE}"));
TAG #     docs.push(format!("{BASE}\u{0}"));
TAG #     docs.push(format!("\u{c}{BASE}"));
TAG #     docs.push(format!("{BASE}\u{b}"));
TAG #     for doc in docs {
TAG #         all_err_s(&env, &doc, "invalid json");
TAG #     }
TAG #     // surrounding JSON whitespace is fine
TAG #     valid(&env, &format!(" \n\t\r{BASE}\r\n\t "), "whitespace");
TAG #     valid(&env, &BASE.replace(",", ",\n  ").replace(":", " : "), "pretty printed");
TAG # }
TAG # #[test]
TAG # fn raw_control_characters_and_bad_utf8_are_rejected_but_escapes_are_fine() {
TAG #     let env = Env::new("ctrl");
TAG #     for c in ["\n", "\t", "\r", "\u{1}", "\u{8}", "\u{b}", "\u{c}", "\u{1f}", "\u{0}"] {
TAG #         all_err_s(&env, &BASE.replacen("release.bin", &format!("rel{c}ease"), 1), &format!("control {c:?} in a value"));
TAG #         all_err_s(&env, &BASE.replacen("\"actual\":[", &format!("\"ac{c}tual\":["), 1), &format!("control {c:?} in a key"));
TAG #         all_err_s(&env, &BASE.replacen("artifact-membership", &format!("{c}"), 1), &format!("control {c:?} as id"));
TAG #     }
TAG #     for esc in ["\\n", "\\t", "\\r", "\\b", "\\f", "\\u0001", "\\u001f", "\\u0000", "\\\"", "\\\\", "\\/"] {
TAG #         valid(&env, &set_doc("subset", &format!("[\"a{esc}b\"]"), "[]"), esc);
TAG #     }
TAG #     // 0x7f and non-ASCII are not control characters of the JSON grammar
TAG #     valid(&env, &set_doc("subset", "[\"a\u{7f}b\"]", "[]"), "DEL");
TAG #     valid(&env, &set_doc("subset", "[\"\u{85}\u{2028}\u{2029}\"]", "[]"), "unicode separators");
TAG #     let prefix = b"{\"check\":{\"schema\":\"instinct.check/v1\",\"id\":\"t1\",\"revision\":1,\"inputs\":{\"s\":\"string\"},\"claim\":{\"op\":\"eq\",\"left\":{\"fact\":\"s\"},\"right\":{\"fact\":\"s\"}}},\"facts\":{\"s\":\"";
TAG #     let suffix = b"\"}}";
TAG #     let mk = |mid: &[u8]| {
TAG #         let mut v = prefix.to_vec();
TAG #         v.extend_from_slice(mid);
TAG #         v.extend_from_slice(suffix);
TAG #         v
TAG #     };
TAG #     assert_eq!(verdict(&env.run_bytes("run", &mk("caf\u{e9} \u{1F600}".as_bytes()))), "pass");
TAG #     for (name, mid) in [
TAG #         ("0xff", vec![0xffu8]),
TAG #         ("0xfe", vec![0xfe]),
TAG #         ("lone continuation", vec![0x80]),
TAG #         ("truncated 2-byte", vec![b'a', 0xc3]),
TAG #         ("overlong slash", vec![0xc0, 0xaf]),
TAG #         ("overlong nul", vec![0xc0, 0x80]),
TAG #         ("truncated 3-byte", vec![0xe2, 0x82]),
TAG #         ("encoded surrogate", vec![0xed, 0xa0, 0x80]),
TAG #         ("encoded low surrogate", vec![0xed, 0xbf, 0xbf]),
TAG #         ("above U+10FFFF", vec![0xf4, 0x90, 0x80, 0x80]),
TAG #         ("5-byte form", vec![0xf8, 0x88, 0x80, 0x80, 0x80]),
TAG #         ("truncated 4-byte", vec![0xf0, 0x9f, 0x98]),
TAG #     ] {
TAG #         all_err(&env, &mk(&mid), name);
TAG #     }
TAG #     // invalid UTF-8 outside strings too
TAG #     let mut bad = BASE.as_bytes().to_vec();
TAG #     bad.push(0xff);
TAG #     all_err(&env, &bad, "trailing 0xff");
TAG # }
TAG # #[test]
TAG # fn duplicate_keys_are_rejected_everywhere_including_escaped_spellings() {
TAG #     let env = Env::new("dupkeys");
TAG #     // (anchor that occurs exactly once in BASE, replacement that adds a duplicate)
TAG #     let rows: Vec<(&str, &str)> = vec![
TAG #         ("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"id\":\"artifact-membership\""),
TAG #         ("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"id\":\"other\""),
TAG #         ("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"\\u0069d\":\"artifact-membership\""),
TAG #         ("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"i\\u0064\":\"x\""),
TAG #         ("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"\\u0049d\":\"x\",\"i\\u0064\":\"y\""),
TAG #         ("\"revision\":1", "\"revision\":1,\"revision\":1"),
TAG #         ("\"revision\":1", "\"revision\":1,\"\\u0072evision\":1"),
TAG #         ("\"schema\":\"instinct.check/v1\"", "\"schema\":\"instinct.check/v1\",\"sch\\u0065ma\":\"instinct.check/v1\""),
TAG #         ("\"inputs\":{", "\"inputs\":{\"actual\":\"set<string>\","),
TAG #         ("\"inputs\":{", "\"inputs\":{\"a\\u0063tual\":\"set<string>\","),
TAG #         ("\"inputs\":{\"actual\":\"set<string>\"", "\"inputs\":{\"actual\":\"set<string>\",\"\\u0061ctual\":\"string\""),
TAG #         ("\"inputs\":{\"actual\":\"set<string>\"", "\"inputs\":{\"actual\":\"set<string>\",\"a\\u0063\\u0074ual\":\"set<string>\""),
TAG #         ("\"allowed\":\"set<string>\"}", "\"allowed\":\"set<string>\",\"allowed\":\"set<string>\"}"),
TAG #         ("\"claim\":{\"op\":\"subset\"", "\"claim\":{\"op\":\"subset\",\"op\":\"subset\""),
TAG #         ("\"claim\":{\"op\":\"subset\"", "\"claim\":{\"op\":\"subset\",\"o\\u0070\":\"subset\""),
TAG #         ("\"claim\":{\"op\":\"subset\"", "\"claim\":{\"op\":\"subset\",\"\\u006fp\":\"disjoint\""),
TAG #         ("\"left\":{\"fact\":\"actual\"}", "\"left\":{\"fact\":\"actual\",\"fact\":\"actual\"}"),
TAG #         ("\"left\":{\"fact\":\"actual\"}", "\"left\":{\"fact\":\"actual\",\"f\\u0061ct\":\"actual\"}"),
TAG #         ("\"left\":{\"fact\":\"actual\"}", "\"left\":{\"fact\":\"actual\"},\"left\":{\"fact\":\"actual\"}"),
TAG #         ("\"left\":{\"fact\":\"actual\"}", "\"left\":{\"fact\":\"actual\"},\"l\\u0065ft\":{\"fact\":\"actual\"}"),
TAG #         ("\"right\":{\"fact\":\"allowed\"}", "\"right\":{\"fact\":\"allowed\"},\"right\":{\"fact\":\"allowed\"}"),
TAG #         ("\"right\":{\"fact\":\"allowed\"}", "\"right\":{\"fact\":\"allowed\"},\"r\\u0069ght\":{\"fact\":\"allowed\"}"),
TAG #         ("\"required_conditions\":[", "\"required_conditions\":[\"complete-inventory\"],\"required_conditions\":["),
TAG #         ("\"required_conditions\":[", "\"required_conditions\":[\"complete-inventory\"],\"required_cond\\u0069tions\":["),
TAG #         ("\"scope\":{\"project\":\"release-lab\"}},\"facts\"", "\"scope\":{\"project\":\"release-lab\"},\"scope\":{\"project\":\"release-lab\"}},\"facts\""),
TAG #         ("\"scope\":{\"project\":\"release-lab\"}},\"facts\"", "\"scope\":{\"project\":\"release-lab\",\"project\":\"release-lab\"}},\"facts\""),
TAG #         ("\"scope\":{\"project\":\"release-lab\"}},\"facts\"", "\"scope\":{\"project\":\"release-lab\",\"\\u0070roject\":\"other\"}},\"facts\""),
TAG #         ("\"scope\":{\"project\":\"release-lab\"}},\"facts\"", "\"scope\":{\"project\":\"release-lab\"},\"sc\\u006fpe\":{}},\"facts\""),
TAG #         ("\"facts\":{", "\"facts\":{\"actual\":[],"),
TAG #         ("\"facts\":{", "\"facts\":{\"actual\":[\"release.bin\",\"scratch.env\"],\"\\u0061ctual\":[],"),
TAG #         ("\"facts\":{\"actual\":[\"release.bin\",\"scratch.env\"]", "\"facts\":{\"actual\":[\"release.bin\",\"scratch.env\"],\"actual\":[\"release.bin\",\"scratch.env\"]"),
TAG #         ("\"allowed\":[\"release.bin\"]}", "\"allowed\":[\"release.bin\"],\"allowed\":[\"release.bin\"]}"),
TAG #         ("\"allowed\":[\"release.bin\"]}", "\"allowed\":[\"release.bin\"],\"a\\u006cl\\u006fwed\":[]}"),
TAG #         ("\"allowed\":[\"release.bin\"]}", "\"allowed\":[\"release.bin\"],\"\\u0041llowed\":[],\"allowed\":[]}"),
TAG #         ("\"allowed\":[\"release.bin\"]},\"conditions\"", "\"allowed\":[\"release.bin\"]},\"facts\":{},\"conditions\""),
TAG #         ("\"allowed\":[\"release.bin\"]},\"conditions\"", "\"allowed\":[\"release.bin\"]},\"f\\u0061cts\":{},\"conditions\""),
TAG #         ("\"allowed\":[\"release.bin\"]},\"conditions\"", "\"allowed\":[\"release.bin\"]},\"\\u0066acts\":{\"actual\":[],\"allowed\":[]},\"conditions\""),
TAG #         ("\"conditions\":{", "\"conditions\":{\"complete-inventory\":true,"),
TAG #         ("\"conditions\":{", "\"conditions\":{\"complete\\u002dinventory\":true,"),
TAG #         ("\"conditions\":{", "\"conditions\":{\"complete\\u002Dinventory\":false,"),
TAG #         ("\"explicit-policy\":true}", "\"explicit-policy\":true,\"explicit-policy\":true}"),
TAG #         ("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"conditions\":{},\"scope\":{\"project\":\"release-lab\"}}"),
TAG #         ("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"cond\\u0069tions\":{},\"scope\":{\"project\":\"release-lab\"}}"),
TAG #         ("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"},\"scope\":{\"project\":\"release-lab\"}}"),
TAG #         ("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\",\"project\":\"release-lab\"}}"),
TAG #         ("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"},\"\\u0073cope\":{}}"),
TAG #         ("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"scope\":{\"pro\\u006aect\":\"x\",\"project\":\"release-lab\"}}"),
TAG #         ("{\"check\":{", "{\"check\":{},\"check\":{"),
TAG #         ("{\"check\":{", "{\"ch\\u0065ck\":{},\"check\":{"),
TAG #         ("{\"check\":{", "{\"\\u0063heck\":{\"x\":1},\"check\":{"),
TAG #         ("{\"check\":{", "{\"che\\u0063k\":{\"schema\":\"instinct.check/v1\"},\"check\":{"),
TAG #     ];
TAG #     for (anchor, repl) in rows {
TAG #         let doc = mutate(anchor, repl);
TAG #         all_err_s(&env, &doc, "duplicate key");
TAG #     }
TAG #     // every spelling of a duplicated top-level key, same value or not
TAG #     for (k, v) in [("facts", "{}"), ("conditions", "{}"), ("scope", "{}")] {
TAG #         for esc in [k.to_string(), format!("\\u{:04x}{}", k.as_bytes()[0], &k[1..]), format!("{}\\u{:04x}", &k[..k.len() - 1], k.as_bytes()[k.len() - 1])] {
TAG #             let doc = format!("{{\"check\":{{\"schema\":\"instinct.check/v1\",\"id\":\"t1\",\"revision\":1,\"inputs\":{{\"a\":\"bool\"}},\"claim\":{{\"op\":\"eq\",\"left\":{{\"fact\":\"a\"}},\"right\":{{\"fact\":\"a\"}}}}}},\"{k}\":{v},\"{esc}\":{v}}}");
TAG #             all_err_s(&env, &doc, &format!("top-level {k} as {esc}"));
TAG #         }
TAG #     }
TAG #     // Unicode: the escaped and literal spellings of one key collide, in any object
TAG #     for (a, b) in [
TAG #         ("\\u00e9", "\u{e9}"),
TAG #         ("\\u00E9", "\\u00e9"),
TAG #         ("\\ud83d\\ude00", "\u{1F600}"),
TAG #         ("\\ud83d\\ude00", "\\uD83D\\uDE00"),
TAG #         ("a\\/b", "a/b"),
TAG #         ("\\u0041", "A"),
TAG #         ("\\u00e9\\u0301", "\u{e9}\\u0301"),
TAG #         ("\\u0000", "\\u0000"),
TAG #     ] {
TAG #         let doc = d(&format!("{{\"{a}\":\"string\",\"{b}\":\"string\"}}"), &op2("eq", "x", "x")).json();
TAG #         all_err_s(&env, &doc, &format!("inputs {a} / {b}"));
TAG #         let doc = d("{\"s\":\"string\"}", &op2("eq", "s", "s")).facts(&format!("{{\"s\":\"v\",\"{a}\":\"v\",\"{b}\":\"v\"}}")).json();
TAG #         all_err_s(&env, &doc, &format!("facts {a} / {b}"));
TAG #         let doc = d("{\"s\":\"string\"}", &op2("eq", "s", "s")).dscope(&format!("{{\"{a}\":\"v\",\"{b}\":\"v\"}}")).json();
TAG #         all_err_s(&env, &doc, &format!("scope {a} / {b}"));
TAG #     }
TAG #     // keys that differ only by case or by an extra character are different keys
TAG #     let two = d("{\"e\":\"string\",\"E\":\"string\",\"ee\":\"string\",\"e\\u0045\":\"string\"}", &op2("eq", "e", "E"))
TAG #         .facts("{\"e\":\"3\",\"E\":\"3\",\"ee\":\"1\"}")
TAG #         .json();
TAG #     assert_eq!(verdict(&env.run("run", &two)), "pass");
TAG # }
TAG # #[test]
TAG # fn malformed_numbers_anywhere_are_errors() {
TAG #     let env = Env::new("numbers");
TAG #     for n in [
TAG #         "01", "00", "-01", "1.", ".5", "-.5", "1.e3", "1e", "1e+", "1e-", "+1", "-", "--1", "0x1", "1_0", "1,0", "Infinity", "-Infinity", "NaN",
TAG #         "1.0.0", "1e1e1", "٣", "1 1", "0123", "1E", "- 1", "1d", "0b1", "0o7", "1f", "1L", "0.0.0", "1e0.5",
TAG #     ] {
TAG #         for place in [
TAG #             BASE.replacen("\"revision\":1", &format!("\"revision\":{n}"), 1),
TAG #             d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts(&format!("{{\"a\":{n}}}")).json(),
TAG #             d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts(&format!("{{\"a\":true,\"zz\":[{n}]}}")).json(),
TAG #             format!("{{\"check\":{{}},\"x\":{n}}}"),
TAG #             d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).json().replacen("\"check\":{", &format!("\"x\":{n},\"check\":{{"), 1),
TAG #         ] {
TAG #             all_err_s(&env, &place, &format!("number {n}"));
TAG #         }
TAG #     }
TAG #     for n in ["1e999999", "1e-999999", "123456789012345678901234567890e5", "-1e400", "1E+400", "9".repeat(5000).as_str()] {
TAG #         all_err_s(&env, &BASE.replacen("\"revision\":1", &format!("\"revision\":{n}"), 1), n);
TAG #     }
TAG # }
TAG # #[test]
TAG # fn json_nesting_beyond_64_is_an_error_and_deep_input_does_not_crash() {
TAG #     let env = Env::new("nesting");
TAG #     let head = "{\"check\":{\"schema\":\"instinct.check/v1\",\"id\":\"t1\",\"revision\":1,\"inputs\":{\"a\":\"bool\"},\"claim\":{\"op\":\"eq\",\"left\":{\"fact\":\"a\"},\"right\":{\"fact\":\"a\"}}},\"facts\":{\"a\":";
TAG #     for n in [65usize, 70, 100, 1000, 100_000, 500_000] {
TAG #         for (open, close) in [("[", "]"), ("{\"k\":", "}")] {
TAG #             let doc = format!("{head}{}true{}}}}}", open.repeat(n), close.repeat(n));
TAG #             if doc.len() > 1_048_576 {
TAG #                 continue;
TAG #             }
TAG #             for sub in ["run", "validate"] {
TAG #                 let o = env.run(sub, &doc);
TAG #                 assert!(o.code.is_some(), "deep input killed the process by signal (nesting {n} {open}): stderr={}", trunc(&String::from_utf8_lossy(&o.err)));
TAG #                 err(&o, &format!("{sub} nesting {n} {open}"));
TAG #             }
TAG #         }
TAG #     }
TAG #     // nesting inside the claim is bounded the same way (and the claim depth limit)
TAG #     let mut claim = op2("eq", "a", "a");
TAG #     for _ in 0..70 {
TAG #         claim = not_of(&claim);
TAG #     }
TAG #     all_err_s(&env, &d("{\"a\":\"bool\"}", &claim).facts("{\"a\":true}").json(), "70 nested not");
TAG #     // nesting inside inputs
TAG #     let nested = format!("{}{}", "[".repeat(80), "]".repeat(80));
TAG #     all_err_s(&env, &d(&format!("{{\"a\":{nested}}}"), &op2("eq", "a", "a")).json(), "deep inputs");
TAG # }
TAG # #[test]
TAG # fn input_is_limited_to_one_mebibyte_from_stdin_and_from_files() {
TAG #     let env = Env::new("size");
TAG #     let limit = 1_048_576usize;
TAG #     let mut exact = BASE.as_bytes().to_vec();
TAG #     exact.resize(limit, b' ');
TAG #     assert_eq!(exact.len(), limit);
TAG #     let mut over = exact.clone();
TAG #     over.push(b' ');
TAG #     let mut way_over = BASE.as_bytes().to_vec();
TAG #     way_over.resize(3 * limit, b' ');
TAG #     let ex_path = env.put("exact.json", &exact);
TAG #     let over_path = env.put("over.json", &over);
TAG #     let way_path = env.put("way.json", &way_over);
TAG #     for sub in ["validate", "run", "explain"] {
TAG #         let o = env.run_bytes(sub, &exact);
TAG #         assert_eq!(o.code, Some(0), "{sub} exactly 1 MiB: {}", trunc(&o.text()));
TAG #         let f = env.exec(&["check", sub, "--input", ex_path.to_str().unwrap()], b"");
TAG #         assert_eq!(f.out, o.out, "{sub} file == stdin at the limit");
TAG #         err(&env.run_bytes(sub, &over), &format!("{sub} stdin 1 MiB + 1"));
TAG #         err(&env.exec(&["check", sub, "--input", over_path.to_str().unwrap()], b""), &format!("{sub} file 1 MiB + 1"));
TAG #         err(&env.run_bytes(sub, &way_over), &format!("{sub} stdin 3 MiB"));
TAG #         err(&env.exec(&["check", sub, "--input", way_path.to_str().unwrap()], b""), &format!("{sub} file 3 MiB"));
TAG #     }
TAG #     // oversized garbage is an error, not a hang or crash
TAG #     let junk = vec![b'x'; 8 * limit];
TAG #     err(&env.run_bytes("run", &junk), "8 MiB of junk");
TAG #     // an over-limit document whose first MiB is valid is still an error
TAG #     let mut tail = BASE.as_bytes().to_vec();
TAG #     tail.resize(limit, b' ');
TAG #     tail.extend_from_slice(b"{}");
TAG #     err(&env.run_bytes("run", &tail), "valid prefix, junk after the limit");
TAG # }
TAG # // ---------------------------------------------------------------- structural, fuel and output limits
TAG # #[test]
TAG # fn claim_depth_and_node_limits_are_enforced_before_evaluation() {
TAG #     let env = Env::new("claimlimits");
TAG #     let ins = "{\"a\":\"bool\"}";
TAG #     let leaf = op2("eq", "a", "a");
TAG #     // within limits
TAG #     for k in [0usize, 1, 10, 20, 30] {
TAG #         let mut claim = leaf.clone();
TAG #         for _ in 0..k {
TAG #             claim = not_of(&claim);
TAG #         }
TAG #         let want = if k % 2 == 0 { "pass" } else { "fail" };
TAG #         assert_eq!(verdict(&env.run("run", &d(ins, &claim).facts("{\"a\":true}").json())), want, "not^{k}");
TAG #     }
TAG #     let mut nest = leaf.clone();
TAG #     for _ in 0..20 {
TAG #         nest = all_of(&[nest]);
TAG #     }
TAG #     assert_eq!(verdict(&env.run("run", &d(ins, &nest).facts("{\"a\":true}").json())), "pass");
TAG #     // too deep
TAG #     for k in [40usize, 50, 60] {
TAG #         let mut claim = leaf.clone();
TAG #         for _ in 0..k {
TAG #             claim = not_of(&claim);
TAG #         }
TAG #         all_err_s(&env, &d(ins, &claim).facts("{\"a\":true}").json(), &format!("not^{k}"));
TAG #         let mut claim = leaf.clone();
TAG #         for _ in 0..k {
TAG #             claim = any_of(&[claim]);
TAG #         }
TAG #         all_err_s(&env, &d(ins, &claim).facts("{\"a\":true}").json(), &format!("any^{k}"));
TAG #     }
TAG #     // many nodes, shallow
TAG #     let leaves = |n: usize| (0..n).map(|_| leaf.clone()).collect::<Vec<_>>();
TAG #     assert_eq!(verdict(&env.run("run", &d(ins, &all_of(&leaves(1000))).facts("{\"a\":true}").json())), "pass");
TAG #     assert_eq!(verdict(&env.run("run", &d(ins, &any_of(&leaves(1000))).facts("{\"a\":true}").json())), "pass");
TAG #     for n in [4200usize, 5000, 9000] {
TAG #         all_err_s(&env, &d(ins, &all_of(&leaves(n))).facts("{\"a\":true}").json(), &format!("all of {n} leaves"));
TAG #         all_err_s(&env, &d(ins, &any_of(&leaves(n))).facts("{\"a\":true}").json(), &format!("any of {n} leaves"));
TAG #     }
TAG #     let groups: Vec<String> = (0..100).map(|_| all_of(&leaves(50))).collect();
TAG #     all_err_s(&env, &d(ins, &all_of(&groups)).facts("{\"a\":true}").json(), "100 groups of 50");
TAG # }
TAG # #[test]
TAG # fn oversized_fact_sets_are_bounded_not_passed() {
TAG #     let env = Env::new("factlimits");
TAG #     // within the limit
TAG #     let big = many(4000, "m");
TAG #     assert_eq!(verdict(&env.run("run", &set_doc("subset", &big, &big))), "pass");
TAG #     valid(&env, &set_doc("subset", &big, &big), "4000 members");
TAG #     // beyond 10000 members in aggregate: bounded outcome, never a pass or a crash
TAG #     for (l, r) in [(many(10_500, "m"), "[]".to_string()), (many(6000, "l"), many(6000, "r")), (many(20_000, "m"), many(20_000, "m"))] {
TAG #         let doc = set_doc("subset", &l, &r);
TAG #         for sub in ["run", "validate", "explain"] {
TAG #             let o = env.run_bytes(sub, doc.as_bytes());
TAG #             match o.code {
TAG #                 Some(2) => err(&o, &format!("{sub} oversized facts")),
TAG #                 Some(0) => {
TAG #                     let j = obj(&o);
TAG #                     if sub == "validate" {
TAG #                         panic!("validation accepted facts over the aggregate limit: {}", trunc(&o.text()));
TAG #                     }
TAG #                     assert_eq!(sf(&j, "verdict"), "abstain", "{sub} oversized facts must abstain, got {}", trunc(&o.text()));
TAG #                     assert!(o.out.len() <= 65_537);
TAG #                 }
TAG #                 other => panic!("{sub} oversized facts: unexpected exit {other:?}"),
TAG #             }
TAG #         }
TAG #     }
TAG #     // beyond 10000 entries: many declared scalar facts
TAG #     let n = 10_600;
TAG #     let inputs = format!("{{{}}}", (0..n).map(|i| format!("\"f{i}\":\"bool\"")).collect::<Vec<_>>().join(","));
TAG #     let facts = format!("{{{}}}", (0..n).map(|i| format!("\"f{i}\":true")).collect::<Vec<_>>().join(","));
TAG #     let doc = d(&inputs, &op2("eq", "f0", "f1")).facts(&facts).json();
TAG #     for sub in ["run", "explain"] {
TAG #         let o = env.run(sub, &doc);
TAG #         match o.code {
TAG #             Some(2) => err(&o, "entries over limit"),
TAG #             Some(0) => assert_eq!(sf(&obj(&o), "verdict"), "abstain", "entries over limit must not pass"),
TAG #             other => panic!("unexpected exit {other:?}"),
TAG #         }
TAG #     }
TAG # }
TAG # #[test]
TAG # fn fuel_exhaustion_abstains_and_never_reports_partial_evaluation_as_pass() {
TAG #     let env = Env::new("fuel");
TAG #     let n = 4900;
TAG #     let left = many(n, "m");
TAG #     let mut rev: Vec<String> = (0..n).map(|i| format!("\"m{i:05}\"")).collect();
TAG #     rev.reverse();
TAG #     let right = format!("[{}]", rev.join(","));
TAG #     let sub = op2("subset", "actual", "allowed");
TAG #     let facts = format!("{{\"actual\":{left},\"allowed\":{right}}}");
TAG #     // a single pass over this input is cheap and true
TAG #     assert_eq!(verdict(&env.run("run", &d(SET_IN, &sub).facts(&facts).json())), "pass");
TAG #     // thirty full scans cost at least 30 * 4900 charged operations: over the 100000 budget
TAG #     let heavy = all_of(&(0..30).map(|_| sub.clone()).collect::<Vec<_>>());
TAG #     for s in ["run", "explain"] {
TAG #         let o = env.run(s, &d(SET_IN, &heavy).facts(&facts).json());
TAG #         let j = result(&o);
TAG #         assert_eq!(sf(&j, "verdict"), "abstain", "{s}: fuel exhaustion must abstain: {}", trunc(&o.text()));
TAG #         assert_eq!(j.get("witness"), Some(&J::Null));
TAG #         assert!(o.out.len() <= 65_537);
TAG #     }
TAG #     // negation, nesting and any must not turn the exhausted evaluation into a pass or a fail
TAG #     for claim in [not_of(&heavy), all_of(&[heavy.clone()]), not_of(&not_of(&heavy)), all_of(&[heavy.clone(), heavy.clone()])] {
TAG #         let v = verdict(&env.run("run", &d(SET_IN, &claim).facts(&facts).json()));
TAG #         assert_eq!(v, "abstain", "exhaustion under a wrapper");
TAG #     }
TAG #     // validation never spends the fuel
TAG #     valid(&env, &d(SET_IN, &heavy).facts(&facts).json(), "heavy claim validates");
TAG #     // a definition that cannot be evaluated cheaply still reports where it was declared
TAG #     let j = result(&env.run("run", &d(SET_IN, &heavy).id("\"burner\"").rev("7").facts(&facts).json()));
TAG #     assert_eq!(sf(&j, "check_id"), "burner");
TAG #     assert_eq!(j.get("revision"), Some(&J::Num("7".into())));
TAG # }
TAG # #[test]
TAG # fn witnesses_and_errors_are_bounded_to_64_kib() {
TAG #     let env = Env::new("bounded");
TAG #     // a witness that cannot fit in 64 KiB is a bounded explicit error, never a truncated or substituted witness
TAG #     for n in [100_000usize, 300_000] {
TAG #         let huge = "x".repeat(n);
TAG #         for sub in ["run", "explain"] {
TAG #             for doc in [
TAG #                 set_doc("subset", &format!("[\"{huge}\"]"), "[]"),
TAG #                 set_doc("disjoint", &format!("[\"{huge}\"]"), &format!("[\"{huge}\"]")),
TAG #             ] {
TAG #                 err(&env.run(sub, &doc), &format!("{sub} {n}-byte witness"));
TAG #             }
TAG #         }
TAG #     }
TAG #     let wide = "\u{1F600}".repeat(60_000);
TAG #     err(&env.run("run", &set_doc("subset", &format!("[\"{wide}\"]"), "[]")), "240000-byte multibyte witness");
TAG #     // an error never echoes the request
TAG #     let long_key = "k".repeat(300_000);
TAG #     let docs = [
TAG #         BASE.replacen("\"facts\":{", &format!("\"facts\":{{\"{long_key}\":1,"), 1),
TAG #         BASE.replacen("\"id\":\"artifact-membership\"", &format!("\"id\":\"{long_key}\""), 1),
TAG #         BASE.replacen("\"op\":\"subset\"", &format!("\"op\":\"{long_key}\""), 1),
TAG #         BASE.replacen("\"actual\":\"set<string>\"", &format!("\"actual\":\"{long_key}\""), 1),
TAG #         BASE.replacen("\"project\":\"release-lab\"}},", &format!("\"{long_key}\":\"x\"}},"), 1),
TAG #         format!("{{\"{long_key}\":1}}"),
TAG #         BASE.replacen("\"complete-inventory\":true", &format!("\"{long_key}\":true"), 1),
TAG #         set_doc("subset", &format!("[\"{long_key}\",\"{long_key}\"]"), "[]"),
TAG #         set_doc("subset", &format!("[1,\"{long_key}\"]"), "[]"),
TAG #     ];
TAG #     for doc in &docs {
TAG #         for sub in ["run", "validate", "explain"] {
TAG #             let o = env.run(sub, doc);
TAG #             err(&o, &format!("{sub} long-key error"));
TAG #             assert!(!o.text().contains(&"k".repeat(1000)), "{sub}: the error repeated the request");
TAG #         }
TAG #     }
TAG # }
TAG # // ---------------------------------------------------------------- CLI
TAG # #[test]
TAG # fn cli_argument_mistakes_are_errors_and_have_no_side_effects() {
TAG #     let env = Env::new("cliargs");
TAG #     let f = env.put("good.json", BASE.as_bytes());
TAG #     let f = f.to_str().unwrap();
TAG #     let rows: Vec<Vec<&str>> = vec![
TAG #         vec!["check", "frob"],
TAG #         vec!["check", "RUN", "--input", f],
TAG #         vec!["check", "Run", "--input", f],
TAG #         vec!["check", "", "--input", f],
TAG #         vec!["check", "--input", f],
TAG #         vec!["check", "-"],
TAG #         vec!["check", f],
TAG #         vec!["check", "run"],
TAG #         vec!["check", "validate"],
TAG #         vec!["check", "explain"],
TAG #         vec!["check", "run", "--input"],
TAG #         vec!["check", "validate", "--input"],
TAG #         vec!["check", "explain", "--input"],
TAG #         vec!["check", "run", "--input", f, "--input", f],
TAG #         vec!["check", "validate", "--input", f, "--input", f],
TAG #         vec!["check", "explain", "--input", f, "--input", f],
TAG #         vec!["check", "run", "--input", "-", "--input", "-"],
TAG #         vec!["check", "run", "--input", f, "--input", "-"],
TAG #         vec!["check", "run", "--input", "-", "--input", f],
TAG #         vec!["check", "run", "--input", f, "extra"],
TAG #         vec!["check", "run", "extra", "--input", f],
TAG #         vec!["check", "run", f],
TAG #         vec!["check", "run", "-"],
TAG #         vec!["check", "validate", "--input", f, "run"],
TAG #         vec!["check", "run", "run", "--input", f],
TAG #         vec!["check", "run", "--input", f, "--input"],
TAG #         vec!["check", "run", "--bogus"],
TAG #         vec!["check", "run", "--bogus", "--input", f],
TAG #         vec!["check", "run", "--input", f, "--bogus"],
TAG #         vec!["check", "run", "--input", f, "--bogus=1"],
TAG #         vec!["check", "run", "-i", f],
TAG #         vec!["check", "run", "-input", f],
TAG #         vec!["check", "run", "--Input", f],
TAG #         vec!["check", "run", "--INPUT", f],
TAG #         vec!["check", "run", "--inputs", f],
TAG #         vec!["check", "run", "--in", f],
TAG #         vec!["check", "run", "--file", f],
TAG #         vec!["check", "run", "--json", "--input", f],
TAG #         vec!["check", "run", "--input", f, "--json"],
TAG #         vec!["check", "run", "--verbose", "--input", f],
TAG #         vec!["check", "run", "--store", f, "--input", f],
TAG #         vec!["check", "validate", "--bogus"],
TAG #         vec!["check", "explain", "--bogus"],
TAG #         vec!["check", "explain", "--input", f, "-x"],
TAG #         vec!["check", "run", "--"],
TAG #         vec!["check", "run", "--", "--input", f],
TAG #         vec!["check", "run", "--input", "--input", f],
TAG #         vec!["check", "run", "--input", f, "--help", "--help"],
TAG #     ];
TAG #     for row in &rows {
TAG #         let o = env.exec(row, BASE.as_bytes());
TAG #         if row == &vec!["check", "-"] || row == &vec!["check", f] {
TAG #             assert_ne!(o.code, Some(0), "{row:?}");
TAG #             continue;
TAG #         }
TAG #         err(&o, &format!("{row:?}"));
TAG #     }
TAG #     // a bare `check` is not a success either
TAG #     let o = env.exec(&["check"], BASE.as_bytes());
TAG #     assert_ne!(o.code, Some(0), "bare `check`");
TAG #     assert!(!o.text().contains("\"pass\""));
TAG # }
TAG # #[test]
TAG # fn help_is_explicit_and_side_effect_free() {
TAG #     let env = Env::new("help");
TAG #     let f = env.put("good.json", BASE.as_bytes());
TAG #     let f = f.to_str().unwrap();
TAG #     for args in [
TAG #         vec!["check", "--help"],
TAG #         vec!["check", "-h"],
TAG #     ] {
TAG #         let o = env.exec(&args, b"");
TAG #         if args.contains(&"-h") {
TAG #             // -h is not promised by the contract; it must at least not run a check
TAG #             assert!(!o.text().contains("\"verdict\":\"pass\""), "{args:?}");
TAG #             continue;
TAG #         }
TAG #         assert_eq!(o.code, Some(0), "{args:?}: {}", trunc(&String::from_utf8_lossy(&o.err)));
TAG #         let all = format!("{}{}", o.text(), String::from_utf8_lossy(&o.err));
TAG #         assert!(all.contains("--input"), "{args:?}: help must describe --input: {}", trunc(&all));
TAG #         assert!(!o.text().contains("check-error") && !o.text().contains("check-result"), "{args:?}");
TAG #         assert!(!all.trim().is_empty());
TAG #     }
TAG #     // `--help` is explicit: it does not read stdin or the named file
TAG #     let o = env.exec(&["check", "--help"], BASE.as_bytes());
TAG #     assert_eq!(o.code, Some(0));
TAG #     assert!(!o.text().contains("artifact-membership"));
TAG #     let o = env.exec(&["check", "--help", "--input", f], b"");
TAG #     assert!(!o.text().contains("check-result"), "help must not run the check");
TAG # }
TAG # // docs/checks.md says "`--help` is explicit" without saying whether it is per subcommand; a subcommand
TAG # // asked for help should explain itself, not fail as a bad argument.
TAG # #[test]
TAG # fn subcommand_help_is_explicit_and_side_effect_free() {
TAG #     let env = Env::new("subhelp");
TAG #     for sub in ["run", "validate", "explain"] {
TAG #         let o = env.exec(&["check", sub, "--help"], BASE.as_bytes());
TAG #         assert_eq!(o.code, Some(0), "check {sub} --help: {}", trunc(&o.text()));
TAG #         let all = format!("{}{}", o.text(), String::from_utf8_lossy(&o.err));
TAG #         assert!(all.contains("--input"), "check {sub} --help must describe --input: {}", trunc(&all));
TAG #         assert!(!o.text().contains("check-error") && !o.text().contains("check-result"));
TAG #     }
TAG # }
TAG # #[test]
TAG # fn a_successful_check_writes_one_json_object_and_nothing_before_it() {
TAG #     let env = Env::new("stdout");
TAG #     for sub in ["run", "validate", "explain"] {
TAG #         for doc in [BASE.to_string(), mutate("\"revision\":1", "\"revision\":0")] {
TAG #             let o = env.run(sub, &doc);
TAG #             let t = o.text();
TAG #             assert!(t.starts_with('{'), "{sub}: stdout must begin with the JSON object: {}", trunc(&t));
TAG #             assert!(parse_json(t.trim()).is_ok(), "{sub}: stdout is exactly one JSON value: {}", trunc(&t));
TAG #             assert!(!t.trim().contains("\n\n\n"), "{sub}");
TAG #         }
TAG #     }
TAG # }
TAG # // ---------------------------------------------------------------- no bank, no environment, no side effects
TAG # #[test]
TAG # fn no_bank_is_opened_or_created_and_a_corrupt_bank_is_untouched() {
TAG #     let env = Env::new("nobank");
TAG #     assert!(!env.bank().exists());
TAG #     for sub in ["run", "validate", "explain"] {
TAG #         let o = env.run(sub, BASE);
TAG #         assert_eq!(o.code, Some(0), "{sub}");
TAG #     }
TAG #     assert!(!env.bank().exists(), "check must not create a bank");
TAG #     assert!(!env.bank().parent().unwrap().exists(), "check must not create the bank folder");
TAG #     // the exec wrapper compares the whole tree, so anything new anywhere would already have failed above
TAG #     std::fs::create_dir_all(env.bank().parent().unwrap()).unwrap();
TAG #     std::fs::write(env.bank(), b"\xff\xfenot a bank at all\n{{{").unwrap();
TAG #     let a = env.run("run", BASE);
TAG #     let b = env.run("validate", BASE);
TAG #     assert_eq!(a.code, Some(0));
TAG #     assert_eq!(b.code, Some(0));
TAG #     assert_eq!(std::fs::read(env.bank()).unwrap(), b"\xff\xfenot a bank at all\n{{{");
TAG #     // a store override that points nowhere usable changes nothing
TAG #     let missing = env.root.join("elsewhere").join("deep").join("bank.hxdb");
TAG #     let blocked = env.put("blocker", b"i am a file");
TAG #     let blocked_store = blocked.join("bank.hxdb");
TAG #     let clean = env.run("run", BASE).out;
TAG #     for store in [missing.to_str().unwrap(), blocked_store.to_str().unwrap(), "", "/nonexistent-root-dir/bank.hxdb"] {
TAG #         for sub in ["run", "validate", "explain"] {
TAG #             let o = env.exec_env(&["check", sub, "--input", "-"], BASE.as_bytes(), &[("INSTINCT_STORE", store)]);
TAG #             assert_eq!(o.code, Some(0), "{sub} with store {store:?}: {}", trunc(&o.text()));
TAG #             if sub == "run" {
TAG #                 assert_eq!(o.out, clean, "store {store:?}");
TAG #             }
TAG #         }
TAG #     }
TAG #     assert!(!missing.exists() && !missing.parent().unwrap().exists());
TAG #     // even failures leave the machine alone
TAG #     err(&env.run("run", "{"), "bad json");
TAG #     assert!(!missing.exists());
TAG # }
TAG # #[test]
TAG # fn the_environment_never_supplies_scope_or_changes_results() {
TAG #     let env = Env::new("envscope");
TAG #     let envs = [
TAG #         ("INSTINCT_PROJECT", "release-lab"),
TAG #         ("INSTINCT_PERSONA", "p"),
TAG #         ("INSTINCT_HARNESS", "h"),
TAG #         ("INSTINCT_HARNESS_VERSION", "1"),
TAG #         ("INSTINCT_MACHINE", "m"),
TAG #         ("INSTINCT_SESSION", "s"),
TAG #         ("INSTINCT_EXPLORE", "1"),
TAG #         ("INSTINCT_METER", "1"),
TAG #         ("CLAUDE_PROJECT_DIR", "release-lab"),
TAG #         ("PROJECT", "release-lab"),
TAG #         ("HOSTNAME", "m"),
TAG #     ];
TAG #     let ins = "{\"one\":\"bool\",\"zero\":\"bool\"}";
TAG #     let doc = d(ins, &op2("eq", "one", "zero")).facts("{\"one\":true,\"zero\":false}").dscope("{\"project\":\"release-lab\",\"machine\":\"m\",\"persona\":\"p\"}").json();
TAG #     for sub in ["run", "explain"] {
TAG #         let plain = env.run(sub, &doc);
TAG #         let with = env.exec_env(&["check", sub, "--input", "-"], doc.as_bytes(), &envs);
TAG #         let j = result(&with);
TAG #         assert_eq!(sf(&j, "verdict"), "abstain", "{sub}: the environment must not satisfy a required scope");
TAG #         assert_eq!(pairs(j.get("scope").unwrap()), vec![]);
TAG #         assert_eq!(plain.out, with.out, "{sub}: environment changed the output");
TAG #     }
TAG #     // the working directory name is not a scope either
TAG #     let sub_cwd = env.root.join("cwd");
TAG #     assert!(sub_cwd.exists());
TAG #     let j = result(&env.run("run", &doc));
TAG #     assert_eq!(sf(&j, "verdict"), "abstain");
TAG #     // the opposite direction: the explicit request scope is what counts, whatever the environment says
TAG #     let doc = d(ins, &op2("eq", "one", "zero")).facts("{\"one\":true,\"zero\":false}").dscope("{\"project\":\"release-lab\"}").scope("{\"project\":\"release-lab\"}").json();
TAG #     let o = env.exec_env(&["check", "run", "--input", "-"], doc.as_bytes(), &[("INSTINCT_PROJECT", "something-else")]);
TAG #     assert_eq!(verdict(&o), "fail");
TAG # }
TAG # #[test]
TAG # fn nothing_in_the_input_is_executed_read_or_followed() {
TAG #     let env = Env::new("inert");
TAG #     let marker = env.root.join("home").join("pwned");
TAG #     let marker_s = marker.to_str().unwrap().to_string();
TAG #     let hostile = [
TAG #         format!("$(touch {marker_s})"),
TAG #         format!("`touch {marker_s}`"),
TAG #         format!("; touch {marker_s}"),
TAG #         "../../../../etc/passwd".to_string(),
TAG #         "/etc/shadow".to_string(),
TAG #         "file:///etc/passwd".to_string(),
TAG #         "http://127.0.0.1:1/x".to_string(),
TAG #         "-rf /".to_string(),
TAG #         "%n%n%n%s%s".to_string(),
TAG #         "{{7*7}}".to_string(),
TAG #     ];
TAG #     for h in hostile {
TAG #         let esc = h.replace('\\', "\\\\").replace('"', "\\\"");
TAG #         let ins = "{\"p\":\"string\",\"q\":\"string\",\"x\":\"set<string>\"}";
TAG #         let claim = all_of(&[op2("eq", "p", "q"), op2("contains", "x", "p")]);
TAG #         let doc = d(ins, &claim)
TAG #             .facts(&format!("{{\"p\":\"{esc}\",\"q\":\"{esc}\",\"x\":[\"{esc}\"]}}"))
TAG #             .dscope(&format!("{{\"project\":\"{esc}\"}}"))
TAG #             .scope(&format!("{{\"project\":\"{esc}\"}}"))
TAG #             .json();
TAG #         for sub in ["run", "validate", "explain"] {
TAG #             let o = env.run(sub, &doc);
TAG #             assert_eq!(o.code, Some(0), "{sub} {h}");
TAG #         }
TAG #         assert_eq!(verdict(&env.run("run", &doc)), "pass", "{h}");
TAG #         assert!(!marker.exists(), "input text was executed: {h}");
TAG #     }
TAG #     // host paths in facts are plain strings, not access grants and not read
TAG #     let doc = d("{\"p\":\"string\"}", &op2("eq", "p", "p")).facts("{\"p\":\"/etc/passwd\"}").json();
TAG #     assert_eq!(verdict(&env.run("run", &doc)), "pass");
TAG # }
TAG # #[test]
TAG # fn authorization_is_never_evaluated_and_evidence_is_always_caller_reported() {
TAG #     let env = Env::new("authz");
TAG #     let cases = [
TAG #         BASE.to_string(),
TAG #         mutate("\"complete-inventory\":true", "\"complete-inventory\":false"),
TAG #         mutate("\"allowed\":[\"release.bin\"]", "\"allowed\":[\"scratch.env\",\"release.bin\"]"),
TAG #         d(SET_IN, &op2("subset", "actual", "allowed")).json(),
TAG #     ];
TAG #     for doc in cases {
TAG #         for sub in ["run", "explain"] {
TAG #             let o = env.run(sub, &doc);
TAG #             let j = result(&o);
TAG #             assert_eq!(sf(&j, "authorization"), "not_evaluated");
TAG #             assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
TAG #         }
TAG #         let o = env.run("validate", &doc);
TAG #         assert_eq!(sf(&obj(&o), "authorization"), "not_evaluated");
TAG #     }
TAG #     // a condition that says true is still only a caller report
TAG #     let j = result(&env.run("run", BASE));
TAG #     assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
TAG #     for bad in [
TAG #         mutate("\"id\":\"artifact-membership\"", "\"id\":\"0bad\""),
TAG #         "{".to_string(),
TAG #         mutate("\"op\":\"subset\"", "\"op\":\"zzz\""),
TAG #     ] {
TAG #         let o = env.run("run", &bad);
TAG #         err(&o, "error shape");
TAG #         assert_eq!(sf(&obj(&o), "authorization"), "not_evaluated");
TAG #     }
TAG # }
TAG # // docs/checks.md bounds witness/explanation output at 64 KiB and calls the result scope "explicit current scope".
TAG # // Ordinary scope values (up to 20,000 characters) must be echoed exactly. Past the output bound, a bounded structured
TAG # // error is acceptable (docs clarification); a success must echo the scope exactly and the JSON text must stay within
TAG # // 65536 bytes (stdout within 65537 with the CLI newline). Silent truncation or an empty scope is never acceptable.
TAG # #[test]
TAG # fn a_huge_request_scope_value_is_rejected_or_echoed_exactly_never_truncated_or_unbounded() {
TAG #     let env = Env::new("hugescope");
TAG #     let ins = "{\"a\":\"bool\"}";
TAG #     let mk = |n: usize| {
TAG #         let v = "p".repeat(n);
TAG #         (d(ins, &op2("eq", "a", "a")).facts("{\"a\":true}").scope(&format!("{{\"project\":\"{v}\"}}")).json(), v)
TAG #     };
TAG #     // ordinary sizes: success with an exact echo is required, not an arbitrary rejection
TAG #     for n in [1usize, 1_000, 20_000, 60_000] {
TAG #         let (doc, v) = mk(n);
TAG #         for sub in ["run", "explain"] {
TAG #             let o = env.run(sub, &doc);
TAG #             let j = result(&o);
TAG #             assert_eq!(sf(&j, "verdict"), "pass", "{sub} scope {n}");
TAG #             assert_eq!(pairs(j.get("scope").unwrap()), vec![("project".to_string(), v.clone())], "{sub}: scope {n} must echo exactly");
TAG #             assert!(o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537, "{sub}: scope {n} produced {} bytes", o.out.len());
TAG #         }
TAG #         valid(&env, &doc, &format!("validate scope {n}"));
TAG #     }
TAG #     // around the 64 KiB boundary and far beyond it: error, or an exact in-bound echo
TAG #     for n in [64_000usize, 65_000, 65_300, 65_500, 65_536, 65_537, 66_000, 70_000, 90_000, 300_000] {
TAG #         let (doc, v) = mk(n);
TAG #         for sub in ["run", "explain", "validate"] {
TAG #             let o = env.run(sub, &doc);
TAG #             match o.code {
TAG #                 Some(2) => err(&o, &format!("{sub} scope {n}")),
TAG #                 Some(0) => {
TAG #                     assert!(o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537, "{sub}: {n}-char scope produced {} bytes", o.out.len());
TAG #                     if sub != "validate" {
TAG #                         let j = result(&o);
TAG #                         assert_eq!(pairs(j.get("scope").unwrap()), vec![("project".to_string(), v.clone())], "{sub}: scope {n} must not be truncated");
TAG #                     }
TAG #                 }
TAG #                 other => panic!("{sub}: unexpected exit {other:?}"),
TAG #             }
TAG #         }
TAG #     }
TAG #     // a definition-side huge scope value is bounded the same way
TAG #     for n in [20_000usize, 90_000] {
TAG #         let v = "q".repeat(n);
TAG #         let doc = d(ins, &op2("eq", "a", "a")).facts("{\"a\":true}").dscope(&format!("{{\"project\":\"{v}\"}}")).scope(&format!("{{\"project\":\"{v}\"}}")).json();
TAG #         for sub in ["run", "explain"] {
TAG #             let o = env.run(sub, &doc);
TAG #             match o.code {
TAG #                 Some(2) => err(&o, &format!("{sub} definition scope {n}")),
TAG #                 Some(0) => assert!(o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537, "{sub}: definition scope {n} produced {} bytes", o.out.len()),
TAG #                 other => panic!("{sub}: unexpected exit {other:?}"),
TAG #             }
TAG #         }
TAG #     }
TAG # }
TAG # fn pattern(n: usize) -> String {
TAG #     // non-uniform, so truncation, padding or substitution is detectable
TAG #     let mut s: String = (0..n).map(|i| (b'a' + (i * 7 % 26) as u8) as char).collect();
TAG #     if n > 0 {
TAG #         s.replace_range(n - 1..n, "Z");
TAG #     }
TAG #     s
TAG # }
TAG # #[test]
TAG # fn witnesses_that_fit_64_kib_are_echoed_exactly() {
TAG #     let env = Env::new("witness-exact");
TAG #     for n in [1usize, 100, 1_000, 4_096, 4_110, 4_111, 5_000, 8_192, 20_000, 60_000] {
TAG #         let m = pattern(n);
TAG #         for sub in ["run", "explain"] {
TAG #             let o = env.run(sub, &set_doc("subset", &format!("[\"{m}\"]"), "[]"));
TAG #             let j = result(&o);
TAG #             assert_eq!(sf(&j, "verdict"), "fail", "{sub} {n}");
TAG #             assert_eq!(j.get("witness"), Some(&J::Str(m.clone())), "{sub}: {n}-char witness must be exact");
TAG #             let o = env.run(sub, &set_doc("disjoint", &format!("[\"{m}\",\"zz\"]"), &format!("[\"{m}\"]")));
TAG #             let j = result(&o);
TAG #             assert_eq!(sf(&j, "verdict"), "fail", "{sub} {n}");
TAG #             assert_eq!(j.get("witness"), Some(&J::Str(m.clone())), "{sub}: {n}-char disjoint witness must be exact");
TAG #             assert!(o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537);
TAG #         }
TAG #     }
TAG #     // multi-byte scalars and escapes, long
TAG #     for (raw, json) in [
TAG #         ("\u{e9}".repeat(20_000) + "Z", format!("{}Z", "\\u00e9".repeat(20_000))),
TAG #         ("\u{1F600}".repeat(10_000) + "Z", format!("{}Z", "\\ud83d\\ude00".repeat(10_000))),
TAG #         ("a\"b\\c\nd\u{1}".repeat(3_000), "a\\\"b\\\\c\\nd\\u0001".repeat(3_000)),
TAG #         ("\u{e9}\u{301}\u{4e2d}".repeat(5_000), "\\u00e9\\u0301\\u4e2d".repeat(5_000)),
TAG #     ] {
TAG #         let j = result(&env.run("run", &set_doc("subset", &format!("[\"{json}\"]"), "[]")));
TAG #         assert_eq!(j.get("witness"), Some(&J::Str(raw)), "long escaped/multibyte witness");
TAG #     }
TAG #     // the lexicographically first of several long unexpected members is the one named, whole
TAG #     let (a, b) = (pattern(5_000), format!("{}!", pattern(5_000)));
TAG #     let j = result(&env.run("run", &set_doc("subset", &format!("[\"{b}\",\"{a}\"]"), "[]")));
TAG #     assert_eq!(j.get("witness"), Some(&J::Str(a.min(b))));
TAG #     // around the 64 KiB boundary: an exact in-bound witness or a bounded error, never a different witness
TAG #     for n in [64_000usize, 64_500, 65_000, 65_200, 65_400, 65_536, 65_537, 66_000] {
TAG #         let m = pattern(n);
TAG #         for sub in ["run", "explain"] {
TAG #             let o = env.run(sub, &set_doc("subset", &format!("[\"{m}\"]"), "[]"));
TAG #             match o.code {
TAG #                 Some(2) => err(&o, &format!("{sub} {n}-char witness")),
TAG #                 Some(0) => {
TAG #                     let j = result(&o);
TAG #                     assert_eq!(j.get("witness"), Some(&J::Str(m.clone())), "{sub}: {n}-char witness must be exact or an error");
TAG #                     assert!(o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537, "{sub} {n}: {} bytes", o.out.len());
TAG #                 }
TAG #                 other => panic!("unexpected exit {other:?}"),
TAG #             }
TAG #         }
TAG #     }
TAG # }