lemma-engine 0.8.13

A language that means business.
Documentation
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
//! Integration tests for temporal slicing of execution plans.
//!
//! When a spec's active range spans dependency spec boundaries,
//! planning must produce one ExecutionPlan per temporal slice and each
//! slice must independently validate.
//!
//! These tests define the target behavior. Many will fail until the
//! temporal slicing implementation is complete.

use lemma::{DateTimeValue, Engine};
use std::collections::HashMap;

fn date(year: i32, month: u32, day: u32) -> DateTimeValue {
    DateTimeValue {
        year,
        month,
        day,
        hour: 0,
        minute: 0,
        second: 0,
        microsecond: 0,
        timezone: None,
    }
}

fn eval(engine: &Engine, spec_name: &str, effective: &DateTimeValue) -> lemma::Response {
    engine
        .run(None, spec_name, Some(effective), HashMap::new(), false)
        .unwrap()
}

fn eval_with(
    engine: &Engine,
    spec_name: &str,
    effective: &DateTimeValue,
    data: Vec<(&str, &str)>,
) -> lemma::Response {
    let map: HashMap<String, String> = data
        .into_iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
    engine
        .run(None, spec_name, Some(effective), map, false)
        .unwrap()
}

fn assert_rule_value(response: &lemma::Response, rule: &str, expected: &str) {
    let result = response
        .results
        .get(rule)
        .unwrap_or_else(|| panic!("rule '{}' not in results", rule));
    let val = result
        .result
        .value()
        .unwrap_or_else(|| panic!("rule '{}' is Veto, expected Value", rule));
    assert_eq!(
        val.to_string(),
        expected,
        "rule '{}': expected {}, got {}",
        rule,
        expected,
        val
    );
}

// ============================================================================
// 1. SINGLE DEPENDENCY — NO VERSIONING
// ============================================================================

#[test]
fn single_unversioned_dependency() {
    let mut engine = Engine::new();

    engine
        .load(
            "spec config\ndata base_rate: 100",
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "config.lemma",
            ))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec pricing 2025-01-01
uses cfg: config
rule rate: cfg.base_rate * 2
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "pricing.lemma",
            ))),
        )
        .unwrap();

    for d in [date(2025, 1, 15), date(2025, 7, 1), date(2025, 12, 15)] {
        assert_rule_value(&eval(&engine, "pricing", &d), "rate", "200");
    }
}

// ============================================================================
// 2. SINGLE DEPENDENCY — ONE VERSION BOUNDARY
// ============================================================================

#[test]
fn one_boundary_produces_two_slices() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec config
data base_rate: 100

spec config 2025-04-01
data base_rate: 200
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "config.lemma",
            ))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec pricing 2025-01-01
uses cfg: config
rule rate: cfg.base_rate
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "pricing.lemma",
            ))),
        )
        .unwrap();

    assert_rule_value(&eval(&engine, "pricing", &date(2025, 2, 1)), "rate", "100");
    assert_rule_value(&eval(&engine, "pricing", &date(2025, 3, 31)), "rate", "100");
    assert_rule_value(&eval(&engine, "pricing", &date(2025, 4, 1)), "rate", "200");
    assert_rule_value(&eval(&engine, "pricing", &date(2025, 6, 15)), "rate", "200");
}

#[test]
fn boundary_exactly_at_spec_effective_from_no_split() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec config
data rate: 50

spec config 2025-01-01
data rate: 75
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "config.lemma",
            ))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec pricing 2025-01-01
uses cfg: config
rule rate: cfg.rate
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "pricing.lemma",
            ))),
        )
        .unwrap();

    assert_rule_value(&eval(&engine, "pricing", &date(2025, 1, 1)), "rate", "75");
    assert_rule_value(&eval(&engine, "pricing", &date(2025, 5, 1)), "rate", "75");
}

// ============================================================================
// 3. SINGLE DEPENDENCY — MULTIPLE VERSION BOUNDARIES
// ============================================================================

#[test]
fn three_versions_produce_three_slices() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec rates
data rate: 10

spec rates 2025-03-01
data rate: 20

spec rates 2025-07-01
data rate: 30
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("rates.lemma"))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec pricing 2025-01-01
uses r: rates
data quantity: number
rule total: quantity * r.rate
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "pricing.lemma",
            ))),
        )
        .unwrap();

    let cases = [
        (date(2025, 2, 1), "100"), // v1: 10*10
        (date(2025, 5, 1), "200"), // v2: 10*20
        (date(2025, 9, 1), "300"), // v3: 10*30
    ];
    for (d, expected) in &cases {
        assert_rule_value(
            &eval_with(&engine, "pricing", d, vec![("quantity", "10")]),
            "total",
            expected,
        );
    }
}

