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
//! Fact resolution, staleness, closed/open world, and the fact-id registry —
//! plan 02 §2e, PRD §Facts.
//!
//! The resolution order, verbatim from the PRD:
//!
//! ```text
//! absent, or a kind we do not know          -> Unknown(Absent)
//! now − observed_at > max_age_s + leeway_s  -> Unknown(Stale)
//! outside valid_from / valid_until          -> Unknown(Stale)
//! miss AND closed_world                     -> False
//! miss otherwise                            -> Unknown(OpenWorldMiss)
//! ```
//!
//! A `fact_ref` that is unfetchable, oversize or hash-mismatching resolves as
//! `Unknown(Absent)` — never a default, never a bundle rejection. **There is no
//! fact-level fallback anywhere**: ⊥ on an atom's condition routes to that
//! atom's `on_inconclusive` (Monitor is always `allow_and_flag`) and lands in
//! `decision.inconclusive_facts[]`.
//!
//! # `now_ms` is a parameter, never a clock
//!
//! Staleness is measured against a timestamp that arrived in the frame. Nothing
//! here reads a clock, which is what makes a replay of the same row reproducible
//! — and what `ci/check-engine-purity.py` rule `wall-clock` enforces.
//!
//! # Timestamps carry an offset, and an offset-less one is UTC
//!
//! PRD §Bundle schema 2, amended 2026-09-03: `observed_at`, `valid_from` and
//! `valid_until` are RFC 3339 **with an offset**, and a value without one is read
//! as UTC on both sides. Reading it in the host's local zone spreads sixteen
//! hours across `UTC`, `Asia/Tokyo` and `America/Los_Angeles` — enough to flip a
//! fact between fresh and stale under `max_age_s: 3600`, and the atom between its
//! verdict and its `on_inconclusive` branch, on two machines running the same
//! bundle. Fact staleness is not allowed to depend on `TZ`.

use chrono::{DateTime, NaiveDate, NaiveDateTime};
use serde_json::Value;

use crate::generated::types::{BundleFact, FactId};

use super::kleene::{Inconclusive, Kleene};

/// The fact-id registry — D-17. Mirrors `schemas/enums.schema.json`
/// `$defs/FactId` `x-known-values`.
///
/// A fact id outside this list **warns and still evaluates**. It must never fail
/// a bundle: an unknown fact id stays valid, and the warning exists only because
/// a typo currently produces a silent, permanent `on_inconclusive` that nothing
/// surfaces.
pub const KNOWN_FACT_IDS: &[&str] = &[
    "env_selectors",
    "data_store_roots",
    "classified_sources",
    "approved_registries",
    "approved_mcp_servers",
    "approved_domains",
    "approved_region_hosts",
    "pricebook",
];

/// The fact shapes this engine can interpret — PRD §Bundle schema 2, Phase 1.
///
/// A fact whose `kind` is anything else resolves as [`FactStatus::Absent`],
/// never as a default. The schema deliberately leaves `kind` open (R14), so a
/// newer platform shipping a fourth shape degrades to ⊥ on this client rather
/// than failing the whole bundle for the fleet.
pub const KNOWN_FACT_KINDS: &[&str] = &["set", "map", "scalar"];

/// The comparisons a `pred: fact` leaf may carry in `leaf.fact.op`.
///
/// Checked at LOAD (`tier1::validate_node`), for the reason the oracle's
/// `KNOWN_FACT_OPS` gives: an unreadable op caught mid-evaluation would take the
/// whole bundle's denies with it, where a load-time check skips one artifact.
pub const KNOWN_FACT_OPS: &[&str] = &["equals", "in_set", "int_cmp"];

/// The JSON `null` a missing `value` compares as, so "the key is absent" and
/// "the key is null" are one case rather than two — the reading the oracle gets
/// for free from Python's `dict.get`.
///
/// A `static` and not a `const` because a borrow of it has to outlive the
/// expression: [`field_values`] hands back references INTO the fact, and a
/// `const` would promote a fresh temporary at each use site. It is a constant,
/// not state — nothing writes it, and `Value::Null` holds no allocation.
static NULL: Value = Value::Null;

/// One fact's resolution against `now_ms`.
///
/// There is deliberately no fourth variant and no `Default`: a fact is readable,
/// missing, or out of date, and "assume it said yes" is not a state this engine
/// can represent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FactStatus {
    /// Readable, in date, and of a kind this engine interprets.
    Present,
    /// Not in the bundle, of an unknown kind, or carrying an `observed_at` that
    /// does not parse. A `fact_refs[]` entry the poller never inlined is this.
    Absent,
    /// Older than `max_age_s + leeway_s`, or outside `valid_from`/`valid_until`.
    Stale,
}

impl FactStatus {
    /// The ⊥ reason this status produces, or `None` when the fact is readable.
    pub fn inconclusive(self) -> Option<Inconclusive> {
        match self {
            FactStatus::Present => None,
            FactStatus::Absent => Some(Inconclusive::Absent),
            FactStatus::Stale => Some(Inconclusive::Stale),
        }
    }

    pub fn is_present(self) -> bool {
        matches!(self, FactStatus::Present)
    }
}

/// The facts one action is evaluated against, resolved once per event.
///
/// A value derived from the bundle and `now_ms`, never a resident cache: the
/// process may cache what is derived from its inputs, never what is derived from
/// its history.
///
/// # `facts` is not "the inline facts"
///
/// It is every fact id the bundle DECLARES, in the oracle's order: one
/// placeholder per `fact_refs[]` entry first, then `facts[]` in bundle order.
/// A later entry shadows an earlier one with the same id, which is how a ref the
/// poller inlined resolves as present while an un-inlined one stays ⊥ absent.
/// **Do not read `.value` off an element of this vector directly** — a
/// placeholder carries none, and an entry that is here may still be stale. Use
/// [`FactSet::present`], which is the `status != "present"` guard the oracle's
/// classifier applies at `effect.py:314`.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct FactSet {
    /// Every declared fact, refs first then inline; last entry with an id wins.
    pub facts: Vec<BundleFact>,
    /// The frame's timestamp, carried so a caller with no `now_ms` of its own —
    /// the effect classifier — can still tell a fresh fact from a stale one.
    /// Injected, never read from a clock.
    pub now_ms: i64,
}

impl FactSet {
    /// The set a caller assembles by hand — tests, and the effect classifier's
    /// fixtures. Prefer [`resolve`] for a real bundle.
    pub fn new(facts: Vec<BundleFact>, now_ms: i64) -> FactSet {
        FactSet { facts, now_ms }
    }

    /// Every fact id the bundle *declares*, for the D-17 registry warning on the
    /// declaring side — a bundle shipping `aproved_domains` resolves every leaf
    /// reading `approved_domains` to ⊥ and would otherwise say nothing.
    pub fn declared_ids(&self) -> Vec<String> {
        self.facts
            .iter()
            .filter_map(|f| f.fact_id.as_ref().map(|id| id.0.clone()))
            .collect()
    }

    /// Look up one fact by id, whatever its status. The LAST declaration wins,
    /// so an inline `facts[]` entry shadows the `fact_refs[]` placeholder of the
    /// same id exactly as the oracle's dict overwrite does.
    pub fn get(&self, fact_id: &str) -> Option<&BundleFact> {
        self.facts
            .iter()
            .rev()
            .find(|f| f.fact_id.as_ref().is_some_and(|id| id.0 == fact_id))
    }

