openlatch-client 0.3.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
//! Tier 1 — one shared scan table, many predicate trees. Plan 02 §2c, PRD §Field
//! vocabulary.
//!
//! # The performance design, and why 2,000 atoms fit the p99 budget
//!
//! 1. EVERY `keyword` and `prefix` leaf across EVERY artifact compiles into ONE
//!    aho-corasick automaton **at bundle load**.
//! 2. EVERY `regex_lite` leaf compiles into ONE regex-automata pattern set at
//!    bundle load — `(?-u)`, an explicit `size_limit`, validated by
//!    `regex-syntax`. (D-5: `regex`'s bytes semantics, **not** the
//!    `regex-lite` crate, which has neither a bytes API nor pattern sets.)
//! 3. Per event, each automaton runs ONCE over the scan surface.
//! 4. Each predicate tree then reads BOOLEANS out of that shared result. **A tree
//!    never touches a pattern.**
//!
//! Measured envelope: p50 66 µs / p99 183 µs at 2,000 atoms, ASCII. Unicode `\b`
//! regresses it 15×, which is why the bench carries that fixture.
//!
//! ## The scan surface is per FIELD, and it has to be
//!
//! "One pass over the scan surface" is one pass per *field a pattern leaf reads*,
//! not one pass over every string the event carries. A `keyword` leaf over
//! `result.strings` must not fire on a keyword that only ever appeared in
//! `input.strings`, so the two surfaces cannot be concatenated into one haystack.
//! [`ScanTable::scanned_fields`] is the list the bundle's own leaves produced, so
//! a bundle with three pattern fields makes three passes and a bundle with none
//! makes zero — the cost is bounded by the *bundle*, never by the vocabulary.
//!
//! ## Where the per-EVENT sharing stops today
//!
//! [`ScanTable::scan`] is called once per artifact, not once per event, because
//! [`evaluate`](super::evaluate) hands each tier `&mut EvalContext` and
//! `&ScanTable` and there is nowhere on either to hang a value derived from the
//! *event*. Caching it on the bundle would be exactly the thing
//! `ci/check-engine-purity.py` rule `global-state` forbids — retaining what is
//! derived from history rather than from inputs.
//!
//! So the sharing that matters most is already here (one automaton pass covers
//! every pattern, instead of one pass per pattern), and the remaining factor is
//! one line in the entry point: compute a [`ScanResult`] per event and call
//! [`contribution_with`] / [`evaluate_node_with`], which take one. Both are
//! public for exactly that reason.
//!
//! # The leaf field vocabulary is CLOSED
//!
//! Adding a field is a contract change against the PRD, not a code change:
//! `tool.name` · `input.<json_pointer>` · `input.strings` · `result.strings` ·
//! `result.exit_code` · `command.{program,argv,simple}` · `path.{class,value}` ·
//! `url.{host,tld,scheme,boundary}` · `effect.{verb,target_class}` ·
//! `effect.attrs.<name>` · `agent.{type,environment,function,id,principal}` ·
//! `fact.<fact_id>` · `session.{elapsed_ms,tool_calls,spend_micro_usd,tokens}`.

use std::collections::HashMap;

use aho_corasick::{AhoCorasick, AhoCorasickBuilder, MatchKind};
use regex_automata::{meta, nfa::thompson::WhichCaptures, util::syntax, Input, PatternSet};
use serde_json::Value;

use crate::generated::types::{T1Leaf, T1Node, T1PredicateTree, Verdict};

use super::bundle::{ArtifactBody, LoadedArtifact};
use super::facts;
use super::kleene::Kleene;
use super::tier2::{build, declared_mode, on_inconclusive_verdict};
use super::types::{Contribution, EvalContext};

// ── The closed vocabularies ──────────────────────────────────────────

/// Every `pred` the evaluator can read. R14 leaves the field open on the wire, so
/// an unrecognised one is caught at LOAD — where the loader skips ONE artifact —
/// rather than mid-tree, where it would cost the whole bundle its denies.
pub const KNOWN_PREDS: &[&str] = &[
    "equals",
    "in_set",
    "prefix",
    "glob",
    "keyword",
    "regex_lite",
    "tld_in",
    "int_cmp",
    "exists",
    "effect",
    "fact",
];

/// The node operators. `leaf` carries a `leaf` where the others carry `children`.
pub const KNOWN_NODE_OPS: &[&str] = &["and", "or", "not", "leaf"];

/// `pred: fact` carries its comparison one level down, in `leaf.fact.op`. As open
/// as `pred` is, so checked at load for the same reason.
pub const KNOWN_FACT_OPS: &[&str] = &["equals", "in_set", "int_cmp"];

/// The closed field vocabulary, literal members. Three families are PREFIXES and
/// are checked against [`FIELD_PREFIXES`] instead.
pub const KNOWN_FIELDS: &[&str] = &[
    "tool.name",
    "input.strings",
    "result.strings",
    "result.exit_code",
    "command.program",
    "command.argv",
    "command.simple",
    "path.class",
    "path.value",
    "url.host",
    "url.tld",
    "url.scheme",
    "url.boundary",
    "effect.verb",
    "effect.target_class",
    "agent.type",
    "agent.environment",
    "agent.function",
    "agent.id",
    "agent.principal",
    "session.elapsed_ms",
    "session.tool_calls",
    "session.spend_micro_usd",
    "session.tokens",
];

/// The three families that are prefixes rather than literals:
/// `input.<json_pointer>`, `fact.<fact_id>[.dotted.path]` and
/// `effect.attrs.<name>` (D-16).
pub const FIELD_PREFIXES: &[&str] = &["input.", "fact.", "effect.attrs."];

/// The tools whose `tool_result` carries an exit code. `result.exit_code` is
/// `null` for every other tool, and a leaf reading it there is FALSE.
pub const SHELL_TOOLS: &[&str] = &["Bash", "BashOutput", "PowerShell"];

/// The `regex_lite` **source** length cap, in bytes — **the semantic rule**.
///
/// This is the budget that is part of what the engine promises. It is what the
/// oracle enforces (`tools/zone-eval-ref/tier1.py`, `REGEX_SIZE_LIMIT = 1024`),
/// it is what the corpus recorded, and a source over it is `bad_pattern` and
/// skips its artifact.
///
/// `schemas/conformance/bundles/07-parse-regex-lite-over-the-size-limit.json`
/// settles which of the two budgets that row is about, and it is not close: its
/// pattern is **1100 bytes of source** and compiles to **35,408 bytes** of
/// program. The source cap rejects it; a 64 KiB compiled cap would have
/// *accepted* it, the artifact would have loaded, and
/// `parse-skips-regex-lite-over-the-size-limit-and-keeps-the-rest` would fail.
/// So the semantic rule is measured on the SOURCE, and
/// [`REGEX_SIZE_LIMIT`] must never be the thing that decides.
pub const REGEX_SOURCE_LIMIT: usize = 1024;

/// The compiled-program budget, per pattern — **a memory guard, not a rule**.
///
/// Python's `re` has no counterpart, which is why the oracle has none, so every
/// byte this rejects that [`REGEX_SOURCE_LIMIT`] would have allowed is an
/// artifact this engine disarms and the oracle arms: a divergence in
/// *enforcement*, invisible to a corpus of verdicts. It is therefore set to the
/// `regex` crate's own default (10 MiB) — deliberately **not tighter than what
/// `regex` would accept anyway**, so it cannot fire on a pattern the crate was
/// willing to compile.
///
/// # It cannot be ordered strictly after the source cap, and here is why
///
/// There is no finite value that "can never fire before the source cap": counted
/// repetition nests, so a *tiny* source can demand unbounded memory. Measured
/// against this build —
///
/// | source | bytes | compiled program |
/// | --- | --- | --- |
/// | `[a-z]{5000}` | 11 | 360 KB |
/// | `(?:[a-z]{100}){1000}` | 20 | 7.2 MB |
/// | `(?:a{1000}){1000}` | 17 | 30.5 MB |
/// | `((((a{100}){100}){100}){100})` | 29 | does not compile at 1 GiB |
///
/// Every one of those is far under 1024 bytes. So the residual divergence is
/// real and cannot be designed away — only bounded, and pointed the safe way:
/// it is reachable *only* by a counted-repetition bomb, which is a pattern the
/// oracle's Python `re` also cannot run (it compiles cheaply there and then
/// backtracks catastrophically at match time). Between disarming one authored
/// bomb and letting an authored pattern exhaust a developer machine's memory,
/// this takes the first. Flagged to the PRD rather than resolved here.
pub const REGEX_SIZE_LIMIT: usize = 10 * (1 << 20);

// ── The shared scan table ────────────────────────────────────────────

/// Which automaton a pattern source belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PatternKind {
    Keyword,
    Prefix,
    Regex,
    Glob,
}

/// The shared scan result for one bundle: every pattern in every artifact,
/// compiled once.
///
/// # It is a VALUE, never a static
///
/// The automata are built at bundle load and carried here, inside the
/// [`Bundle`](super::bundle::Bundle) that `evaluate` is handed. A `OnceLock` or a
/// `Lazy` holding them would be global state — the thing `ci/check-engine-purity.py`
/// rule `global-state` exists to catch — and the process would then retain
/// something derived from its history rather than from its inputs.
///
/// # Why `PartialEq` is hand-written
///
/// `ResidentBundle` derives `PartialEq`, so everything reachable from it must
/// compare. `aho_corasick::AhoCorasick` and `meta::Regex` implement no
/// `PartialEq` and never will. Two tables built from the same patterns *are* the
/// same table, so equality is defined on the pattern SOURCES.
#[derive(Debug, Clone, Default)]
pub struct ScanTable {
    /// Sources of every `keyword` leaf, in compile order. The index into this
    /// vector is the pattern id a tree reads its boolean by.
    pub keyword_sources: Vec<String>,
    /// Sources of every `prefix` leaf, same indexing rule.
    pub prefix_sources: Vec<String>,
    /// Sources of every `regex_lite` leaf, same indexing rule.
    pub regex_sources: Vec<String>,
    /// Sources of every `glob` leaf, same indexing rule.
    pub glob_sources: Vec<String>,
    /// Every field a pattern leaf reads, deduplicated. The per-event scan touches
    /// these and nothing else.
    pub scanned_fields: Vec<String>,

    // ── Compiled. Derived from the sources above, so deliberately OUT of `eq`. ──
    /// Source → pattern id, so a tree finds its boolean without a linear walk.
    keyword_index: HashMap<String, usize>,
    prefix_index: HashMap<String, usize>,
    regex_index: HashMap<String, usize>,
    glob_index: HashMap<String, usize>,
    /// ASCII-case-insensitive, because `keyword` is a case-insensitive
    /// containment test.
    keyword_ac: Option<AhoCorasick>,
    /// Case-sensitive; a hit only counts at offset 0 of a value.
    prefix_ac: Option<AhoCorasick>,
    /// `(?-u)` bytes mode. See [`compile_regex_set`].
    regex_set: Option<meta::Regex>,
    /// Globs are anchored full matches over `&str`, so they keep Unicode
    /// semantics: `?` means one CHARACTER, exactly as the oracle's `[^/]` does.
    glob_set: Option<meta::Regex>,
}

impl PartialEq for ScanTable {
    fn eq(&self, other: &Self) -> bool {
        self.keyword_sources == other.keyword_sources
            && self.prefix_sources == other.prefix_sources
            && self.regex_sources == other.regex_sources
            && self.glob_sources == other.glob_sources
    }
}

impl ScanTable {
    /// Compile every pattern in every surviving artifact into the shared automata.
    ///
    /// Runs **once per bundle**, after the two-stage parse has dropped the
    /// artifacts that could not be read, so a bad pattern never reaches here —
    /// [`validate_patterns`] rejected its artifact first.
    pub fn compile(artifacts: &[LoadedArtifact]) -> ScanTable {
        let mut table = ScanTable::default();
        for artifact in artifacts {
            let node = match &artifact.body {
                ArtifactBody::T1(body) => body.node.as_ref(),
                ArtifactBody::T3(body) => body.trigger.as_ref(),
                _ => None,
            };
            if let Some(node) = node {
                walk_leaves(node, &mut |leaf| table.collect(leaf));
            }
        }
        table.finish();
        table
    }