#[test]
fn four_versions_only_two_boundaries_inside_range() {
    let mut engine = Engine::new();

    // v1: [-∞, Mar), v2: [Mar, Jun), v3: [Jun, Sep), v4: [Sep, +∞)
    engine
        .load(
            r#"
spec rates
data rate: 10

spec rates 2025-03-01
data rate: 20

spec rates 2025-06-01
data rate: 30

spec rates 2025-09-01
data rate: 40
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("rates.lemma"))),
        )
        .unwrap();

    // pricing active [Apr, +∞) → Jun and Sep boundaries are inside
    engine
        .load(
            r#"
spec pricing 2025-04-01
uses r: rates
rule rate: r.rate
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "pricing.lemma",
            ))),
        )
        .unwrap();

    assert_rule_value(&eval(&engine, "pricing", &date(2025, 4, 15)), "rate", "20");
    assert_rule_value(&eval(&engine, "pricing", &date(2025, 5, 31)), "rate", "20");
    assert_rule_value(&eval(&engine, "pricing", &date(2025, 6, 1)), "rate", "30");
    assert_rule_value(&eval(&engine, "pricing", &date(2025, 7, 15)), "rate", "30");
}

// ============================================================================
// 4. MULTIPLE DEPENDENCIES — INDEPENDENT BOUNDARIES
// ============================================================================

#[test]
fn two_deps_boundaries_at_different_times() {
    let mut engine = Engine::new();

    // tax_rates: boundary at April
    engine
        .load(
            r#"
spec tax_rates
data vat: 19

spec tax_rates 2025-04-01
data vat: 21
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "tax_rates.lemma",
            ))),
        )
        .unwrap();

    // shipping_rates: boundary at July
    engine
        .load(
            r#"
spec shipping_rates
data fee: 5

spec shipping_rates 2025-07-01
data fee: 8
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "shipping_rates.lemma",
            ))),
        )
        .unwrap();

    // invoice: depends on both → boundaries at {April, July} → three slices
    engine
        .load(
            r#"
spec invoice 2025-01-01
uses tax: tax_rates
uses shipping: shipping_rates
data price: number
rule vat_amount: price * tax.vat / 100
rule shipping_fee: shipping.fee
rule total: price + vat_amount + shipping_fee
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "invoice.lemma",
            ))),
        )
        .unwrap();

    // Slice 1: [Jan, Apr) — vat=19, fee=5
    let r = eval_with(
        &engine,
        "invoice",
        &date(2025, 2, 1),
        vec![("price", "100")],
    );
    assert_rule_value(&r, "vat_amount", "19");
    assert_rule_value(&r, "shipping_fee", "5");
    assert_rule_value(&r, "total", "124");

    // Slice 2: [Apr, Jul) — vat=21, fee=5
    let r = eval_with(
        &engine,
        "invoice",
        &date(2025, 5, 1),
        vec![("price", "100")],
    );
    assert_rule_value(&r, "vat_amount", "21");
    assert_rule_value(&r, "shipping_fee", "5");
    assert_rule_value(&r, "total", "126");

    // Slice 3: [Jul, +∞) — vat=21, fee=8
    let r = eval_with(
        &engine,
        "invoice",
        &date(2025, 9, 1),
        vec![("price", "100")],
    );
    assert_rule_value(&r, "vat_amount", "21");
    assert_rule_value(&r, "shipping_fee", "8");
    assert_rule_value(&r, "total", "129");
}

#[test]
fn two_deps_boundaries_at_same_time() {
    let mut engine = Engine::new();

    // Both deps change on April 1
    engine
        .load(
            r#"
spec tax_rates
data vat: 19

spec tax_rates 2025-04-01
data vat: 21
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "tax_rates.lemma",
            ))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec shipping_rates
data fee: 5

spec shipping_rates 2025-04-01
data fee: 8
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "shipping_rates.lemma",
            ))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec invoice 2025-01-01
uses tax: tax_rates
uses shipping: shipping_rates
rule combined: tax.vat + shipping.fee
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "invoice.lemma",
            ))),
        )
        .unwrap();

    // Coincident boundary → two slices, not three
    assert_rule_value(
        &eval(&engine, "invoice", &date(2025, 2, 1)),
        "combined",
        "24",
    );
    assert_rule_value(
        &eval(&engine, "invoice", &date(2025, 6, 1)),
        "combined",
        "29",
    );
}

#[test]
fn one_dep_versioned_one_dep_unversioned() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec constants
data pi: 3
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "constants.lemma",
            ))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec rates
data multiplier: 2