    /// This fact's resolution as of `now_ms`.
    pub fn status_at(&self, fact_id: &str, now_ms: i64) -> FactStatus {
        match self.get(fact_id) {
            Some(fact) => status_of(fact, now_ms),
            None => FactStatus::Absent,
        }
    }

    /// This fact's resolution as of the frame's own timestamp.
    pub fn status(&self, fact_id: &str) -> FactStatus {
        self.status_at(fact_id, self.now_ms)
    }

    /// The fact **only when it is readable** — the one accessor a caller that
    /// wants a value should use. `None` covers absent, unknown-kind and stale
    /// alike, and none of those is a value.
    pub fn present(&self, fact_id: &str) -> Option<&BundleFact> {
        self.get(fact_id)
            .filter(|fact| status_of(fact, self.now_ms).is_present())
    }
}

/// Whether `fact_id` is in the D-17 registry. A miss warns; it never rejects.
pub fn is_known_fact_id(fact_id: &str) -> bool {
    KNOWN_FACT_IDS.contains(&fact_id)
}

/// Resolve the bundle's facts for this action.
///
/// `fact_refs[]` become placeholders: the engine performs no network call, ever,
/// so an out-of-band fact is one the poller has already inlined. A ref with no
/// inline twin is ⊥ absent — which is also, and by the same route, what an
/// unfetchable, oversize or hash-mismatching ref resolves to. There is nothing
/// for a fetch failure to be *instead of*.
pub fn resolve(bundle: &super::bundle::Bundle, now_ms: i64) -> FactSet {
    let mut facts: Vec<BundleFact> =
        Vec::with_capacity(bundle.facts.len() + bundle.fact_refs.len());
    for reference in &bundle.fact_refs {
        if let Some(fact_id) = reference.fact_id.as_ref() {
            facts.push(BundleFact {
                fact_id: Some(FactId(fact_id.0.clone())),
                ..BundleFact::default()
            });
        }
    }
    for fact in &bundle.facts {
        if fact.fact_id.is_some() {
            facts.push(fact.clone());
        }
    }
    FactSet { facts, now_ms }
}

/// Resolve one fact leaf — *the fact is the subject* ("is the ticket approved?").
///
/// `pred` is the `leaf.fact.op` of a compiled `pred: fact` leaf, one of
/// [`KNOWN_FACT_OPS`]; `value` is its literal. An op outside that set is ⊥ and
/// not a panic, because the loader already skipped the artifact carrying one.
///
/// **The caller notes the fact id** when the answer is ⊥ *and*
/// [`Inconclusive::names_a_fact`] — an open-world miss is ⊥ without being a fact
/// the engine failed to read.
pub fn resolve_leaf(
    facts: &FactSet,
    fact_id: &str,
    pred: &str,
    value: Option<&Value>,
    now_ms: i64,
) -> Kleene {
    let Some(fact) = readable(facts, fact_id, now_ms) else {
        return Kleene::Unknown(unreadable_reason(facts, fact_id, now_ms));
    };
    match pred {
        "equals" => {
            Kleene::from_bool(fact.value.as_ref().unwrap_or(&NULL) == value.unwrap_or(&NULL))
        }
        "in_set" => {
            // A set-kind fact SUPPLIES the set. Any other kind is the inverted
            // reading: the fact's own value is tested against a literal list.
            if fact.kind.as_deref() == Some("set") {
                membership_in(fact, value.unwrap_or(&NULL))
            } else {
                let own = fact.value.as_ref().unwrap_or(&NULL);
                let literal = as_list(value.unwrap_or(&NULL));
                Kleene::from_bool(literal.contains(&own))
            }
        }
        "int_cmp" => Kleene::from_bool(int_cmp(fact.value.as_ref(), value)),
        _ => Kleene::UNKNOWN,
    }
}

/// Resolve the set an `in_fact_set` leaf compares against — *the attribute is
/// the subject, the fact supplies the set* ("url.host ∈ approved_domains").
///
/// `None` means the set is unresolvable, which makes the leaf ⊥ `Absent` or ⊥
/// `Stale`. **A `Some` that does not contain the candidate is not a `false`** —
/// whether a miss is a real negative is `closed_world`'s to say, so use
/// [`membership`], which answers the whole question in one call. This function
/// exists for a caller that needs the members themselves.
pub fn resolve_set(facts: &FactSet, fact_id: &str, now_ms: i64) -> Option<Vec<String>> {
    let fact = readable(facts, fact_id, now_ms)?;
    Some(
        set_members(fact)
            .into_iter()
            .map(|member| match member {
                Value::String(text) => text,
                other => other.to_string(),
            })
            .collect(),
    )
}

/// Is `candidate` a member of the set `fact_id` supplies?
///
/// The one call that carries the whole open/closed-world rule:
///
/// | outcome | answer |
/// | ------- | ------ |
/// | the fact is absent, of an unknown kind, or stale | ⊥ `Absent` / ⊥ `Stale` |
/// | the candidate is a member | `True` |
/// | a miss, and the fact declares `closed_world` | `False` |
/// | a miss otherwise | ⊥ `OpenWorldMiss` |
///
/// That last row is the difference between "this host is not approved" and "we
/// do not know whether it is", and it is the only place in the engine where a
/// perfectly readable fact still produces ⊥.
pub fn membership(facts: &FactSet, fact_id: &str, candidate: &Value, now_ms: i64) -> Kleene {
    match readable(facts, fact_id, now_ms) {
        Some(fact) => membership_in(fact, candidate),
        None => Kleene::Unknown(unreadable_reason(facts, fact_id, now_ms)),
    }
}

/// Split `fact.<fact_id>[.dotted.path]` into its id and its path — ONE reading,
/// never two.
///
/// The first dot-separated segment after `fact.` is the fact id; everything
/// after it is a path into that fact's value, so `fact.change_ticket.approved`
/// reads the fact `change_ticket` and then the key `approved`. A fact literally
/// named `change_ticket.approved` is **not reachable and is not looked for** —
/// the corpus pins that as `fact-field-dotted-id-is-not-a-second-reading`. An
/// engine that silently tries a second reading cannot be adjudicated against.
///
/// `None` when `field` is not a `fact.` field at all.
pub fn split_field(field: &str) -> Option<(&str, &str)> {
    let rest = field.strip_prefix("fact.")?;
    Some(match rest.split_once('.') {
        Some((fact_id, path)) => (fact_id, path),
        None => (rest, ""),
    })
}

/// The values behind `fact.<fact_id>[.dotted.path]` — the ATTRIBUTE route into a
/// fact, where the fact supplies the value a predicate is then tested against.
///
/// A list value spreads into its members, so `fact.change_ticket.reviewers`
/// matches `"bo"`. Anything else is a one-element list. `Err` when the fact is
/// unreadable **or the path misses**: a key that is not there is not `null`, and
/// a path through a scalar is not an empty match — both are ⊥, and both name the
/// fact in `inconclusive_facts[]` ([`Inconclusive::names_a_fact`] is true for
/// each).
pub fn field_values<'a>(
    facts: &'a FactSet,
    field: &str,
    now_ms: i64,
) -> Result<Vec<&'a Value>, Inconclusive> {
    let Some((fact_id, path)) = split_field(field) else {
        return Err(Inconclusive::Absent);
    };
    let Some(fact) = readable(facts, fact_id, now_ms) else {
        return Err(unreadable_reason(facts, fact_id, now_ms));
    };
    let mut value = fact.value.as_ref().unwrap_or(&NULL);
    if !path.is_empty() {
        for segment in path.split('.') {
            value = match value.as_object().and_then(|map| map.get(segment)) {
                Some(next) => next,
                None => return Err(Inconclusive::Absent),
            };
        }
    }
    Ok(match value {
        Value::Array(members) => members.iter().collect(),
        single => vec![single],
    })
}