    /// Record one leaf's patterns and the field they are read against.
    fn collect(&mut self, leaf: &T1Leaf) {
        let Some(pred) = leaf.pred.as_deref() else {
            return;
        };
        let kind = match pred {
            "keyword" => PatternKind::Keyword,
            "prefix" => PatternKind::Prefix,
            "regex_lite" => PatternKind::Regex,
            "glob" => PatternKind::Glob,
            _ => return,
        };
        let Some(field) = leaf.field.as_deref() else {
            return;
        };
        if !self.scanned_fields.iter().any(|f| f == field) {
            self.scanned_fields.push(field.to_string());
        }
        for source in pattern_sources(leaf, kind) {
            let (sources, index) = match kind {
                PatternKind::Keyword => (&mut self.keyword_sources, &mut self.keyword_index),
                PatternKind::Prefix => (&mut self.prefix_sources, &mut self.prefix_index),
                PatternKind::Regex => (&mut self.regex_sources, &mut self.regex_index),
                PatternKind::Glob => (&mut self.glob_sources, &mut self.glob_index),
            };
            // `keyword` is indexed by its FOLDED form, because that is what the
            // automaton was built over and what a leaf will look itself up by.
            let key = match kind {
                PatternKind::Keyword => fold_keyword(&source).into_owned(),
                _ => source.clone(),
            };
            if let std::collections::hash_map::Entry::Vacant(slot) = index.entry(key) {
                let id = sources.len();
                slot.insert(id);
                sources.push(source);
            }
        }
    }

    /// Build the automata from the collected sources.
    fn finish(&mut self) {
        if !self.keyword_sources.is_empty() {
            // Folded needles against a folded haystack. `ascii_case_insensitive`
            // is deliberately NOT set: it would fold only the ASCII half and
            // silently disagree with `fold_keyword` on everything else.
            let folded: Vec<String> = self
                .keyword_sources
                .iter()
                .map(|source| fold_keyword(source).into_owned())
                .collect();
            self.keyword_ac = AhoCorasickBuilder::new()
                .match_kind(MatchKind::Standard)
                .build(&folded)
                .ok();
        }
        if !self.prefix_sources.is_empty() {
            self.prefix_ac = AhoCorasickBuilder::new()
                .match_kind(MatchKind::Standard)
                .build(&self.prefix_sources)
                .ok();
        }
        if !self.regex_sources.is_empty() {
            self.regex_set = compile_regex_set(&self.regex_sources);
        }
        if !self.glob_sources.is_empty() {
            let translated: Vec<String> =
                self.glob_sources.iter().map(|g| glob_to_regex(g)).collect();
            self.glob_set = compile_pattern_set(&translated, true);
        }
    }

    /// Run every automaton ONCE over every scanned field, and hand back the
    /// booleans the trees read.
    ///
    /// An empty table scans nothing and allocates nothing, which is what makes a
    /// bundle with no pattern leaves cost zero here.
    pub fn scan(&self, ctx: &EvalContext<'_>) -> ScanResult {
        let mut result = ScanResult::default();
        if self.scanned_fields.is_empty() {
            return result;
        }
        for field in &self.scanned_fields {
            let mut matches = FieldMatches {
                keyword: vec![false; self.keyword_sources.len()],
                prefix: vec![false; self.prefix_sources.len()],
                regex: vec![false; self.regex_sources.len()],
                glob: vec![false; self.glob_sources.len()],
            };
            for value in field_values(field, ctx) {
                let Some(text) = value.as_str() else {
                    continue;
                };
                if let Some(automaton) = &self.keyword_ac {
                    // Folded ONCE per value, not once per needle, and only when
                    // the bundle actually carries a keyword leaf.
                    let folded = fold_keyword(text);
                    for hit in automaton.find_overlapping_iter(folded.as_ref()) {
                        matches.keyword[hit.pattern().as_usize()] = true;
                    }
                }
                if let Some(automaton) = &self.prefix_ac {
                    // A prefix is a match at offset 0 and nowhere else. One
                    // overlapping pass finds every candidate; the filter is what
                    // makes it a prefix rather than a containment test.
                    for hit in automaton.find_overlapping_iter(text) {
                        if hit.start() == 0 {
                            matches.prefix[hit.pattern().as_usize()] = true;
                        }
                    }
                }
                if let Some(set) = &self.regex_set {
                    for id in matching_patterns(set, text.as_bytes()).iter() {
                        matches.regex[id.as_usize()] = true;
                    }
                }
                if let Some(set) = &self.glob_set {
                    for id in matching_patterns(set, text.as_bytes()).iter() {
                        matches.glob[id.as_usize()] = true;
                    }
                }
            }
            result.fields.push((field.clone(), matches));
        }
        result
    }

    /// The boolean for one `(field, pattern)` pair, or `None` when this table did
    /// not compile that pattern — which is what makes a tree evaluated against a
    /// foreign or empty table fall back to a direct test rather than silently
    /// answer FALSE.
    fn lookup(
        &self,
        result: &ScanResult,
        field: &str,
        kind: PatternKind,
        source: &str,
    ) -> Option<bool> {
        let index = match kind {
            PatternKind::Keyword => &self.keyword_index,
            PatternKind::Prefix => &self.prefix_index,
            PatternKind::Regex => &self.regex_index,
            PatternKind::Glob => &self.glob_index,
        };
        let id = match kind {
            PatternKind::Keyword => *index.get(fold_keyword(source).as_ref())?,
            _ => *index.get(source)?,
        };
        let matches = &result.fields.iter().find(|(name, _)| name == field)?.1;
        let bits = match kind {
            PatternKind::Keyword => &matches.keyword,
            PatternKind::Prefix => &matches.prefix,
            PatternKind::Regex => &matches.regex,
            PatternKind::Glob => &matches.glob,
        };
        bits.get(id).copied()
    }
}

/// One event's worth of pattern booleans, per scanned field.
///
/// The object the design's step 4 reads: a tree holds this and never touches a
/// pattern.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScanResult {
    fields: Vec<(String, FieldMatches)>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct FieldMatches {
    keyword: Vec<bool>,
    prefix: Vec<bool>,
    regex: Vec<bool>,
    glob: Vec<bool>,
}

/// Case-fold one string for `keyword` matching.
///
/// # Why folding, and not `ascii_case_insensitive`
///
/// `keyword` is a case-insensitive containment test and the oracle spells it
/// `k.casefold() in value.casefold()` — **Unicode** folding. `(?-u)` is stated in
/// the PRD for `regex_lite` specifically and says nothing about `keyword`, so
/// D-25 applies: where the PRD is silent the oracle is the recorded reading.
/// aho-corasick's `ascii_case_insensitive` folds ASCII only, which matches
/// strictly FEWER things — and a keyword rule that fires less often than the
/// spec says is the fail-open direction.
///
/// # Full folding, not `to_lowercase` — they are different operations
///
/// Rust's std has no `casefold`, and `to_lowercase` is NOT a substitute: case
/// folding applies **full** foldings that change length, and lowercasing does
/// not. Checked against the interpreter that defines the oracle's behaviour:
///
/// | input | `str.casefold()` | `str.lower()` |
/// | --- | --- | --- |
/// | `ß` | `ss` | `ß` |
/// | `fi` | `fi` | `fi` |
/// | `ΣΊΣΥΦΟΣ` | `σίσυφοσ` | `σίσυφος` |
///
/// Three classes, not one — Greek final sigma is the one that is easy to miss,
/// because `to_lowercase` gets it *contextually* right and folding deliberately
/// does not. `caseless::default_case_fold_str` is Unicode C+F, which is exactly
/// what `str.casefold()` implements, so the two agree by construction rather
/// than by a table someone maintains here.
///
/// # What it costs, measured
///
/// Paths, commands and tool names are overwhelmingly lowercase ASCII, and a
/// borrowed `Cow` costs nothing there. Only a string that is non-ASCII, or ASCII
/// with an uppercase byte in it, allocates. Measured against the automaton this
/// replaced (`ascii_case_insensitive`, no folding), at 2,000 keyword patterns
/// and 40 values on the scan surface — release build, per event:
///
/// | scan surface | ASCII automaton | folded | delta | share of the 183 µs p99 |
/// | --- | --- | --- | --- | --- |
/// | lowercase ASCII (the common case) | 2.08 µs | 3.02 µs | +0.93 µs | +0.5% |
/// | mixed-case ASCII | 2.11 µs | 4.52 µs | +2.41 µs | +1.3% |
/// | non-ASCII (every value) | 3.00 µs | 29.61 µs | +26.61 µs | **+14.5%** |
///
/// **The last row is the real cost of correctness here, and it is not small.**
/// `caseless` walks a folding table per character where `to_ascii_lowercase` is
/// a byte mask, so a surface that is *entirely* non-ASCII pays fourteen per cent
/// of the p99 budget. That row is a worst case by construction — all forty
/// values non-ASCII — and a realistic surface pays in proportion to how much of
/// it is non-ASCII, which for paths, commands and tool names is usually none of
/// it.
///
/// The ASCII fast path above is therefore not an optimisation, it is what keeps
/// this affordable: a string with no uppercase ASCII and no high byte never
/// reaches `caseless` at all.
fn fold_keyword(text: &str) -> std::borrow::Cow<'_, str> {
    // ONE pass for the case that actually occurs. A string with no uppercase
    // ASCII and no high byte folds to itself, so it is borrowed and the second
    // pass never happens.
    if !text
        .bytes()
        .any(|b| b.is_ascii_uppercase() || !b.is_ascii())
    {
        return std::borrow::Cow::Borrowed(text);
    }
    if text.is_ascii() {
        std::borrow::Cow::Owned(text.to_ascii_lowercase())
    } else {
        std::borrow::Cow::Owned(caseless::default_case_fold_str(text))
    }
}

/// Use the same engine, flags and budgets as `regex`'s string/bytes builders,
/// but fix the cache pool at the engine's fallback capacity. Its automatic
/// sizing probes CPU limits (including cgroup files) during construction, which
/// violates evaluator purity. This pool only caches input-derived search work.
/// `utf8` selects Unicode string semantics for globs or ASCII bytes for regex_lite.
fn pattern_builder(utf8: bool) -> meta::Builder {
    let mut builder = meta::Regex::builder();
    builder
        .configure(
            meta::Regex::config()
                .match_kind(regex_automata::MatchKind::LeftmostFirst)
                .utf8_empty(utf8)
                .nfa_size_limit(Some(REGEX_SIZE_LIMIT))
                .hybrid_cache_capacity(2 * (1 << 20))
                .pool_capacity(8),
        )
        .syntax(syntax::Config::new().utf8(utf8).unicode(utf8));
    builder
}

/// Preserve RegexSet's all-pattern matching and source-order pattern IDs.
fn compile_pattern_set(sources: &[String], utf8: bool) -> Option<meta::Regex> {
    pattern_builder(utf8)
        .configure(
            meta::Regex::config()
                .match_kind(regex_automata::MatchKind::All)
                .which_captures(WhichCaptures::None)
                .nfa_size_limit(Some(REGEX_SIZE_LIMIT.saturating_mul(sources.len().max(1)))),
        )
        .build_many(sources)
        .ok()
}

fn matching_patterns(set: &meta::Regex, text: &[u8]) -> PatternSet {
    let mut matches = PatternSet::new(set.pattern_len());
    set.which_overlapping_matches(&Input::new(text), &mut matches);
    matches
}

/// Compile the whole `regex_lite` corpus into one `(?-u)` bytes pattern set.
///
/// `unicode(false)` is not a tuning knob. PRD §Bundle schema 2 pins `regex_lite`
/// to ASCII `(?-u)` mode, and the measured reason is in the module header: a
/// Unicode `\b` regresses the p99 fifteenfold. The set's own `size_limit` is the
/// per-pattern budget times the number of patterns, so [`REGEX_SIZE_LIMIT`] stays
/// the per-pattern promise it is documented as — a bundle does not get to fail
/// its 900th cheap pattern because it also shipped 899 others.
fn compile_regex_set(sources: &[String]) -> Option<meta::Regex> {
    compile_pattern_set(sources, false)
}

/// Compile one `regex_lite` source the way the shared set does, for validation
/// and for the fallback path.
fn compile_one_regex(source: &str) -> Option<meta::Regex> {
    pattern_builder(false).build(source).ok()
}

fn compile_one_glob(source: &str) -> Option<meta::Regex> {
    pattern_builder(true).build(&glob_to_regex(source)).ok()
}

