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
//! Tier 2 — a straight-line register interpreter. Plan 02 §2d, PRD §Session
//! shapes → Tier 2 programs.
//!
//! Programs are instances of the SIX shape templates only — `count_le`, `seen`,
//! `elapsed_le`, `run_le`, `budget_le`, `followed_by`. The compiler emits no
//! other op sequence, so the interpreter needs no general evaluator; a general
//! one would accept programs the compiler cannot produce and the "no loops" bound
//! would stop being structural.
//!
//! # The instruction encoding
//!
//! Positional — `[op, operands…]` — and this module is its specification,
//! because the compiler that will emit it does not exist yet. The schema types
//! the instruction as `Vec<serde_json::Value>` on purpose (R14): one unknown op
//! must not fail the document, so the op list is closed HERE, at
//! [`validate_program`], and an artifact carrying anything else is skipped while
//! the rest of the bundle stays active.
//!
//! ```text
//! ["MATCH",      <t1 node>, b]              b := the tree, ⊥ coerced to false
//! ["INC_SAT",    c, b?]                     if b (or unconditionally): c := sat(c + 1)
//! ["RESET",      c]                         c := 0
//! ["CMP_GE",     bank, i, k, b]             b := state[bank][i] >= k   bank ∈ c|a|t|run
//! ["SET",        f, b?] ["CLR", f, b?]      if b (or unconditionally): f := true/false
//! ["TEST",       f, b]                      b := f
//! ["TS_STORE",   t, b?]                     if b (or unconditionally): t := now_ms
//! ["TS_ELAPSED", t, a]                      a := now_ms − t   (0 when t is unset)
//! ["ADD_SAT",    a, "spend_delta.tokens"]   a := sat(a + the event's field)
//! ["RUN_TRACK"]                             run := extend-or-restart on the action shape
//! ["AND", x, y, d] ["OR", x, y, d] ["NOT", x, d]
//! ["VERDICT",    b]                         if b: the program fires with body.verdict
//! ["ANOMALY",    b, code]                   if b: record the anomaly code
//! ["DONE",       b]                         if b: stop executing this program
//! ```
//!
//! Bool registers are **transient per run and are not session state** — they are
//! absent from `state_layout` and never appear in `state_out`.
//!
//! # Four hard constraints, and what they buy
//!
//! No loops · no register-indexed addressing (a register index is a **literal in
//! the program**, checked by [`validate_program`], so no program can compute the
//! slot it reads) · saturating arithmetic ([`sat`] never wraps) · integer only
//! (`bundle::contains_float` skips a body carrying one, and [`operand_index`]
//! refuses a non-integer where an index belongs). Together these make every
//! program terminate in bounded time on bounded memory.
//!
//! # Which half runs, and why there is no event-type leaf
//!
//! `pre` runs on the deciding event, `post` on the post event. There is no
//! event-type leaf in the closed field vocabulary, so a template that must act
//! only on `session_start` (`elapsed_le`'s `TS_STORE`) writes the **store-once
//! idiom** with a flag instead:
//! `["TEST", f, 0] ["NOT", 0, 1] ["TS_STORE", t, 1] ["SET", f, 1]`.
//!
//! **The templates are the guarded form.** Every `pre` program consumes its
//! trigger bit — `… · AND b,v→v2 · VERDICT v2`. Dropping the conjunct makes a
//! `count_le` policy at its cap block the whole session rather than the action it
//! names, and a `seen` policy block every event while its bit is clear.
//!
//! # The engine never allocates per event
//!
//! `state_layout {c, f, t, a, run}` sizes [`SessionState`] **at bundle load**
//! ([`bundle_state_layout`]); the daemon owns the storage and passes `&mut`.
//! Per-event allocation would put the memory bound somewhere nobody can see it.

use std::collections::BTreeMap;
use std::fmt::Write as _;

use serde::Deserialize as _;
use serde_json::Value;
use sha2::{Digest as _, Sha256};

use crate::generated::types::{Lever, PolicyMode, T1Node, T2RegisterProgram, Verdict};

use super::bundle::LoadedArtifact;
use super::kleene::Kleene;
use super::tier1::ScanTable;
use super::types::{
    Contribution, EvalContext, RunState, SessionState, StateLayout, MODE_ENFORCE, MODE_MONITOR,
};

/// Every number on this bundle is an integer with `|n| <= 2^53-1` (PRD §Bundle
/// schema 2), so that is the saturation point of a saturating counter or amount —
/// **not** `i64::MAX`. A counter that wrapped, or that saturated somewhere the
/// platform does not, is a verdict the two implementations disagree about.
pub const SAT_MAX: i64 = (1_i64 << 53) - 1;

/// The events the `pre` half runs on. `pre` decides.
pub const PRE_EVENTS: &[&str] = &["pre_tool_use", "session_start", "message_display"];

/// The events the `post` half runs on. `post` records: `post_tool_use` has no
/// deny channel for the call that already ran (PRD §Coverage matrix), so a
/// verdict there is a steer.
pub const POST_EVENTS: &[&str] = &["post_tool_use", "post_tool_batch", "stop"];

/// The only two fields `ADD_SAT` may accumulate.
///
/// `micro_usd` exists **only** when the bundle ships a `pricebook` fact — the
/// client never invents money (PRD §Session shapes, `budget_le`). The engine does
/// not enforce that here because it does not compute the delta: the daemon does,
/// from the pricebook, and an event without one carries no `micro_usd` at all,
/// which accumulates zero.
pub const ADD_SAT_SOURCES: &[&str] = &["spend_delta.tokens", "spend_delta.micro_usd"];

/// The banks `CMP_GE` may read. `run` is the run length, and its index operand is
/// ignored — there is one run per session.
pub const CMP_GE_BANKS: &[&str] = &["c", "a", "t", "run"];

/// The CLOSED op list — PRD §Bundle schema 2.
///
/// **There is no jump, no branch target and no call.** That is what makes "no
/// loops" structural rather than a property somebody has to keep checking:
/// `DONE` stops the program, and nothing can restart it.
pub const OPS: &[&str] = &[
    "MATCH",
    "INC_SAT",
    "RESET",
    "CMP_GE",
    "SET",
    "CLR",
    "TEST",
    "TS_STORE",
    "TS_ELAPSED",
    "ADD_SAT",
    "RUN_TRACK",
    "AND",
    "OR",
    "NOT",
    "VERDICT",
    "ANOMALY",
    "DONE",
];

/// A state whose array lengths disagree with the bundle's layout.
///
/// **Malformed, never padded.** Two implementations cannot agree about which
/// counter is which if one of them silently invents a slot, and the disagreement
/// would surface as a wrong verdict months later rather than as a failure here.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MalformedState {
    pub expected: StateLayout,
    pub found: String,
}

impl std::fmt::Display for MalformedState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "session state disagrees with the bundle's state_layout: expected {:?}, found {}",
            self.expected, self.found
        )
    }
}

/// Which half of a program to execute.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Half {
    /// The deciding event. This is the half that can produce a verdict.
    Pre,
    /// The post event. This is the half that updates state.
    Post,
}

/// The half `event_type` runs, or `None` for an event this engine does not
/// evaluate — which is not an error and leaves the state untouched.
pub fn half_for(event_type: &str) -> Option<Half> {
    if PRE_EVENTS.contains(&event_type) {
        Some(Half::Pre)
    } else if POST_EVENTS.contains(&event_type) {
        Some(Half::Post)
    } else {
        None
    }
}

/// What one execution of one half produced.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ProgramResult {
    /// A `VERDICT` op read a true bit.
    pub fired: bool,
    /// The body's verdict, carried out only when [`ProgramResult::fired`].
    pub verdict: Option<Verdict>,
    /// Codes raised by `ANOMALY`. An anomaly **records**; it never decides.
    pub anomalies: Vec<String>,
}

/// Saturating at the contract's bound, in both directions.
///
/// `saturating_add` alone stops the machine word overflowing; the `.min` is what
/// stops the *contract* overflowing, and they are not the same bound. Written as
/// one function so no call site can pick just one of them.
pub fn sat(value: i64, delta: i64) -> i64 {
    value.saturating_add(delta).min(SAT_MAX)
}

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