spec rates 2025-06-01
data multiplier: 4
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("rates.lemma"))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec calc 2025-01-01
uses c: constants
uses r: rates
rule result: c.pi * r.multiplier
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("calc.lemma"))),
        )
        .unwrap();

    assert_rule_value(&eval(&engine, "calc", &date(2025, 3, 1)), "result", "6");
    assert_rule_value(&eval(&engine, "calc", &date(2025, 9, 1)), "result", "12");
}

// ============================================================================
// 5. TRANSITIVE DEPENDENCIES
// ============================================================================

#[test]
fn transitive_two_levels_deep() {
    let mut engine = Engine::new();

    // SpecC: two specs
    engine
        .load(
            r#"
spec base_rates
data multiplier: 2

spec base_rates 2025-06-01
data multiplier: 3
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "base_rates.lemma",
            ))),
        )
        .unwrap();

    // SpecB: unversioned, depends on SpecC
    engine
        .load(
            r#"
spec intermediate
uses base: base_rates
data value: 10
rule adjusted: value * base.multiplier
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "intermediate.lemma",
            ))),
        )
        .unwrap();

    // SpecA: depends on SpecB → transitively on SpecC
    engine
        .load(
            r#"
spec top 2025-01-01
uses mid: intermediate
rule result: mid.adjusted
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("top.lemma"))),
        )
        .unwrap();

    assert_rule_value(&eval(&engine, "top", &date(2025, 3, 1)), "result", "20");
    assert_rule_value(&eval(&engine, "top", &date(2025, 9, 1)), "result", "30");
}

#[test]
fn transitive_both_levels_versioned() {
    let mut engine = Engine::new();

    // SpecC: boundary at June
    engine
        .load(
            r#"
spec deep
data factor: 2

spec deep 2025-06-01
data factor: 5
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("deep.lemma"))),
        )
        .unwrap();

    // SpecB: boundary at April, depends on SpecC
    engine
        .load(
            r#"
spec middle
uses d: deep
data base: 10
rule value: base * d.factor

spec middle 2025-04-01
uses d: deep
data base: 100
rule value: base * d.factor
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "middle.lemma",
            ))),
        )
        .unwrap();

    // SpecA: active from Jan → boundaries at {April, June} → three slices
    engine
        .load(
            r#"
spec top 2025-01-01
uses m: middle
rule result: m.value
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("top.lemma"))),
        )
        .unwrap();

    // [Jan, Apr): middle v1 (base=10) * deep v1 (factor=2) = 20
    assert_rule_value(&eval(&engine, "top", &date(2025, 2, 1)), "result", "20");
    // [Apr, Jun): middle v2 (base=100) * deep v1 (factor=2) = 200
    assert_rule_value(&eval(&engine, "top", &date(2025, 5, 1)), "result", "200");
    // [Jun, +∞): middle v2 (base=100) * deep v2 (factor=5) = 500
    assert_rule_value(&eval(&engine, "top", &date(2025, 9, 1)), "result", "500");
}

#[test]
fn diamond_dependency_single_boundary() {
    let mut engine = Engine::new();

    // Shared dep at the bottom
    engine
        .load(
            r#"
spec shared
data value: 10

spec shared 2025-06-01
data value: 20
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "shared.lemma",
            ))),
        )
        .unwrap();

    // Two intermediate specs both depend on shared
    engine
        .load(
            r#"
spec left_branch
uses s: shared
rule doubled: s.value * 2
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("left.lemma"))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec right_branch
uses s: shared
rule tripled: s.value * 3
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("right.lemma"))),
        )
        .unwrap();

    // Top depends on both branches (diamond through shared)
    engine
        .load(
            r#"
spec top 2025-01-01
uses l: left_branch
uses r: right_branch
rule total: l.doubled + r.tripled
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("top.lemma"))),
        )
        .unwrap();

    // Before June: 10*2 + 10*3 = 50
    assert_rule_value(&eval(&engine, "top", &date(2025, 3, 1)), "total", "50");
    // After June: 20*2 + 20*3 = 100
    assert_rule_value(&eval(&engine, "top", &date(2025, 9, 1)), "total", "100");
}