/// globset semantics, narrowed to what the PRD's seed lists actually use: `**`
/// crosses `/`, `*` and `?` do not, and every other character is a literal.
///
/// `{a,b}` alternation and `[…]` classes are deliberately NOT supported — a brace
/// or a bracket matches itself. The oracle makes the same narrowing
/// (`tools/zone-eval-ref/tier1.py::glob_to_regex`) and the corpus is written
/// against it; reaching for `globset` here would quietly add two pattern
/// syntaxes the other implementation does not have.
fn glob_to_regex(pattern: &str) -> String {
    let mut out = String::from("(?s)\\A");
    let chars: Vec<char> = pattern.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '*' && i + 1 < chars.len() && chars[i + 1] == '*' {
            out.push_str(".*");
            i += 2;
            continue;
        }
        match chars[i] {
            '*' => out.push_str("[^/]*"),
            '?' => out.push_str("[^/]"),
            other => out.push_str(&regex::escape(&other.to_string())),
        }
        i += 1;
    }
    out.push_str("\\z");
    out
}

// ── Tree walking ─────────────────────────────────────────────────────

/// Visit every leaf of a tree, in document order.
fn walk_leaves(node: &T1Node, visit: &mut impl FnMut(&T1Leaf)) {
    if let Some(leaf) = node.leaf.as_ref() {
        visit(leaf);
    }
    for child in &node.children {
        walk_leaves(child, visit);
    }
}

/// The literal sources one pattern leaf carries. `pattern` wins over `value`, and
/// either may be a single string or a list of them.
fn pattern_sources(leaf: &T1Leaf, kind: PatternKind) -> Vec<String> {
    let carrier = match kind {
        // `keyword` and `prefix` take literals, never a `pattern`.
        PatternKind::Keyword | PatternKind::Prefix => leaf.value.as_ref(),
        // `glob` and `regex_lite` prefer `pattern` and fall back to `value`.
        PatternKind::Regex | PatternKind::Glob => leaf
            .pattern
            .as_ref()
            .map(|_| None)
            .unwrap_or_else(|| leaf.value.as_ref())
            .or(None),
    };
    let mut out = Vec::new();
    if matches!(kind, PatternKind::Regex | PatternKind::Glob) {
        if let Some(pattern) = leaf.pattern.as_ref() {
            out.push(pattern.clone());
            return out;
        }
    }
    if let Some(value) = carrier.or(leaf.value.as_ref()) {
        for item in as_list(value) {
            if let Some(text) = item.as_str() {
                out.push(text.to_string());
            }
        }
    }
    out
}

// ── Load-time validation ─────────────────────────────────────────────

/// Reject a predicate tree the evaluator cannot read, so its artifact is skipped
/// rather than the bundle rejected.
///
/// The schema leaves `op`, `pred` and `field` open (R14), so an unrecognised one
/// has to be caught HERE — where the loader can skip the one artifact — rather
/// than at evaluation time, where it would cost every other rule its verdict.
pub fn validate_node(node: Option<&T1Node>) -> Result<(), String> {
    let Some(node) = node else {
        return Err("t1 body carries no node".to_string());
    };
    let op = node.op.as_deref().unwrap_or("");
    if !KNOWN_NODE_OPS.contains(&op) {
        return Err(format!("unknown node op '{op}'"));
    }
    if op == "leaf" {
        let Some(leaf) = node.leaf.as_ref() else {
            return Err("leaf node without a leaf".to_string());
        };
        return validate_leaf(leaf);
    }
    if node.children.is_empty() {
        return Err(format!("{op} node without children"));
    }
    if op == "not" && node.children.len() != 1 {
        return Err(format!(
            "not takes exactly one child, got {}",
            node.children.len()
        ));
    }
    for child in &node.children {
        validate_node(Some(child))?;
    }
    Ok(())
}

fn validate_leaf(leaf: &T1Leaf) -> Result<(), String> {
    let pred = leaf.pred.as_deref().unwrap_or("");
    if !KNOWN_PREDS.contains(&pred) {
        return Err(format!("unknown predicate '{pred}'"));
    }
    if pred == "fact" {
        let op = leaf
            .fact
            .as_ref()
            .and_then(|f| f.op.as_deref())
            .unwrap_or("");
        if !KNOWN_FACT_OPS.contains(&op) {
            return Err(format!("unknown fact op '{op}'"));
        }
        return Ok(());
    }
    if pred == "effect" {
        return Ok(());
    }
    let Some(field) = leaf.field.as_deref() else {
        return Err("leaf without a field".to_string());
    };
    if !KNOWN_FIELDS.contains(&field) && !FIELD_PREFIXES.iter().any(|p| field.starts_with(p)) {
        return Err(format!("unknown field '{field}'"));
    }
    Ok(())
}

/// Reject an artifact whose `regex_lite` or `glob` patterns do not compile, or
/// whose regex exceeds a budget. Produces the `bad_pattern` skip.
///
/// Two budgets, and the ORDER between them is the contract:
/// [`REGEX_SOURCE_LIMIT`] is the semantic rule and is checked **first**;
/// [`REGEX_SIZE_LIMIT`] is a memory guard of last resort, loose enough that it
/// cannot fire on anything short of a counted-repetition bomb. Both constants
/// carry the reasoning. Reversing them would let the guard decide which
/// artifacts are ARMED, and a disagreement about that is invisible to a corpus
/// of verdicts.
pub fn validate_patterns(node: Option<&T1Node>) -> Result<(), String> {
    let Some(node) = node else {
        return Ok(());
    };
    let mut failure: Option<String> = None;
    walk_leaves(node, &mut |leaf| {
        if failure.is_some() {
            return;
        }
        failure = validate_leaf_patterns(leaf).err();
    });
    match failure {
        Some(reason) => Err(reason),
        None => Ok(()),
    }
}

fn validate_leaf_patterns(leaf: &T1Leaf) -> Result<(), String> {
    match leaf.pred.as_deref() {
        Some("regex_lite") => {
            let sources = pattern_sources(leaf, PatternKind::Regex);
            if sources.is_empty() {
                return Err("regex_lite without a pattern".to_string());
            }
            for source in sources {
                if source.len() > REGEX_SOURCE_LIMIT {
                    return Err(format!(
                        "regex_lite over the {REGEX_SOURCE_LIMIT}-byte source limit"
                    ));
                }
                // `regex-syntax` is what the PRD names as the validator; the
                // builder runs it and then applies the compiled-size budget, so
                // one call covers both halves of the promise.
                if compile_one_regex(&source).is_none() {
                    return Err(format!("regex_lite does not compile: {source}"));
                }
            }
            Ok(())
        }
        Some("glob") => {
            let sources = pattern_sources(leaf, PatternKind::Glob);
            if sources.is_empty() {
                return Err("glob without a pattern".to_string());
            }
            for source in sources {
                if compile_one_glob(&source).is_none() {
                    return Err(format!("glob does not compile: {source}"));
                }
            }
            Ok(())
        }
        _ => Ok(()),
    }
}

// ── The field vocabulary ─────────────────────────────────────────────

/// Every string value under `value`, recursively — the value-shaped scan surface.
fn all_strings(value: &Value, out: &mut Vec<Value>) {
    match value {
        Value::String(_) => out.push(value.clone()),
        Value::Object(map) => {
            for child in map.values() {
                all_strings(child, out);
            }
        }
        Value::Array(items) => {
            for child in items {
                all_strings(child, out);
            }
        }
        _ => {}
    }
}

/// RFC 6901. `input./command` carries the pointer `/command`.
fn json_pointer<'a>(document: &'a Value, pointer: &str) -> Option<&'a Value> {
    if pointer.is_empty() || pointer == "/" {
        return Some(document);
    }
    if !pointer.starts_with('/') {
        return None;
    }
    let mut current = document;
    for raw in pointer[1..].split('/') {
        let token = raw.replace("~1", "/").replace("~0", "~");
        match current {
            Value::Object(map) => current = map.get(&token)?,
            Value::Array(items) => {
                if token.is_empty() || !token.bytes().all(|b| b.is_ascii_digit()) {
                    return None;
                }
                let index: usize = token.parse().ok()?;
                current = items.get(index)?;
            }
            _ => return None,
        }
    }
    Some(current)
}

/// `result.exit_code` — `null` outside a `post_tool_use` shell command.
///
/// Spike amendment 8, and the reason it has its own branch: a null here makes the
/// leaf FALSE, not ⊥ and not true. `None` yields an empty value list, and an
/// empty value list is FALSE for every predicate including `exists`.
fn exit_code(event: &super::types::Event) -> Option<i64> {
    if event.event_type != "post_tool_use" {
        return None;
    }
    if !SHELL_TOOLS.contains(&event.tool_name.as_str()) {
        return None;
    }
    let result = event.tool_result.as_ref()?.as_object()?;
    for key in ["exit_code", "exitCode", "returncode"] {
        if let Some(code) = result.get(key).and_then(Value::as_i64) {
            return Some(code);
        }
    }
    None
}

/// Every value a field takes for this action. A leaf matches if ANY does.
///
/// An empty list means the field has no value here, and **every predicate over an
/// empty list is FALSE** — including `exists`, and including `result.exit_code`
/// on a non-shell event.
pub fn field_values(field: &str, ctx: &EvalContext<'_>) -> Vec<Value> {
    let event = ctx.event;
    let class = ctx.classification;

    match field {
        "tool.name" => {
            if event.tool_name.is_empty() {
                Vec::new()
            } else {
                vec![Value::String(event.tool_name.clone())]
            }
        }
        "input.strings" => {
            let mut out = Vec::new();
            all_strings(&event.tool_input, &mut out);
            out
        }
        "result.strings" => {
            let mut out = Vec::new();
            if let Some(result) = event.tool_result.as_ref() {
                all_strings(result, &mut out);
            }
            out
        }
        "result.exit_code" => exit_code(event).map(Value::from).into_iter().collect(),
        "command.program" => class
            .simple
            .iter()
            .filter(|s| !s.program.is_empty())
            .map(|s| Value::String(s.program.clone()))
            .collect(),
        "command.argv" => class
            .simple
            .iter()
            .flat_map(|s| s.argv.iter())
            .map(|a| Value::String(a.clone()))
            .collect(),
        "command.simple" => class.simple.iter().map(|s| s.as_value()).collect(),
        "path.class" => class
            .paths
            .iter()
            .map(|p| Value::String(p.class.0.clone()))
            .collect(),
        "path.value" => class
            .paths
            .iter()
            .map(|p| Value::String(p.value.clone()))
            .collect(),
        "url.host" => class
            .urls
            .iter()
            .map(|u| Value::String(u.host.clone()))
            .collect(),
        "url.tld" => class
            .urls
            .iter()
            .map(|u| Value::String(u.tld.clone()))
            .collect(),
        "url.scheme" => class
            .urls
            .iter()
            .map(|u| Value::String(u.scheme.clone()))
            .collect(),
        "url.boundary" => class
            .urls
            .iter()
            .map(|u| Value::String(u.boundary.as_str().to_string()))
            .collect(),
        "effect.verb" => class
            .effects
            .iter()
            .map(|e| Value::String(e.verb.0.clone()))
            .collect(),
        "effect.target_class" => class
            .effects
            .iter()
            .map(|e| Value::String(e.target_class.0.clone()))
            .collect(),
        _ => {
            if let Some(pointer) = field.strip_prefix("input.") {
                return json_pointer(&event.tool_input, pointer)
                    .cloned()
                    .into_iter()
                    .collect();
            }
            if let Some(key) = field.strip_prefix("agent.") {
                let Some(agent) = event.agent.as_ref() else {
                    return Vec::new();
                };
                // `agent.type` reads `agent_type` and `agent.id` reads `agent_id`;
                // the other three are named identically on the Event.
                let value = match key {
                    "type" => agent.agent_type.as_ref(),
                    "id" => agent.agent_id.as_ref(),
                    "environment" => agent.environment.as_ref(),
                    "function" => agent.function.as_ref(),
                    "principal" => agent.principal.as_ref(),
                    _ => None,
                };
                return value
                    .map(|v| Value::String(v.clone()))
                    .into_iter()
                    .collect();
            }
            if let Some(key) = field.strip_prefix("session.") {
                let Some(session) = event.session.as_ref() else {
                    return Vec::new();
                };
                let value = match key {
                    "elapsed_ms" => session.elapsed_ms,
                    "tool_calls" => session.tool_calls,
                    "spend_micro_usd" => session.spend_micro_usd,
                    "tokens" => session.tokens,
                    _ => None,
                };
                return value.map(Value::from).into_iter().collect();
            }
            Vec::new()
        }
    }
}