/// Reject a program the interpreter cannot run, so its artifact is skipped rather
/// than the bundle rejected.
///
/// Checks the closed op list, the `CMP_GE` bank, the `ADD_SAT` source, that every
/// register index is an **integer literal**, and — for `MATCH` — that the operand
/// is a Tier 1 tree this evaluator can read.
///
/// That last one is the load-bearing case. A `MATCH` over an unreadable node
/// would otherwise raise in the middle of evaluation, where nothing catches it,
/// and a bundle whose OTHER artifacts are healthy would lose their denies to this
/// one's typo. The two-stage parse exists precisely so one unparseable artifact
/// is skipped and the rest of the bundle stays active.
pub fn validate_program(body: &T2RegisterProgram) -> Result<(), String> {
    for (half, instructions) in [("pre", &body.pre), ("post", &body.post)] {
        for instruction in instructions.iter() {
            validate_instruction(half, instruction)?;
        }
    }
    Ok(())
}

fn validate_instruction(half: &str, instruction: &[Value]) -> Result<(), String> {
    let Some(op) = instruction.first().and_then(Value::as_str) else {
        return Err(format!(
            "{half}: instruction is not a non-empty [op, …] array"
        ));
    };
    if !OPS.contains(&op) {
        return Err(format!("{half}: unknown op {op:?}"));
    }
    let args = &instruction[1..];

    // Where an operand names a register, it must be a non-negative integer
    // LITERAL. This is the "no register-indexed addressing" constraint, and it is
    // a load-time property or it is nothing: an operand that could be a string,
    // an object or a float is an operand a program could compute, and the
    // bounded-memory argument would rest on the compiler's good manners.
    let literal_indices: &[usize] = match op {
        "MATCH" => &[1],
        "INC_SAT" | "RESET" | "SET" | "CLR" | "TS_STORE" => &[0, 1],
        "CMP_GE" => &[1, 2, 3],
        "TEST" | "TS_ELAPSED" | "NOT" => &[0, 1],
        "ADD_SAT" => &[0],
        "AND" | "OR" => &[0, 1, 2],
        "VERDICT" | "DONE" => &[0],
        "ANOMALY" => &[0],
        _ => &[],
    };
    for &position in literal_indices {
        if let Some(operand) = args.get(position) {
            if operand_index(Some(operand)).is_none() {
                return Err(format!(
                    "{half}: {op} operand {position} is not an integer register literal: {operand}"
                ));
            }
        }
    }

    match op {
        "MATCH" => {
            let Some(node) = args.first() else {
                return Err(format!("{half}: MATCH needs a node and a destination"));
            };
            if !node.is_object() {
                return Err(format!("{half}: MATCH operand 0 is not a node"));
            }
            if args.len() < 2 {
                return Err(format!("{half}: MATCH needs a destination register"));
            }
            let parsed = T1Node::deserialize(node)
                .map_err(|e| format!("{half}: MATCH node does not parse: {e}"))?;
            super::tier1::validate_node(Some(&parsed)).map_err(|e| format!("{half}: MATCH {e}"))?;
        }
        "CMP_GE" => {
            let bank = args.first().and_then(Value::as_str);
            if !bank.is_some_and(|bank| CMP_GE_BANKS.contains(&bank)) {
                return Err(format!("{half}: CMP_GE bank {:?}", args.first()));
            }
            if args.len() < 4 {
                return Err(format!(
                    "{half}: CMP_GE needs bank, index, K and a destination"
                ));
            }
        }
        "ADD_SAT" => {
            let source = args.get(1).and_then(Value::as_str);
            if !source.is_some_and(|source| ADD_SAT_SOURCES.contains(&source)) {
                return Err(format!("{half}: ADD_SAT source {:?}", args.get(1)));
            }
        }
        "ANOMALY" if args.get(1).and_then(Value::as_str).is_none() => {
            return Err(format!("{half}: ANOMALY needs a code string"));
        }
        _ => {}
    }
    Ok(())
}

/// An operand read as a register index or an integer constant.
///
/// `None` for anything that is not a JSON integer — a string, an object, a float,
/// a negative. Both halves of that matter: the float is the integer-only
/// constraint and the non-number is the no-register-indexed-addressing one.
fn operand_index(operand: Option<&Value>) -> Option<usize> {
    let value = operand?.as_i64()?;
    usize::try_from(value).ok()
}

/// An operand read as an integer constant (`CMP_GE`'s `K`), which may be large
/// but is still never a float.
fn operand_int(operand: Option<&Value>) -> Option<i64> {
    operand?.as_i64()
}

// ── State ────────────────────────────────────────────────────────────

/// The union of every Tier 2 program's `state_layout`, computed **at bundle
/// load** so the caller can size and evict session state without executing
/// anything. The engine never allocates per event.
///
/// **Element-wise MAX, not a sum.** Plan 01 §Step 6 says "lengths come from the
/// bundle's `state_layout`", singular, while each program declares its own; the
/// max satisfies both readings — identical if the compiler allocates globally,
/// and the smallest file that fits if it allocates per program. A sum would make
/// `05-two-programs.json` (declaring `c: 1` and `c: 2`) demand three counters
/// where the corpus row carries two, and every state would then be malformed.
pub fn bundle_state_layout(artifacts: &[LoadedArtifact]) -> StateLayout {
    let mut layout = StateLayout::default();
    for artifact in artifacts {
        let Some(body) = artifact.as_t2() else {
            continue;
        };
        let Some(declared) = body.state_layout.as_ref() else {
            continue;
        };
        layout.c = layout.c.max(declared.c.unwrap_or(0).max(0) as usize);
        layout.f = layout.f.max(declared.f.unwrap_or(0).max(0) as usize);
        layout.t = layout.t.max(declared.t.unwrap_or(0).max(0) as usize);
        layout.a = layout.a.max(declared.a.unwrap_or(0).max(0) as usize);
        layout.run |= declared.run.unwrap_or(false);
    }
    layout
}

/// Check a caller-supplied state against the bundle's layout.
pub fn validate_state(state: &SessionState, layout: &StateLayout) -> Result<(), MalformedState> {
    if state.matches(layout) {
        return Ok(());
    }
    Err(MalformedState {
        expected: *layout,
        found: format!(
            "c={} f={} t={} a={} run={}",
            state.c.len(),
            state.f.len(),
            state.t.len(),
            state.a.len(),
            state.run.is_some()
        ),
    })
}

// ── The action shape ─────────────────────────────────────────────────

/// `sha256(tool_name ‖ first effect tuple (verb, target_class) ‖ command.program
/// or "")`, hex-encoded lowercase — the `run_le` shape (PRD §Session shapes).
///
/// `‖` is plain concatenation of the UTF-8 bytes: no separator, no length prefix.
///
/// **Argument values are ignored on purpose**, so `Read a.py` and `Read b.py`
/// share a shape. This is DISTINCT from the `loop_stop` lever, which keys on an
/// identical `(tool, normalised input, result hash)`. Two different "identical"s;
/// merging them would make `run_le` stop counting a repetition the moment one
/// argument changed, which is the exact loop it exists to catch.
pub fn action_shape(tool_name: &str, first_effect: Option<(&str, &str)>, program: &str) -> String {
    let (verb, target_class) = first_effect.unwrap_or(("", ""));
    let mut hasher = Sha256::new();
    hasher.update(tool_name.as_bytes());
    hasher.update(verb.as_bytes());
    hasher.update(target_class.as_bytes());
    hasher.update(program.as_bytes());
    let digest = hasher.finalize();
    let mut hex = String::with_capacity(64);
    for byte in digest {
        // `hex` the crate is `full-cli`-only; the engine is gated on `policy`.
        let _ = write!(hex, "{byte:02x}");
    }
    hex
}

/// The action shape of the event in `ctx`.
fn shape_of(ctx: &EvalContext<'_>) -> String {
    let first = ctx
        .classification
        .effects
        .first()
        .map(|effect| (effect.verb.as_str(), effect.target_class.as_str()));
    let program = ctx
        .classification
        .simple
        .first()
        .map(|simple| simple.program.as_str())
        .unwrap_or("");
    action_shape(&ctx.event.tool_name, first, program)
}

// ── The interpreter ──────────────────────────────────────────────────