#[test]
fn diamond_dependency_boundaries_at_different_levels() {
    let mut engine = Engine::new();

    // Shared base: boundary at August
    engine
        .load(
            r#"
spec shared
data base: 10

spec shared 2025-08-01
data base: 50
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "shared.lemma",
            ))),
        )
        .unwrap();

    // Left branch: boundary at April
    engine
        .load(
            r#"
spec left
uses s: shared
data add: 1
rule result: s.base + add

spec left 2025-04-01
uses s: shared
data add: 2
rule result: s.base + add
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("left.lemma"))),
        )
        .unwrap();

    // Right branch: unversioned
    engine
        .load(
            r#"
spec right
uses s: shared
rule result: s.base * 2
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("right.lemma"))),
        )
        .unwrap();

    // Top: active from Jan → boundaries at {April, August} → three slices
    engine
        .load(
            r#"
spec top 2025-01-01
uses l: left
uses r: right
rule total: l.result + r.result
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("top.lemma"))),
        )
        .unwrap();

    // [Jan, Apr): left v1 (10+1=11) + right (10*2=20) = 31
    assert_rule_value(&eval(&engine, "top", &date(2025, 2, 1)), "total", "31");
    // [Apr, Aug): left v2 (10+2=12) + right (10*2=20) = 32
    assert_rule_value(&eval(&engine, "top", &date(2025, 5, 1)), "total", "32");
    // [Aug, +∞): left v2 (50+2=52) + right (50*2=100) = 152
    assert_rule_value(&eval(&engine, "top", &date(2025, 9, 1)), "total", "152");
}

// ============================================================================
// 6. UNRANGED DOC (−∞ to +∞) WITH VERSIONED DEPENDENCY
// ============================================================================

#[test]
fn unranged_spec_sliced_by_versioned_dep() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec rates
data tax: 19

spec rates 2026-01-01
data tax: 21
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("rates.lemma"))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec calculator
uses r: rates
data income: number
rule tax_amount: income * r.tax / 100
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "calculator.lemma",
            ))),
        )
        .unwrap();

    assert_rule_value(
        &eval_with(
            &engine,
            "calculator",
            &date(2025, 6, 1),
            vec![("income", "1000")],
        ),
        "tax_amount",
        "190",
    );
    assert_rule_value(
        &eval_with(
            &engine,
            "calculator",
            &date(2026, 6, 1),
            vec![("income", "1000")],
        ),
        "tax_amount",
        "210",
    );
}

// ============================================================================
// 7. DEPENDENCY COVERAGE GAPS — PLANNING ERRORS
// ============================================================================

#[test]
fn three_versions_seamlessly_chained() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec policy 2025-01-01
data limit: 1000

spec policy 2025-04-01
data limit: 2000

spec policy 2025-08-01
data limit: 3000
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "policy.lemma",
            ))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec contract 2025-01-01
uses p: policy
data amount: number
rule under_limit: amount < p.limit
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "contract.lemma",
            ))),
        )
        .unwrap();

    // 1500 < 1000 = false, 1500 < 2000 = true, 1500 < 3000 = true
    assert_rule_value(
        &eval_with(
            &engine,
            "contract",
            &date(2025, 2, 1),
            vec![("amount", "1500")],
        ),
        "under_limit",
        "false",
    );
    assert_rule_value(
        &eval_with(
            &engine,
            "contract",
            &date(2025, 5, 1),
            vec![("amount", "1500")],
        ),
        "under_limit",
        "true",
    );
    assert_rule_value(
        &eval_with(
            &engine,
            "contract",
            &date(2025, 9, 1),
            vec![("amount", "1500")],
        ),
        "under_limit",
        "true",
    );
}

// ============================================================================
// 9. SAME DOC EVALUATED AT DIFFERENT TIMES — CORRECT SLICE SELECTED
// ============================================================================

#[test]
fn evaluate_at_boundary_instant_uses_new_version() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec dep
data val: 1

spec dep 2025-06-01
data val: 2
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("dep.lemma"))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec main
uses d: dep
rule result: d.val
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("main.lemma"))),
        )
        .unwrap();

    // Exactly at the boundary: effective_from is inclusive
    assert_rule_value(&eval(&engine, "main", &date(2025, 5, 31)), "result", "1");
    assert_rule_value(&eval(&engine, "main", &date(2025, 6, 1)), "result", "2");
}

// ============================================================================
// 10. DEPENDENT SPEC (SpecC) REFERENCES VERSIONED SPEC (SpecB)
// ============================================================================

#[test]
fn third_level_spec_depends_on_versioned_spec() {
    let mut engine = Engine::new();

    // SpecB: versioned
    engine
        .load(
            r#"
spec rates
data base: 100

spec rates 2025-05-01
data base: 200
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("rates.lemma"))),
        )
        .unwrap();

    // SpecA: unversioned, depends on SpecB
    engine
        .load(
            r#"
spec policy
uses r: rates
rule threshold: r.base * 2
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "policy.lemma",
            ))),
        )
        .unwrap();

    // SpecC: depends on SpecA (which transitively depends on SpecB)
    engine
        .load(
            r#"
spec contract 2025-01-01
uses p: policy
data amount: number
rule is_over_threshold: amount > p.threshold
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "contract.lemma",
            ))),
        )
        .unwrap();

    // Before May: threshold = 100*2 = 200. amount=250 > 200 → true
    assert_rule_value(
        &eval_with(
            &engine,
            "contract",
            &date(2025, 3, 1),
            vec![("amount", "250")],
        ),
        "is_over_threshold",
        "true",
    );
    // After May: threshold = 200*2 = 400. amount=250 > 400 → false
    assert_rule_value(
        &eval_with(
            &engine,
            "contract",
            &date(2025, 9, 1),
            vec![("amount", "250")],
        ),
        "is_over_threshold",
        "false",
    );
}