// ── Predicates ───────────────────────────────────────────────────────

/// A literal that may be a single value or a list of them.
fn as_list(value: &Value) -> Vec<&Value> {
    match value {
        Value::Array(items) => items.iter().collect(),
        other => vec![other],
    }
}

/// `int_cmp` over `{op, n}`. A bool is not an integer here, and neither is a
/// string that looks like one.
fn int_cmp(left: &Value, spec: Option<&Value>) -> bool {
    let (Some(spec), Some(left)) = (spec.and_then(Value::as_object), left.as_i64()) else {
        return false;
    };
    let Some(n) = spec.get("n").and_then(Value::as_i64) else {
        return false;
    };
    match spec.get("op").and_then(Value::as_str) {
        Some("lt") => left < n,
        Some("le") => left <= n,
        Some("gt") => left > n,
        Some("ge") => left >= n,
        Some("eq") => left == n,
        _ => false,
    }
}

/// One value against one predicate, two-valued. ⊥ is decided by the caller.
///
/// The pattern predicates take their answer from `scan` when the table compiled
/// the source — the fast path, and the one production always takes — and fall
/// back to a direct test otherwise, so a tree evaluated against an empty or
/// foreign table still answers correctly instead of silently answering FALSE.
fn test_predicate(
    pred: &str,
    field: &str,
    value: &Value,
    leaf: &T1Leaf,
    scan: &ScanTable,
    result: &ScanResult,
) -> bool {
    match pred {
        "equals" => leaf.value.as_ref().is_some_and(|literal| value == literal),
        "in_set" | "tld_in" => leaf
            .value
            .as_ref()
            .is_some_and(|literal| as_list(literal).into_iter().any(|item| item == value)),
        "prefix" => {
            let Some(text) = value.as_str() else {
                return false;
            };
            pattern_sources(leaf, PatternKind::Prefix)
                .iter()
                .any(|source| {
                    scan.lookup(result, field, PatternKind::Prefix, source)
                        .unwrap_or_else(|| text.starts_with(source.as_str()))
                })
        }
        "keyword" => {
            let Some(text) = value.as_str() else {
                return false;
            };
            pattern_sources(leaf, PatternKind::Keyword)
                .iter()
                .any(|source| {
                    scan.lookup(result, field, PatternKind::Keyword, source)
                        .unwrap_or_else(|| {
                            fold_keyword(text).contains(fold_keyword(source).as_ref())
                        })
                })
        }
        "glob" => {
            let Some(text) = value.as_str() else {
                return false;
            };
            pattern_sources(leaf, PatternKind::Glob)
                .iter()
                .any(|source| {
                    scan.lookup(result, field, PatternKind::Glob, source)
                        .unwrap_or_else(|| {
                            compile_one_glob(source).is_some_and(|re| re.is_match(text))
                        })
                })
        }
        "regex_lite" => {
            let Some(text) = value.as_str() else {
                return false;
            };
            pattern_sources(leaf, PatternKind::Regex)
                .iter()
                .any(|source| {
                    scan.lookup(result, field, PatternKind::Regex, source)
                        .unwrap_or_else(|| {
                            compile_one_regex(source).is_some_and(|re| re.is_match(text.as_bytes()))
                        })
                })
        }
        "int_cmp" => int_cmp(value, leaf.value.as_ref()),
        // `exists` never reaches here — it is answered from the value LIST, not
        // from a value. Anything else was rejected by `validate_node` at load.
        _ => false,
    }
}

// ── Leaves ───────────────────────────────────────────────────────────

/// D-17, the REFERENCING side: a fact id outside the registry is reported, never
/// rejected. The wording matches [`evaluate`](super::evaluate)'s declaring-side
/// warning so the two deduplicate into one line.
fn note_fact_id(ctx: &mut EvalContext<'_>, fact_id: &str) {
    if !facts::is_known_fact_id(fact_id) {
        ctx.warn(format!(
            "fact_id '{fact_id}' is not a known FactId \
             (schemas/enums.schema.json $defs/FactId x-known-values)"
        ));
    }
}

/// Record a ⊥ that names a FACT. An open-world miss is ⊥ and is deliberately NOT
/// recorded: the fact resolved perfectly well, and what is unknown is whether a
/// candidate is in a set that never claimed to be exhaustive.
fn note_if_fact_unresolved(ctx: &mut EvalContext<'_>, fact_id: &str, value: Kleene) {
    if value.reason().is_some_and(|reason| reason.names_a_fact()) {
        ctx.note_inconclusive(fact_id);
    }
}

/// `pred: fact` — the FACT is the subject ("is the ticket approved?").
///
/// The comparison itself lives in `facts::resolve_leaf`, which owns staleness,
/// closed/open world and the kind rules. Duplicating any of it here would give
/// the engine two fact truth tables to disagree with each other.
fn leaf_fact_subject(leaf: &T1Leaf, ctx: &mut EvalContext<'_>) -> Kleene {
    let spec = leaf.fact.as_ref();
    let fact_id = spec
        .and_then(|f| f.fact_id.as_ref())
        .map(|id| id.0.clone())
        .unwrap_or_default();
    let op = spec.and_then(|f| f.op.as_deref()).unwrap_or("");
    let wanted = spec.and_then(|f| f.value.as_ref());
    note_fact_id(ctx, &fact_id);
    let value = facts::resolve_leaf(ctx.facts, &fact_id, op, wanted, ctx.now_ms);
    note_if_fact_unresolved(ctx, &fact_id, value);
    value
}

/// `pred: effect` — any tuple of the action equals this one.
///
/// Never ⊥: the action's tuples are all known. A coverage gap is an
/// `unknown × shell` tuple carried ALONGSIDE them (D-15), not an absence.
fn leaf_effect_tuple(leaf: &T1Leaf, ctx: &EvalContext<'_>) -> Kleene {
    let Some(wanted) = leaf.effect.as_ref() else {
        return Kleene::False;
    };
    let hit = ctx.classification.effects.iter().any(|tuple| {
        wanted.verb.as_ref().is_some_and(|v| *v == tuple.verb)
            && wanted
                .target_class
                .as_ref()
                .is_some_and(|c| *c == tuple.target_class)
    });
    Kleene::from_bool(hit)
}

/// `effect.attrs.<name>` — an attribute NO tuple carries is ⊥, never false.
///
/// The distinction is the whole point of D-16: "no tuple said whether this was
/// production" and "a tuple said it was not" are different answers, and only the
/// first one should reach `on_inconclusive`.
fn leaf_effect_attribute(
    leaf: &T1Leaf,
    pred: &str,
    field: &str,
    ctx: &EvalContext<'_>,
    scan: &ScanTable,
    result: &ScanResult,
) -> Kleene {
    let name = &field["effect.attrs.".len()..];
    let values: Vec<&Value> = ctx
        .classification
        .effects
        .iter()
        .filter_map(|tuple| tuple.attrs.get(name))
        .collect();
    if values.is_empty() {
        return Kleene::UNKNOWN;
    }
    if pred == "exists" {
        return Kleene::True;
    }
    Kleene::from_bool(
        values
            .into_iter()
            .any(|value| test_predicate(pred, field, value, leaf, scan, result)),
    )
}

/// `fact.<fact_id>[.dotted.path]` as a FIELD — the attribute route into a fact.
///
/// The split and the walk are `facts::field_values`', not a second copy here:
/// **one reading, never two**, and the id/path split in particular is the thing
/// the corpus pins (`fact-field-dotted-id-is-not-a-second-reading`).
fn fact_field_values<'a>(ctx: &mut EvalContext<'a>, field: &str) -> Option<Vec<&'a Value>> {
    let fact_id = facts::split_field(field)
        .map(|(id, _)| id.to_string())
        .unwrap_or_default();
    note_fact_id(ctx, &fact_id);
    match facts::field_values(ctx.facts, field, ctx.now_ms) {
        Ok(values) => Some(values),
        Err(reason) => {
            if reason.names_a_fact() {
                ctx.note_inconclusive(&fact_id);
            }
            None
        }
    }
}

/// Any other field — an attribute of the action, tested value by value.
///
/// ⊥ enters here through `set_ref` alone: the compiled form of `in_fact_set`,
/// where the ATTRIBUTE is the subject and a fact supplies the set
/// ("url.host ∈ approved_domains"), and then only on an open-world miss.
fn leaf_attribute(
    leaf: &T1Leaf,
    pred: &str,
    field: &str,
    ctx: &mut EvalContext<'_>,
    scan: &ScanTable,
    result: &ScanResult,
) -> Kleene {
    let values = field_values(field, ctx);

    if let Some(set_ref) = leaf.set_ref.as_ref() {
        let fact_id = set_ref.0.clone();
        note_fact_id(ctx, &fact_id);
        if values.is_empty() {
            // Nothing to test the set against. A known negative, not an unknown:
            // the fact may be perfectly readable and the action simply names no
            // host.
            return Kleene::False;
        }
        // Membership is `facts`' truth table, not a second one written here:
        // `facts::membership` carries the whole open/closed-world rule, and its
        // open-world ⊥ is the only ⊥ this route can produce.
        let each: Vec<Kleene> = values
            .iter()
            .map(|value| facts::membership(ctx.facts, &fact_id, value, ctx.now_ms))
            .collect();
        let folded = Kleene::any(&each);
        note_if_fact_unresolved(ctx, &fact_id, folded);
        return folded;
    }

    if pred == "exists" {
        return Kleene::from_bool(!values.is_empty());
    }
    Kleene::from_bool(
        values
            .iter()
            .any(|value| test_predicate(pred, field, value, leaf, scan, result)),
    )
}

/// One leaf, three-valued. Five kinds, and where each one's ⊥ comes from:
///
/// | leaf kind        | written as                   | ⊥ when                                          |
/// | ---              | ---                          | ---                                             |
/// | fact as subject  | `pred: fact`                 | the fact is absent or stale                     |
/// | effect tuple     | `pred: effect`               | never — the action's tuples are all known        |
/// | effect attribute | `field: effect.attrs.<name>` | no tuple carries the attribute                  |
/// | fact as field    | `field: fact.<id>[.path]`    | the fact is absent or stale, or the path misses |
/// | attribute        | any other `field`            | `set_ref`, and an open-world miss               |
///
/// Everything else is a known FALSE: an empty value list, a predicate that does
/// not match. **⊥ only ever means "we could not find out".**
pub fn evaluate_leaf(
    leaf: &T1Leaf,
    ctx: &mut EvalContext<'_>,
    scan: &ScanTable,
    result: &ScanResult,
) -> Kleene {
    let pred = leaf.pred.as_deref().unwrap_or("");
    if pred == "fact" {
        return leaf_fact_subject(leaf, ctx);
    }
    if pred == "effect" {
        return leaf_effect_tuple(leaf, ctx);
    }
    let field = leaf.field.as_deref().unwrap_or("").to_string();
    if field.starts_with("effect.attrs.") {
        return leaf_effect_attribute(leaf, pred, &field, ctx, scan, result);
    }
    if field.starts_with("fact.") {
        let Some(values) = fact_field_values(ctx, &field) else {
            return Kleene::UNKNOWN;
        };
        if pred == "exists" {
            return Kleene::from_bool(!values.is_empty());
        }
        return Kleene::from_bool(
            values
                .iter()
                .any(|value| test_predicate(pred, &field, value, leaf, scan, result)),
        );
    }
    leaf_attribute(leaf, pred, &field, ctx, scan, result)
}

// ── Nodes ────────────────────────────────────────────────────────────

/// Evaluate one predicate tree against the shared scan result.
///
/// Computes a [`ScanResult`] for this call. A caller that already holds one —
/// because it is evaluating several trees against the same event — passes it to
/// [`evaluate_node_with`] instead and pays for the scan once.
pub fn evaluate_node(node: &T1Node, ctx: &mut EvalContext<'_>, scan: &ScanTable) -> Kleene {
    let result = scan.scan(ctx);
    evaluate_node_with(node, ctx, scan, &result)
}