// ── Internals ────────────────────────────────────────────────────────

/// The fact, only when it resolves as [`FactStatus::Present`] at `now_ms`.
fn readable<'a>(facts: &'a FactSet, fact_id: &str, now_ms: i64) -> Option<&'a BundleFact> {
    facts
        .get(fact_id)
        .filter(|fact| status_of(fact, now_ms).is_present())
}

/// Why a fact that is not readable is not readable. `Absent` covers the fact
/// that was never there, and `Stale` the one that was.
fn unreadable_reason(facts: &FactSet, fact_id: &str, now_ms: i64) -> Inconclusive {
    match facts.status_at(fact_id, now_ms).inconclusive() {
        Some(reason) => reason,
        // Unreachable through `readable`, which only returns `None` for a fact
        // whose status is not Present. Absent is the answer that assumes least.
        None => Inconclusive::Absent,
    }
}

/// One fact's resolution, in the PRD's order. The order is load-bearing: a fact
/// whose `kind` this engine cannot read is absent BEFORE its age is considered,
/// so a shape the client does not understand never reports as merely out of date.
fn status_of(fact: &BundleFact, now_ms: i64) -> FactStatus {
    let Some(kind) = fact.kind.as_deref() else {
        return FactStatus::Absent;
    };
    if !KNOWN_FACT_KINDS.contains(&kind) {
        return FactStatus::Absent;
    }
    let Some(observed_at) = rfc3339_ms(fact.observed_at.as_deref()) else {
        return FactStatus::Absent;
    };
    // `max_age_s` absent or zero means the fact never ages out. Saturating
    // throughout: an authored `max_age_s` is an integer from a bundle, and a
    // wrapping multiply would turn a very patient fact into an instantly stale
    // one.
    let max_age_s = fact.max_age_s.unwrap_or(0);
    if max_age_s != 0 {
        let budget_ms = max_age_s
            .saturating_add(fact.leeway_s.unwrap_or(0))
            .saturating_mul(1_000);
        if now_ms.saturating_sub(observed_at) > budget_ms {
            return FactStatus::Stale;
        }
    }
    if rfc3339_ms(fact.valid_from.as_deref()).is_some_and(|from| now_ms < from) {
        return FactStatus::Stale;
    }
    if rfc3339_ms(fact.valid_until.as_deref()).is_some_and(|until| now_ms > until) {
        return FactStatus::Stale;
    }
    FactStatus::Present
}

/// RFC 3339 → epoch milliseconds. `None` when the text does not parse, which is
/// [`FactStatus::Absent`] and never "now".
///
/// An offset-less value is read as **UTC**; see the module header for the sixteen
/// hours that costs otherwise.
fn rfc3339_ms(text: Option<&str>) -> Option<i64> {
    let text = text?;
    if let Ok(parsed) = DateTime::parse_from_rfc3339(text) {
        return Some(parsed.timestamp_millis());
    }
    for format in ["%Y-%m-%dT%H:%M:%S%.f", "%Y-%m-%d %H:%M:%S%.f"] {
        if let Ok(naive) = NaiveDateTime::parse_from_str(text, format) {
            return Some(naive.and_utc().timestamp_millis());
        }
    }
    if let Ok(date) = NaiveDate::parse_from_str(text, "%Y-%m-%d") {
        return Some(date.and_hms_opt(0, 0, 0)?.and_utc().timestamp_millis());
    }
    None
}

/// The members of a fact read as a set. A map contributes its KEYS — that is
/// what makes `pricebook` testable for membership — and a scalar contributes
/// itself.
fn set_members(fact: &BundleFact) -> Vec<Value> {
    match fact.value.as_ref() {
        Some(Value::Array(members)) => members.clone(),
        Some(Value::Object(map)) => map.keys().map(|key| Value::String(key.clone())).collect(),
        Some(other) => vec![other.clone()],
        None => vec![Value::Null],
    }
}

/// Membership against an already-readable fact — the open/closed-world rule
/// itself.
fn membership_in(fact: &BundleFact, candidate: &Value) -> Kleene {
    if set_members(fact).iter().any(|member| member == candidate) {
        return Kleene::True;
    }
    if fact.closed_world == Some(true) {
        Kleene::False
    } else {
        Kleene::Unknown(Inconclusive::OpenWorldMiss)
    }
}

/// A value read as a list: an array spreads, anything else is one member.
fn as_list(value: &Value) -> Vec<&Value> {
    match value {
        Value::Array(members) => members.iter().collect(),
        single => vec![single],
    }
}