// ============================================================================
// 11. COMPLEX SCENARIO — REALISTIC MULTI-DOC WITH MULTIPLE BOUNDARIES
// ============================================================================

#[test]
fn realistic_tax_and_labor_law_scenario() {
    let mut engine = Engine::new();

    // Tax rates: change April 1
    engine
        .load(
            r#"
spec tax_law
data income_tax_rate: 30

spec tax_law 2025-04-01
data income_tax_rate: 32
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("tax.lemma"))),
        )
        .unwrap();

    // Labor law: change July 1
    engine
        .load(
            r#"
spec labor_law
data min_wage_hourly: 12
data max_weekly_hours: 40

spec labor_law 2025-07-01
data min_wage_hourly: 15
data max_weekly_hours: 38
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("labor.lemma"))),
        )
        .unwrap();

    // Employment contract: depends on both, active from Jan
    engine
        .load(
            r#"
spec employment 2025-01-01
uses tax: tax_law
uses labor: labor_law
data hourly_rate: number
data weekly_hours: number

rule annual_gross: hourly_rate * weekly_hours * 52
rule annual_tax: annual_gross * tax.income_tax_rate / 100
rule annual_net: annual_gross - annual_tax
rule min_annual_gross: labor.min_wage_hourly * labor.max_weekly_hours * 52
rule meets_minimum: annual_gross >= min_annual_gross
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "employment.lemma",
            ))),
        )
        .unwrap();

    let data = vec![("hourly_rate", "20"), ("weekly_hours", "40")];

    // Slice [Jan, Apr): tax=30%, labor v1 (min=12, max_h=40)
    let r = eval_with(&engine, "employment", &date(2025, 2, 1), data.clone());
    assert_rule_value(&r, "annual_gross", "41600");
    assert_rule_value(&r, "annual_tax", "12480");
    assert_rule_value(&r, "annual_net", "29120");
    assert_rule_value(&r, "min_annual_gross", "24960");
    assert_rule_value(&r, "meets_minimum", "true");

    // Slice [Apr, Jul): tax=32%, labor v1 (min=12, max_h=40)
    let r = eval_with(&engine, "employment", &date(2025, 5, 1), data.clone());
    assert_rule_value(&r, "annual_tax", "13312");
    assert_rule_value(&r, "annual_net", "28288");
    assert_rule_value(&r, "min_annual_gross", "24960");

    // Slice [Jul, +∞): tax=32%, labor v2 (min=15, max_h=38)
    let r = eval_with(&engine, "employment", &date(2025, 9, 1), data.clone());
    assert_rule_value(&r, "annual_tax", "13312");
    assert_rule_value(&r, "min_annual_gross", "29640");
    assert_rule_value(&r, "meets_minimum", "true");
}

// ============================================================================
// 12. SELF-VERSIONED DOC REFERENCING VERSIONED DEP
// ============================================================================

#[test]
fn both_spec_and_dep_are_versioned() {
    let mut engine = Engine::new();

    // dep: boundary at June
    engine
        .load(
            r#"
spec dep
data val: 10

spec dep 2025-06-01
data val: 20
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("dep.lemma"))),
        )
        .unwrap();

    // main v1: [Jan, Apr), main v2: [Apr, +∞)
    // main v1's range [Jan, Apr) has no dep boundary → single slice for v1
    // main v2's range [Apr, +∞) has dep boundary at June → two slices for v2
    engine
        .load(
            r#"
spec main 2025-01-01
uses d: dep
data multiplier: 2
rule result: d.val * multiplier

spec main 2025-04-01
uses d: dep
data multiplier: 3
rule result: d.val * multiplier
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("main.lemma"))),
        )
        .unwrap();

    // main v1 [Jan, Apr): dep v1 (10) * 2 = 20
    assert_rule_value(&eval(&engine, "main", &date(2025, 2, 1)), "result", "20");
    // main v2 [Apr, Jun): dep v1 (10) * 3 = 30
    assert_rule_value(&eval(&engine, "main", &date(2025, 5, 1)), "result", "30");
    // main v2 [Jun, +∞): dep v2 (20) * 3 = 60
    assert_rule_value(&eval(&engine, "main", &date(2025, 9, 1)), "result", "60");
}