/// [`evaluate_node`] over a scan result the caller already computed.
///
/// **Every child is evaluated: no short-circuit.** A ⊥ in a branch a
/// short-circuiting evaluator would have skipped still reaches
/// `inconclusive_facts[]`, which is the gap the decision exists to make visible.
pub fn evaluate_node_with(
    node: &T1Node,
    ctx: &mut EvalContext<'_>,
    scan: &ScanTable,
    result: &ScanResult,
) -> Kleene {
    match node.op.as_deref().unwrap_or("") {
        "leaf" => match node.leaf.as_ref() {
            Some(leaf) => evaluate_leaf(leaf, ctx, scan, result),
            // Unreachable through `load`: `validate_node` skipped the artifact.
            None => Kleene::UNKNOWN,
        },
        "and" => {
            let children = evaluate_children(node, ctx, scan, result);
            Kleene::all(&children)
        }
        "or" => {
            let children = evaluate_children(node, ctx, scan, result);
            Kleene::any(&children)
        }
        "not" => {
            let children = evaluate_children(node, ctx, scan, result);
            match children.len() {
                1 => !children[0],
                _ => Kleene::UNKNOWN,
            }
        }
        _ => Kleene::UNKNOWN,
    }
}

fn evaluate_children(
    node: &T1Node,
    ctx: &mut EvalContext<'_>,
    scan: &ScanTable,
    result: &ScanResult,
) -> Vec<Kleene> {
    node.children
        .iter()
        .map(|child| evaluate_node_with(child, ctx, scan, result))
        .collect()
}

// ── The artifact's contribution ──────────────────────────────────────

/// One `t1_predicate_tree` artifact's contribution, or `None` when its tree came
/// out false and the artifact therefore did not fire.
pub fn contribution(
    artifact: &LoadedArtifact,
    body: &T1PredicateTree,
    ctx: &mut EvalContext<'_>,
    scan: &ScanTable,
) -> Option<Contribution> {
    let result = scan.scan(ctx);
    contribution_with(artifact, body, ctx, scan, &result)
}