/// `{op, n}` against an integer fact value. A non-integer on either side is a
/// plain `false`: the fact was READ, and a string is not greater than four.
fn int_cmp(left: Option<&Value>, spec: Option<&Value>) -> bool {
    let (Some(left), Some(spec)) = (left.and_then(Value::as_i64), spec) 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,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// 2025-09-01T16:00:00Z — the corpus's `now_ms`, so a fixture read here and
    /// a fixture read by `04-facts-kleene.jsonl` mean the same instant.
    const NOW: i64 = 1_756_742_400_000;

    fn fact(value: serde_json::Value) -> BundleFact {
        serde_json::from_value(value).expect("the fixture is a BundleFact")
    }

    fn one(value: serde_json::Value) -> FactSet {
        FactSet::new(vec![fact(value)], NOW)
    }

    /// A fact observed one minute before `NOW`, well inside a day's `max_age_s`.
    fn fresh_ticket() -> serde_json::Value {
        json!({
            "fact_id": "change_ticket",
            "kind": "scalar",
            "revision": 1,
            "source": "platform",
            "observed_at": "2025-09-01T15:59:00+00:00",
            "max_age_s": 86400,
            "leeway_s": 300,
            "closed_world": false,
            "value": true,
        })
    }

    fn domains(closed_world: bool) -> serde_json::Value {
        json!({
            "fact_id": "approved_domains",
            "kind": "set",
            "observed_at": "2025-09-01T15:59:00+00:00",
            "max_age_s": 86400,
            "leeway_s": 300,
            "closed_world": closed_world,
            "value": ["api.example.com"],
        })
    }

    // ── Status, one cause at a time ──────────────────────────────────

    #[test]
    fn a_readable_fact_is_present() {
        assert_eq!(
            one(fresh_ticket()).status("change_ticket"),
            FactStatus::Present
        );
    }

    #[test]
    fn a_fact_nobody_declared_is_absent() {
        let facts = one(fresh_ticket());
        assert_eq!(facts.status("change_ticket_typo"), FactStatus::Absent);
        assert_eq!(
            facts.status_at("change_ticket_typo", NOW).inconclusive(),
            Some(Inconclusive::Absent)
        );
    }

    #[test]
    fn a_kind_this_engine_does_not_know_is_absent_not_stale() {
        let mut raw = fresh_ticket();
        raw["kind"] = json!("graph");
        assert_eq!(one(raw).status("change_ticket"), FactStatus::Absent);
    }

    #[test]
    fn a_fact_with_no_kind_at_all_is_absent() {
        let raw = json!({"fact_id": "change_ticket", "value": true});
        assert_eq!(one(raw).status("change_ticket"), FactStatus::Absent);
    }

    #[test]
    fn an_unparseable_observed_at_is_absent_never_now() {
        let mut raw = fresh_ticket();
        raw["observed_at"] = json!("not-a-date");
        assert_eq!(one(raw).status("change_ticket"), FactStatus::Absent);
    }

    #[test]
    fn a_missing_observed_at_is_absent() {
        let mut raw = fresh_ticket();
        raw.as_object_mut().expect("object").remove("observed_at");
        assert_eq!(one(raw).status("change_ticket"), FactStatus::Absent);
    }

    // ── Staleness, at the boundary ───────────────────────────────────

    #[test]
    fn a_fact_older_than_max_age_plus_leeway_is_stale() {
        let mut raw = fresh_ticket();
        raw["observed_at"] = json!("2025-09-01T14:53:20+00:00"); // 4000 s before NOW
        raw["max_age_s"] = json!(3600);
        assert_eq!(one(raw).status("change_ticket"), FactStatus::Stale);
    }

    #[test]
    fn the_leeway_is_added_to_max_age_not_subtracted() {
        // 3700 s old against 3600 + 300: stale without the leeway, fresh with it.
        let mut raw = fresh_ticket();
        raw["observed_at"] = json!("2025-09-01T14:58:20+00:00");
        raw["max_age_s"] = json!(3600);
        assert_eq!(one(raw).status("change_ticket"), FactStatus::Present);
    }

    #[test]
    fn the_staleness_boundary_is_exclusive_to_the_millisecond() {
        let mut raw = fresh_ticket();
        raw["max_age_s"] = json!(3600);
        raw["leeway_s"] = json!(300);
        // Exactly max_age_s + leeway_s old: `>` and not `>=`, so still fresh.
        raw["observed_at"] = json!("2025-09-01T14:55:00+00:00");
        assert_eq!(
            one(raw.clone()).status("change_ticket"),
            FactStatus::Present
        );
        // One millisecond older.
        raw["observed_at"] = json!("2025-09-01T14:54:59.999+00:00");
        assert_eq!(one(raw).status("change_ticket"), FactStatus::Stale);
    }

    #[test]
    fn max_age_zero_or_absent_never_ages_a_fact_out() {
        let mut raw = fresh_ticket();
        raw["observed_at"] = json!("2025-09-01T04:53:20+00:00"); // eleven hours old
        raw["max_age_s"] = json!(0);
        assert_eq!(
            one(raw.clone()).status("change_ticket"),
            FactStatus::Present
        );
        raw.as_object_mut().expect("object").remove("max_age_s");
        assert_eq!(one(raw).status("change_ticket"), FactStatus::Present);
    }

    #[test]
    fn an_absurd_max_age_saturates_instead_of_wrapping() {
        // i64::MAX seconds × 1000 overflows. Wrapping would turn the most
        // patient fact in the bundle into an instantly stale one.
        let mut raw = fresh_ticket();
        raw["max_age_s"] = json!(i64::MAX);
        raw["leeway_s"] = json!(i64::MAX);
        assert_eq!(one(raw).status("change_ticket"), FactStatus::Present);
    }

    #[test]
    fn before_valid_from_is_stale() {
        let mut raw = fresh_ticket();
        raw["valid_from"] = json!("2025-09-02T16:00:00+00:00");
        assert_eq!(one(raw).status("change_ticket"), FactStatus::Stale);
    }

    #[test]
    fn after_valid_until_is_stale() {
        let mut raw = fresh_ticket();
        raw["valid_until"] = json!("2025-08-31T16:00:00+00:00");
        assert_eq!(one(raw).status("change_ticket"), FactStatus::Stale);
    }

    #[test]
    fn inside_the_validity_window_is_present() {
        let mut raw = fresh_ticket();
        raw["valid_from"] = json!("2025-08-31T16:00:00+00:00");
        raw["valid_until"] = json!("2025-09-02T16:00:00+00:00");
        assert_eq!(one(raw).status("change_ticket"), FactStatus::Present);
    }

    #[test]
    fn an_offsetless_observed_at_is_read_as_utc_never_as_local_time() {
        // The 2026-09-03 amendment. Read in `Asia/Tokyo` this timestamp is nine
        // hours further in the past and the fact flips to stale under
        // max_age_s 3600; read as UTC it is sixty seconds old and fresh.
        let mut raw = fresh_ticket();
        raw["observed_at"] = json!("2025-09-01T15:59:00");
        raw["max_age_s"] = json!(3600);
        assert_eq!(one(raw).status("change_ticket"), FactStatus::Present);
        assert_eq!(
            rfc3339_ms(Some("2025-09-01T15:59:00")),
            rfc3339_ms(Some("2025-09-01T15:59:00+00:00")),
            "the two spellings are the same instant"
        );
    }

    #[test]
    fn a_z_suffix_and_a_non_utc_offset_both_parse() {
        assert_eq!(
            rfc3339_ms(Some("2025-09-01T16:00:00Z")),
            rfc3339_ms(Some("2025-09-01T18:00:00+02:00"))
        );
        assert_eq!(rfc3339_ms(Some("2025-09-01T16:00:00Z")), Some(NOW));
    }

    #[test]
    fn an_unparseable_timestamp_is_none_and_never_a_substitute_instant() {
        for text in ["not-a-date", "", "2025-13-45T99:99:99Z", "16:00:00"] {
            assert_eq!(rfc3339_ms(Some(text)), None, "{text:?} must not parse");
        }
        assert_eq!(rfc3339_ms(None), None);
    }

    // ── Open world, closed world ─────────────────────────────────────

    #[test]
    fn a_membership_hit_is_true_under_either_world() {
        for closed in [true, false] {
            let facts = one(domains(closed));
            assert_eq!(
                membership(&facts, "approved_domains", &json!("api.example.com"), NOW),
                Kleene::True
            );
        }
    }

    #[test]
    fn a_closed_world_miss_is_false_and_not_an_unknown() {
        let facts = one(domains(true));
        assert_eq!(
            membership(&facts, "approved_domains", &json!("evil.example.net"), NOW),
            Kleene::False,
            "closed_world means 'not in the set' is a real negative"
        );
    }

    #[test]
    fn an_open_world_miss_is_unknown_and_names_no_fact() {
        let facts = one(domains(false));
        let answer = membership(&facts, "approved_domains", &json!("evil.example.net"), NOW);
        assert_eq!(answer, Kleene::Unknown(Inconclusive::OpenWorldMiss));
        assert!(
            !answer.reason().expect("⊥ carries a reason").names_a_fact(),
            "the fact was read — it does not belong in inconclusive_facts[]"
        );
    }

    #[test]
    fn an_absent_or_stale_set_is_unknown_before_membership_is_even_asked() {
        let facts = FactSet::new(vec![], NOW);
        assert_eq!(
            membership(&facts, "approved_domains", &json!("api.example.com"), NOW),
            Kleene::Unknown(Inconclusive::Absent)
        );

        let mut raw = domains(true);
        raw["observed_at"] = json!("2025-09-01T14:53:20+00:00");
        raw["max_age_s"] = json!(3600);
        let facts = one(raw);
        assert_eq!(
            membership(&facts, "approved_domains", &json!("api.example.com"), NOW),
            Kleene::Unknown(Inconclusive::Stale),
            "a stale set does not get to answer, hit or miss"
        );
    }

    #[test]
    fn a_map_fact_supplies_its_keys_as_the_set() {
        let facts = one(json!({
            "fact_id": "pricebook",
            "kind": "set",
            "observed_at": "2025-09-01T15:59:00+00:00",
            "closed_world": true,
            "value": {"claude-opus-5": {"input_micro_usd": 15}},
        }));
        assert_eq!(
            membership(&facts, "pricebook", &json!("claude-opus-5"), NOW),
            Kleene::True
        );
        assert_eq!(
            resolve_set(&facts, "pricebook", NOW),
            Some(vec!["claude-opus-5".to_string()])
        );
    }

    #[test]
    fn resolve_set_is_none_for_anything_that_is_not_present() {
        let facts = FactSet::new(vec![], NOW);
        assert_eq!(resolve_set(&facts, "approved_domains", NOW), None);
        assert_eq!(
            resolve_set(&one(domains(false)), "approved_domains", NOW),
            Some(vec!["api.example.com".to_string()])
        );
    }

    // ── `pred: fact` — the fact is the subject ───────────────────────

    #[test]
    fn equals_compares_the_facts_own_value() {
        let facts = one(fresh_ticket());
        assert_eq!(
            resolve_leaf(&facts, "change_ticket", "equals", Some(&json!(true)), NOW),
            Kleene::True
        );
        assert_eq!(
            resolve_leaf(&facts, "change_ticket", "equals", Some(&json!(false)), NOW),
            Kleene::False,
            "present-and-not-matching is a decided FALSE, never a ⊥"
        );
    }

    #[test]
    fn in_set_on_a_non_set_kind_tests_the_value_against_a_literal_list() {
        // The inverted reading, corpus row
        // `fact-non-set-kind-is-tested-against-a-literal-list`.
        let facts = one(json!({
            "fact_id": "pricebook",
            "kind": "map",
            "observed_at": "2025-09-01T15:59:00+00:00",
            "value": {"claude-opus-5": {"input_micro_usd": 15}},
        }));
        assert_eq!(
            resolve_leaf(
                &facts,
                "pricebook",
                "in_set",
                Some(&json!("claude-opus-5")),
                NOW
            ),
            Kleene::False,
            "the MAP is not a member of [\"claude-opus-5\"] — no ⊥ anywhere"
        );

        let mut raw = fresh_ticket();
        raw["kind"] = json!("scalar");
        raw["value"] = json!("green");
        let facts = one(raw);
        assert_eq!(
            resolve_leaf(
                &facts,
                "change_ticket",
                "in_set",
                Some(&json!(["green", "amber"])),
                NOW
            ),
            Kleene::True
        );
    }

    #[test]
    fn int_cmp_reads_the_facts_integer_and_a_non_integer_is_a_plain_false() {
        let mut raw = fresh_ticket();
        raw["value"] = json!(7);
        let facts = one(raw);
        for (op, expected) in [
            ("ge", Kleene::True),
            ("gt", Kleene::False),
            ("le", Kleene::True),
            ("lt", Kleene::False),
            ("eq", Kleene::True),
        ] {
            assert_eq!(
                resolve_leaf(
                    &facts,
                    "change_ticket",
                    "int_cmp",
                    Some(&json!({"op": op, "n": 7})),
                    NOW
                ),
                expected,
                "int_cmp {op} 7 against 7"
            );
        }
        // A boolean is not an integer, and the fact was READ, so this is FALSE.
        let facts = one(fresh_ticket());
        assert_eq!(
            resolve_leaf(
                &facts,
                "change_ticket",
                "int_cmp",
                Some(&json!({"op": "ge", "n": 1})),
                NOW
            ),
            Kleene::False
        );
    }

    #[test]
    fn an_op_the_loader_should_have_rejected_is_bottom_and_not_a_panic() {
        // `04-t1-fact-op-unreadable` skips the artifact at LOAD. If one ever
        // reached here, ⊥ is the answer that decides nothing.
        let facts = one(fresh_ticket());
        assert!(!resolve_leaf(&facts, "change_ticket", "is_approved", None, NOW).is_known());
    }

    #[test]
    fn every_unreadable_cause_reaches_the_leaf_as_its_own_reason() {
        let mut stale = fresh_ticket();
        stale["observed_at"] = json!("2025-09-01T14:53:20+00:00");
        stale["max_age_s"] = json!(3600);
        let cases: [(FactSet, Inconclusive); 3] = [
            (FactSet::new(vec![], NOW), Inconclusive::Absent),
            (one(stale), Inconclusive::Stale),
            (one(domains(false)), Inconclusive::OpenWorldMiss),
        ];
        let (absent, stale, miss) = (&cases[0], &cases[1], &cases[2]);
        assert_eq!(
            resolve_leaf(
                &absent.0,
                "change_ticket",
                "equals",
                Some(&json!(true)),
                NOW
            ),
            Kleene::Unknown(absent.1)
        );
        assert_eq!(
            resolve_leaf(&stale.0, "change_ticket", "equals", Some(&json!(true)), NOW),
            Kleene::Unknown(stale.1)
        );
        assert_eq!(
            resolve_leaf(
                &miss.0,
                "approved_domains",
                "in_set",
                Some(&json!("evil.example.net")),
                NOW
            ),
            Kleene::Unknown(miss.1)
        );
    }

    // ── `fact.<id>[.path]` — the fact supplies a value ───────────────

    #[test]
    fn a_dotted_field_splits_on_the_first_segment_only() {
        assert_eq!(
            split_field("fact.change_ticket"),
            Some(("change_ticket", ""))
        );
        assert_eq!(
            split_field("fact.change_ticket.approved"),
            Some(("change_ticket", "approved"))
        );
        assert_eq!(
            split_field("fact.a.b.c"),
            Some(("a", "b.c")),
            "everything after the first dot is the PATH"
        );
        assert_eq!(split_field("url.host"), None);
    }

    #[test]
    fn a_fact_literally_named_with_a_dot_is_not_a_second_reading() {
        // `04-fact-field-dotted-id.json`: the bundle ships a fact whose id is
        // `change_ticket.approved`, and `fact.change_ticket.approved` still
        // reads the fact `change_ticket` — which is absent. Two readings cannot
        // be adjudicated against an oracle.
        let facts = one(json!({
            "fact_id": "change_ticket.approved",
            "kind": "scalar",
            "observed_at": "2025-09-01T15:59:00+00:00",
            "value": true,
        }));
        assert_eq!(
            field_values(&facts, "fact.change_ticket.approved", NOW),
            Err(Inconclusive::Absent)
        );
    }

    #[test]
    fn a_dotted_path_reads_into_a_map() {
        let facts = one(json!({
            "fact_id": "change_ticket",
            "kind": "map",
            "observed_at": "2025-09-01T15:59:00+00:00",
            "value": {"approved": true, "reviewers": ["ana", "bo"]},
        }));
        assert_eq!(
            field_values(&facts, "fact.change_ticket.approved", NOW),
            Ok(vec![&json!(true)])
        );
        assert_eq!(
            field_values(&facts, "fact.change_ticket.reviewers", NOW),
            Ok(vec![&json!("ana"), &json!("bo")]),
            "a list value spreads, so any member can match"
        );
        assert!(
            field_values(&facts, "fact.change_ticket", NOW)
                .expect("the whole value is readable")
                .len()
                == 1,
            "no path reads the value whole"
        );
    }

    #[test]
    fn a_path_that_misses_is_bottom_and_names_the_fact() {
        let facts = one(json!({
            "fact_id": "change_ticket",
            "kind": "map",
            "observed_at": "2025-09-01T15:59:00+00:00",
            "value": {"approved": true},
        }));
        let miss = field_values(&facts, "fact.change_ticket.signed", NOW);
        assert_eq!(miss, Err(Inconclusive::Absent));
        assert!(miss.expect_err("").names_a_fact());
        // …and so does a path THROUGH a scalar.
        assert_eq!(
            field_values(&one(fresh_ticket()), "fact.change_ticket.approved", NOW),
            Err(Inconclusive::Absent)
        );
    }

    #[test]
    fn a_field_on_a_stale_fact_is_stale_not_absent() {
        let mut raw = fresh_ticket();
        raw["kind"] = json!("map");
        raw["value"] = json!({"approved": true});
        raw["observed_at"] = json!("2025-09-01T14:53:20+00:00");
        raw["max_age_s"] = json!(3600);
        assert_eq!(
            field_values(&one(raw), "fact.change_ticket.approved", NOW),
            Err(Inconclusive::Stale)
        );
    }

    // ── Refs, inline and not ─────────────────────────────────────────

    fn bundle_with(extra: serde_json::Value) -> super::super::bundle::Bundle {
        let mut doc = json!({
            "schema_version": 2,
            "organization_id": "org",
            "revision": 1,
            "built_at": "2026-09-01T00:00:00Z",
            "enforcement_enabled": true,
            "signature": null,
            "artifacts": [],
        });
        for (key, value) in extra.as_object().expect("object") {
            doc[key] = value.clone();
        }
        super::super::bundle::load(doc).expect("the envelope parses")
    }

    fn a_ref() -> serde_json::Value {
        json!([{
            "fact_id": "change_ticket",
            "sha256": "0000000000000000000000000000000000000000000000000000000000000000",
            "size_bytes": 4096,
            "url": "https://platform.example.com/facts/change_ticket",
            "observed_at": "2025-09-01T15:59:00+00:00",
            "max_age_s": 86400,
            "revision": 1,
        }])
    }

    #[test]
    fn a_ref_the_poller_never_inlined_is_absent_not_a_default() {
        let bundle = bundle_with(json!({"fact_refs": a_ref()}));
        let facts = resolve(&bundle, NOW);
        assert_eq!(facts.status("change_ticket"), FactStatus::Absent);
        assert_eq!(
            resolve_leaf(&facts, "change_ticket", "equals", Some(&json!(true)), NOW),
            Kleene::Unknown(Inconclusive::Absent),
            "unfetchable, oversize and hash-mismatching all land here — there is \
             nothing for a fetch failure to be INSTEAD of"
        );
        assert!(
            facts.declared_ids().contains(&"change_ticket".to_string()),
            "a ref is still a declaration, so a typo in one is still warned about"
        );
    }

    #[test]
    fn an_inlined_ref_resolves_as_the_inline_fact() {
        let bundle = bundle_with(json!({
            "facts": [fresh_ticket()],
            "fact_refs": a_ref(),
        }));
        let facts = resolve(&bundle, NOW);
        assert_eq!(facts.status("change_ticket"), FactStatus::Present);
        assert_eq!(
            resolve_leaf(&facts, "change_ticket", "equals", Some(&json!(true)), NOW),
            Kleene::True,
            "the inline entry shadows the placeholder, whatever their order"
        );
    }

    #[test]
    fn a_plain_inline_fact_needs_no_ref() {
        let bundle = bundle_with(json!({"facts": [fresh_ticket()]}));
        let facts = resolve(&bundle, NOW);
        assert_eq!(
            facts.present("change_ticket").map(|f| f.value.clone()),
            Some(Some(json!(true)))
        );
    }

    #[test]
    fn a_later_declaration_of_the_same_id_wins() {
        let mut second = fresh_ticket();
        second["value"] = json!(false);
        let bundle = bundle_with(json!({"facts": [fresh_ticket(), second]}));
        let facts = resolve(&bundle, NOW);
        assert_eq!(
            resolve_leaf(&facts, "change_ticket", "equals", Some(&json!(true)), NOW),
            Kleene::False
        );
    }

    #[test]
    fn a_fact_with_no_id_is_carried_by_nobody() {
        let bundle = bundle_with(json!({"facts": [{"kind": "scalar", "value": true}]}));
        assert!(resolve(&bundle, NOW).declared_ids().is_empty());
    }

    // ── The D-17 registry ────────────────────────────────────────────

    #[test]
    fn the_registry_warns_and_never_rejects() {
        assert!(is_known_fact_id("approved_domains"));
        assert!(!is_known_fact_id("aproved_domains"));
        assert!(
            !is_known_fact_id("change_ticket"),
            "the corpus's own probe fact is outside the registry — which is why \
             every 04 row expects the warning, and why none of them expects a \
             rejection"
        );
        // An id outside the registry still resolves exactly as any other would.
        let facts = one(fresh_ticket());
        assert_eq!(
            resolve_leaf(&facts, "change_ticket", "equals", Some(&json!(true)), NOW),
            Kleene::True
        );
    }

    #[test]
    fn present_is_the_guard_a_caller_without_a_now_ms_uses() {
        // The effect classifier has no `now_ms` of its own; `FactSet` carries
        // the frame's. A stale root list must not silently classify paths.
        let mut raw = domains(true);
        raw["observed_at"] = json!("2025-09-01T14:53:20+00:00");
        raw["max_age_s"] = json!(3600);
        let facts = one(raw);
        assert!(facts.get("approved_domains").is_some(), "still declared");
        assert!(
            facts.present("approved_domains").is_none(),
            "but not readable"
        );
    }

    // ── The corpus, at the leaf ──────────────────────────────────────
    //
    // The whole-`Decision` runner cannot see this slice: while `join::assemble`
    // is a stub every row answers `allow`/`null` whatever fact resolution did,
    // so a runner tally of 7/46 and one of 46/46 would say exactly as much about
    // the Kleene semantics — nothing. These two tests read the same 46 rows and
    // assert what the row IMPLIES about fact resolution, which is a number that
    // means something today and keeps meaning it after the join lands: the
    // runner proves the pipeline assembles, this proves the semantics are right,
    // and a row can pass the first while the second is wrong for a compensating
    // reason.
    //
    // The tree walk below is deliberately this test's OWN, not `tier1`'s. A
    // measurement of `facts` taken through `tier1::evaluate_node` cannot tell a
    // fact-resolution bug from a node-walk bug, and would go green on a pair of
    // errors that cancel.

    /// What one artifact's tree came out as, and which fact ids it named on the
    /// way. `None` for a tree this test cannot evaluate — one reading the effect
    /// classifier, which is another slice's answer, not `facts`'.
    struct Walked {
        value: Kleene,
        noted: Vec<String>,
    }

    fn walk(
        node: &crate::generated::types::T1Node,
        facts: &FactSet,
        event: &serde_json::Value,
        now_ms: i64,
        noted: &mut Vec<String>,
    ) -> Option<Kleene> {
        match node.op.as_deref() {
            // Children are ALL evaluated before the fold, never short-circuited:
            // that is what keeps a later ⊥ in `noted`.
            Some("and") | Some("or") => {
                let mut children = Vec::with_capacity(node.children.len());
                for child in &node.children {
                    children.push(walk(child, facts, event, now_ms, noted)?);
                }
                Some(if node.op.as_deref() == Some("and") {
                    Kleene::all(&children)
                } else {
                    Kleene::any(&children)
                })
            }
            Some("not") => {
                let child = node.children.first()?;
                Some(!walk(child, facts, event, now_ms, noted)?)
            }
            Some("leaf") => walk_leaf(node.leaf.as_ref()?, facts, event, now_ms, noted),
            _ => None,
        }
    }

    fn walk_leaf(
        leaf: &crate::generated::types::T1Leaf,
        facts: &FactSet,
        event: &serde_json::Value,
        now_ms: i64,
        noted: &mut Vec<String>,
    ) -> Option<Kleene> {
        let pred = leaf.pred.as_deref().unwrap_or_default();
        // `pred: fact` — the fact is the subject.
        if pred == "fact" {
            let spec = leaf.fact.as_ref()?;
            let fact_id = spec.fact_id.as_ref().map(|id| id.0.as_str()).unwrap_or("");
            let value = resolve_leaf(
                facts,
                fact_id,
                spec.op.as_deref().unwrap_or(""),
                spec.value.as_ref(),
                now_ms,
            );
            note(noted, fact_id, value.reason());
            return Some(value);
        }
        let field = leaf.field.as_deref().unwrap_or_default();
        // `fact.<id>[.path]` — the fact supplies the value.
        if let Some((fact_id, _)) = split_field(field) {
            return Some(match field_values(facts, field, now_ms) {
                Ok(values) => {
                    if pred == "exists" {
                        Kleene::from_bool(!values.is_empty())
                    } else {
                        Kleene::from_bool(values.iter().any(|v| Some(*v) == leaf.value.as_ref()))
                    }
                }
                Err(reason) => {
                    note(noted, fact_id, Some(reason));
                    Kleene::Unknown(reason)
                }
            });
        }
        // The one non-fact field the 04 fixtures use, to make a sibling TRUE or
        // FALSE. Anything else — an effect tuple, an effect attribute — belongs
        // to the classifier and this test declines to guess it.
        if field == "tool.name" && pred == "equals" {
            return Some(Kleene::from_bool(
                event.get("tool_name") == leaf.value.as_ref(),
            ));
        }
        None
    }

    /// Record a ⊥ that NAMES a fact. An open-world miss is ⊥ and is deliberately
    /// not recorded — the rule `Inconclusive::names_a_fact` carries.
    fn note(noted: &mut Vec<String>, fact_id: &str, reason: Option<Inconclusive>) {
        if reason.is_some_and(|reason| reason.names_a_fact())
            && !noted.iter().any(|seen| seen == fact_id)
        {
            noted.push(fact_id.to_string());
        }
    }

    /// The verdict an artifact contributes when its tree came out ⊥. Monitor is
    /// ALWAYS `allow_and_flag`, whatever the artifact declares.
    fn on_inconclusive_verdict(artifact: &serde_json::Value) -> &'static str {
        let declared = if artifact["mode"].as_str() == Some("monitor") {
            "allow_and_flag"
        } else {
            artifact["on_inconclusive"]
                .as_str()
                .unwrap_or("allow_and_flag")
        };
        match declared {
            "ask" => "ask",
            "block" => "block",
            _ => "allow",
        }
    }

    /// Every row of `04-facts-kleene.jsonl`, with its bundle and its expectation.
    fn corpus_rows() -> Vec<(
        String,
        serde_json::Value,
        super::super::bundle::Bundle,
        serde_json::Value,
    )> {
        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("schemas/conformance");
        let text = std::fs::read_to_string(dir.join("04-facts-kleene.jsonl"))
            .expect("the corpus file is readable");
        let mut rows = Vec::new();
        for line in text.lines().filter(|line| !line.trim().is_empty()) {
            let row: serde_json::Value =
                serde_json::from_str(line).expect("every corpus row is valid JSON");
            let bundle_ref = row["bundle_ref"]
                .as_str()
                .expect("every row names a bundle");
            let raw: 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(raw.clone()).expect("the fixture bundle loads");
            let id = row["id"].as_str().unwrap_or_default().to_string();
            rows.push((id, row, bundle, raw));
        }
        assert_eq!(rows.len(), 46, "the corpus was found and read in full");
        rows
    }

    /// Walk every Tier 1 artifact of one row, in bundle order.
    fn walk_row(
        row: &serde_json::Value,
        bundle: &super::super::bundle::Bundle,
    ) -> Option<Vec<Walked>> {
        let now_ms = row["now_ms"].as_i64().expect("every row carries now_ms");
        let facts = resolve(bundle, now_ms);
        let mut out = Vec::new();
        for artifact in &bundle.artifacts {
            let super::super::bundle::ArtifactBody::T1(body) = &artifact.body else {
                return None; // not a predicate tree; not this slice's row
            };
            let node = body.node.as_ref()?;
            let mut noted = Vec::new();
            let value = walk(node, &facts, &row["event"], now_ms, &mut noted)?;
            out.push(Walked { value, noted });
        }
        Some(out)
    }

    /// `inconclusive_facts[]` is the union, over artifacts whose tree came out ⊥,
    /// of the fact ids that tree could not read — sorted and deduplicated.
    ///
    /// It is the sharpest thing the corpus says about this slice, because it is
    /// where three separate rules land at once: absent and stale name the fact,
    /// an open-world miss does NOT, and an artifact whose tree came out a decided
    /// FALSE reports nothing at all even though a ⊥ was evaluated inside it
    /// (`inconclusive-only-from-a-tree-that-was-bottom`).
    #[test]
    fn the_corpus_pins_which_facts_reach_inconclusive_facts() {
        let mut checked = 0usize;
        let mut disagreements: Vec<String> = Vec::new();

        for (id, row, bundle, _raw) in corpus_rows() {
            let Some(walked) = walk_row(&row, &bundle) else {
                continue; // a classifier-dependent row; not this slice's to answer
            };
            let mut got: Vec<String> = walked
                .iter()
                .filter(|artifact| !artifact.value.is_known())
                .flat_map(|artifact| artifact.noted.clone())
                .collect();
            got.sort();
            got.dedup();

            let expected: Vec<String> = row["expected"]["decision"]["inconclusive_facts"]
                .as_array()
                .expect("every row carries inconclusive_facts")
                .iter()
                .map(|value| value.as_str().unwrap_or_default().to_string())
                .collect();

            checked += 1;
            if got != expected {
                disagreements.push(format!("{id}: expected {expected:?}, got {got:?}"));
            }
        }

        // Exact, so a row that silently stops being walkable shrinks the
        // measurement loudly rather than in silence: 46 rows less the four whose
        // trees read the effect classifier (three `sa3-*`, and
        // `t1-unreadable-fact-op-is-skipped-at-load`, whose surviving artifact
        // is an effect leaf).
        assert_eq!(checked, 42, "every walkable corpus row was read");
        assert!(
            disagreements.is_empty(),
            "{} of {checked} corpus rows disagree with fact resolution — the \
             corpus is oracle-authored, so the engine is wrong until the spec \
             says the row was:\n  {}",
            disagreements.len(),
            disagreements.join("\n  ")
        );
    }

    /// The same 46 rows, read back as the TRUTH VALUE each one's verdict implies.
    ///
    /// The probe bundles carry one artifact with a declared verdict `V` and an
    /// `on_inconclusive` `O`, so the decision names which branch the tree took:
    /// `undecided` is a decided FALSE (nothing fired), `V` is TRUE, and `O`'s
    /// verdict is ⊥. Where `V` and `O` coincide the two are told apart by
    /// `inconclusive_facts[]`, and a row where they coincide AND that list is
    /// empty would be genuinely unreadable — the assertion below records that no
    /// such row exists rather than silently skipping one that appears later.
    #[test]
    fn the_corpus_pins_every_fact_leaf_as_a_truth_value() {
        let mut checked = 0usize;
        let mut skipped: Vec<String> = Vec::new();
        let mut disagreements: Vec<String> = Vec::new();

        for (id, row, bundle, raw) in corpus_rows() {
            let Some(walked) = walk_row(&row, &bundle) else {
                skipped.push(id);
                continue;
            };
            // One artifact, so "the tree" is unambiguous. Multi-artifact rows
            // pin the join's scoping, which the test above covers.
            let envelopes = raw["artifacts"].as_array().cloned().unwrap_or_default();
            let ([single], [artifact]) = (&walked[..], &envelopes[..]) else {
                skipped.push(id);
                continue;
            };

            let decision = &row["expected"]["decision"];
            let verdict = decision["verdict"].as_str().unwrap_or_default();
            let declared = artifact["body"]["verdict"].as_str().unwrap_or_default();
            let on_inconclusive = on_inconclusive_verdict(artifact);
            let named_a_fact = !decision["inconclusive_facts"]
                .as_array()
                .map(|list| list.is_empty())
                .unwrap_or(true);

            // Two DIFFERENT readings of the probe-bundle contract that happen to
            // agree on an answer, not one rule written twice. Merging them into
            // `A || B` would tell a future reader there is one rule where there
            // are two, and the day one of them has to change the other would
            // change silently with it. Verified before silencing: reading 2 fires
            // for exactly one row (`on-inconclusive-block`, where `V` and `O` are
            // both `block`), and only where reading 1 structurally cannot.
            #[allow(clippy::if_same_then_else)]
            let expected = if decision["undecided"].as_bool() == Some(true) {
                Kleene::False
            } else if verdict == declared && verdict != on_inconclusive {
                Kleene::True
            } else if verdict == on_inconclusive && verdict != declared {
                // Reading 1: the decision carries the `on_inconclusive` verdict
                // and that is not the artifact's own, so the tree was ⊥.
                Kleene::UNKNOWN
            } else if verdict == on_inconclusive && named_a_fact {
                // Reading 2: `V` and `O` coincide, so the verdict alone cannot
                // separate TRUE from ⊥ — `inconclusive_facts[]` does. The
                // `verdict == on_inconclusive` guard is deliberate: a row naming
                // a fact whose verdict is NOT the on-inconclusive one is
                // self-contradictory, and belongs in the panic below rather than
                // being read as ⊥.
                Kleene::UNKNOWN
            } else {
                panic!(
                    "{id}: verdict {verdict:?} is both the artifact's own and its \
                     on_inconclusive, and it names no fact — the row cannot be \
                     read as a truth value and this decoder must grow a rule"
                );
            };

            checked += 1;
            let agrees = match (expected, single.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 {:?}",
                    single.value
                ));
            }
        }

        // The same four, plus `inconclusive-only-from-a-tree-that-was-bottom`,
        // whose two artifacts make "the tree" ambiguous — that row pins the
        // per-artifact scoping of `inconclusive_facts[]`, and the test above
        // covers it in full.
        assert_eq!(checked, 41, "every single-artifact corpus row was read");
        assert_eq!(
            skipped.len(),
            5,
            "and every skipped row was skipped for a named reason"
        );
        assert!(
            disagreements.is_empty(),
            "{} of {checked} corpus leaves disagree with fact resolution (skipped \
             {}, which read the effect classifier):\n  {}",
            disagreements.len(),
            skipped.len(),
            disagreements.join("\n  ")
        );
    }

    // ── D12, as a test rather than a comment ─────────────────────────

    #[test]
    fn no_unresolvable_fact_ever_yields_a_decided_value() {
        // Every way a fact can fail to resolve, crossed with every op a leaf can
        // carry. Not one cell may come back True or False: that would be a
        // fact-level default, and D12 says there is no such thing here.
        let mut unknown_kind = fresh_ticket();
        unknown_kind["kind"] = json!("graph");
        let mut bad_stamp = fresh_ticket();
        bad_stamp["observed_at"] = json!("not-a-date");
        let mut aged_out = fresh_ticket();
        aged_out["observed_at"] = json!("2025-09-01T14:53:20+00:00");
        aged_out["max_age_s"] = json!(3600);
        let mut too_early = fresh_ticket();
        too_early["valid_from"] = json!("2025-09-02T16:00:00+00:00");
        let mut too_late = fresh_ticket();
        too_late["valid_until"] = json!("2025-08-31T16:00:00+00:00");

        let unresolvable = [
            ("never declared", FactSet::new(vec![], NOW)),
            ("unknown kind", one(unknown_kind)),
            ("unparseable observed_at", one(bad_stamp)),
            ("aged out", one(aged_out)),
            ("before valid_from", one(too_early)),
            ("after valid_until", one(too_late)),
            (
                "a ref nobody inlined",
                resolve(&bundle_with(json!({"fact_refs": a_ref()})), NOW),
            ),
        ];
        let literals = [
            json!(true),
            json!(false),
            json!(null),
            json!({"op": "ge", "n": 0}),
            json!(["anything"]),
        ];

        for (cause, facts) in &unresolvable {
            for op in KNOWN_FACT_OPS {
                for literal in &literals {
                    let answer = resolve_leaf(facts, "change_ticket", op, Some(literal), NOW);
                    assert!(
                        !answer.is_known(),
                        "{cause}: `{op}` against {literal} decided {answer:?} — a \
                         fact-level default is not expressible in this engine"
                    );
                    let reason = answer.reason().expect("⊥ carries a reason");
                    assert!(
                        reason.names_a_fact(),
                        "{cause}: an UNREADABLE fact must name itself in \
                         inconclusive_facts[], and {reason:?} does not"
                    );
                }
                // The same, through the leaf that carries no literal at all.
                assert!(!resolve_leaf(facts, "change_ticket", op, None, NOW).is_known());
            }
            assert!(
                field_values(facts, "fact.change_ticket.approved", NOW).is_err(),
                "{cause}: the field route has no default either"
            );
            assert!(
                !membership(facts, "change_ticket", &json!("anything"), NOW).is_known(),
                "{cause}: membership has no default either"
            );
            assert!(facts.present("change_ticket").is_none(), "{cause}");
        }
    }

    /// The source-level half of the same claim: this module writes no fallback.
    #[test]
    fn this_module_expresses_no_truth_value_fallback() {
        // The SHIPPED half only: everything from `#[cfg(test)]` on is this
        // module's own tests, and the forbidden strings are spelled out below.
        let source = include_str!("facts.rs");
        let shipped = source
            .split_once("#[cfg(test)]")
            .map_or(source, |(before, _)| before);
        let code: String = shipped
            .lines()
            .filter(|line| !line.trim_start().starts_with("//"))
            .collect::<Vec<_>>()
            .join("\n");
        for forbidden in [
            "unwrap_or(false)",
            "unwrap_or(true)",
            "unwrap_or(Kleene",
            "unwrap_or_else(|| Kleene",
            "unwrap_or_default()",
            "Kleene::from_bool(fact.closed_world",
        ] {
            assert!(
                !code.contains(forbidden),
                "`{forbidden}` is a fact-level default; the resolution order has \
                 no branch that produces one"
            );
        }
    }
}