/// Execute one half of one program, mutating `state` in place.
///
/// # Nothing here panics on a malformed program
///
/// `validate_program` ran at load, but it validates the program, not the program
/// *against this session's state*: a compiler bug could still name `c[7]` under a
/// layout of one counter. Every register access goes through `get`/`get_mut` and
/// an out-of-range instruction is skipped, because the client must never panic on
/// input it did not author (`.claude/rules/error-handling.md`).
pub fn run_program(
    body: &T2RegisterProgram,
    half: Half,
    ctx: &mut EvalContext<'_>,
    scan: &ScanTable,
    state: &mut SessionState,
) -> ProgramResult {
    let instructions = match half {
        Half::Pre => &body.pre,
        Half::Post => &body.post,
    };
    let mut result = ProgramResult::default();
    // Transient, per run, and never session state — see the module header.
    let mut bools: BTreeMap<usize, bool> = BTreeMap::new();

    // Straight-line: each instruction is visited at most once and there is no way
    // back. `DONE` leaves early; nothing re-enters.
    for instruction in instructions.iter() {
        let Some(op) = instruction.first().and_then(Value::as_str) else {
            continue;
        };
        let args = &instruction[1..];
        let read = |bools: &BTreeMap<usize, bool>, position: usize| -> bool {
            operand_index(args.get(position)).is_some_and(|reg| *bools.get(&reg).unwrap_or(&false))
        };
        // `SET f` / `INC_SAT c` with no guard operand run unconditionally; with
        // one, they run on that bit.
        let guarded = |bools: &BTreeMap<usize, bool>, position: usize| -> bool {
            args.len() <= position || read(bools, position)
        };

        match op {
            "MATCH" => {
                let (Some(node), Some(dest)) = (args.first(), operand_index(args.get(1))) else {
                    continue;
                };
                let Ok(node) = T1Node::deserialize(node) else {
                    continue;
                };
                // ⊥ coerces to false HERE and only here: a register machine has
                // two values. Three-valuedness stays on the Tier 1 plane, where
                // `on_inconclusive` can still see it — which is why the ⊥ facts a
                // MATCH notes are dropped by `contribution` rather than reported.
                let value = super::tier1::evaluate_node(&node, ctx, scan);
                bools.insert(dest, matches!(value, Kleene::True));
            }
            "INC_SAT" => {
                if guarded(&bools, 1) {
                    if let Some(slot) = operand_index(args.first()).and_then(|i| state.c.get_mut(i))
                    {
                        *slot = sat(*slot, 1);
                    }
                }
            }
            "RESET" => {
                if let Some(slot) = operand_index(args.first()).and_then(|i| state.c.get_mut(i)) {
                    *slot = 0;
                }
            }
            "CMP_GE" => {
                let bank = args.first().and_then(Value::as_str).unwrap_or("");
                let (Some(index), Some(k), Some(dest)) = (
                    operand_index(args.get(1)),
                    operand_int(args.get(2)),
                    operand_index(args.get(3)),
                ) else {
                    continue;
                };
                let Some(value) = bank_value(state, bank, index) else {
                    continue;
                };
                bools.insert(dest, value >= k);
            }
            "SET" | "CLR" => {
                if guarded(&bools, 1) {
                    if let Some(slot) = operand_index(args.first()).and_then(|i| state.f.get_mut(i))
                    {
                        *slot = op == "SET";
                    }
                }
            }
            "TEST" => {
                let (Some(flag), Some(dest)) =
                    (operand_index(args.first()), operand_index(args.get(1)))
                else {
                    continue;
                };
                if let Some(value) = state.f.get(flag) {
                    bools.insert(dest, *value);
                }
            }
            "TS_STORE" => {
                if guarded(&bools, 1) {
                    if let Some(slot) = operand_index(args.first()).and_then(|i| state.t.get_mut(i))
                    {
                        // `now_ms` arrived in the frame. There is no clock here,
                        // and `ci/check-engine-purity.py` is what keeps it that way.
                        *slot = ctx.now_ms;
                    }
                }
            }
            "TS_ELAPSED" => {
                let (Some(stamp), Some(amount)) =
                    (operand_index(args.first()), operand_index(args.get(1)))
                else {
                    continue;
                };
                let Some(stored) = state.t.get(stamp).copied() else {
                    continue;
                };
                // An UNSET timestamp is 0 and elapses 0 — not "the whole epoch".
                // Clamped at zero so a `now_ms` behind a stored stamp (a clock
                // step on the daemon's side) reads as no time passed rather than
                // as a negative amount a `CMP_GE` would silently pass.
                let elapsed = if stored == 0 {
                    0
                } else {
                    (ctx.now_ms - stored).max(0)
                };
                if let Some(slot) = state.a.get_mut(amount) {
                    *slot = elapsed;
                }
            }
            "ADD_SAT" => {
                let (Some(index), Some(source)) = (
                    operand_index(args.first()),
                    args.get(1).and_then(Value::as_str),
                ) else {
                    continue;
                };
                let delta = event_amount(ctx, source);
                if let Some(slot) = state.a.get_mut(index) {
                    *slot = sat(*slot, delta);
                }
            }
            "RUN_TRACK" => {
                let shape = shape_of(ctx);
                let run = state.run.get_or_insert_with(RunState::default);
                run.len = if run.shape.as_deref() == Some(shape.as_str()) {
                    run.len.saturating_add(1)
                } else {
                    1
                };
                run.shape = Some(shape);
            }
            "AND" | "OR" => {
                let Some(dest) = operand_index(args.get(2)) else {
                    continue;
                };
                let (left, right) = (read(&bools, 0), read(&bools, 1));
                bools.insert(
                    dest,
                    if op == "AND" {
                        left && right
                    } else {
                        left || right
                    },
                );
            }
            "NOT" => {
                let Some(dest) = operand_index(args.get(1)) else {
                    continue;
                };
                let value = read(&bools, 0);
                bools.insert(dest, !value);
            }
            "VERDICT" => {
                if read(&bools, 0) {
                    result.fired = true;
                    result.verdict = body.verdict;
                }
            }
            "ANOMALY" if read(&bools, 0) => {
                if let Some(code) = args.get(1).and_then(Value::as_str) {
                    result.anomalies.push(code.to_string());
                }
            }
            "DONE" if read(&bools, 0) => break,
            // Unreachable for a loaded artifact — `validate_program` closed the
            // op list at load. Skipped rather than panicked for the same reason
            // every other malformed operand is.
            _ => {}
        }
    }
    result
}

/// The value `CMP_GE` compares, or `None` when the slot is out of range.
///
/// `run` is the run LENGTH, and its index operand is ignored: there is one run
/// per session, which is why `state_layout.run` is a bool and not a count.
fn bank_value(state: &SessionState, bank: &str, index: usize) -> Option<i64> {
    match bank {
        "c" => state.c.get(index).copied(),
        "a" => state.a.get(index).copied(),
        "t" => state.t.get(index).copied(),
        "run" => Some(state.run.as_ref().map(|run| run.len).unwrap_or(0)),
        _ => None,
    }
}

/// What `ADD_SAT` accumulates from this event, or zero.
///
/// Zero and not ⊥: a `post_tool_use` with no `spend_delta` is an event the daemon
/// could not price, and a budget that cannot be advanced simply is not advanced.
/// `micro_usd` is absent unless a `pricebook` fact shipped — the client never
/// invents money — so the without-pricebook case accrues nothing by construction.
fn event_amount(ctx: &EvalContext<'_>, source: &str) -> i64 {
    let Some(delta) = ctx.event.spend_delta.as_ref() else {
        return 0;
    };
    match source {
        "spend_delta.tokens" => delta.tokens.unwrap_or(0),
        "spend_delta.micro_usd" => delta.micro_usd.unwrap_or(0),
        _ => 0,
    }
}

// ── Contributions ────────────────────────────────────────────────────