// ============================================================================
// 13. INTERFACE CONSISTENCY — TEMPORAL VALIDATION
// ============================================================================
// Different specs in a dependency set CAN have different interfaces.
// Every slice must resolve to a spec that satisfies what the
// dependent spec actually references (per-slice interface validation).

#[test]
fn dep_version_removes_referenced_data_rejected() {
    let mut engine = Engine::new();

    // config v1 has base_rate. config v2 renames it to cost.
    engine
        .load(
            r#"
spec config
data base_rate: 100

spec config 2025-04-01
data cost: 200
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "config.lemma",
            ))),
        )
        .unwrap();

    // pricing references config.base_rate → v2 slice fails (no base_rate in v2)
    let result = engine.load(
        r#"
spec pricing 2025-01-01
uses cfg: config
rule rate: cfg.base_rate
"#,
        lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
            "pricing.lemma",
        ))),
    );

    assert!(
        result.is_err(),
        "Must reject: config v2 (April+) removed 'base_rate' that pricing references"
    );
    let errs = result.unwrap_err();
    assert!(
        errs.iter().any(|e| e.to_string().contains("base_rate")),
        "Error should mention missing 'base_rate'. Got: {}",
        errs.iter()
            .map(|e| e.to_string())
            .collect::<Vec<_>>()
            .join(", ")
    );
}

#[test]
fn dep_version_adds_rule_that_other_spec_doesnt_use_accepted() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec policy
data base: 100
rule discount: 10

spec policy 2025-06-01
data base: 200
rule discount: 20
rule bonus: 5
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "policy.lemma",
            ))),
        )
        .unwrap();

    // contract only references policy.discount — bonus is irrelevant
    engine
        .load(
            r#"
spec contract 2025-01-01
uses p: policy
rule applied_discount: p.discount
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "contract.lemma",
            ))),
        )
        .unwrap();

    assert_rule_value(
        &eval(&engine, "contract", &date(2025, 3, 1)),
        "applied_discount",
        "10",
    );
    assert_rule_value(
        &eval(&engine, "contract", &date(2025, 9, 1)),
        "applied_discount",
        "20",
    );
}

// ============================================================================
// SLICE INTERFACE — CATEGORY 1: COMPATIBLE INTERFACES (planning succeeds)
// ============================================================================

#[test]
fn slice_compat_dep_adds_unreferenced_data() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec settings
data limit: 10

spec settings 2025-05-01
data limit: 20
data description: "updated settings"
data extra_number: 999
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "settings.lemma",
            ))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec app 2025-01-01
uses s: settings
rule max: s.limit
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("app.lemma"))),
        )
        .unwrap();

    assert_rule_value(&eval(&engine, "app", &date(2025, 3, 1)), "max", "10");
    assert_rule_value(&eval(&engine, "app", &date(2025, 8, 1)), "max", "20");
}

#[test]
fn slice_compat_dep_adds_unreferenced_rules() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec calc
rule base_fee: 100

spec calc 2025-04-01
rule base_fee: 150
rule surcharge: 25
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("calc.lemma"))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec invoice 2025-01-01
uses c: calc
rule fee: c.base_fee
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "invoice.lemma",
            ))),
        )
        .unwrap();

    assert_rule_value(&eval(&engine, "invoice", &date(2025, 2, 1)), "fee", "100");
    assert_rule_value(&eval(&engine, "invoice", &date(2025, 6, 1)), "fee", "150");
}

/// Dep changes data interface across time (number → text). Dependent adds temporal specs
/// so each era only binds to the matching dep slice. Target: load + eval succeed; if not,
/// validation is too strict (e.g. one consumer spec checked against every dep slice).
#[test]
fn dependent_versions_track_dep_interface_change() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec dep
data x: 10

spec dep 2025-06-01
data x: "hello"

spec consumer 2025-01-01
uses d: dep
rule val: d.x

spec consumer 2025-06-01
uses d: dep
rule val: d.x
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("t.lemma"))),
        )
        .unwrap();

    assert_rule_value(&eval(&engine, "consumer", &date(2025, 3, 1)), "val", "10");
    assert_rule_value(
        &eval(&engine, "consumer", &date(2025, 9, 1)),
        "val",
        "hello",
    );
}

#[test]
fn app_temporal_versions_distinct_rules_per_dep_interface_era() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec dep
data x: 10

spec dep 2025-06-01
data x: "hello"

spec app 2025-01-01
uses d: dep
rule total: d.x + 2