/// [`contribution`] over a scan result the caller already computed.
pub fn contribution_with(
    artifact: &LoadedArtifact,
    body: &T1PredicateTree,
    ctx: &mut EvalContext<'_>,
    scan: &ScanTable,
    result: &ScanResult,
) -> Option<Contribution> {
    let node = body.node.as_ref()?;

    // A context for ONE artifact, so the ⊥ facts it notes are its own. The
    // alternative — one shared list, recorded into and sliced back off when the
    // tree turns out not to need it — leaked in the oracle: deduplication meant a
    // fact one artifact had already noted went missing from the next one's list.
    let mut child = ctx.fork();
    let value = evaluate_node_with(node, &mut child, scan, result);
    // Warnings are about the BUNDLE, not about whether this tree came out false,
    // so they come back whatever the tree said.
    ctx.merge_warnings(&child);

    if value == Kleene::False {
        // A known FALSE: whatever went ⊥ inside the tree could not have changed
        // the answer, so it is not reported.
        return None;
    }
    let inconclusive = !value.is_known();

    // `declared_mode`, `on_inconclusive_verdict` and `build` are shared with
    // Tier 2 and Tier 3 rather than copied here. The org-wide kill switch is
    // deliberately NOT applied: `contribution` is handed an artifact and a
    // context, never the bundle, so composing `enforcement_enabled: false` into
    // monitor is the caller's, in one place, for all three tiers.
    let mode = declared_mode(artifact);
    let verdict = if inconclusive {
        on_inconclusive_verdict(artifact, &mode)
    } else {
        // A tree that came out TRUE fires the body's verdict. `block` is the
        // default because an artifact that reached here matched: the safe
        // reading of a body that forgot to say what it wanted is not "allow".
        body.verdict.unwrap_or(Verdict::Block)
    };

    Some(build(
        artifact,
        mode,
        verdict,
        body.reason.clone().unwrap_or_default(),
        // A decided TRUE reports nothing: whatever went ⊥ inside a tree that
        // resolved anyway could not have changed the answer.
        if inconclusive {
            child.inconclusive.clone()
        } else {
            Vec::new()
        },
        Vec::new(),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::generated::types::{EffectVerb, TargetClass};
    use crate::zone_eval::types::{
        AgentContext, Classification, ClassifiedPath, ClassifiedUrl, Effect, Event, SessionFacts,
        SimpleCommand, UrlBoundary,
    };

    // ── Scaffolding ──────────────────────────────────────────────────

    fn node(json: serde_json::Value) -> T1Node {
        serde_json::from_value(json).expect("the fixture node parses")
    }

    fn artifact_of(node_json: serde_json::Value) -> LoadedArtifact {
        let doc = serde_json::json!({
            "schema_version": 2,
            "organization_id": "org",
            "revision": 1,
            "built_at": "2026-09-01T00:00:00Z",
            "enforcement_enabled": true,
            "signature": null,
            "artifacts": [{
                "artifact_id": "probe",
                "atom_id": "atom-probe",
                "kind": "t1_predicate_tree",
                "on_inconclusive": "ask",
                "tier": 1,
                "body": {"node": node_json, "verdict": "block", "reason": "probe fired"},
            }],
        });
        super::super::bundle::load(doc)
            .expect("the fixture bundle loads")
            .artifacts
            .remove(0)
    }

    /// Evaluate one tree, returning both the value and the ⊥ facts it noted.
    fn run(
        node_json: serde_json::Value,
        event: &Event,
        class: &Classification,
        set: &super::super::facts::FactSet,
    ) -> (Kleene, Vec<String>) {
        let tree = node(node_json);
        let table = ScanTable::compile(&[artifact_of(
            serde_json::to_value(&tree).expect("the tree serialises"),
        )]);
        let mut ctx = EvalContext::new(event, class, set, 1_756_742_400_000);
        let value = evaluate_node(&tree, &mut ctx, &table);
        (value, ctx.inconclusive.clone())
    }

    fn value_of(node_json: serde_json::Value, event: &Event, class: &Classification) -> Kleene {
        let set = super::super::facts::FactSet::default();
        run(node_json, event, class, &set).0
    }

    fn bash(command: &str) -> Event {
        Event {
            event_type: "pre_tool_use".to_string(),
            tool_name: "Bash".to_string(),
            tool_input: serde_json::json!({"command": command}),
            ..Event::default()
        }
    }

    fn leaf(pred: &str, field: &str, value: serde_json::Value) -> serde_json::Value {
        serde_json::json!({
            "op": "leaf",
            "leaf": {"pred": pred, "field": field, "value": value},
        })
    }

    fn effect(verb: &str, target: &str) -> Effect {
        Effect {
            verb: EffectVerb(verb.to_string()),
            target_class: TargetClass(target.to_string()),
            attrs: serde_json::Map::new(),
        }
    }

    // ── Every leaf predicate against its field ───────────────────────

    #[test]
    fn equals_reads_tool_name() {
        let event = bash("rm -rf /data/x");
        let class = Classification::default();
        assert_eq!(
            value_of(leaf("equals", "tool.name", "Bash".into()), &event, &class),
            Kleene::True
        );
        assert_eq!(
            value_of(leaf("equals", "tool.name", "Read".into()), &event, &class),
            Kleene::False
        );
    }

    #[test]
    fn in_set_matches_any_member() {
        let event = Event {
            tool_name: "Edit".to_string(),
            ..Event::default()
        };
        let class = Classification::default();
        let literal = serde_json::json!(["Write", "Edit", "MultiEdit"]);
        assert_eq!(
            value_of(leaf("in_set", "tool.name", literal), &event, &class),
            Kleene::True
        );
    }

    #[test]
    fn a_json_pointer_reads_into_the_tool_input() {
        let event = Event {
            tool_input: serde_json::json!({"edits": [{"new_string": "hello"}]}),
            ..Event::default()
        };
        let class = Classification::default();
        assert_eq!(
            value_of(
                leaf("equals", "input./edits/0/new_string", "hello".into()),
                &event,
                &class
            ),
            Kleene::True
        );
        // A pointer that misses yields no value, and no value is FALSE.
        assert_eq!(
            value_of(
                leaf("equals", "input./edits/9/new_string", "hello".into()),
                &event,
                &class
            ),
            Kleene::False
        );
    }

    #[test]
    fn input_strings_scans_recursively() {
        let event = Event {
            tool_input: serde_json::json!({"a": {"b": ["src/deep/nested.rs"]}}),
            ..Event::default()
        };
        let class = Classification::default();
        assert_eq!(
            value_of(
                leaf("equals", "input.strings", "src/deep/nested.rs".into()),
                &event,
                &class
            ),
            Kleene::True
        );
    }

    #[test]
    fn keyword_is_case_insensitive_containment() {
        let event = Event {
            tool_input: serde_json::json!({"note": "the PASSWORD is here"}),
            ..Event::default()
        };
        let class = Classification::default();
        let literal = serde_json::json!(["password", "secret"]);
        assert_eq!(
            value_of(leaf("keyword", "input.strings", literal), &event, &class),
            Kleene::True
        );
    }

    #[test]
    fn keyword_folds_unicode_case_not_just_ascii() {
        // The oracle spells this `k.casefold() in value.casefold()`, and `(?-u)`
        // is stated for `regex_lite`, not for `keyword`. ASCII-only folding
        // matches strictly fewer things, and a keyword rule that fires less often
        // than the spec says is the fail-open direction.
        let event = Event {
            tool_input: serde_json::json!({"note": "le CAFÉ est FERMÉ"}),
            ..Event::default()
        };
        let class = Classification::default();
        assert_eq!(
            value_of(
                leaf("keyword", "input.strings", serde_json::json!(["café"])),
                &event,
                &class
            ),
            Kleene::True,
            "an ASCII-only fold would miss this, and the rule would not fire"
        );
        // Folding runs on the NEEDLE too, not only the haystack.
        let lower = Event {
            tool_input: serde_json::json!({"note": "le café est fermé"}),
            ..Event::default()
        };
        assert_eq!(
            value_of(
                leaf("keyword", "input.strings", serde_json::json!(["CAFÉ"])),
                &lower,
                &class
            ),
            Kleene::True
        );
    }

    #[test]
    fn the_folded_fast_path_and_the_direct_fallback_agree() {
        // They did not, and nothing caught it: the automaton was built with
        // `ascii_case_insensitive` while the fallback used `to_lowercase`, so the
        // same leaf answered differently depending on whether the table happened
        // to carry its pattern. The fallback is only reachable off a table that
        // did not compile the pattern, which is exactly where a divergence hides.
        let event = Event {
            tool_input: serde_json::json!({"note": "le CAFÉ est FERMÉ"}),
            ..Event::default()
        };
        let class = Classification::default();
        let set = super::super::facts::FactSet::default();
        let tree = node(leaf(
            "keyword",
            "input.strings",
            serde_json::json!(["café", "STRASSE"]),
        ));

        let compiled = ScanTable::compile(&[artifact_of(
            serde_json::to_value(&tree).expect("serialises"),
        )]);
        let empty = ScanTable::default();

        let mut ctx = EvalContext::new(&event, &class, &set, 1_756_742_400_000);
        let fast = evaluate_node(&tree, &mut ctx, &compiled);
        let mut ctx = EvalContext::new(&event, &class, &set, 1_756_742_400_000);
        let fallback = evaluate_node(&tree, &mut ctx, &empty);

        assert_eq!(fast, Kleene::True);
        assert_eq!(
            fast, fallback,
            "the shared automaton and the direct test are one rule, not two"
        );
    }

    #[test]
    fn full_case_folding_matches_the_oracle() {
        // This assertion used to run the other way, recording the gap std left.
        // It is kept pointing at the same strings on purpose: the test that named
        // the divergence is the test that now proves it closed.
        assert_eq!(fold_keyword("STRASSE").as_ref(), "strasse");
        assert_eq!(
            fold_keyword("straße").as_ref(),
            "strasse",
            "FULL folding: `ß` becomes `ss`, which `to_lowercase` will not do"
        );
        assert_eq!(
            fold_keyword("straße"),
            fold_keyword("STRASSE"),
            "the last place this engine and the oracle disagreed on `keyword`"
        );
        assert_eq!(
            fold_keyword("\u{fb01}").as_ref(),
            "fi",
            "the ligature decomposes under folding, not under lowercasing"
        );

        // Greek final sigma folds to sigma; `to_lowercase` keeps the two distinct,
        // so this pair is the third length-preserving-but-still-different case.
        for (needle, hay) in [
            ("café", "CAFÉ"),
            ("\u{01c6}", "\u{01c4}"),
            ("σίσυφος", "ΣΊΣΥΦΟΣ"),
        ] {
            assert_eq!(
                fold_keyword(needle),
                fold_keyword(hay),
                "{needle} and {hay} fold together"
            );
        }
    }

    #[test]
    fn prefix_matches_only_at_offset_zero() {
        let event = Event {
            tool_input: serde_json::json!({"file_path": "/data/warehouse/x.db"}),
            ..Event::default()
        };
        let class = Classification::default();
        let literal = serde_json::json!(["/data/", "/lake/"]);
        assert_eq!(
            value_of(
                leaf("prefix", "input./file_path", literal.clone()),
                &event,
                &class
            ),
            Kleene::True
        );
        let inner = Event {
            tool_input: serde_json::json!({"file_path": "/srv/data/warehouse/x.db"}),
            ..Event::default()
        };
        assert_eq!(
            value_of(leaf("prefix", "input./file_path", literal), &inner, &class),
            Kleene::False,
            "a prefix found mid-string is not a prefix"
        );
    }

    #[test]
    fn a_single_star_glob_does_not_cross_a_slash() {
        let class = Classification {
            paths: vec![ClassifiedPath {
                class: TargetClass("data_store".to_string()),
                value: "/data/warehouse/x.db".to_string(),
            }],
            ..Classification::default()
        };
        let event = Event::default();
        assert_eq!(
            value_of(
                leaf("glob", "path.value", serde_json::json!(["/data/*"])),
                &event,
                &class
            ),
            Kleene::False
        );
        assert_eq!(
            value_of(
                leaf("glob", "path.value", serde_json::json!(["/data/**"])),
                &event,
                &class
            ),
            Kleene::True
        );
    }

    #[test]
    fn a_brace_in_a_glob_is_a_literal_brace() {
        // The dialect is `**`, `*`, `?` and literals — no alternation, matching
        // the oracle. A pattern list writes its roots out one per entry.
        let class = Classification {
            paths: vec![ClassifiedPath {
                class: TargetClass("data_store".to_string()),
                value: "/data/a".to_string(),
            }],
            ..Classification::default()
        };
        assert_eq!(
            value_of(
                leaf("glob", "path.value", serde_json::json!(["/data/{a,b}"])),
                &Event::default(),
                &class
            ),
            Kleene::False
        );
    }

    #[test]
    fn regex_lite_searches_unanchored() {
        let event = Event {
            tool_input: serde_json::json!({"note": "ssn 123-45-6789 here"}),
            ..Event::default()
        };
        let class = Classification::default();
        let tree = serde_json::json!({
            "op": "leaf",
            "leaf": {
                "pred": "regex_lite",
                "field": "input.strings",
                "pattern": r"\b[0-9]{3}-[0-9]{2}-[0-9]{4}\b",
            },
        });
        assert_eq!(value_of(tree, &event, &class), Kleene::True);
    }

    #[test]
    fn tld_in_is_membership_over_the_url_tld() {
        let class = Classification {
            urls: vec![ClassifiedUrl {
                value: "https://api.example.com/x".to_string(),
                host: "api.example.com".to_string(),
                tld: "com".to_string(),
                scheme: "https".to_string(),
                boundary: UrlBoundary::External,
            }],
            ..Classification::default()
        };
        assert_eq!(
            value_of(
                leaf("tld_in", "url.tld", serde_json::json!(["com", "io"])),
                &Event::default(),
                &class
            ),
            Kleene::True
        );
        assert_eq!(
            value_of(
                leaf("tld_in", "url.tld", serde_json::json!(["dev"])),
                &Event::default(),
                &class
            ),
            Kleene::False
        );
    }

    #[test]
    fn int_cmp_covers_all_five_operators() {
        let event = Event {
            session: Some(SessionFacts {
                tool_calls: Some(12),
                ..SessionFacts::default()
            }),
            ..Event::default()
        };
        let class = Classification::default();
        for (op, n, expected) in [
            ("lt", 20, Kleene::True),
            ("le", 12, Kleene::True),
            ("gt", 5, Kleene::True),
            ("ge", 12, Kleene::True),
            ("eq", 12, Kleene::True),
            ("eq", 99, Kleene::False),
        ] {
            let spec = serde_json::json!({"op": op, "n": n});
            assert_eq!(
                value_of(leaf("int_cmp", "session.tool_calls", spec), &event, &class),
                expected,
                "int_cmp {op} {n}"
            );
        }
    }

    #[test]
    fn int_cmp_refuses_a_boolean() {
        // A JSON `true` is not an integer, however cheerfully Python would
        // compare it to one.
        let event = Event {
            tool_input: serde_json::json!({"flag": true}),
            ..Event::default()
        };
        let class = Classification::default();
        let spec = serde_json::json!({"op": "ge", "n": 1});
        assert_eq!(
            value_of(leaf("int_cmp", "input./flag", spec), &event, &class),
            Kleene::False
        );
    }

    #[test]
    fn exists_is_false_over_an_empty_value_list() {
        let class = Classification::default();
        let tree = serde_json::json!({
            "op": "leaf",
            "leaf": {"pred": "exists", "field": "url.host"},
        });
        assert_eq!(
            value_of(tree.clone(), &Event::default(), &class),
            Kleene::False
        );
        let with_url = Classification {
            urls: vec![ClassifiedUrl {
                value: "https://api.example.com".to_string(),
                host: "api.example.com".to_string(),
                tld: "com".to_string(),
                scheme: "https".to_string(),
                boundary: UrlBoundary::External,
            }],
            ..Classification::default()
        };
        assert_eq!(value_of(tree, &Event::default(), &with_url), Kleene::True);
    }

    #[test]
    fn the_effect_tuple_leaf_matches_any_tuple() {
        let class = Classification {
            effects: vec![effect("delete", "data_store")],
            ..Classification::default()
        };
        let hit = serde_json::json!({
            "op": "leaf",
            "leaf": {"pred": "effect", "effect": {"verb": "delete", "target_class": "data_store"}},
        });
        let miss = serde_json::json!({
            "op": "leaf",
            "leaf": {"pred": "effect", "effect": {"verb": "write", "target_class": "data_store"}},
        });
        assert_eq!(value_of(hit, &Event::default(), &class), Kleene::True);
        assert_eq!(
            value_of(miss, &Event::default(), &class),
            Kleene::False,
            "a wrong verb is a known FALSE, never ⊥"
        );
    }

    #[test]
    fn command_and_path_families_read_the_classification() {
        let class = Classification {
            simple: vec![SimpleCommand {
                program: "rm".to_string(),
                argv: vec!["-rf".to_string(), "/data/x".to_string()],
                raw: "rm -rf /data/x".to_string(),
                redirects: Vec::new(),
                raw_argv: vec!["-rf".to_string(), "/data/x".to_string()],
            }],
            paths: vec![ClassifiedPath {
                class: TargetClass("secret_material".to_string()),
                value: "/home/a/.env".to_string(),
            }],
            ..Classification::default()
        };
        let event = Event::default();
        assert_eq!(
            value_of(
                leaf("equals", "command.program", "rm".into()),
                &event,
                &class
            ),
            Kleene::True
        );
        assert_eq!(
            value_of(
                leaf(
                    "in_set",
                    "command.argv",
                    serde_json::json!(["-rf", "--force"])
                ),
                &event,
                &class
            ),
            Kleene::True
        );
        assert_eq!(
            value_of(
                leaf("equals", "path.class", "secret_material".into()),
                &event,
                &class
            ),
            Kleene::True
        );
        let simple_exists = serde_json::json!({
            "op": "leaf", "leaf": {"pred": "exists", "field": "command.simple"},
        });
        assert_eq!(value_of(simple_exists, &event, &class), Kleene::True);
    }

    #[test]
    fn agent_type_and_id_read_their_aliases() {
        let event = Event {
            agent: Some(AgentContext {
                agent_id: Some("agent-conformance".to_string()),
                agent_type: Some("coding_assistant".to_string()),
                ..AgentContext::default()
            }),
            ..Event::default()
        };
        let class = Classification::default();
        assert_eq!(
            value_of(
                leaf("equals", "agent.type", "coding_assistant".into()),
                &event,
                &class
            ),
            Kleene::True
        );
        assert_eq!(
            value_of(
                leaf("equals", "agent.id", "agent-conformance".into()),
                &event,
                &class
            ),
            Kleene::True
        );
    }

    #[test]
    fn an_absent_agent_field_is_false_not_unknown() {
        let event = Event {
            agent: Some(AgentContext::default()),
            ..Event::default()
        };
        let class = Classification::default();
        assert_eq!(
            value_of(
                leaf("equals", "agent.principal", "svc-deployer".into()),
                &event,
                &class
            ),
            Kleene::False
        );
    }

    #[test]
    fn an_absent_session_object_is_false_not_unknown() {
        let class = Classification::default();
        let spec = serde_json::json!({"op": "ge", "n": 1});
        assert_eq!(
            value_of(
                leaf("int_cmp", "session.tool_calls", spec),
                &Event::default(),
                &class
            ),
            Kleene::False,
            "an absent session is a known negative, not a gap in what we know"
        );
    }

    // ── result.exit_code, and the null that is FALSE ─────────────────

    #[test]
    fn exit_code_reads_only_a_post_tool_use_shell_result() {
        let class = Classification::default();
        let spec = serde_json::json!({"op": "eq", "n": 1});
        let tree = leaf("int_cmp", "result.exit_code", spec);

        let post_shell = Event {
            event_type: "post_tool_use".to_string(),
            tool_name: "Bash".to_string(),
            tool_result: Some(serde_json::json!({"exit_code": 1})),
            ..Event::default()
        };
        assert_eq!(value_of(tree.clone(), &post_shell, &class), Kleene::True);

        // Same result payload, a pre event: the field is null, and the leaf is
        // FALSE — not ⊥, and not true.
        let pre = Event {
            event_type: "pre_tool_use".to_string(),
            tool_name: "Bash".to_string(),
            tool_result: Some(serde_json::json!({"exit_code": 1})),
            ..Event::default()
        };
        assert_eq!(value_of(tree.clone(), &pre, &class), Kleene::False);

        // Same event type, a non-shell tool: also null, also FALSE.
        let post_read = Event {
            event_type: "post_tool_use".to_string(),
            tool_name: "Read".to_string(),
            tool_result: Some(serde_json::json!({"exit_code": 1})),
            ..Event::default()
        };
        assert_eq!(value_of(tree.clone(), &post_read, &class), Kleene::False);

        // And `exists` over the null is FALSE too, which is the rule that makes
        // the other three consistent rather than special-cased.
        let exists = serde_json::json!({
            "op": "leaf", "leaf": {"pred": "exists", "field": "result.exit_code"},
        });
        assert_eq!(value_of(exists, &pre, &class), Kleene::False);
    }

    // ── effect.attrs.<name> — absent is ⊥, present-and-wrong is FALSE ─

    #[test]
    fn an_effect_attribute_no_tuple_carries_is_unknown() {
        let mut with_attr = effect("write", "data_store");
        with_attr
            .attrs
            .insert("is_production".to_string(), serde_json::json!(true));
        let carried = Classification {
            effects: vec![with_attr],
            ..Classification::default()
        };
        let bare = Classification {
            effects: vec![effect("write", "data_store")],
            ..Classification::default()
        };
        let tree = leaf("equals", "effect.attrs.is_production", true.into());

        assert_eq!(
            value_of(tree.clone(), &Event::default(), &carried),
            Kleene::True
        );
        assert_eq!(
            value_of(tree, &Event::default(), &bare),
            Kleene::UNKNOWN,
            "no tuple said whether this was production — that is a gap, not a no"
        );

        let mut false_attr = effect("write", "data_store");
        false_attr
            .attrs
            .insert("is_production".to_string(), serde_json::json!(false));
        let denied = Classification {
            effects: vec![false_attr],
            ..Classification::default()
        };
        assert_eq!(
            value_of(
                leaf("equals", "effect.attrs.is_production", true.into()),
                &Event::default(),
                &denied
            ),
            Kleene::False,
            "a tuple that said `false` is a known negative"
        );
    }

    // ── The shared scan result IS N independent scans ────────────────

    #[test]
    fn one_shared_scan_result_feeds_n_trees_identically_to_n_independent_scans() {
        // The correctness proof of the whole design. Four trees over three
        // different fields and all four pattern predicates, compiled into ONE
        // table, then evaluated twice: once with a scan result computed per tree,
        // and once with a single shared one.
        let trees = [
            node(leaf(
                "keyword",
                "input.strings",
                serde_json::json!(["password", "secret"]),
            )),
            node(leaf(
                "prefix",
                "input./file_path",
                serde_json::json!(["/data/", "/lake/"]),
            )),
            node(serde_json::json!({
                "op": "leaf",
                "leaf": {"pred": "regex_lite", "field": "input.strings",
                         "pattern": r"[0-9]{3}-[0-9]{2}-[0-9]{4}"},
            })),
            node(leaf("glob", "path.value", serde_json::json!(["/data/**"]))),
        ];
        let artifacts: Vec<LoadedArtifact> = trees
            .iter()
            .map(|tree| artifact_of(serde_json::to_value(tree).expect("serialises")))
            .collect();
        let table = ScanTable::compile(&artifacts);
        assert_eq!(table.scanned_fields.len(), 3, "three surfaces, not one");

        let event = Event {
            tool_input: serde_json::json!({
                "file_path": "/data/warehouse/x.db",
                "note": "the PASSWORD is 123-45-6789",
            }),
            ..Event::default()
        };
        let class = Classification {
            paths: vec![ClassifiedPath {
                class: TargetClass("data_store".to_string()),
                value: "/data/warehouse/x.db".to_string(),
            }],
            ..Classification::default()
        };
        let set = super::super::facts::FactSet::default();

        let independent: Vec<Kleene> = trees
            .iter()
            .map(|tree| {
                let mut ctx = EvalContext::new(&event, &class, &set, 1_756_742_400_000);
                evaluate_node(tree, &mut ctx, &table)
            })
            .collect();

        let shared_result = {
            let ctx = EvalContext::new(&event, &class, &set, 1_756_742_400_000);
            table.scan(&ctx)
        };
        let shared: Vec<Kleene> = trees
            .iter()
            .map(|tree| {
                let mut ctx = EvalContext::new(&event, &class, &set, 1_756_742_400_000);
                evaluate_node_with(tree, &mut ctx, &table, &shared_result)
            })
            .collect();

        assert_eq!(independent, shared);
        assert_eq!(
            independent,
            vec![Kleene::True, Kleene::True, Kleene::True, Kleene::True],
            "and all four actually fired, so the comparison is not vacuous"
        );
    }

    #[test]
    fn the_scan_surface_is_per_field_not_one_concatenated_haystack() {
        // The failure a single global haystack would produce: a keyword that only
        // ever appears in `input.strings` firing a leaf that reads
        // `result.strings`.
        let over_result = node(leaf(
            "keyword",
            "result.strings",
            serde_json::json!(["password"]),
        ));
        let over_input = node(leaf(
            "keyword",
            "input.strings",
            serde_json::json!(["password"]),
        ));
        let table = ScanTable::compile(&[
            artifact_of(serde_json::to_value(&over_result).expect("serialises")),
            artifact_of(serde_json::to_value(&over_input).expect("serialises")),
        ]);
        assert_eq!(
            table.keyword_sources.len(),
            1,
            "the same source compiles once and is shared by both trees"
        );

        let event = Event {
            tool_input: serde_json::json!({"note": "password"}),
            tool_result: Some(serde_json::json!({"stdout": "all clear"})),
            ..Event::default()
        };
        let class = Classification::default();
        let set = super::super::facts::FactSet::default();
        let mut ctx = EvalContext::new(&event, &class, &set, 1_756_742_400_000);
        let result = table.scan(&ctx);

        assert_eq!(
            evaluate_node_with(&over_input, &mut ctx, &table, &result),
            Kleene::True
        );
        assert_eq!(
            evaluate_node_with(&over_result, &mut ctx, &table, &result),
            Kleene::False,
            "the keyword is in the input, not in the result"
        );
    }

    // ── (?-u), and the budgets ───────────────────────────────────────

    #[test]
    fn every_regex_constructor_explicitly_sizes_its_cache_pool() {
        let sources = vec![r"\w+".to_string(), r"\d+".to_string()];
        let globs = vec![glob_to_regex("*"), glob_to_regex("?")];
        for re in [
            compile_one_regex(&sources[0]).unwrap(),
            compile_regex_set(&sources).unwrap(),
            compile_one_glob("*").unwrap(),
            compile_pattern_set(&globs, true).unwrap(),
        ] {
            // Overlay on capacity 1: an unset capacity cannot pass even when
            // the host happens to have 8 CPUs. Builder configuration is merged,
            // so this proves the production regex supplied an explicit value.
            let inherited = meta::Regex::builder()
                .configure(meta::Regex::config().pool_capacity(1))
                .configure(re.get_config().clone())
                .build("")
                .unwrap();
            assert_eq!(inherited.get_config().get_pool_capacity(), 8);
        }
    }

    #[test]
    fn pattern_sets_preserve_bytes_unicode_and_every_matching_source_id() {
        let regexes: Vec<String> = [r"", r"\w+", r"(?u:\w+)", r"\xFF", r"a|ab"]
            .map(str::to_string)
            .into();
        let set = compile_regex_set(&regexes).unwrap();
        for (text, expected) in [
            (b"ab".as_slice(), vec![0, 1, 2, 4]),
            ("".as_bytes(), vec![0, 2]),
            (b"\xFF".as_slice(), vec![0, 3]),
            (b"".as_slice(), vec![0]),
        ] {
            let actual: Vec<usize> = matching_patterns(&set, text)
                .iter()
                .map(|id| id.as_usize())
                .collect();
            assert_eq!(actual, expected);
            for (id, source) in regexes.iter().enumerate() {
                assert_eq!(
                    compile_one_regex(source).unwrap().is_match(text),
                    expected.contains(&id),
                );
            }
        }

        let globs = ["**", "?", "*", "a*", "a?", "[a]", "{a,b}"];
        let translated = globs.map(glob_to_regex);
        let set = compile_pattern_set(&translated, true).unwrap();
        for (text, expected) in [
            ("é", vec![0, 1, 2]),
            ("a/b", vec![0]),
            ("a\n", vec![0, 2, 3, 4]),
            ("[a]", vec![0, 2, 5]),
            ("{a,b}", vec![0, 2, 6]),
            ("", vec![0, 2]),
        ] {
            let actual: Vec<usize> = matching_patterns(&set, text.as_bytes())
                .iter()
                .map(|id| id.as_usize())
                .collect();
            assert_eq!(actual, expected);
            for (id, source) in globs.iter().enumerate() {
                assert_eq!(
                    compile_one_glob(source).unwrap().is_match(text),
                    expected.contains(&id),
                );
            }
        }
    }

    #[test]
    fn regex_lite_runs_in_ascii_mode() {
        // `\w` is the whole test: under Unicode it matches `ï`, under `(?-u)` it
        // does not. A build that quietly left Unicode on answers TRUE here and
        // pays the measured 15× p99 regression on `\b`.
        let event = Event {
            tool_input: serde_json::json!({"word": "naïve"}),
            ..Event::default()
        };
        let class = Classification::default();
        let tree = serde_json::json!({
            "op": "leaf",
            "leaf": {"pred": "regex_lite", "field": "input./word", "pattern": r"^\w+$"},
        });
        assert_eq!(value_of(tree, &event, &class), Kleene::False);

        // The control: the same pattern over an ASCII word still matches, so the
        // assertion above is about Unicode and not about the pattern being broken.
        let ascii = Event {
            tool_input: serde_json::json!({"word": "naive"}),
            ..Event::default()
        };
        let control = serde_json::json!({
            "op": "leaf",
            "leaf": {"pred": "regex_lite", "field": "input./word", "pattern": r"^\w+$"},
        });
        assert_eq!(value_of(control, &ascii, &class), Kleene::True);
    }

    #[test]
    fn a_regex_over_the_source_limit_skips_its_artifact_and_leaves_the_others_active() {
        let oversized = "a".repeat(REGEX_SOURCE_LIMIT + 1);
        let doc = serde_json::json!({
            "schema_version": 2,
            "organization_id": "org",
            "revision": 1,
            "built_at": "2026-09-01T00:00:00Z",
            "enforcement_enabled": true,
            "signature": null,
            "artifacts": [
                {
                    "artifact_id": "big",
                    "kind": "t1_predicate_tree",
                    "body": {
                        "node": {"op": "leaf", "leaf": {
                            "pred": "regex_lite", "field": "input.strings", "pattern": oversized,
                        }},
                        "verdict": "block", "reason": "r",
                    },
                },
                {
                    "artifact_id": "small",
                    "kind": "t1_predicate_tree",
                    "body": {
                        "node": {"op": "leaf", "leaf": {
                            "pred": "equals", "field": "tool.name", "value": "Bash",
                        }},
                        "verdict": "block", "reason": "r",
                    },
                },
            ],
        });
        let bundle = super::super::bundle::load(doc).expect("one bad pattern is not a bad bundle");
        assert_eq!(bundle.artifacts.len(), 1, "the other artifact stayed armed");
        assert_eq!(bundle.artifacts[0].artifact_id(), Some("small"));
        assert_eq!(bundle.skipped.len(), 1);
        assert_eq!(bundle.skipped[0].id, "big");
        assert_eq!(
            bundle.skipped[0].reason,
            super::super::types::SKIP_BAD_PATTERN
        );
    }

    #[test]
    fn the_corpus_size_limit_row_is_about_the_source_cap_not_the_memory_guard() {
        // The row is `parse-skips-regex-lite-over-the-size-limit-and-keeps-the-rest`
        // and it is the one that settles which budget the spec meant. Its pattern
        // is 1100 bytes of source and compiles to ~35 KB of program — so a
        // compiled-size cap anywhere near the old 64 KiB would have ACCEPTED it,
        // the artifact would have loaded, and the row would fail while every unit
        // test here stayed green.
        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("schemas/conformance");
        let document: serde_json::Value = serde_json::from_str(
            &std::fs::read_to_string(
                dir.join("bundles/07-parse-regex-lite-over-the-size-limit.json"),
            )
            .expect("the fixture is readable"),
        )
        .expect("the fixture is valid JSON");

        let source = document["artifacts"][0]["body"]["node"]["leaf"]["pattern"]
            .as_str()
            .expect("the fixture carries a pattern");
        assert!(
            source.len() > REGEX_SOURCE_LIMIT,
            "the fixture is over the source cap: {} bytes",
            source.len()
        );
        assert!(
            compile_one_regex(source).is_some(),
            "and the MEMORY GUARD would have let it through — which is the whole \
             point of the row: the source cap is what rejects it"
        );

        let bundle =
            super::super::bundle::load(document).expect("one bad pattern is not a bad bundle");
        let skipped: Vec<&str> = bundle.skipped.iter().map(|s| s.id.as_str()).collect();
        assert_eq!(skipped, vec!["bad"], "the oversize artifact is skipped");
        assert_eq!(
            bundle.skipped[0].reason,
            super::super::types::SKIP_BAD_PATTERN
        );
        assert_eq!(
            bundle
                .artifacts
                .iter()
                .filter_map(|a| a.artifact_id())
                .collect::<Vec<_>>(),
            vec!["good"],
            "and the rest of the bundle stays armed"
        );
    }

    #[test]
    fn the_memory_guard_is_a_last_resort_and_never_decides_before_the_source_cap() {
        // Nothing a human plausibly writes reaches the guard. The corpus's real
        // pattern needs under 1 KB of program; a 5000-wide character class needs
        // 360 KB. Both compile.
        for ordinary in [r"\b[0-9]{3}-[0-9]{2}-[0-9]{4}\b", "[a-z]{5000}"] {
            assert!(
                compile_one_regex(ordinary).is_some(),
                "the guard must not fire on {ordinary:?}"
            );
        }

        // What DOES reach it is a counted-repetition bomb: 17 bytes of source
        // asking for ~30 MB of program. This is the residual divergence from the
        // oracle, which has no compiled budget at all — documented on
        // `REGEX_SIZE_LIMIT`, and deliberately pointed at memory exhaustion
        // rather than away from it.
        let bomb = "(?:a{1000}){1000}";
        assert!(
            bomb.len() < REGEX_SOURCE_LIMIT,
            "the source cap does not catch it"
        );
        assert!(compile_one_regex(bomb).is_none(), "the guard does");
    }

    #[test]
    fn look_around_and_back_references_are_not_expressible_and_skip_their_artifact() {
        // The oracle rejects these by scanning for the syntax; the `regex` crate
        // rejects them by refusing to compile. Same outcome, and the corpus has a
        // row for each (`07-parse-regex-lite-look-around`, `-back-reference`).
        for unsupported in ["(?=secret)x", r"(a)\1"] {
            assert!(
                validate_patterns(Some(&node(serde_json::json!({
                    "op": "leaf",
                    "leaf": {"pred": "regex_lite", "field": "input.strings", "pattern": unsupported},
                }))))
                .is_err(),
                "{unsupported:?} is not expressible in (?-u) mode"
            );
        }
    }

    // ── Load-time validation ─────────────────────────────────────────

    #[test]
    fn validation_closes_the_operator_predicate_and_field_sets() {
        assert!(validate_node(None).is_err());
        assert!(validate_node(Some(&node(serde_json::json!({
            "op": "xor", "children": [],
        }))))
        .is_err());
        assert!(validate_node(Some(&node(serde_json::json!({
            "op": "leaf", "leaf": {"pred": "sounds_like", "field": "tool.name", "value": "x"},
        }))))
        .is_err());
        assert!(validate_node(Some(&node(serde_json::json!({
            "op": "leaf", "leaf": {"pred": "equals", "field": "tool.nombre", "value": "x"},
        }))))
        .is_err());
        assert!(validate_node(Some(&node(serde_json::json!({
            "op": "leaf", "leaf": {"pred": "fact", "fact": {"fact_id": "x", "op": "matches"}},
        }))))
        .is_err());
        assert!(validate_node(Some(&node(
            serde_json::json!({"op": "and", "children": []})
        )))
        .is_err());
        assert!(validate_node(Some(&node(serde_json::json!({
            "op": "not",
            "children": [
                {"op": "leaf", "leaf": {"pred": "equals", "field": "tool.name", "value": "a"}},
                {"op": "leaf", "leaf": {"pred": "equals", "field": "tool.name", "value": "b"}},
            ],
        }))))
        .is_err());
        // The three prefixed families are members of the vocabulary too.
        for field in ["input./command", "fact.change_ticket", "effect.attrs.force"] {
            assert!(
                validate_node(Some(&node(serde_json::json!({
                    "op": "leaf", "leaf": {"pred": "exists", "field": field},
                }))))
                .is_ok(),
                "{field} is in the vocabulary"
            );
        }
    }

    // ── Kleene propagation through the node ops ──────────────────────

    /// A tree whose only leaf is ⊥: `effect.attrs.<name>` no tuple carries.
    fn unknown_leaf() -> serde_json::Value {
        leaf("equals", "effect.attrs.is_production", true.into())
    }

    fn truth(value: bool) -> serde_json::Value {
        leaf(
            "equals",
            "tool.name",
            if value { "Bash" } else { "Read" }.into(),
        )
    }

    #[test]
    fn an_unknown_propagates_through_and_or_and_not_without_collapsing() {
        let event = bash("rm -rf /data/x");
        let class = Classification {
            effects: vec![effect("delete", "data_store")],
            ..Classification::default()
        };
        assert_eq!(
            value_of(unknown_leaf(), &event, &class),
            Kleene::UNKNOWN,
            "the fixture leaf really is ⊥"
        );

        // T ∧ ⊥ = ⊥, and F ∧ ⊥ = F — a decided false DOMINATES.
        let and_true = serde_json::json!({"op": "and", "children": [truth(true), unknown_leaf()]});
        let and_false =
            serde_json::json!({"op": "and", "children": [truth(false), unknown_leaf()]});
        assert_eq!(value_of(and_true, &event, &class), Kleene::UNKNOWN);
        assert_eq!(value_of(and_false, &event, &class), Kleene::False);

        // T ∨ ⊥ = T, and F ∨ ⊥ = ⊥.
        let or_true = serde_json::json!({"op": "or", "children": [truth(true), unknown_leaf()]});
        let or_false = serde_json::json!({"op": "or", "children": [truth(false), unknown_leaf()]});
        assert_eq!(value_of(or_true, &event, &class), Kleene::True);
        assert_eq!(value_of(or_false, &event, &class), Kleene::UNKNOWN);

        // ¬⊥ = ⊥. This is the one an `unwrap_or(false)` would silently turn into
        // a TRUE, and a `NOT only_if` is where every compiled atom puts it.
        let negated = serde_json::json!({"op": "not", "children": [unknown_leaf()]});
        assert_eq!(value_of(negated, &event, &class), Kleene::UNKNOWN);
    }

    #[test]
    fn the_node_ops_are_two_valued_when_nothing_is_unknown() {
        let event = bash("rm -rf /data/x");
        let class = Classification {
            effects: vec![effect("delete", "data_store")],
            ..Classification::default()
        };
        let and_both = serde_json::json!({"op": "and", "children": [truth(true), truth(true)]});
        let and_one = serde_json::json!({"op": "and", "children": [truth(true), truth(false)]});
        let or_second = serde_json::json!({"op": "or", "children": [truth(false), truth(true)]});
        let or_neither = serde_json::json!({"op": "or", "children": [truth(false), truth(false)]});
        assert_eq!(value_of(and_both, &event, &class), Kleene::True);
        assert_eq!(value_of(and_one, &event, &class), Kleene::False);
        assert_eq!(value_of(or_second, &event, &class), Kleene::True);
        assert_eq!(value_of(or_neither, &event, &class), Kleene::False);
        assert_eq!(
            value_of(
                serde_json::json!({"op": "not", "children": [truth(false)]}),
                &event,
                &class
            ),
            Kleene::True
        );
    }

    #[test]
    fn every_child_is_evaluated_so_a_bottom_still_reaches_the_report() {
        // A short-circuiting AND would stop at the FALSE and never notice the ⊥
        // beside it. Nothing about the verdict changes; what changes is whether
        // the fact that could not be read is ever named.
        let event = Event::default();
        let class = Classification::default();
        let set = super::super::facts::FactSet::default();
        let tree = serde_json::json!({
            "op": "and",
            "children": [
                truth(false),
                {"op": "leaf", "leaf": {"pred": "fact",
                                        "fact": {"fact_id": "change_ticket", "op": "equals",
                                                 "value": true}}},
            ],
        });
        let (value, inconclusive) = run(tree, &event, &class, &set);
        assert_eq!(value, Kleene::False, "the verdict is unchanged");
        assert_eq!(
            inconclusive,
            vec!["change_ticket".to_string()],
            "and the gap is still reported"
        );
    }

    // ── The contribution ─────────────────────────────────────────────

    // ── The corpus, read as truth values ─────────────────────────────

    /// Every row of `01-tier1-preds.jsonl`, evaluated as a TRUTH VALUE.
    ///
    /// The corpus runner compares whole `Decision`s, so every row of this file
    /// stays red until the join lands and cannot say whether a *leaf* is right.
    /// The probe bundles were built to be readable the other way round — one
    /// artifact, one leaf, `verdict: block`, `on_inconclusive: ask` — and
    /// `schemas/conformance/README.md` writes the mapping out:
    ///
    /// | Decision | the leaf evaluated to |
    /// | --- | --- |
    /// | `block` | TRUE |
    /// | `allow`, `undecided: true` | FALSE |
    /// | `ask` | ⊥ |
    ///
    /// So this reads the oracle's expectations for what they are — the answer to
    /// *this slice's* question — and holds Tier 1 to them now rather than after
    /// two other slices land. The corpus is consumed, never edited: a
    /// disagreement here is this file being wrong.
    #[test]
    fn the_corpus_pins_every_leaf_as_a_truth_value() {
        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("schemas/conformance");
        let rows = std::fs::read_to_string(dir.join("01-tier1-preds.jsonl"))
            .expect("the corpus file is readable");

        let mut checked = 0usize;
        let mut disagreements: Vec<String> = Vec::new();

        for line in rows.lines().filter(|l| !l.trim().is_empty()) {
            let row: serde_json::Value =
                serde_json::from_str(line).expect("every corpus row is valid JSON");
            let id = row["id"].as_str().unwrap_or_default().to_string();
            let bundle_ref = row["bundle_ref"]
                .as_str()
                .expect("every row names a bundle");
            let document: serde_json::Value = serde_json::from_str(
                &std::fs::read_to_string(dir.join(bundle_ref)).expect("the bundle is readable"),
            )
            .expect("the bundle is valid JSON");
            let bundle = super::super::bundle::load(document).expect("the bundle loads");

            let Some(artifact) = bundle.artifacts.first() else {
                continue; // an artifact-free bundle pins a classification, not a leaf
            };
            let ArtifactBody::T1(body) = &artifact.body else {
                continue;
            };
            let Some(tree) = body.node.as_ref() else {
                continue;
            };

            let event: Event =
                serde_json::from_value(row["event"].clone()).expect("the event deserialises");
            let now_ms = row["now_ms"].as_i64().expect("every row carries now_ms");
            let facts = super::super::facts::resolve(&bundle, now_ms);
            let class =
                super::super::effect::classify(&event, &facts, bundle.effect_classes.as_ref());
            let mut ctx = EvalContext::new(&event, &class, &facts, now_ms);
            let value = evaluate_node(tree, &mut ctx, &bundle.scan);

            let decision = &row["expected"]["decision"];
            let expected = match decision["verdict"].as_str() {
                Some("block") => Kleene::True,
                Some("ask") => Kleene::UNKNOWN,
                Some("allow") if decision["undecided"].as_bool() == Some(true) => Kleene::False,
                // An artifact that decided `allow` on purpose is not a truth
                // value this table can read; no `01-` row is one today.
                _ => continue,
            };
            checked += 1;
            let agrees = match (expected, value) {
                // ⊥ compares by being ⊥: the REASON is the engine's own, and the
                // corpus reports it through `inconclusive_facts[]` instead.
                (Kleene::Unknown(_), Kleene::Unknown(_)) => true,
                (left, right) => left == right,
            };
            if !agrees {
                disagreements.push(format!("{id}: expected {expected:?}, got {value:?}"));
            }
        }

        assert!(
            checked >= 70,
            "the corpus was found and read: {checked} rows"
        );
        assert!(
            disagreements.is_empty(),
            "{} of {checked} corpus leaves disagree with Tier 1 - the engine is wrong \
             until the spec says the row was:\n  {}",
            disagreements.len(),
            disagreements.join("\n  ")
        );
    }

    #[test]
    fn a_false_tree_contributes_nothing() {
        let artifact = artifact_of(leaf("equals", "tool.name", "Bash".into()));
        let ArtifactBody::T1(body) = &artifact.body else {
            panic!("the fixture is a t1 artifact");
        };
        let event = Event {
            tool_name: "Read".to_string(),
            ..Event::default()
        };
        let class = Classification::default();
        let set = super::super::facts::FactSet::default();
        let mut ctx = EvalContext::new(&event, &class, &set, 1_756_742_400_000);
        let table = ScanTable::compile(std::slice::from_ref(&artifact));
        assert!(contribution(&artifact, body, &mut ctx, &table).is_none());
    }

    #[test]
    fn a_true_tree_contributes_the_bodys_verdict_and_the_envelopes_identity() {
        let artifact = artifact_of(leaf("equals", "tool.name", "Bash".into()));
        let ArtifactBody::T1(body) = &artifact.body else {
            panic!("the fixture is a t1 artifact");
        };
        let event = bash("rm -rf /data/x");
        let class = Classification::default();
        let set = super::super::facts::FactSet::default();
        let mut ctx = EvalContext::new(&event, &class, &set, 1_756_742_400_000);
        let table = ScanTable::compile(std::slice::from_ref(&artifact));
        let contribution =
            contribution(&artifact, body, &mut ctx, &table).expect("a true tree fires");
        assert_eq!(contribution.verdict, Verdict::Block);
        assert_eq!(contribution.reason, "probe fired");
        assert_eq!(contribution.artifact_id.as_deref(), Some("probe"));
        assert_eq!(contribution.atom_id.as_deref(), Some("atom-probe"));
        assert_eq!(contribution.tier, Some(1));
        assert!(contribution.inconclusive.is_empty());
    }

    #[test]
    fn an_unknown_tree_takes_the_artifacts_on_inconclusive_branch() {
        let artifact = artifact_of(unknown_leaf());
        let ArtifactBody::T1(body) = &artifact.body else {
            panic!("the fixture is a t1 artifact");
        };
        let event = Event::default();
        let class = Classification {
            effects: vec![effect("delete", "data_store")],
            ..Classification::default()
        };
        let set = super::super::facts::FactSet::default();
        let mut ctx = EvalContext::new(&event, &class, &set, 1_756_742_400_000);
        let table = ScanTable::compile(std::slice::from_ref(&artifact));
        let contribution = contribution(&artifact, body, &mut ctx, &table)
            .expect("⊥ contributes, it does not fire");
        assert_eq!(
            contribution.verdict,
            Verdict::Ask,
            "the fixture declares on_inconclusive: ask"
        );
    }
}