/// Run one `t2_register_program` against the session state, mutating it in place.
///
/// Returns `None` when the program neither fired nor raised an anomaly — an
/// artifact that did not fire contributes nothing, and `Decision::undecided` is
/// how the caller says so.
pub fn contribution(
    artifact: &LoadedArtifact,
    body: &T2RegisterProgram,
    ctx: &mut EvalContext<'_>,
    scan: &ScanTable,
    state: &mut SessionState,
    layout: &StateLayout,
) -> Option<Contribution> {
    // The layout is what SIZED `state`, at load. It is taken here so the
    // signature says where the memory bound comes from, and so a future caller
    // cannot start sizing per event without changing this line.
    debug_assert!(
        state.matches(layout),
        "the caller validates before evaluating"
    );

    let half = half_for(&ctx.event.event_type)?;

    // A program's own context, so the ⊥ facts its `MATCH` instructions note are
    // its own — and then dropped: a register machine coerced them to false, so
    // they decided nothing and reporting them would claim an atom was
    // inconclusive when it was not. The warnings are NOT dropped; a D-17 registry
    // warning is about the bundle, not about what one artifact contributed.
    let mut child = ctx.fork();
    let result = run_program(body, half, &mut child, scan, state);
    ctx.merge_warnings(&child);

    if !result.fired && result.anomalies.is_empty() {
        return None;
    }
    // An ANOMALY-only run contributes `allow`: it records, it does not decide.
    let verdict = if result.fired {
        result.verdict.unwrap_or(Verdict::Block)
    } else {
        Verdict::Allow
    };
    Some(build(
        artifact,
        declared_mode(artifact),
        verdict,
        body.reason.clone().unwrap_or_default(),
        Vec::new(),
        result.anomalies,
    ))
}

/// The contribution of a program whose session state was **evicted** — the honest
/// question, answered out loud per the artifact's `on_evict`.
///
/// | `on_evict` | answer |
/// | ---------- | ------ |
/// | `reinit` (and the default) | `None` here; the caller starts from [`SessionState::blank`] and runs [`contribution`] |
/// | `unknown` | undecidable — the artifact's `on_inconclusive`, with `session_state_evicted` named |
/// | `fail_static` | the artifact keeps its own verdict |
///
/// **`fail_static` is the house invariant** (AGENTS.md, *fail-static, not
/// fail-open*): a resident bundle keeps enforcing, so eviction must not become a
/// quiet fail-open. Collapsing an evicted state into a blank one makes all three
/// answer `reinit` and turns `fail_static` into an allow — which is why the
/// entry point carries `Option<&SessionState>` rather than flattening it.
///
/// `mode` is the **composed** mode, so the org-wide kill switch reaches the
/// `unknown` branch: monitor is always `allow_and_flag`, whatever the artifact
/// declares.
pub fn evicted_contribution(
    artifact: &LoadedArtifact,
    body: &T2RegisterProgram,
    mode: PolicyMode,
    layout: &StateLayout,
) -> Option<Contribution> {
    let _ = layout;
    let reason = body.reason.clone().unwrap_or_default();
    match body.on_evict.as_deref().unwrap_or("reinit") {
        "unknown" => Some(build(
            artifact,
            mode.clone(),
            on_inconclusive_verdict(artifact, &mode),
            reason,
            vec!["session_state_evicted".to_string()],
            Vec::new(),
        )),
        "fail_static" => Some(build(
            artifact,
            mode,
            body.verdict.unwrap_or(Verdict::Block),
            reason,
            Vec::new(),
            Vec::new(),
        )),
        // `reinit`, the default, and any value this client does not know: an
        // `on_evict` it cannot read must not invent a third eviction policy, and
        // counting from zero is the one answer that never changes a verdict the
        // fresh session would not also have given (R14 — an open string degrades,
        // it does not fail).
        _ => None,
    }
}

/// The verdict an artifact contributes when its condition came out ⊥.
///
/// **Monitor is ALWAYS `allow_and_flag`**, whatever the artifact declares (PRD
/// §Facts): a monitor artifact never blocks, so it cannot block on a fact it
/// could not read either.
///
/// Shared with [`super::tier3`], which resolves an unknown trigger the same way
/// Tier 1 does — one rule, one implementation.
pub fn on_inconclusive_verdict(artifact: &LoadedArtifact, mode: &PolicyMode) -> Verdict {
    let declared = if mode.as_str() == MODE_MONITOR {
        "allow_and_flag"
    } else {
        artifact
            .envelope
            .on_inconclusive
            .as_ref()
            .map(|value| value.0.as_str())
            .unwrap_or("allow_and_flag")
    };
    match declared {
        "ask" => Verdict::Ask,
        "block" => Verdict::Block,
        // `allow_and_flag`, and anything an older client does not recognise. The
        // flag is `inconclusive_facts[]`, which is carried whatever the verdict.
        _ => Verdict::Allow,
    }
}

/// The artifact's **declared** mode.
///
/// The org-wide kill switch (`enforcement_enabled: false` composes every artifact
/// as monitor) is not visible from a tier: `contribution` is handed an artifact
/// and a context, never the bundle, which is the same shape `tier1::contribution`
/// and `tier3::contribution` have. The caller composes it — and does so already
/// for the evicted path, which takes `mode` as an argument for exactly this reason.
pub fn declared_mode(artifact: &LoadedArtifact) -> PolicyMode {
    artifact
        .envelope
        .mode
        .clone()
        .unwrap_or_else(|| PolicyMode(MODE_ENFORCE.to_string()))
}