spec app 2025-06-01
uses d: dep
rule greeting: d.x
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "app_dep.lemma",
            ))),
        )
        .unwrap();

    assert_rule_value(&eval(&engine, "app", &date(2025, 3, 1)), "total", "12");
    assert_rule_value(
        &eval(&engine, "app", &date(2025, 9, 1)),
        "greeting",
        "hello",
    );
}

#[test]
fn slice_compat_dep_rule_value_changes_but_type_same() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec policy
rule discount: 10

spec policy 2025-05-01
rule discount: 25
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "policy.lemma",
            ))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec shop 2025-01-01
uses p: policy
rule d: p.discount
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("shop.lemma"))),
        )
        .unwrap();

    assert_rule_value(&eval(&engine, "shop", &date(2025, 2, 1)), "d", "10");
    assert_rule_value(&eval(&engine, "shop", &date(2025, 8, 1)), "d", "25");
}

#[test]
fn slice_compat_dep_data_type_annotation_identical() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec cfg
data threshold: number

spec cfg 2025-04-01
data threshold: number
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("cfg.lemma"))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec consumer 2025-01-01
uses c: cfg
data c.threshold: 50
rule t: c.threshold
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "consumer.lemma",
            ))),
        )
        .unwrap();

    assert_rule_value(&eval(&engine, "consumer", &date(2025, 2, 1)), "t", "50");
    assert_rule_value(&eval(&engine, "consumer", &date(2025, 6, 1)), "t", "50");
}

// ============================================================================
// SLICE INTERFACE — CATEGORY 2: INCOMPATIBLE INTERFACES (planning rejects)
// ============================================================================

#[test]
fn slice_incompat_multiple_deps_one_unstable() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec stable_dep
data x: 10

spec stable_dep 2025-06-01
data x: 20
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "stable.lemma",
            ))),
        )
        .unwrap();

    engine
        .load(
            r#"
spec unstable_dep
data y: 5

spec unstable_dep 2025-06-01
data y: "five"
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "unstable.lemma",
            ))),
        )
        .unwrap();

    let result = engine.load(
        r#"
spec consumer 2025-01-01
uses a: stable_dep
uses b: unstable_dep
rule sx: a.x
rule sy: b.y
"#,
        lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
            "consumer.lemma",
        ))),
    );

    assert!(
        result.is_err(),
        "Must reject: unstable_dep.y changes from number to text"
    );
    let errs = result.unwrap_err();
    let joined = errs
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join(" | ");
    assert!(
        joined.contains("changed its interface between temporal slices"),
        "Error must come from SliceInterface validation. Got: {}",
        joined
    );
    assert!(
        joined.contains("unstable_dep"),
        "Error must identify unstable_dep as the changed dependency. Got: {}",
        joined
    );
}

// ============================================================================
// SLICE INTERFACE — CATEGORY 3: EDGE CASES & BOUNDARY CONDITIONS
// ============================================================================

#[test]
fn slice_edge_data_referenced_only_in_unless_branch() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec dep
data main_val: 10
data alt_val: 20

spec dep 2025-06-01
data main_val: "ten"
data alt_val: "twenty"
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("dep.lemma"))),
        )
        .unwrap();

    // alt_val only appears in the unless then-branch, not the default.
    // Both slices are individually valid (branches have matching types within
    // each slice), but the interface changes across slices.
    let result = engine.load(
        r#"
spec caller 2025-01-01
uses d: dep
data use_alt: boolean
rule result: d.main_val
 unless use_alt then d.alt_val
"#,
        lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
            "caller.lemma",
        ))),
    );

    assert!(
        result.is_err(),
        "Must reject: dep data change from number to text across slices"
    );
    let errs = result.unwrap_err();
    let joined = errs
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join(" | ");
    assert!(
        joined.contains("changed its interface between temporal slices"),
        "Error must come from SliceInterface validation. Got: {}",
        joined
    );
}

#[test]
fn slice_edge_data_in_both_condition_and_expression() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec amounts
data amount: 100

spec amounts 2025-05-01
data amount: 200
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "amounts.lemma",
            ))),
        )
        .unwrap();

    // amount appears in both the unless condition and the then expression
    engine
        .load(
            r#"
spec calc 2025-01-01
uses d: amounts
rule result: 0
 unless d.amount > 50 then d.amount * 2
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("calc.lemma"))),
        )
        .unwrap();

    assert_rule_value(&eval(&engine, "calc", &date(2025, 3, 1)), "result", "200");
    assert_rule_value(&eval(&engine, "calc", &date(2025, 8, 1)), "result", "400");
}

#[test]
fn slice_edge_dep_removes_referenced_rule_caught_by_per_slice() {
    let mut engine = Engine::new();

    engine
        .load(
            r#"
spec svc
rule compute: 42

spec svc 2025-06-01
rule other_compute: 99
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("svc.lemma"))),
        )
        .unwrap();

    let result = engine.load(
        r#"
spec caller 2025-01-01
uses s: svc
rule val: s.compute
"#,
        lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
            "caller.lemma",
        ))),
    );

    assert!(
        result.is_err(),
        "Must reject: svc v2 no longer has rule 'compute' that caller references"
    );
    let errs = result.unwrap_err();
    let joined = errs
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join(" | ");
    assert!(
        joined.contains("compute"),
        "Error should mention the missing rule 'compute'. Got: {}",
        joined
    );
}

// ============================================================================
// ADVERSARIAL — half-open range boundaries (ranges_overlap semantics)
// ============================================================================

/// Consumer `[2025-01-01, 2025-06-01)` must not treat dep body starting exactly at
/// consumer end as covering the consumer.
#[test]
fn adversarial_consumer_range_end_exclusive_dep_starting_at_end_not_covering() {
    let mut engine = Engine::new();
    let err = engine
        .load(
            r#"
spec consumer 2025-01-01
uses d: dep
rule x: d.v

spec dep 2025-06-01
data v: 1
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("adv.lemma"))),
        )
        .expect_err("dep must not cover consumer range ending at 2025-06-01");

    let joined = err
        .errors
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join(" ");
    assert!(
        joined.contains("consumer") && joined.contains("dep"),
        "expected coverage error; got {joined}"
    );
}

/// Consumer starts before any dep body exists (half-open coverage).
#[test]
fn adversarial_consumer_starts_before_dep_first_effective_errors() {
    let mut engine = Engine::new();
    let err = engine
        .load(
            r#"
spec consumer 2025-03-01
uses d: dep
rule x: d.v

spec dep 2025-08-01
data v: 1
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("adv2.lemma"))),
        )
        .expect_err("gap before dep exists");

    let joined = err
        .errors
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join(" ");
    assert!(joined.contains("dep"), "got {joined}");
}

// ============================================================================
// ADVERSARIAL — slice interface matrix (distinct failure shapes)
// ============================================================================

#[test]
fn slice_incompat_data_field_type_changes_number_to_text() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec dep 2025-01-01
data rate: number

spec dep 2025-07-01
data rate: text
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("dep.lemma"))),
        )
        .unwrap();

    let err = engine
        .load(
            r#"
spec app 2025-01-01
uses d: dep
rule r: d.rate
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("app.lemma"))),
        )
        .expect_err("interface change");

    let joined = err
        .errors
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join(" ");
    assert!(
        joined.contains("interface") || joined.contains("temporal") || joined.contains("dep"),
        "got {joined}"
    );
}

#[test]
fn slice_incompat_rule_result_type_changes() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec dep 2025-01-01
rule discount: 5

spec dep 2025-07-01
rule discount: true
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("dep.lemma"))),
        )
        .unwrap();

    let err = engine
        .load(
            r#"
spec app 2025-01-01
uses d: dep
rule out: d.discount
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("app.lemma"))),
        )
        .expect_err("rule type mismatch across slices");

    let joined = err
        .errors
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join(" ");
    assert!(
        joined.contains("interface") || joined.contains("dep"),
        "got {joined}"
    );
}

#[test]
fn slice_incompat_named_type_adds_unit_across_slices() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec dep 2025-01-01
data money: scale
 -> unit eur 1.0

spec dep 2025-07-01
data money: scale
 -> unit eur 1.0
 -> unit usd 1.1
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("dep.lemma"))),
        )
        .unwrap();

    let err = engine
        .load(
            r#"
spec app 2025-01-01
data m: money from dep
rule x: 1
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("app.lemma"))),
        )
        .expect_err("type shape change");

    let joined = err
        .errors
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join(" ");
    assert!(
        joined.contains("interface") || joined.contains("dep") || joined.contains("money"),
        "got {joined}"
    );
}

#[test]
fn slice_incompat_three_versions_middle_breaks_adjacent_pair() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec dep 2025-01-01
data rate: number

spec dep 2025-04-01
data rate: text

spec dep 2025-10-01
data rate: number
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("dep.lemma"))),
        )
        .unwrap();

    let err = engine
        .load(
            r#"
spec app 2025-01-01
uses d: dep
rule r: d.rate
"#,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("app.lemma"))),
        )
        .expect_err("middle slice incompatible");

    let joined = err
        .errors
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join(" ");
    assert!(!joined.is_empty(), "expected errors");
}