/// Assemble a contribution from an artifact's envelope.
///
/// `lever` and `steer_instruction` are read off the RAW body rather than the
/// typed one: `t2_register_program` declares neither in the schema, and R10's
/// single rewrite is owned by whichever artifact fired as `optimize` regardless
/// of the tier it lives on.
pub fn build(
    artifact: &LoadedArtifact,
    mode: PolicyMode,
    verdict: Verdict,
    reason: String,
    inconclusive: Vec<String>,
    anomalies: Vec<String>,
) -> Contribution {
    let body = &artifact.envelope.body;
    Contribution {
        artifact_id: artifact.artifact_id().map(str::to_string),
        atom_id: artifact.atom_id().map(str::to_string),
        policy_public_id: artifact.envelope.policy_public_id.clone(),
        dimension: artifact.envelope.dimension.clone(),
        mode,
        tier: artifact.envelope.tier,
        verdict,
        reason,
        inconclusive,
        anomalies,
        hold: None,
        exception_ground_key: None,
        lever: body.get("lever").and_then(|v| Lever::deserialize(v).ok()),
        steer_instruction: body
            .get("steer_instruction")
            .and_then(Value::as_str)
            .map(str::to_string),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::generated::types::T2StateLayout;
    use crate::zone_eval::facts::FactSet;
    use crate::zone_eval::types::{Classification, Effect, Event, SimpleCommand, SpendDelta};

    const NOW: i64 = 1_756_742_400_000;

    fn program(pre: serde_json::Value, post: serde_json::Value) -> T2RegisterProgram {
        T2RegisterProgram {
            pre: serde_json::from_value(pre).expect("pre parses"),
            post: serde_json::from_value(post).expect("post parses"),
            verdict: Some(Verdict::Block),
            reason: Some("tier 2 fired".to_string()),
            ..Default::default()
        }
    }

    fn state(c: &[i64], f: &[bool], t: &[i64], a: &[i64], run: Option<RunState>) -> SessionState {
        SessionState {
            c: c.to_vec(),
            f: f.to_vec(),
            t: t.to_vec(),
            a: a.to_vec(),
            run,
        }
    }

    /// Runs `pre` against a state, with an empty classification and no facts.
    fn run_pre(body: &T2RegisterProgram, state: &mut SessionState) -> ProgramResult {
        run_pre_with(body, state, &Event::default(), &Classification::default())
    }

    fn run_pre_with(
        body: &T2RegisterProgram,
        state: &mut SessionState,
        event: &Event,
        classification: &Classification,
    ) -> ProgramResult {
        let facts = FactSet::default();
        let mut ctx = EvalContext::new(event, classification, &facts, NOW);
        run_program(body, Half::Pre, &mut ctx, &ScanTable::default(), state)
    }

    // ── The four hard constraints ────────────────────────────────────

    #[test]
    fn the_op_list_carries_no_jump_so_no_loop_is_expressible() {
        // "No loops" is structural, not a rule somebody enforces: the closed op
        // list has no jump, no branch target and no call, so the only control
        // flow is DONE, which stops.
        for op in OPS {
            assert!(
                !matches!(*op, "JMP" | "JUMP" | "BRANCH" | "CALL" | "LOOP" | "GOTO"),
                "{op} would make the bounded-time argument a convention"
            );
        }
        assert_eq!(
            OPS.len(),
            17,
            "the op list is CLOSED — PRD §Bundle schema 2"
        );
    }

    #[test]
    fn every_instruction_runs_at_most_once() {
        // Five unconditional increments of one counter. A loop of any kind — a
        // re-entered program, a repeated instruction — reads as more than five.
        let body = program(
            serde_json::json!([
                ["INC_SAT", 0],
                ["INC_SAT", 0],
                ["INC_SAT", 0],
                ["INC_SAT", 0],
                ["INC_SAT", 0]
            ]),
            serde_json::json!([]),
        );
        let mut session = state(&[0], &[], &[], &[], None);
        run_pre(&body, &mut session);
        assert_eq!(session.c, vec![5], "one pass over the program, and no more");
    }

    #[test]
    fn a_register_index_must_be_an_integer_literal() {
        // No register-indexed addressing: an operand that is a string, an object
        // or a nested expression is an operand a PROGRAM could compute, and the
        // bounded-memory bound would rest on the compiler's good manners.
        for operand in [
            serde_json::json!("c0"),
            serde_json::json!({ "reg": 0 }),
            serde_json::json!([0]),
            serde_json::json!(-1),
        ] {
            let body = program(
                serde_json::json!([["INC_SAT", operand]]),
                serde_json::json!([]),
            );
            assert!(
                validate_program(&body).is_err(),
                "a computed register index must be rejected at load"
            );
        }
        let literal = program(serde_json::json!([["INC_SAT", 0]]), serde_json::json!([]));
        assert!(
            validate_program(&literal).is_ok(),
            "a literal is the only form"
        );
    }

    #[test]
    fn arithmetic_is_integer_only() {
        // A float where an index or a bound belongs. `bundle::contains_float`
        // catches a float anywhere in the body at load; this is the second half of
        // that guarantee, inside the op's own operands.
        let indexed = program(serde_json::json!([["INC_SAT", 0.5]]), serde_json::json!([]));
        assert!(validate_program(&indexed).is_err());
        let bound = program(
            serde_json::json!([["CMP_GE", "c", 0, 3.5, 0]]),
            serde_json::json!([]),
        );
        assert!(validate_program(&bound).is_err());
    }

    #[test]
    fn inc_sat_saturates_at_the_boundary_rather_than_wrapping() {
        // AT the boundary: SAT_MAX is the value where a wrapping implementation
        // differs. SAT_MAX - 1 is the value where it does not, which is why both
        // are here — the second proves the first is a cap and not a freeze.
        let body = program(serde_json::json!([["INC_SAT", 0]]), serde_json::json!([]));

        let mut at = state(&[SAT_MAX], &[], &[], &[], None);
        run_pre(&body, &mut at);
        assert_eq!(at.c, vec![SAT_MAX], "saturates; a wrap would give 2^53");

        let mut below = state(&[SAT_MAX - 1], &[], &[], &[], None);
        run_pre(&body, &mut below);
        assert_eq!(below.c, vec![SAT_MAX], "and still counts up to it");
    }

    #[test]
    fn add_sat_saturates_at_the_boundary_rather_than_wrapping() {
        let body = program(
            serde_json::json!([]),
            serde_json::json!([["ADD_SAT", 0, "spend_delta.tokens"]]),
        );
        let event = Event {
            event_type: "post_tool_use".to_string(),
            spend_delta: Some(SpendDelta {
                tokens: Some(4_200),
                micro_usd: None,
            }),
            ..Default::default()
        };
        let facts = FactSet::default();
        let classification = Classification::default();
        let mut ctx = EvalContext::new(&event, &classification, &facts, NOW);

        let mut at = state(&[], &[], &[], &[SAT_MAX], None);
        run_program(&body, Half::Post, &mut ctx, &ScanTable::default(), &mut at);
        assert_eq!(at.a, vec![SAT_MAX], "a wrapping add would go negative here");

        let mut under = state(&[], &[], &[], &[50_000], None);
        run_program(
            &body,
            Half::Post,
            &mut ctx,
            &ScanTable::default(),
            &mut under,
        );
        assert_eq!(under.a, vec![54_200]);
    }

    #[test]
    fn sat_never_overflows_the_machine_word_either() {
        assert_eq!(sat(SAT_MAX, i64::MAX), SAT_MAX);
        assert_eq!(sat(i64::MAX, 1), SAT_MAX);
    }

    // ── Every op ─────────────────────────────────────────────────────

    #[test]
    fn op_reset_zeroes_a_counter() {
        let body = program(serde_json::json!([["RESET", 0]]), serde_json::json!([]));
        let mut session = state(&[7], &[], &[], &[], None);
        run_pre(&body, &mut session);
        assert_eq!(session.c, vec![0]);
    }

    #[test]
    fn op_set_clr_and_test_move_a_flag_both_ways() {
        let body = program(
            serde_json::json!([["SET", 0], ["TEST", 0, 0], ["CLR", 1, 0]]),
            serde_json::json!([]),
        );
        let mut session = state(&[], &[false, true], &[], &[], None);
        run_pre(&body, &mut session);
        assert_eq!(
            session.f,
            vec![true, false],
            "SET unconditional, CLR on the bit"
        );
    }

    #[test]
    fn op_clr_conditional_does_not_fire_on_a_false_bit() {
        let body = program(serde_json::json!([["CLR", 0, 3]]), serde_json::json!([]));
        let mut session = state(&[], &[true], &[], &[], None);
        run_pre(&body, &mut session);
        assert_eq!(session.f, vec![true], "an unset bool register reads false");
    }

    #[test]
    fn op_cmp_ge_reads_all_four_banks() {
        let banks = [
            ("c", state(&[3], &[], &[], &[], None)),
            ("a", state(&[], &[], &[], &[3], None)),
            ("t", state(&[], &[], &[3], &[], None)),
            (
                "run",
                state(
                    &[],
                    &[],
                    &[],
                    &[],
                    Some(RunState {
                        shape: Some("x".to_string()),
                        len: 3,
                    }),
                ),
            ),
        ];
        for (bank, mut session) in banks {
            let body = program(
                serde_json::json!([["CMP_GE", bank, 0, 3, 0], ["VERDICT", 0]]),
                serde_json::json!([]),
            );
            assert!(run_pre(&body, &mut session).fired, "{bank} at the bound");

            let body = program(
                serde_json::json!([["CMP_GE", bank, 0, 4, 0], ["VERDICT", 0]]),
                serde_json::json!([]),
            );
            assert!(
                !run_pre(&body, &mut session).fired,
                "{bank} below the bound"
            );
        }
    }

    #[test]
    fn op_ts_store_and_ts_elapsed_measure_against_the_injected_now() {
        let body = program(
            serde_json::json!([["TS_ELAPSED", 0, 0]]),
            serde_json::json!([]),
        );
        let mut session = state(&[], &[], &[NOW - 5_000], &[0], None);
        run_pre(&body, &mut session);
        assert_eq!(
            session.a,
            vec![5_000],
            "now_ms is a parameter, never a clock"
        );

        // An unset stamp elapses zero, not the whole epoch.
        let mut unset = state(&[], &[], &[0], &[0], None);
        run_pre(&body, &mut unset);
        assert_eq!(unset.a, vec![0]);

        let store = program(serde_json::json!([["TS_STORE", 0]]), serde_json::json!([]));
        let mut stamped = state(&[], &[], &[0], &[], None);
        run_pre(&store, &mut stamped);
        assert_eq!(stamped.t, vec![NOW]);
    }

    #[test]
    fn op_and_or_not_are_two_valued() {
        let body = program(
            serde_json::json!([
                ["TEST", 0, 0],
                ["TEST", 1, 1],
                ["AND", 0, 1, 2],
                ["OR", 0, 1, 3],
                ["NOT", 0, 4],
                ["SET", 2, 2],
                ["SET", 3, 3],
                ["SET", 4, 4]
            ]),
            serde_json::json!([]),
        );
        let mut session = state(&[], &[true, false, false, false, false], &[], &[], None);
        run_pre(&body, &mut session);
        assert!(!session.f[2], "true ∧ false");
        assert!(session.f[3], "true ∨ false");
        assert!(!session.f[4], "¬true");
    }

    #[test]
    fn op_verdict_carries_the_body_verdict_and_anomaly_carries_a_code() {
        let mut body = program(
            serde_json::json!([
                ["TEST", 0, 0],
                ["VERDICT", 0],
                ["ANOMALY", 0, "followed_by_unsatisfied"]
            ]),
            serde_json::json!([]),
        );
        body.verdict = Some(Verdict::Optimize);
        let mut session = state(&[], &[true], &[], &[], None);
        let result = run_pre(&body, &mut session);
        assert!(result.fired);
        assert_eq!(result.verdict, Some(Verdict::Optimize));
        assert_eq!(
            result.anomalies,
            vec!["followed_by_unsatisfied".to_string()]
        );
    }

    #[test]
    fn op_done_stops_the_program_and_only_when_taken() {
        let taken = program(
            serde_json::json!([["SET", 0], ["TEST", 0, 0], ["DONE", 0], ["SET", 1]]),
            serde_json::json!([]),
        );
        let mut session = state(&[], &[false, false], &[], &[], None);
        run_pre(&taken, &mut session);
        assert_eq!(session.f, vec![true, false], "the tail never ran");

        let not_taken = program(
            serde_json::json!([["TEST", 0, 0], ["DONE", 0], ["SET", 1]]),
            serde_json::json!([]),
        );
        let mut session = state(&[], &[false, false], &[], &[], None);
        run_pre(&not_taken, &mut session);
        assert_eq!(session.f, vec![false, true], "the tail ran");
    }

    #[test]
    fn op_match_coerces_bottom_to_false() {
        // A leaf over a fact the bundle does not ship is ⊥. A register machine
        // has two values, so ⊥ is false HERE — and the guarded increment must not
        // advance. ⊥ staying ⊥ into the counter is the bug this pins.
        let body = program(
            serde_json::json!([
                ["MATCH", {"op": "leaf", "leaf": {"pred": "fact", "fact": {"fact_id": "approved_registries", "op": "equals", "value": true}}}, 0],
                ["INC_SAT", 0, 0]
            ]),
            serde_json::json!([]),
        );
        let mut session = state(&[0], &[], &[], &[], None);
        let facts = FactSet::default();
        let event = Event::default();
        let classification = Classification::default();
        let mut ctx = EvalContext::new(&event, &classification, &facts, NOW);
        run_program(
            &body,
            Half::Pre,
            &mut ctx,
            &ScanTable::default(),
            &mut session,
        );
        assert_eq!(session.c, vec![0], "⊥ is false, so the guard did not open");

        // And through `contribution`, which forks the context: the ⊥ decided
        // nothing on a two-valued plane, so reporting it would claim the atom was
        // inconclusive when it was not.
        let artifact = loaded(body.clone());
        let deciding = Event {
            event_type: "pre_tool_use".to_string(),
            ..Default::default()
        };
        let mut ctx = EvalContext::new(&deciding, &classification, &facts, NOW);
        let layout = StateLayout {
            c: 1,
            ..Default::default()
        };
        let mut forked = state(&[0], &[], &[], &[], None);
        let _ = contribution(
            &artifact,
            &body,
            &mut ctx,
            &ScanTable::default(),
            &mut forked,
            &layout,
        );
        assert!(
            ctx.inconclusive.is_empty(),
            "a MATCH's ⊥ is dropped, not carried into inconclusive_facts[]"
        );
    }

    // ── RUN_TRACK ────────────────────────────────────────────────────

    fn read_classification() -> Classification {
        Classification {
            effects: vec![Effect {
                verb: "read".to_string().into(),
                target_class: "data_store".to_string().into(),
                attrs: serde_json::Map::new(),
            }],
            ..Default::default()
        }
    }

    #[test]
    fn run_track_ignores_argument_values() {
        // `Read a.py` and `Read b.py` share a shape: the shape is
        // sha256(tool_name ‖ first effect tuple ‖ command.program), and argument
        // values are not in it. Distinct from the `loop_stop` lever, which keys
        // on identical (tool, normalised input, result hash).
        let body = program(serde_json::json!([["RUN_TRACK"]]), serde_json::json!([]));
        let classification = read_classification();
        let mut session = state(&[], &[], &[], &[], Some(RunState::default()));

        for path in ["/data/warehouse/a.py", "/data/warehouse/b.py"] {
            let event = Event {
                tool_name: "Read".to_string(),
                tool_input: serde_json::json!({ "file_path": path }),
                ..Default::default()
            };
            run_pre_with(&body, &mut session, &event, &classification);
        }
        let run = session.run.expect("the run is tracked");
        assert_eq!(run.len, 2, "two different files, one shape, one run");
    }

    #[test]
    fn run_track_restarts_on_a_different_shape() {
        let body = program(serde_json::json!([["RUN_TRACK"]]), serde_json::json!([]));
        let mut session = state(
            &[],
            &[],
            &[],
            &[],
            Some(RunState {
                shape: Some("something-else".to_string()),
                len: 9,
            }),
        );
        let event = Event {
            tool_name: "Read".to_string(),
            ..Default::default()
        };
        run_pre_with(&body, &mut session, &event, &read_classification());
        assert_eq!(session.run.expect("tracked").len, 1);
    }

    #[test]
    fn the_action_shape_is_the_prd_concatenation() {
        // Pinned against the corpus's own `state_out.run.shape`, so a
        // re-derivation that changes the hash is caught here rather than by a
        // whole conformance file.
        assert_eq!(
            action_shape("Read", Some(("read", "data_store")), ""),
            "cfee545cf5b5bfdd83a48a592933feb054e56637409011fbdd2633cc6b17a674"
        );
        assert_eq!(
            action_shape("Bash", Some(("network_egress", "network_host")), "curl"),
            "c3d4b38848360f19b22341f1adcafabac5c6d7bd318a7dfd4406ceba9f500279"
        );
    }

    #[test]
    fn the_action_shape_reads_the_first_simple_commands_program() {
        let classification = Classification {
            effects: vec![Effect {
                verb: "network_egress".to_string().into(),
                target_class: "network_host".to_string().into(),
                attrs: serde_json::Map::new(),
            }],
            simple: vec![SimpleCommand {
                program: "curl".to_string(),
                ..Default::default()
            }],
            ..Default::default()
        };
        let event = Event {
            tool_name: "Bash".to_string(),
            ..Default::default()
        };
        let facts = FactSet::default();
        let ctx = EvalContext::new(&event, &classification, &facts, NOW);
        assert_eq!(
            shape_of(&ctx),
            "c3d4b38848360f19b22341f1adcafabac5c6d7bd318a7dfd4406ceba9f500279"
        );
    }

    // ── The six shape templates ──────────────────────────────────────

    #[test]
    fn shape_count_le_decides_in_pre_and_counts_in_post() {
        let body = program(
            serde_json::json!([
                ["MATCH", {"op": "leaf", "leaf": {"pred": "exists", "field": "tool.name"}}, 0],
                ["CMP_GE", "c", 0, 3, 1],
                ["AND", 0, 1, 2],
                ["VERDICT", 2]
            ]),
            serde_json::json!([["INC_SAT", 0]]),
        );
        let matching = Event {
            tool_name: "Bash".to_string(),
            ..Default::default()
        };
        let mut at_cap = state(&[3], &[], &[], &[], None);
        assert!(
            run_pre_with(&body, &mut at_cap, &matching, &Classification::default()).fired,
            "at the cap, on the action it names"
        );

        let mut under = state(&[2], &[], &[], &[], None);
        assert!(
            !run_pre_with(&body, &mut under, &matching, &Classification::default()).fired,
            "below the cap"
        );

        // The GUARDED form. At the cap but on an action the trigger does not
        // match, the program must NOT fire: an unguarded sketch computes `b` and
        // never reads it, and then blocks the whole session rather than the
        // action the atom names.
        let mut unrelated = state(&[3], &[], &[], &[], None);
        assert!(
            !run_pre_with(
                &body,
                &mut unrelated,
                &Event::default(),
                &Classification::default()
            )
            .fired,
            "the trigger bit is consumed, not computed and dropped"
        );

        let event = Event {
            event_type: "post_tool_use".to_string(),
            ..Default::default()
        };
        let facts = FactSet::default();
        let classification = Classification::default();
        let mut ctx = EvalContext::new(&event, &classification, &facts, NOW);
        let mut counting = state(&[0], &[], &[], &[], None);
        run_program(
            &body,
            Half::Post,
            &mut ctx,
            &ScanTable::default(),
            &mut counting,
        );
        assert_eq!(counting.c, vec![1]);
    }

    #[test]
    fn shape_seen_blocks_until_the_bit_latches() {
        let body = program(
            serde_json::json!([["TEST", 0, 1], ["NOT", 1, 2], ["VERDICT", 2]]),
            serde_json::json!([["SET", 0]]),
        );
        let mut unseen = state(&[], &[false], &[], &[], None);
        assert!(run_pre(&body, &mut unseen).fired, "not yet seen → fires");

        let mut seen = state(&[], &[true], &[], &[], None);
        assert!(!run_pre(&body, &mut seen).fired, "already seen → allows");
    }

    #[test]
    fn shape_elapsed_le_stores_once_and_does_not_restamp() {
        // The store-once idiom: there is no event-type leaf in the field
        // vocabulary, so `TS_STORE t on session_start` is written with a flag.
        let body = program(
            serde_json::json!([
                ["TEST", 0, 0],
                ["NOT", 0, 1],
                ["TS_STORE", 0, 1],
                ["SET", 0, 1]
            ]),
            serde_json::json!([]),
        );
        let mut first = state(&[], &[false], &[0], &[], None);
        run_pre(&body, &mut first);
        assert_eq!(first.t, vec![NOW]);
        assert_eq!(first.f, vec![true]);

        let mut again = state(&[], &[true], &[NOW - 900_000], &[], None);
        run_pre(&body, &mut again);
        assert_eq!(again.t, vec![NOW - 900_000], "idempotent — never restamped");
    }

    #[test]
    fn shape_run_le_fires_at_the_cap() {
        let body = program(
            serde_json::json!([["RUN_TRACK"], ["CMP_GE", "run", 0, 3, 0], ["VERDICT", 0]]),
            serde_json::json!([]),
        );
        let shape = action_shape("Read", Some(("read", "data_store")), "");
        let mut session = state(
            &[],
            &[],
            &[],
            &[],
            Some(RunState {
                shape: Some(shape),
                len: 2,
            }),
        );
        let event = Event {
            tool_name: "Read".to_string(),
            ..Default::default()
        };
        let result = run_pre_with(&body, &mut session, &event, &read_classification());
        assert!(result.fired, "the third consecutive same-shape action");
    }

    #[test]
    fn shape_budget_le_accrues_in_post_and_decides_in_pre() {
        let body = program(
            serde_json::json!([["CMP_GE", "a", 0, 100_000, 0], ["VERDICT", 0]]),
            serde_json::json!([["ADD_SAT", 0, "spend_delta.tokens"]]),
        );
        let mut under = state(&[], &[], &[], &[99_999], None);
        assert!(!run_pre(&body, &mut under).fired);

        let mut at = state(&[], &[], &[], &[100_000], None);
        assert!(run_pre(&body, &mut at).fired);
    }

    #[test]
    fn shape_budget_le_without_a_priced_delta_accrues_nothing() {
        // `micro_usd` exists only when the bundle ships a `pricebook` fact — the
        // client never invents money.
        let body = program(
            serde_json::json!([]),
            serde_json::json!([["ADD_SAT", 0, "spend_delta.micro_usd"]]),
        );
        let event = Event {
            event_type: "post_tool_use".to_string(),
            spend_delta: Some(SpendDelta {
                tokens: Some(4_200),
                micro_usd: None,
            }),
            ..Default::default()
        };
        let facts = FactSet::default();
        let classification = Classification::default();
        let mut ctx = EvalContext::new(&event, &classification, &facts, NOW);
        let mut session = state(&[], &[], &[], &[50_000], None);
        run_program(
            &body,
            Half::Post,
            &mut ctx,
            &ScanTable::default(),
            &mut session,
        );
        assert_eq!(session.a, vec![50_000]);
    }

    #[test]
    fn shape_followed_by_raises_an_anomaly_and_decides_nothing() {
        let body = program(
            serde_json::json!([]),
            serde_json::json!([["TEST", 0, 0], ["ANOMALY", 0, "followed_by_unsatisfied"]]),
        );
        let event = Event {
            event_type: "stop".to_string(),
            ..Default::default()
        };
        let facts = FactSet::default();
        let classification = Classification::default();
        let mut ctx = EvalContext::new(&event, &classification, &facts, NOW);
        let mut still_set = state(&[], &[true], &[], &[], None);
        let raised = run_program(
            &body,
            Half::Post,
            &mut ctx,
            &ScanTable::default(),
            &mut still_set,
        );
        assert!(!raised.fired, "an anomaly records; it never decides");
        assert_eq!(
            raised.anomalies,
            vec!["followed_by_unsatisfied".to_string()]
        );

        let mut met = state(&[], &[false], &[], &[], None);
        let quiet = run_program(&body, Half::Post, &mut ctx, &ScanTable::default(), &mut met);
        assert!(quiet.anomalies.is_empty());
    }

    // ── Halves, layout and validation ────────────────────────────────

    #[test]
    fn each_half_runs_on_its_own_events_and_nothing_else() {
        for event_type in PRE_EVENTS {
            assert_eq!(half_for(event_type), Some(Half::Pre), "{event_type}");
        }
        for event_type in POST_EVENTS {
            assert_eq!(half_for(event_type), Some(Half::Post), "{event_type}");
        }
        assert_eq!(
            half_for("notification"),
            None,
            "not an error — just not ours"
        );
    }

    #[test]
    fn the_bundle_layout_is_element_wise_across_programs() {
        let layout = |c, f, t, a, run| T2StateLayout {
            c: Some(c),
            f: Some(f),
            t: Some(t),
            a: Some(a),
            run: Some(run),
        };
        let mut first = program(serde_json::json!([]), serde_json::json!([]));
        first.state_layout = Some(layout(1, 0, 0, 0, false));
        let mut second = program(serde_json::json!([]), serde_json::json!([]));
        second.state_layout = Some(layout(2, 1, 0, 0, true));

        let artifacts = vec![loaded(first), loaded(second)];
        let union = bundle_state_layout(&artifacts);
        assert_eq!(union.c, 2, "MAX, not the sum: a sum would demand three");
        assert_eq!(union.f, 1);
        assert!(union.run);
    }

    fn loaded(body: T2RegisterProgram) -> LoadedArtifact {
        LoadedArtifact {
            envelope: crate::generated::types::PolicyArtifact {
                artifact_id: Some("prog".to_string()),
                atom_id: Some("atom-prog".to_string()),
                tier: Some(2),
                ..Default::default()
            },
            body: super::super::bundle::ArtifactBody::T2(Box::new(body)),
        }
    }

    #[test]
    fn a_state_that_disagrees_with_the_layout_is_malformed_never_padded() {
        let layout = StateLayout {
            c: 2,
            f: 1,
            t: 0,
            a: 0,
            run: false,
        };
        let short = state(&[0], &[false], &[], &[], None);
        assert!(validate_state(&short, &layout).is_err());
        let exact = state(&[0, 0], &[false], &[], &[], None);
        assert!(validate_state(&exact, &layout).is_ok());
    }

    #[test]
    fn validate_program_closes_the_op_list_and_the_operand_vocabularies() {
        let unknown_op = program(
            serde_json::json!([["FROBNICATE", 0]]),
            serde_json::json!([]),
        );
        assert!(validate_program(&unknown_op).is_err());

        let bad_bank = program(
            serde_json::json!([["CMP_GE", "z", 0, 1, 0]]),
            serde_json::json!([]),
        );
        assert!(validate_program(&bad_bank).is_err());

        let bad_source = program(
            serde_json::json!([]),
            serde_json::json!([["ADD_SAT", 0, "event.anything"]]),
        );
        assert!(validate_program(&bad_source).is_err());

        let not_an_array = T2RegisterProgram {
            pre: vec![vec![]],
            ..Default::default()
        };
        assert!(validate_program(&not_an_array).is_err());
    }

    #[test]
    fn a_match_over_an_unreadable_node_is_rejected_at_load() {
        // The whole point of checking it HERE: raised mid-evaluation, an
        // unreadable node would take the denies of every OTHER artifact in the
        // bundle with it.
        let body = program(serde_json::json!([["MATCH", 42, 0]]), serde_json::json!([]));
        assert!(validate_program(&body).is_err());
    }

    // ── Eviction ─────────────────────────────────────────────────────

    fn evict_body(on_evict: Option<&str>) -> T2RegisterProgram {
        T2RegisterProgram {
            on_evict: on_evict.map(str::to_string),
            verdict: Some(Verdict::Block),
            reason: Some("tier 2 fired".to_string()),
            ..Default::default()
        }
    }

    fn evict_artifact(on_inconclusive: &str) -> LoadedArtifact {
        LoadedArtifact {
            envelope: crate::generated::types::PolicyArtifact {
                artifact_id: Some("prog".to_string()),
                on_inconclusive: Some(on_inconclusive.to_string().into()),
                ..Default::default()
            },
            body: super::super::bundle::ArtifactBody::T2(Box::new(evict_body(None))),
        }
    }

    #[test]
    fn on_evict_reinit_and_the_default_defer_to_a_blank_state() {
        let artifact = evict_artifact("ask");
        let enforce = PolicyMode(MODE_ENFORCE.to_string());
        let layout = StateLayout::default();
        for on_evict in [None, Some("reinit"), Some("something-newer")] {
            assert!(
                evicted_contribution(&artifact, &evict_body(on_evict), enforce.clone(), &layout)
                    .is_none(),
                "{on_evict:?} counts from zero"
            );
        }
    }

    #[test]
    fn on_evict_unknown_routes_to_on_inconclusive_and_names_the_gap() {
        let artifact = evict_artifact("ask");
        let contribution = evicted_contribution(
            &artifact,
            &evict_body(Some("unknown")),
            PolicyMode(MODE_ENFORCE.to_string()),
            &StateLayout::default(),
        )
        .expect("undecidable is a contribution, not a silence");
        assert_eq!(contribution.verdict, Verdict::Ask);
        assert_eq!(contribution.inconclusive, vec!["session_state_evicted"]);
    }

    #[test]
    fn on_evict_fail_static_keeps_enforcing_and_never_becomes_an_allow() {
        // The house invariant. A resident bundle keeps enforcing; eviction is not
        // a quiet fail-open.
        let artifact = evict_artifact("ask");
        let contribution = evicted_contribution(
            &artifact,
            &evict_body(Some("fail_static")),
            PolicyMode(MODE_ENFORCE.to_string()),
            &StateLayout::default(),
        )
        .expect("fail_static contributes");
        assert_eq!(contribution.verdict, Verdict::Block);
        assert!(contribution.inconclusive.is_empty());
    }

    #[test]
    fn fail_static_under_monitor_contributes_block_but_does_not_enforce() {
        // `on_evict` composes with mode; it does not outrank it. `fail_static`
        // keeps the artifact's verdict, so the contribution still SAYS block —
        // that is what `would_have_verdict` reports — but a monitor artifact
        // never joins, so the block never reaches the developer.
        //
        // The direction matters: `enforcement_enabled: false` composes every
        // artifact as monitor, so the org-wide kill switch outranks fail-static.
        // The house invariant is that a resident bundle keeps enforcing when it
        // cannot REFRESH; an explicit instruction to stop enforcing is not that,
        // and a fail_static rule that survived the kill switch would mean turning
        // enforcement off did not turn enforcement off.
        let artifact = evict_artifact("ask");
        let body = evict_body(Some("fail_static"));
        let layout = StateLayout::default();

        let enforcing = evicted_contribution(
            &artifact,
            &body,
            PolicyMode(MODE_ENFORCE.to_string()),
            &layout,
        )
        .expect("fail_static contributes");
        assert_eq!(enforcing.verdict, Verdict::Block);
        assert!(
            enforcing.is_enforcing(),
            "an enforce atom blocks the action"
        );

        let monitored = evicted_contribution(
            &artifact,
            &body,
            PolicyMode(MODE_MONITOR.to_string()),
            &layout,
        )
        .expect("a monitor artifact still contributes");
        assert_eq!(
            monitored.verdict,
            Verdict::Block,
            "it still says what it would have done"
        );
        assert!(
            !monitored.is_enforcing(),
            "monitor never joins — the kill switch outranks fail-static"
        );
    }

    #[test]
    fn monitor_is_always_allow_and_flag_whatever_the_artifact_declares() {
        let artifact = evict_artifact("block");
        let monitor = evicted_contribution(
            &artifact,
            &evict_body(Some("unknown")),
            PolicyMode(MODE_MONITOR.to_string()),
            &StateLayout::default(),
        )
        .expect("a monitor artifact still contributes");
        assert_eq!(monitor.verdict, Verdict::Allow, "monitor never blocks");
    }

    // ── Contributions ────────────────────────────────────────────────

    #[test]
    fn an_unevaluated_event_contributes_nothing_and_leaves_the_state_alone() {
        let body = program(serde_json::json!([["INC_SAT", 0]]), serde_json::json!([]));
        let artifact = loaded(body.clone());
        let event = Event {
            event_type: "notification".to_string(),
            ..Default::default()
        };
        let facts = FactSet::default();
        let classification = Classification::default();
        let mut ctx = EvalContext::new(&event, &classification, &facts, NOW);
        let layout = StateLayout {
            c: 1,
            ..Default::default()
        };
        let mut session = state(&[4], &[], &[], &[], None);
        let contribution = contribution(
            &artifact,
            &body,
            &mut ctx,
            &ScanTable::default(),
            &mut session,
            &layout,
        );
        assert!(contribution.is_none());
        assert_eq!(session.c, vec![4], "untouched");
    }

    #[test]
    fn a_program_that_neither_fires_nor_raises_contributes_nothing() {
        let body = program(serde_json::json!([["INC_SAT", 0]]), serde_json::json!([]));
        let artifact = loaded(body.clone());
        let event = Event {
            event_type: "pre_tool_use".to_string(),
            ..Default::default()
        };
        let facts = FactSet::default();
        let classification = Classification::default();
        let mut ctx = EvalContext::new(&event, &classification, &facts, NOW);
        let layout = StateLayout {
            c: 1,
            ..Default::default()
        };
        let mut session = state(&[0], &[], &[], &[], None);
        assert!(contribution(
            &artifact,
            &body,
            &mut ctx,
            &ScanTable::default(),
            &mut session,
            &layout
        )
        .is_none());
        assert_eq!(session.c, vec![1], "but the state still advanced");
    }

    #[test]
    fn a_fired_program_carries_the_envelope_and_the_body_reason() {
        let body = program(
            serde_json::json!([["TEST", 0, 0], ["VERDICT", 0]]),
            serde_json::json!([]),
        );
        let artifact = loaded(body.clone());
        let event = Event {
            event_type: "pre_tool_use".to_string(),
            ..Default::default()
        };
        let facts = FactSet::default();
        let classification = Classification::default();
        let mut ctx = EvalContext::new(&event, &classification, &facts, NOW);
        let layout = StateLayout {
            f: 1,
            ..Default::default()
        };
        let mut session = state(&[], &[true], &[], &[], None);
        let contribution = contribution(
            &artifact,
            &body,
            &mut ctx,
            &ScanTable::default(),
            &mut session,
            &layout,
        )
        .expect("it fired");
        assert_eq!(contribution.verdict, Verdict::Block);
        assert_eq!(contribution.reason, "tier 2 fired");
        assert_eq!(contribution.artifact_id.as_deref(), Some("prog"));
        assert_eq!(contribution.tier, Some(2));
    }

    #[test]
    fn an_anomaly_only_run_contributes_allow() {
        let body = program(
            serde_json::json!([]),
            serde_json::json!([["TEST", 0, 0], ["ANOMALY", 0, "followed_by_unsatisfied"]]),
        );
        let artifact = loaded(body.clone());
        let event = Event {
            event_type: "stop".to_string(),
            ..Default::default()
        };
        let facts = FactSet::default();
        let classification = Classification::default();
        let mut ctx = EvalContext::new(&event, &classification, &facts, NOW);
        let layout = StateLayout {
            f: 1,
            ..Default::default()
        };
        let mut session = state(&[], &[true], &[], &[], None);
        let contribution = contribution(
            &artifact,
            &body,
            &mut ctx,
            &ScanTable::default(),
            &mut session,
            &layout,
        )
        .expect("an anomaly is a contribution");
        assert_eq!(contribution.verdict, Verdict::Allow);
        assert_eq!(contribution.anomalies, vec!["followed_by_unsatisfied"]);
    }
}