lemma-engine 0.8.10

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
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
use crate::evaluation::Evaluator;
use crate::parsing::ast::{DateTimeValue, LemmaSpec};
use crate::planning::SpecSchema;
use crate::spec_id;
use crate::{parse, Error, ResourceLimits, Response};
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;

#[cfg(not(target_arch = "wasm32"))]
use std::collections::HashSet;
#[cfg(not(target_arch = "wasm32"))]
use std::path::Path;

/// Load failure: errors plus the source files we attempted to load.
#[derive(Debug, Clone)]
pub struct Errors {
    pub errors: Vec<Error>,
    pub sources: HashMap<String, String>,
}

impl Errors {
    /// Iterate over the errors.
    pub fn iter(&self) -> std::slice::Iter<'_, Error> {
        self.errors.iter()
    }
}

// ─── Temporal bound for Option<DateTimeValue> comparisons ────────────

/// Explicit representation of a temporal bound, eliminating the ambiguity
/// of `Option<DateTimeValue>` where `None` means `-∞` for start bounds
/// and `+∞` for end bounds.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum TemporalBound {
    NegInf,
    At(DateTimeValue),
    PosInf,
}

impl PartialOrd for TemporalBound {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for TemporalBound {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        use std::cmp::Ordering;
        match (self, other) {
            (TemporalBound::NegInf, TemporalBound::NegInf) => Ordering::Equal,
            (TemporalBound::NegInf, _) => Ordering::Less,
            (_, TemporalBound::NegInf) => Ordering::Greater,
            (TemporalBound::PosInf, TemporalBound::PosInf) => Ordering::Equal,
            (TemporalBound::PosInf, _) => Ordering::Greater,
            (_, TemporalBound::PosInf) => Ordering::Less,
            (TemporalBound::At(a), TemporalBound::At(b)) => a.cmp(b),
        }
    }
}

impl TemporalBound {
    /// Convert an `Option<&DateTimeValue>` used as a start bound (None = -∞).
    pub(crate) fn from_start(opt: Option<&DateTimeValue>) -> Self {
        match opt {
            None => TemporalBound::NegInf,
            Some(d) => TemporalBound::At(d.clone()),
        }
    }

    /// Convert an `Option<&DateTimeValue>` used as an end bound (None = +∞).
    pub(crate) fn from_end(opt: Option<&DateTimeValue>) -> Self {
        match opt {
            None => TemporalBound::PosInf,
            Some(d) => TemporalBound::At(d.clone()),
        }
    }

    /// Convert back to `Option<DateTimeValue>` for a start bound (NegInf → None).
    pub(crate) fn to_start(&self) -> Option<DateTimeValue> {
        match self {
            TemporalBound::NegInf => None,
            TemporalBound::At(d) => Some(d.clone()),
            TemporalBound::PosInf => {
                unreachable!("BUG: PosInf cannot represent a start bound")
            }
        }
    }

    /// Convert back to `Option<DateTimeValue>` for an end bound (PosInf → None).
    pub(crate) fn to_end(&self) -> Option<DateTimeValue> {
        match self {
            TemporalBound::NegInf => {
                unreachable!("BUG: NegInf cannot represent an end bound")
            }
            TemporalBound::At(d) => Some(d.clone()),
            TemporalBound::PosInf => None,
        }
    }
}

// ─── Spec store with temporal resolution ──────────────────────────────

/// Ordered set of specs with temporal versioning.
///
/// Specs with the same name are ordered by effective_from.
/// A temporal version's end is derived from the next temporal version's effective_from, or +inf.
#[derive(Debug, Default)]
/// Index: name -> (effective_from -> Arc<LemmaSpec>). Lookups by spec_id (name, effective_from) are O(log n).
pub struct Context {
    specs: BTreeMap<String, BTreeMap<Option<DateTimeValue>, Arc<LemmaSpec>>>,
}

impl Context {
    pub fn new() -> Self {
        Self {
            specs: BTreeMap::new(),
        }
    }

    pub(crate) fn specs_for_name(&self, name: &str) -> Vec<Arc<LemmaSpec>> {
        self.specs
            .get(name)
            .map(|m| m.values().cloned().collect())
            .unwrap_or_default()
    }

    /// Exact identity lookup by (name, effective_from).
    ///
    /// None matches specs without temporal versioning.
    /// Some(d) matches the temporal version whose effective_from equals d.
    pub fn get_spec_effective_from(
        &self,
        name: &str,
        effective_from: Option<&DateTimeValue>,
    ) -> Option<Arc<LemmaSpec>> {
        let key = effective_from.cloned();
        self.specs.get(name).and_then(|m| m.get(&key).cloned())
    }

    /// Temporal range resolution: find the temporal version of `name` that is active at `effective`.
    ///
    /// A spec is active at `effective` when:
    ///   effective_from <= effective < effective_to
    /// where `effective_to` is the next temporal version's `effective_from`, or +∞ if there is no successor.
    ///
    /// Open bounds: `effective_from() == None` on a spec means no lower bound (treat as active from −∞).
    /// For the upper bound, `effective_to.map(...).unwrap_or(true)` means “no next slice” ⇒ active until +∞.
    pub fn get_spec(&self, name: &str, effective: &DateTimeValue) -> Option<Arc<LemmaSpec>> {
        let versions = self.specs_for_name(name);
        if versions.is_empty() {
            return None;
        }

        for (i, spec) in versions.iter().enumerate() {
            let from_ok = spec
                .effective_from()
                .map(|f| *effective >= *f)
                .unwrap_or(true);
            if !from_ok {
                continue;
            }

            let effective_to: Option<&DateTimeValue> =
                versions.get(i + 1).and_then(|next| next.effective_from());
            let to_ok = effective_to.map(|end| *effective < *end).unwrap_or(true);

            if to_ok {
                return Some(spec.clone());
            }
        }

        None
    }

    pub fn iter(&self) -> impl Iterator<Item = Arc<LemmaSpec>> + '_ {
        self.specs.values().flat_map(|m| m.values().cloned())
    }

    /// Insert a spec. Set `from_registry` to `true` for pre-fetched registry
    /// specs; `false` rejects `@`-prefixed spec definitions.
    ///
    /// When `from_registry` is true, only `@`-prefixed specs are accepted —
    /// registry bundles must not introduce bare-named specs into the local namespace.
    pub fn insert_spec(&mut self, spec: Arc<LemmaSpec>, from_registry: bool) -> Result<(), Error> {
        if spec.from_registry && !from_registry {
            return Err(Error::validation_with_context(
                format!(
                    "Spec '{}' uses '@' registry prefix, which is reserved for dependencies",
                    spec.name
                ),
                None,
                Some("Remove the '@' prefix, or load this file as a dependency."),
                Some(Arc::clone(&spec)),
                None,
            ));
        }

        if from_registry && !spec.from_registry {
            return Err(Error::validation_with_context(
                format!(
                    "Registry bundle contains spec '{}' without '@' prefix; \
                     all specs in a registry bundle must use '@'-prefixed names \
                     to avoid conflicts with local specs",
                    spec.name
                ),
                None,
                Some("Prefix the spec name with '@' (e.g. spec @org/project/name)."),
                Some(Arc::clone(&spec)),
                None,
            ));
        }

        let key = spec.effective_from().cloned();
        if self
            .specs
            .get(&spec.name)
            .is_some_and(|m| m.contains_key(&key))
        {
            return Err(Error::validation_with_context(
                format!(
                    "Duplicate spec '{}' (same name and effective_from already in context)",
                    spec.name
                ),
                None,
                None::<String>,
                Some(Arc::clone(&spec)),
                None,
            ));
        }

        self.specs
            .entry(spec.name.clone())
            .or_default()
            .insert(key, spec);
        Ok(())
    }

    pub fn remove_spec(&mut self, spec: &Arc<LemmaSpec>) -> bool {
        let key = spec.effective_from().cloned();
        self.specs
            .get_mut(&spec.name)
            .and_then(|m| m.remove(&key))
            .is_some()
    }

    #[cfg(test)]
    pub(crate) fn len(&self) -> usize {
        self.specs.values().map(|m| m.len()).sum()
    }

    // ─── Temporal helpers ────────────────────────────────────────────

    /// Returns the effective range `[from, to)` for a spec in this context.
    ///
    /// - `from`: `spec.effective_from()` (None = -∞)
    /// - `to`: next temporal version's `effective_from`, or None (+∞) if no successor.
    pub fn effective_range(
        &self,
        spec: &Arc<LemmaSpec>,
    ) -> (Option<DateTimeValue>, Option<DateTimeValue>) {
        let from = spec.effective_from().cloned();
        let versions = self.specs_for_name(&spec.name);
        let pos = versions
            .iter()
            .position(|v| Arc::ptr_eq(v, spec))
            .unwrap_or_else(|| {
                unreachable!(
                    "BUG: effective_range called with spec '{}' not in context",
                    spec.name
                )
            });
        let to = versions
            .get(pos + 1)
            .and_then(|next| next.effective_from().cloned());
        (from, to)
    }

    /// Returns all `effective_from` dates for temporal versions of `name`, sorted ascending.
    /// Temporal versions without `effective_from` are excluded (they represent -∞).
    pub fn version_boundaries(&self, name: &str) -> Vec<DateTimeValue> {
        self.specs_for_name(name)
            .iter()
            .filter_map(|s| s.effective_from().cloned())
            .collect()
    }

    /// Check if temporal versions of `dep_name` fully cover the range
    /// `[required_from, required_to)`.
    ///
    /// Returns gaps as `(start, end)` intervals. Empty vec = fully covered.
    /// Start: None = -∞, End: None = +∞.
    pub fn dep_coverage_gaps(
        &self,
        dep_name: &str,
        required_from: Option<&DateTimeValue>,
        required_to: Option<&DateTimeValue>,
    ) -> Vec<(Option<DateTimeValue>, Option<DateTimeValue>)> {
        let versions = self.specs_for_name(dep_name);
        if versions.is_empty() {
            return vec![(required_from.cloned(), required_to.cloned())];
        }

        let req_start = TemporalBound::from_start(required_from);
        let req_end = TemporalBound::from_end(required_to);

        let intervals: Vec<(TemporalBound, TemporalBound)> = versions
            .iter()
            .enumerate()
            .map(|(i, v)| {
                let start = TemporalBound::from_start(v.effective_from());
                let end = match versions.get(i + 1).and_then(|next| next.effective_from()) {
                    Some(next_from) => TemporalBound::At(next_from.clone()),
                    None => TemporalBound::PosInf,
                };
                (start, end)
            })
            .collect();

        let mut gaps = Vec::new();
        let mut cursor = req_start.clone();

        for (v_start, v_end) in &intervals {
            if cursor >= req_end {
                break;
            }

            if *v_end <= cursor {
                continue;
            }

            if *v_start > cursor {
                let gap_end = std::cmp::min(v_start.clone(), req_end.clone());
                if cursor < gap_end {
                    gaps.push((cursor.to_start(), gap_end.to_end()));
                }
            }

            if *v_end > cursor {
                cursor = v_end.clone();
            }
        }

        if cursor < req_end {
            gaps.push((cursor.to_start(), req_end.to_end()));
        }

        gaps
    }
}

// ─── Slice plan lookup ───────────────────────────────────────────────

/// Find the plan whose `[valid_from, valid_to)` interval contains `effective`.
///
/// `None` for `valid_from` / `valid_to` means an open interval on that side (same convention as [`Engine::get_spec`]).
fn find_slice_plan<'a>(
    plans: &'a [crate::planning::ExecutionPlan],
    effective: &DateTimeValue,
) -> Option<&'a crate::planning::ExecutionPlan> {
    for plan in plans {
        let from_ok = plan
            .valid_from
            .as_ref()
            .map(|f| *effective >= *f)
            .unwrap_or(true);
        let to_ok = plan
            .valid_to
            .as_ref()
            .map(|t| *effective < *t)
            .unwrap_or(true);
        if from_ok && to_ok {
            return Some(plan);
        }
    }
    None
}

// ─── Engine ──────────────────────────────────────────────────────────

/// How a single buffer is identified in parse/plan diagnostics and the engine source map.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceType<'a> {
    /// Path, URI, test name, or any non-empty stable id.
    Labeled(&'a str),
    /// No stable path (pasted string, REPL). Stored under [`SourceType::INLINE_KEY`].
    Inline,
    // Pre-resolved registry bundle
    Dependency(&'a str),
}

impl SourceType<'_> {
    /// Source map key and span attribute for [`SourceType::Inline`].
    pub const INLINE_KEY: &'static str = "inline source (no path)";

    fn storage_key(self) -> Result<String, Vec<Error>> {
        match self {
            SourceType::Labeled(s) => {
                if s.trim().is_empty() {
                    return Err(vec![Error::request(
                        "source label must be non-empty, or use SourceType::Inline",
                        None::<String>,
                    )]);
                }
                Ok(s.to_string())
            }
            SourceType::Inline => Ok(Self::INLINE_KEY.to_string()),
            SourceType::Dependency(s) => Ok(s.to_string()),
        }
    }
}

/// Engine for evaluating Lemma rules.
///
/// Pure Rust implementation that evaluates Lemma specs directly from the AST.
/// Uses pre-built execution plans that are self-contained and ready for evaluation.
///
/// The engine never performs network calls. External `@...` references must be
/// pre-resolved before loading — either by including dep files
/// in the file map or by calling `resolve_registry_references` separately
/// (e.g. in a `lemma fetch` command).
pub struct Engine {
    execution_plans: HashMap<Arc<LemmaSpec>, Vec<crate::planning::ExecutionPlan>>,
    plan_hash_registry: crate::planning::PlanHashRegistry,
    specs: Context,
    sources: HashMap<String, String>,
    evaluator: Evaluator,
    limits: ResourceLimits,
    total_expression_count: usize,
}

impl Default for Engine {
    fn default() -> Self {
        Self {
            execution_plans: HashMap::new(),
            plan_hash_registry: crate::planning::PlanHashRegistry::default(),
            specs: Context::new(),
            sources: HashMap::new(),
            evaluator: Evaluator,
            limits: ResourceLimits::default(),
            total_expression_count: 0,
        }
    }
}

impl Engine {
    pub fn new() -> Self {
        Self::default()
    }

    /// Source code map (attribute -> content). Used for error display.
    pub fn sources(&self) -> &HashMap<String, String> {
        &self.sources
    }

    /// Create an engine with custom resource limits.
    pub fn with_limits(limits: ResourceLimits) -> Self {
        Self {
            execution_plans: HashMap::new(),
            plan_hash_registry: crate::planning::PlanHashRegistry::default(),
            specs: Context::new(),
            sources: HashMap::new(),
            evaluator: Evaluator,
            limits,
            total_expression_count: 0,
        }
    }

    /// Load a single spec from source code.
    /// When `source` is [`SourceType::Dependency`], content is treated as from a registry bundle (`from_registry: true`).
    pub fn load(&mut self, code: &str, source: SourceType<'_>) -> Result<(), Errors> {
        let from_registry = matches!(source, SourceType::Dependency(_));
        let mut files = HashMap::new();
        let key = source.storage_key().map_err(|errs| Errors {
            errors: errs,
            sources: HashMap::new(),
        })?;
        files.insert(key, code.to_string());
        self.add_files_inner(files, from_registry)
    }

    /// Load .lemma files from paths (files and/or directories). Directories are expanded one level only (direct child .lemma files). Resource limits `max_files`, `max_loaded_bytes`, `max_file_size_bytes` are enforced in [`add_files_inner`].
    ///
    /// Set `from_registry` to `true` for pre-fetched registry bundles (same rules as [`Context::insert_spec`] with `from_registry`). Not available on wasm32 (no filesystem).
    #[cfg(not(target_arch = "wasm32"))]
    pub fn load_from_paths<P: AsRef<Path>>(
        &mut self,
        paths: &[P],
        from_registry: bool,
    ) -> Result<(), Errors> {
        use std::fs;

        let mut files = HashMap::new();
        let mut seen = HashSet::<String>::new();

        for path in paths {
            let path = path.as_ref();
            if path.is_file() {
                // Skip non-`.lemma` files (extension missing or wrong).
                if !path.extension().map(|e| e == "lemma").unwrap_or(false) {
                    continue;
                }
                let key = path.display().to_string();
                if seen.contains(&key) {
                    continue;
                }
                seen.insert(key.clone());
                let content = fs::read_to_string(path).map_err(|e| Errors {
                    errors: vec![Error::request(
                        format!("Cannot read '{}': {}", path.display(), e),
                        None::<String>,
                    )],
                    sources: HashMap::new(),
                })?;
                files.insert(key, content);
            } else if path.is_dir() {
                let read_dir = fs::read_dir(path).map_err(|e| Errors {
                    errors: vec![Error::request(
                        format!("Cannot read directory '{}': {}", path.display(), e),
                        None::<String>,
                    )],
                    sources: HashMap::new(),
                })?;
                for entry in read_dir.filter_map(Result::ok) {
                    let p = entry.path();
                    if !p.is_file() || !p.extension().map(|e| e == "lemma").unwrap_or(false) {
                        continue;
                    }
                    let key = p.display().to_string();
                    if seen.contains(&key) {
                        continue;
                    }
                    seen.insert(key.clone());
                    let Ok(content) = fs::read_to_string(&p) else {
                        continue;
                    };
                    files.insert(key, content);
                }
            }
        }

        self.add_files_inner(files, from_registry)
    }

    fn add_files_inner(
        &mut self,
        files: HashMap<String, String>,
        from_registry: bool,
    ) -> Result<(), Errors> {
        let limits = &self.limits;
        if files.len() > limits.max_files {
            return Err(Errors {
                errors: vec![Error::resource_limit_exceeded(
                    "max_files",
                    limits.max_files.to_string(),
                    files.len().to_string(),
                    "Reduce the number of paths or files",
                    None::<crate::Source>,
                    None,
                    None,
                )],
                sources: files,
            });
        }
        let total_loaded_bytes: usize = files.values().map(|s| s.len()).sum();
        if total_loaded_bytes > limits.max_loaded_bytes {
            return Err(Errors {
                errors: vec![Error::resource_limit_exceeded(
                    "max_loaded_bytes",
                    limits.max_loaded_bytes.to_string(),
                    total_loaded_bytes.to_string(),
                    "Load fewer or smaller files",
                    None::<crate::Source>,
                    None,
                    None,
                )],
                sources: files,
            });
        }
        for code in files.values() {
            if code.len() > limits.max_file_size_bytes {
                return Err(Errors {
                    errors: vec![Error::resource_limit_exceeded(
                        "max_file_size_bytes",
                        limits.max_file_size_bytes.to_string(),
                        code.len().to_string(),
                        "Use a smaller file or increase limit",
                        None::<crate::Source>,
                        None,
                        None,
                    )],
                    sources: files,
                });
            }
        }

        let mut errors: Vec<Error> = Vec::new();

        for (source_id, code) in &files {
            match parse(code, source_id, &self.limits) {
                Ok(result) => {
                    self.total_expression_count += result.expression_count;
                    if self.total_expression_count > self.limits.max_total_expression_count {
                        errors.push(Error::resource_limit_exceeded(
                            "max_total_expression_count",
                            self.limits.max_total_expression_count.to_string(),
                            self.total_expression_count.to_string(),
                            "Split logic across fewer files or reduce expression complexity",
                            None::<crate::Source>,
                            None,
                            None,
                        ));
                        return Err(Errors {
                            errors,
                            sources: files,
                        });
                    }
                    let new_specs = result.specs;
                    for spec in new_specs {
                        let attribute = spec.attribute.clone().unwrap_or_else(|| spec.name.clone());
                        let start_line = spec.start_line;

                        if from_registry {
                            let bare_refs =
                                crate::planning::validation::collect_bare_registry_refs(&spec);
                            if !bare_refs.is_empty() {
                                let source = crate::Source::new(
                                    &attribute,
                                    crate::parsing::ast::Span {
                                        start: 0,
                                        end: 0,
                                        line: start_line,
                                        col: 0,
                                    },
                                );
                                errors.push(Error::validation(
                                    format!(
                                        "Registry spec '{}' contains references without '@' prefix: {}. \
                                         The registry must rewrite all references to use '@'-prefixed names",
                                        spec.name,
                                        bare_refs.join(", ")
                                    ),
                                    Some(source),
                                    Some(
                                        "The registry must prefix all spec references with '@' \
                                         before serving the bundle.",
                                    ),
                                ));
                                continue;
                            }
                        }

                        match self.specs.insert_spec(Arc::new(spec), from_registry) {
                            Ok(()) => {
                                self.sources.insert(attribute, code.clone());
                            }
                            Err(e) => {
                                let source = crate::Source::new(
                                    &attribute,
                                    crate::parsing::ast::Span {
                                        start: 0,
                                        end: 0,
                                        line: start_line,
                                        col: 0,
                                    },
                                );
                                errors.push(Error::validation(
                                    e.to_string(),
                                    Some(source),
                                    None::<String>,
                                ));
                            }
                        }
                    }
                }
                Err(e) => errors.push(e),
            }
        }

        let planning_result = crate::planning::plan(&self.specs, self.sources.clone());
        self.plan_hash_registry = planning_result.plan_hash_registry.clone();
        for spec_result in &planning_result.per_spec {
            self.execution_plans
                .insert(Arc::clone(&spec_result.spec), spec_result.plans.clone());
        }
        errors.extend(planning_result.global_errors);
        for spec_result in planning_result.per_spec {
            for err in spec_result.errors {
                errors.push(err.with_spec_context(Arc::clone(&spec_result.spec)));
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(Errors {
                errors,
                sources: files,
            })
        }
    }

    /// Build a "not found" error that includes the effective date and lists
    /// available temporal versions when the spec name exists but no temporal version
    /// matches the requested time.
    fn spec_not_found_error(&self, spec_name: &str, effective: &DateTimeValue) -> Error {
        let versions = self.specs.specs_for_name(spec_name);
        let msg = if versions.is_empty() {
            format!("Spec '{}' not found", spec_name)
        } else {
            let version_list: Vec<String> = versions
                .iter()
                .map(|s| match s.effective_from() {
                    Some(dt) => format!("  {} (effective from {})", s.name, dt),
                    None => format!("  {} (no effective_from)", s.name),
                })
                .collect();
            format!(
                "Spec '{}' not found for effective {}. Available temporal versions:\n{}",
                spec_name,
                effective,
                version_list.join("\n")
            )
        };
        Error::request_not_found(msg, None::<String>)
    }

    /// Resolve `spec_id` (name or name~hash) and `effective` (or now if None) to the loaded spec.
    pub fn get_spec(
        &self,
        spec_id: &str,
        effective: Option<&DateTimeValue>,
    ) -> Result<Arc<LemmaSpec>, Error> {
        let (name, hash_pin) = spec_id::parse_spec_id(spec_id)?;
        let eff_val = effective.cloned().unwrap_or_else(DateTimeValue::now);

        if let Some(pin) = &hash_pin {
            let arc = self
                .plan_hash_registry
                .get_by_pin(&name, pin)
                .cloned()
                .ok_or_else(|| {
                    Error::request_not_found(
                        format!("No spec '{}' found with plan hash {}", name, pin),
                        Some("Use lemma schema <spec> --hash to get the current plan hash"),
                    )
                })?;

            if effective.is_some() {
                let slice_plans = self.execution_plans.get(&arc).unwrap_or_else(|| {
                    panic!(
                        "BUG: spec '{}' from pin registry has no execution plan",
                        arc.name
                    )
                });
                let plan = slice_plans
                    .iter()
                    .find(|p| p.plan_hash().trim().eq_ignore_ascii_case(pin.trim()))
                    .ok_or_else(|| {
                        Error::request_not_found(
                            format!("No plan with hash {} for spec '{}'", pin, name),
                            Some("Use lemma schema <spec> --hash to get the current plan hash"),
                        )
                    })?;
                let from_ok = plan
                    .valid_from
                    .as_ref()
                    .map(|f| eff_val >= *f)
                    .unwrap_or(true);
                let to_ok = plan.valid_to.as_ref().map(|t| eff_val < *t).unwrap_or(true);
                if !from_ok || !to_ok {
                    return Err(Error::request_not_found(
                        format!(
                            "Effective {} is outside the temporal range of spec '{}'~{} ([{:?}, {:?}))",
                            eff_val, name, pin, plan.valid_from, plan.valid_to
                        ),
                        Some("Use an effective datetime within the pinned spec's slice"),
                    ));
                }
            }

            return Ok(arc);
        }

        self.specs
            .get_spec(&name, &eff_val)
            .ok_or_else(|| self.spec_not_found_error(&name, &eff_val))
    }

    /// Plan hash for a spec execution plan resolved by `spec_id` and `effective` datetime.
    pub fn get_plan_hash(
        &self,
        spec_id: &str,
        effective: &DateTimeValue,
    ) -> Result<Option<String>, Error> {
        Ok(Some(self.get_plan(spec_id, Some(effective))?.plan_hash()))
    }

    /// Remove the temporal version resolved by `spec_id` (`name` or `name~hash`) and `effective` (or now if None).
    pub fn remove(
        &mut self,
        spec_id: &str,
        effective: Option<&DateTimeValue>,
    ) -> Result<(), Error> {
        let arc = self.get_spec(spec_id, effective)?;
        self.execution_plans.remove(&arc);
        self.specs.remove_spec(&arc);
        Ok(())
    }

    /// All specs, all temporal versions, ordered by (name, effective_from).
    pub fn list_specs(&self) -> Vec<Arc<LemmaSpec>> {
        self.specs.iter().collect()
    }

    /// Specs active at `effective` (one per name).
    pub fn list_specs_effective(&self, effective: &DateTimeValue) -> Vec<Arc<LemmaSpec>> {
        let mut seen_names = std::collections::HashSet::new();
        let mut result = Vec::new();
        for spec in self.specs.iter() {
            if seen_names.contains(&spec.name) {
                continue;
            }
            if let Some(active) = self.specs.get_spec(&spec.name, effective) {
                if seen_names.insert(active.name.clone()) {
                    result.push(active);
                }
            }
        }
        result.sort_by(|a, b| a.name.cmp(&b.name));
        result
    }

    /// Resolve spec identifier (name or name~hash) and return the spec schema. Uses `effective` or now when None.
    pub fn schema(
        &self,
        spec: &str,
        effective: Option<&DateTimeValue>,
    ) -> Result<SpecSchema, Error> {
        Ok(self.get_plan(spec, effective)?.schema())
    }

    /// Resolve spec identifier and return the execution plan. Uses `effective` or now when None.
    ///
    /// With pin (`name~hash`): resolves spec by (name, hash) from the plan hash registry.
    /// If `effective` is given, verifies it falls within the pinned slice's [valid_from, valid_to).
    /// Without pin: resolves by (name, effective) temporal slice.
    pub fn get_plan(
        &self,
        spec_id: &str,
        effective: Option<&DateTimeValue>,
    ) -> Result<&crate::planning::ExecutionPlan, Error> {
        let (name, hash_pin) = spec_id::parse_spec_id(spec_id)?;
        let eff_val = effective.cloned().unwrap_or_else(DateTimeValue::now);

        if let Some(pin) = &hash_pin {
            let arc = self
                .plan_hash_registry
                .get_by_pin(&name, pin)
                .cloned()
                .ok_or_else(|| {
                    Error::request_not_found(
                        format!("No spec '{}' found with plan hash {}", name, pin),
                        Some("Use lemma schema <spec> --hash to get the current plan hash"),
                    )
                })?;

            let slice_plans = self.execution_plans.get(&arc).unwrap_or_else(|| {
                panic!(
                    "BUG: spec '{}' from pin registry has no execution plan",
                    arc.name
                )
            });

            let plan = slice_plans
                .iter()
                .find(|p| p.plan_hash().trim().eq_ignore_ascii_case(pin.trim()))
                .ok_or_else(|| {
                    Error::request_not_found(
                        format!("No plan with hash {} for spec '{}'", pin, name),
                        Some("Use lemma schema <spec> --hash to get the current plan hash"),
                    )
                })?;

            if effective.is_some() {
                let from_ok = plan
                    .valid_from
                    .as_ref()
                    .map(|f| eff_val >= *f)
                    .unwrap_or(true);
                let to_ok = plan.valid_to.as_ref().map(|t| eff_val < *t).unwrap_or(true);

                if !from_ok || !to_ok {
                    return Err(Error::request_not_found(
                        format!(
                            "Effective {} is outside the temporal range of spec '{}'~{} ([{:?}, {:?}))",
                            eff_val, name, pin, plan.valid_from, plan.valid_to
                        ),
                        Some("Use an effective datetime within the pinned spec's slice"),
                    ));
                }
            }

            return Ok(plan);
        }

        let arc = self
            .specs
            .get_spec(&name, &eff_val)
            .ok_or_else(|| self.spec_not_found_error(&name, &eff_val))?;

        let slice_plans = self.execution_plans.get(&arc).unwrap_or_else(|| {
            panic!(
                "BUG: resolved spec '{}' has no execution plan (invariant: every loaded spec is planned)",
                arc.name
            )
        });

        Ok(find_slice_plan(slice_plans, &eff_val).unwrap_or_else(|| {
            panic!(
                "BUG: spec '{}' has {} slice plan(s) but none covers effective={} — every loaded spec has at least one plan covering its effective range",
                arc.name, slice_plans.len(), eff_val
            )
        }))
    }

    /// Run a plan from [`get_plan`]: apply fact values and evaluate all rules.
    ///
    /// When `record_operations` is true, each rule's [`RuleResult::operations`] will
    /// contain a trace of facts used, rules used, computations, and branch evaluations.
    pub fn run_plan(
        &self,
        plan: &crate::planning::ExecutionPlan,
        effective: &DateTimeValue,
        fact_values: HashMap<String, String>,
        record_operations: bool,
    ) -> Result<Response, Error> {
        let plan = plan.clone().with_fact_values(fact_values, &self.limits)?;
        self.evaluate_plan(plan, effective, record_operations)
    }

    /// Run a spec: resolve by spec id, then [`run_plan`]. Returns all rules; filter via [`Response::filter_rules`] if needed.
    ///
    /// When `record_operations` is true, each rule's [`RuleResult::operations`] will
    /// contain a trace of facts used, rules used, computations, and branch evaluations.
    pub fn run(
        &self,
        spec_id: &str,
        effective: Option<&DateTimeValue>,
        fact_values: HashMap<String, String>,
        record_operations: bool,
    ) -> Result<Response, Error> {
        let eff_val = effective.cloned().unwrap_or_else(DateTimeValue::now);
        let plan = self.get_plan(spec_id, effective)?;
        self.run_plan(plan, &eff_val, fact_values, record_operations)
    }

    /// Invert a rule to find input domains that produce a desired outcome.
    ///
    /// Values are provided as name -> value string pairs (e.g., "quantity" -> "5").
    /// They are automatically parsed to the expected type based on the spec schema.
    pub fn invert(
        &self,
        spec_name: &str,
        effective: &DateTimeValue,
        rule_name: &str,
        target: crate::inversion::Target,
        values: HashMap<String, String>,
    ) -> Result<crate::InversionResponse, Error> {
        let base_plan = self.get_plan(spec_name, Some(effective))?;

        let plan = base_plan.clone().with_fact_values(values, &self.limits)?;
        let provided_facts: std::collections::HashSet<_> = plan
            .facts
            .iter()
            .filter(|(_, d)| d.value().is_some())
            .map(|(p, _)| p.clone())
            .collect();

        crate::inversion::invert(rule_name, target, &plan, &provided_facts)
    }

    fn evaluate_plan(
        &self,
        plan: crate::planning::ExecutionPlan,
        effective: &DateTimeValue,
        record_operations: bool,
    ) -> Result<Response, Error> {
        let now_semantic = crate::planning::semantics::date_time_to_semantic(effective);
        let now_literal = crate::planning::semantics::LiteralValue {
            value: crate::planning::semantics::ValueKind::Date(now_semantic),
            lemma_type: crate::planning::semantics::primitive_date().clone(),
        };
        Ok(self
            .evaluator
            .evaluate(&plan, now_literal, record_operations))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rust_decimal::Decimal;
    use std::str::FromStr;

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

    fn make_spec(name: &str) -> LemmaSpec {
        LemmaSpec::new(name.to_string())
    }

    fn make_spec_with_range(name: &str, effective_from: Option<DateTimeValue>) -> LemmaSpec {
        let mut spec = LemmaSpec::new(name.to_string());
        spec.effective_from = effective_from;
        spec
    }

    /// list_specs (and Context::iter) return specs in (name, effective_from) ascending order.
    /// So same-name temporal versions appear in temporal order; definition order in the file
    /// is irrelevant once inserted into the BTreeSet.
    #[test]
    fn list_specs_order_is_name_then_effective_from_ascending() {
        let mut ctx = Context::new();
        let s_2026 = Arc::new(make_spec_with_range("mortgage", Some(date(2026, 1, 1))));
        let s_2025 = Arc::new(make_spec_with_range("mortgage", Some(date(2025, 1, 1))));
        ctx.insert_spec(Arc::clone(&s_2026), false).unwrap();
        ctx.insert_spec(Arc::clone(&s_2025), false).unwrap();
        let listed: Vec<_> = ctx.iter().collect();
        assert_eq!(listed.len(), 2);
        assert_eq!(listed[0].effective_from(), Some(&date(2025, 1, 1)));
        assert_eq!(listed[1].effective_from(), Some(&date(2026, 1, 1)));
    }

    // ─── Context::effective_range tests ──────────────────────────────

    #[test]
    fn effective_range_unbounded_single_version() {
        let mut ctx = Context::new();
        let spec = Arc::new(make_spec("a"));
        ctx.insert_spec(Arc::clone(&spec), false).unwrap();

        let (from, to) = ctx.effective_range(&spec);
        assert_eq!(from, None);
        assert_eq!(to, None);
    }

    #[test]
    fn effective_range_soft_end_from_next_version() {
        let mut ctx = Context::new();
        let v1 = Arc::new(make_spec_with_range("a", Some(date(2025, 1, 1))));
        let v2 = Arc::new(make_spec_with_range("a", Some(date(2025, 6, 1))));
        ctx.insert_spec(Arc::clone(&v1), false).unwrap();
        ctx.insert_spec(Arc::clone(&v2), false).unwrap();

        let (from, to) = ctx.effective_range(&v1);
        assert_eq!(from, Some(date(2025, 1, 1)));
        assert_eq!(to, Some(date(2025, 6, 1)));

        let (from, to) = ctx.effective_range(&v2);
        assert_eq!(from, Some(date(2025, 6, 1)));
        assert_eq!(to, None);
    }

    #[test]
    fn effective_range_unbounded_start_with_successor() {
        let mut ctx = Context::new();
        let v1 = Arc::new(make_spec("a"));
        let v2 = Arc::new(make_spec_with_range("a", Some(date(2025, 3, 1))));
        ctx.insert_spec(Arc::clone(&v1), false).unwrap();
        ctx.insert_spec(Arc::clone(&v2), false).unwrap();

        let (from, to) = ctx.effective_range(&v1);
        assert_eq!(from, None);
        assert_eq!(to, Some(date(2025, 3, 1)));
    }

    // ─── Context::version_boundaries tests ───────────────────────────

    #[test]
    fn version_boundaries_single_unversioned() {
        let mut ctx = Context::new();
        ctx.insert_spec(Arc::new(make_spec("a")), false).unwrap();

        assert!(ctx.version_boundaries("a").is_empty());
    }

    #[test]
    fn version_boundaries_multiple_versions() {
        let mut ctx = Context::new();
        ctx.insert_spec(Arc::new(make_spec("a")), false).unwrap();
        ctx.insert_spec(
            Arc::new(make_spec_with_range("a", Some(date(2025, 3, 1)))),
            false,
        )
        .unwrap();
        ctx.insert_spec(
            Arc::new(make_spec_with_range("a", Some(date(2025, 6, 1)))),
            false,
        )
        .unwrap();

        let boundaries = ctx.version_boundaries("a");
        assert_eq!(boundaries, vec![date(2025, 3, 1), date(2025, 6, 1)]);
    }

    #[test]
    fn version_boundaries_nonexistent_name() {
        let ctx = Context::new();
        assert!(ctx.version_boundaries("nope").is_empty());
    }

    // ─── Context::dep_coverage_gaps tests ────────────────────────────

    #[test]
    fn dep_coverage_no_versions_is_full_gap() {
        let ctx = Context::new();
        let gaps =
            ctx.dep_coverage_gaps("missing", Some(&date(2025, 1, 1)), Some(&date(2025, 6, 1)));
        assert_eq!(gaps, vec![(Some(date(2025, 1, 1)), Some(date(2025, 6, 1)))]);
    }

    #[test]
    fn dep_coverage_single_unbounded_version_covers_everything() {
        let mut ctx = Context::new();
        ctx.insert_spec(Arc::new(make_spec("dep")), false).unwrap();

        let gaps = ctx.dep_coverage_gaps("dep", None, None);
        assert!(gaps.is_empty());

        let gaps = ctx.dep_coverage_gaps("dep", Some(&date(2025, 1, 1)), Some(&date(2025, 12, 1)));
        assert!(gaps.is_empty());
    }

    #[test]
    fn dep_coverage_single_version_with_from_leaves_leading_gap() {
        let mut ctx = Context::new();
        ctx.insert_spec(
            Arc::new(make_spec_with_range("dep", Some(date(2025, 3, 1)))),
            false,
        )
        .unwrap();

        let gaps = ctx.dep_coverage_gaps("dep", None, None);
        assert_eq!(gaps, vec![(None, Some(date(2025, 3, 1)))]);
    }

    #[test]
    fn dep_coverage_continuous_versions_no_gaps() {
        let mut ctx = Context::new();
        ctx.insert_spec(
            Arc::new(make_spec_with_range("dep", Some(date(2025, 1, 1)))),
            false,
        )
        .unwrap();
        ctx.insert_spec(
            Arc::new(make_spec_with_range("dep", Some(date(2025, 6, 1)))),
            false,
        )
        .unwrap();

        let gaps = ctx.dep_coverage_gaps("dep", Some(&date(2025, 1, 1)), Some(&date(2025, 12, 1)));
        assert!(gaps.is_empty());
    }

    #[test]
    fn dep_coverage_dep_starts_after_required_start() {
        let mut ctx = Context::new();
        ctx.insert_spec(
            Arc::new(make_spec_with_range("dep", Some(date(2025, 6, 1)))),
            false,
        )
        .unwrap();

        let gaps = ctx.dep_coverage_gaps("dep", Some(&date(2025, 1, 1)), Some(&date(2025, 12, 1)));
        assert_eq!(gaps, vec![(Some(date(2025, 1, 1)), Some(date(2025, 6, 1)))]);
    }

    #[test]
    fn dep_coverage_unbounded_required_range() {
        let mut ctx = Context::new();
        ctx.insert_spec(
            Arc::new(make_spec_with_range("dep", Some(date(2025, 6, 1)))),
            false,
        )
        .unwrap();

        let gaps = ctx.dep_coverage_gaps("dep", None, None);
        assert_eq!(gaps, vec![(None, Some(date(2025, 6, 1)))]);
    }

    #[test]
    fn get_spec_resolves_temporal_version_by_effective() {
        let mut engine = Engine::new();
        engine
            .load(
                r#"
        spec pricing 2025-01-01
        fact x: 1
        rule r: x
    "#,
                SourceType::Labeled("a.lemma"),
            )
            .unwrap();
        engine
            .load(
                r#"
        spec pricing 2025-06-01
        fact x: 2
        rule r: x
    "#,
                SourceType::Labeled("b.lemma"),
            )
            .unwrap();

        let jan = DateTimeValue {
            year: 2025,
            month: 1,
            day: 15,
            hour: 0,
            minute: 0,
            second: 0,
            microsecond: 0,
            timezone: None,
        };
        let jul = DateTimeValue {
            year: 2025,
            month: 7,
            day: 1,
            hour: 0,
            minute: 0,
            second: 0,
            microsecond: 0,
            timezone: None,
        };

        let v1 = DateTimeValue {
            year: 2025,
            month: 1,
            day: 1,
            hour: 0,
            minute: 0,
            second: 0,
            microsecond: 0,
            timezone: None,
        };
        let v2 = DateTimeValue {
            year: 2025,
            month: 6,
            day: 1,
            hour: 0,
            minute: 0,
            second: 0,
            microsecond: 0,
            timezone: None,
        };

        let s_jan = engine.get_spec("pricing", Some(&jan)).expect("jan spec");
        let s_jul = engine.get_spec("pricing", Some(&jul)).expect("jul spec");
        assert_eq!(s_jan.effective_from(), Some(&v1));
        assert_eq!(s_jul.effective_from(), Some(&v2));
    }

    #[test]
    fn test_evaluate_spec_all_rules() {
        let mut engine = Engine::new();
        engine
            .load(
                r#"
        spec test
        fact x: 10
        fact y: 5
        rule sum: x + y
        rule product: x * y
    "#,
                SourceType::Labeled("test.lemma"),
            )
            .unwrap();

        let now = DateTimeValue::now();
        let response = engine
            .run("test", Some(&now), HashMap::new(), false)
            .unwrap();
        assert_eq!(response.results.len(), 2);

        let sum_result = response
            .results
            .values()
            .find(|r| r.rule.name == "sum")
            .unwrap();
        assert_eq!(
            sum_result.result,
            crate::OperationResult::Value(Box::new(crate::planning::LiteralValue::number(
                Decimal::from_str("15").unwrap()
            )))
        );

        let product_result = response
            .results
            .values()
            .find(|r| r.rule.name == "product")
            .unwrap();
        assert_eq!(
            product_result.result,
            crate::OperationResult::Value(Box::new(crate::planning::LiteralValue::number(
                Decimal::from_str("50").unwrap()
            )))
        );
    }

    #[test]
    fn test_evaluate_empty_facts() {
        let mut engine = Engine::new();
        engine
            .load(
                r#"
        spec test
        fact price: 100
        rule total: price * 2
    "#,
                SourceType::Labeled("test.lemma"),
            )
            .unwrap();

        let now = DateTimeValue::now();
        let response = engine
            .run("test", Some(&now), HashMap::new(), false)
            .unwrap();
        assert_eq!(response.results.len(), 1);
        assert_eq!(
            response.results.values().next().unwrap().result,
            crate::OperationResult::Value(Box::new(crate::planning::LiteralValue::number(
                Decimal::from_str("200").unwrap()
            )))
        );
    }

    #[test]
    fn test_evaluate_boolean_rule() {
        let mut engine = Engine::new();
        engine
            .load(
                r#"
        spec test
        fact age: 25
        rule is_adult: age >= 18
    "#,
                SourceType::Labeled("test.lemma"),
            )
            .unwrap();

        let now = DateTimeValue::now();
        let response = engine
            .run("test", Some(&now), HashMap::new(), false)
            .unwrap();
        assert_eq!(
            response.results.values().next().unwrap().result,
            crate::OperationResult::Value(Box::new(crate::planning::LiteralValue::from_bool(true)))
        );
    }

    #[test]
    fn test_evaluate_with_unless_clause() {
        let mut engine = Engine::new();
        engine
            .load(
                r#"
        spec test
        fact quantity: 15
        rule discount: 0
          unless quantity >= 10 then 10
    "#,
                SourceType::Labeled("test.lemma"),
            )
            .unwrap();

        let now = DateTimeValue::now();
        let response = engine
            .run("test", Some(&now), HashMap::new(), false)
            .unwrap();
        assert_eq!(
            response.results.values().next().unwrap().result,
            crate::OperationResult::Value(Box::new(crate::planning::LiteralValue::number(
                Decimal::from_str("10").unwrap()
            )))
        );
    }

    #[test]
    fn test_spec_not_found() {
        let engine = Engine::new();
        let now = DateTimeValue::now();
        let result = engine.run("nonexistent", Some(&now), HashMap::new(), false);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[test]
    fn test_multiple_specs() {
        let mut engine = Engine::new();
        engine
            .load(
                r#"
        spec spec1
        fact x: 10
        rule result: x * 2
    "#,
                SourceType::Labeled("spec 1.lemma"),
            )
            .unwrap();

        engine
            .load(
                r#"
        spec spec2
        fact y: 5
        rule result: y * 3
    "#,
                SourceType::Labeled("spec 2.lemma"),
            )
            .unwrap();

        let now = DateTimeValue::now();
        let response1 = engine
            .run("spec1", Some(&now), HashMap::new(), false)
            .unwrap();
        assert_eq!(
            response1.results[0].result,
            crate::OperationResult::Value(Box::new(crate::planning::LiteralValue::number(
                Decimal::from_str("20").unwrap()
            )))
        );

        let response2 = engine
            .run("spec2", Some(&now), HashMap::new(), false)
            .unwrap();
        assert_eq!(
            response2.results[0].result,
            crate::OperationResult::Value(Box::new(crate::planning::LiteralValue::number(
                Decimal::from_str("15").unwrap()
            )))
        );
    }

    #[test]
    fn test_runtime_error_mapping() {
        let mut engine = Engine::new();
        engine
            .load(
                r#"
        spec test
        fact numerator: 10
        fact denominator: 0
        rule division: numerator / denominator
    "#,
                SourceType::Labeled("test.lemma"),
            )
            .unwrap();

        let now = DateTimeValue::now();
        let result = engine.run("test", Some(&now), HashMap::new(), false);
        // Division by zero returns a Veto (not an error)
        assert!(result.is_ok(), "Evaluation should succeed");
        let response = result.unwrap();
        let division_result = response
            .results
            .values()
            .find(|r| r.rule.name == "division");
        assert!(
            division_result.is_some(),
            "Should have division rule result"
        );
        match &division_result.unwrap().result {
            crate::OperationResult::Veto(message) => {
                assert!(
                    message
                        .as_ref()
                        .map(|m| m.contains("Division by zero"))
                        .unwrap_or(false),
                    "Veto message should mention division by zero: {:?}",
                    message
                );
            }
            other => panic!("Expected Veto for division by zero, got {:?}", other),
        }
    }

    #[test]
    fn test_rules_sorted_by_source_order() {
        let mut engine = Engine::new();
        engine
            .load(
                r#"
        spec test
        fact a: 1
        fact b: 2
        rule z: a + b
        rule y: a * b
        rule x: a - b
    "#,
                SourceType::Labeled("test.lemma"),
            )
            .unwrap();

        let now = DateTimeValue::now();
        let response = engine
            .run("test", Some(&now), HashMap::new(), false)
            .unwrap();
        assert_eq!(response.results.len(), 3);

        // Verify source positions increase (z < y < x)
        let z_pos = response
            .results
            .values()
            .find(|r| r.rule.name == "z")
            .unwrap()
            .rule
            .source_location
            .span
            .start;
        let y_pos = response
            .results
            .values()
            .find(|r| r.rule.name == "y")
            .unwrap()
            .rule
            .source_location
            .span
            .start;
        let x_pos = response
            .results
            .values()
            .find(|r| r.rule.name == "x")
            .unwrap()
            .rule
            .source_location
            .span
            .start;

        assert!(z_pos < y_pos);
        assert!(y_pos < x_pos);
    }

    #[test]
    fn test_rule_filtering_evaluates_dependencies() {
        let mut engine = Engine::new();
        engine
            .load(
                r#"
        spec test
        fact base: 100
        rule subtotal: base * 2
        rule tax: subtotal * 10%
        rule total: subtotal + tax
    "#,
                SourceType::Labeled("test.lemma"),
            )
            .unwrap();

        // User filters to 'total' after run (deps were still computed)
        let now = DateTimeValue::now();
        let rules = vec!["total".to_string()];
        let mut response = engine
            .run("test", Some(&now), HashMap::new(), false)
            .unwrap();
        response.filter_rules(&rules);

        assert_eq!(response.results.len(), 1);
        assert_eq!(response.results.keys().next().unwrap(), "total");

        // But the value should be correct (dependencies were computed)
        let total = response.results.values().next().unwrap();
        assert_eq!(
            total.result,
            crate::OperationResult::Value(Box::new(crate::planning::LiteralValue::number(
                Decimal::from_str("220").unwrap()
            )))
        );
    }

    // -------------------------------------------------------------------
    // Pre-resolved dependency tests (Engine never fetches from registry)
    // -------------------------------------------------------------------

    use crate::parsing::ast::DateTimeValue;

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

        engine
            .load(
                "spec @org/project/helper\nfact quantity: 42",
                SourceType::Dependency("deps/org_project_helper.lemma"),
            )
            .expect("should load dependency files");

        engine
            .load(
                r#"spec main_spec
fact external: spec @org/project/helper
rule value: external.quantity"#,
                SourceType::Labeled("main.lemma"),
            )
            .expect("should succeed with pre-resolved deps");

        let now = DateTimeValue::now();
        let response = engine
            .run("main_spec", Some(&now), HashMap::new(), false)
            .expect("evaluate should succeed");

        let value_result = response
            .results
            .get("value")
            .expect("rule 'value' should exist");
        assert_eq!(
            value_result.result,
            crate::OperationResult::Value(Box::new(crate::planning::LiteralValue::number(
                Decimal::from_str("42").unwrap()
            )))
        );
    }

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

        engine
            .load(
                r#"spec local_only
fact price: 100
rule doubled: price * 2"#,
                SourceType::Labeled("local.lemma"),
            )
            .expect("should succeed when there are no @... references");

        let now = DateTimeValue::now();
        let response = engine
            .run("local_only", Some(&now), HashMap::new(), false)
            .expect("evaluate should succeed");

        let doubled = response
            .results
            .get("doubled")
            .expect("doubled rule")
            .result
            .value()
            .expect("value");
        assert_eq!(doubled.to_string(), "200");
    }

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

        let result = engine.load(
            r#"spec main_spec
fact external: spec @org/project/missing
rule value: external.quantity"#,
            SourceType::Labeled("main.lemma"),
        );

        let errs = result.expect_err("Should fail when @... dep is not in file map");
        let msg = errs
            .iter()
            .map(|e| e.to_string())
            .collect::<Vec<_>>()
            .join(" ");
        assert!(
            msg.contains("missing") || msg.contains("not found") || msg.contains("Unknown"),
            "error should indicate missing dep: {msg}"
        );
    }

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

        let mut deps = HashMap::new();
        deps.insert(
            "deps/helper.lemma".to_string(),
            "spec @org/example/helper\nfact value: 42".to_string(),
        );
        deps.insert(
            "deps/finance.lemma".to_string(),
            "spec @lemma/std/finance\ntype money: scale\n -> unit eur 1.00\n -> decimals 2"
                .to_string(),
        );
        engine
            .load(
                "spec @org/example/helper\nfact value: 42",
                SourceType::Dependency("deps/helper.lemma"),
            )
            .expect("should load helper file");

        engine
            .load(
                "spec @lemma/std/finance\ntype money: scale\n -> unit eur 1.00\n -> decimals 2",
                SourceType::Dependency("deps/finance.lemma"),
            )
            .expect("should load finance file");

        engine
            .load(
                r#"spec registry_demo
type money from @lemma/std/finance
fact unit_price: 5 eur
fact helper: spec @org/example/helper
rule helper_value: helper.value
rule line_total: unit_price * 2
rule formatted: helper_value + 0"#,
                SourceType::Labeled("main.lemma"),
            )
            .expect("should succeed with pre-resolved spec and type deps");

        let now = DateTimeValue::now();
        let response = engine
            .run("registry_demo", Some(&now), HashMap::new(), false)
            .expect("evaluate should succeed");

        assert_eq!(
            response
                .results
                .get("helper_value")
                .expect("helper_value")
                .result
                .value()
                .expect("value")
                .to_string(),
            "42"
        );
        let line = response
            .results
            .get("line_total")
            .expect("line_total")
            .result
            .value()
            .expect("value")
            .to_string();
        assert!(
            line.contains("10") && line.to_lowercase().contains("eur"),
            "5 eur * 2 => ~10 eur, got {line}"
        );
        assert_eq!(
            response
                .results
                .get("formatted")
                .expect("formatted")
                .result
                .value()
                .expect("value")
                .to_string(),
            "42"
        );
    }

    #[test]
    fn load_empty_labeled_source_is_error() {
        let mut engine = Engine::new();
        let err = engine
            .load("spec x\nfact a: 1", SourceType::Labeled("  "))
            .unwrap_err();
        assert!(err.errors.iter().any(|e| e.message().contains("non-empty")));
    }

    #[test]
    fn load_inline_source_succeeds() {
        let mut engine = Engine::new();
        engine
            .load("spec x\nfact a: 1", SourceType::Inline)
            .expect("inline load");
    }

    #[test]
    fn load_rejects_registry_spec_definitions() {
        let mut engine = Engine::new();
        let result = engine.load(
            "spec @org/example/helper\nfact x: 1",
            SourceType::Labeled("bad.lemma"),
        );
        assert!(result.is_err(), "should reject @-prefixed spec in load");
        let errors = result.unwrap_err();
        assert!(
            errors
                .errors
                .iter()
                .any(|e| e.message().contains("registry prefix")),
            "error should mention registry prefix, got: {:?}",
            errors
        );
    }

    #[test]
    fn add_dependency_files_accepts_registry_spec_definitions() {
        let mut engine = Engine::new();
        let mut files = HashMap::new();
        files.insert(
            "deps/helper.lemma".to_string(),
            "spec @org/my/helper\nfact x: 1".to_string(),
        );
        engine
            .load(
                "spec @org/my/helper\nfact x: 1",
                SourceType::Dependency("helper.lemma"),
            )
            .expect("add_dependency_files should accept @-prefixed specs");
    }

    #[test]
    fn add_dependency_files_rejects_bare_named_spec_in_registry_bundle() {
        let mut engine = Engine::new();
        let result = engine.load(
            "spec local_looking_name\nfact x: 1",
            SourceType::Dependency("bundle.lemma"),
        );
        assert!(
            result.is_err(),
            "should reject non-@-prefixed spec in registry bundle"
        );
        let errors = result.unwrap_err();
        assert!(
            errors
                .errors
                .iter()
                .any(|e| e.message().contains("without '@' prefix")),
            "error should mention missing @ prefix, got: {:?}",
            errors
        );
    }

    #[test]
    fn add_dependency_files_rejects_spec_with_bare_spec_reference() {
        let mut engine = Engine::new();
        let result = engine.load(
            "spec @org/billing\nfact rates: spec local_rates",
            SourceType::Dependency("billing.lemma"),
        );
        assert!(
            result.is_err(),
            "should reject registry spec referencing non-@ spec"
        );
        let errors = result.unwrap_err();
        assert!(
            errors
                .errors
                .iter()
                .any(|e| e.message().contains("local_rates")),
            "error should mention bare ref name, got: {:?}",
            errors
        );
    }

    #[test]
    fn add_dependency_files_rejects_spec_with_bare_type_import() {
        let mut engine = Engine::new();
        let result = engine.load(
            "spec @org/billing\ntype money from local_finance",
            SourceType::Dependency("billing.lemma"),
        );
        assert!(
            result.is_err(),
            "should reject registry spec importing type from non-@ spec"
        );
        let errors = result.unwrap_err();
        assert!(
            errors
                .errors
                .iter()
                .any(|e| e.message().contains("local_finance")),
            "error should mention bare ref name, got: {:?}",
            errors
        );
    }

    #[test]
    fn add_dependency_files_accepts_fully_qualified_references() {
        let mut engine = Engine::new();
        let mut files = HashMap::new();
        files.insert(
            "deps/bundle.lemma".to_string(),
            r#"spec @org/billing
fact rates: spec @org/rates

spec @org/rates
fact rate: 10"#
                .to_string(),
        );
        engine
            .load(
                r#"spec @org/billing
fact rates: spec @org/rates

spec @org/rates
fact rate: 10"#,
                SourceType::Dependency("bundle.lemma"),
            )
            .expect("fully @-prefixed bundle should be accepted");
    }

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

        let result = engine.load(
            r#"spec demo
type money from nonexistent_type_source
fact helper: spec nonexistent_spec
fact price: 10
rule total: helper.value + price"#,
            SourceType::Labeled("test.lemma"),
        );

        assert!(result.is_err(), "Should fail with multiple errors");
        let load_err = result.unwrap_err();
        assert!(
            load_err.errors.len() >= 2,
            "expected at least 2 errors (type + spec ref), got {}",
            load_err.errors.len()
        );
        let error_message = load_err
            .errors
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("; ");

        assert!(
            error_message.contains("nonexistent_type_source"),
            "Should mention type import source spec. Got:\n{}",
            error_message
        );
        assert!(
            error_message.contains("nonexistent_spec"),
            "Should mention spec reference error about 'nonexistent_spec'. Got:\n{}",
            error_message
        );
    }

    // ── Default value type validation ────────────────────────────────
    // Planning must reject default values that don't match the type.
    // These tests cover both primitives and named types (which the parser
    // can't validate because it doesn't resolve type names).

    #[test]
    fn planning_rejects_invalid_number_default() {
        let mut engine = Engine::new();
        let result = engine.load(
            "spec t\nfact x: [number -> default \"10 $$\"]\nrule r: x",
            SourceType::Labeled("t.lemma"),
        );
        assert!(
            result.is_err(),
            "must reject non-numeric default on number type"
        );
    }

    #[test]
    fn planning_rejects_text_literal_as_number_default() {
        // The parser produces CommandArg::Text("10") for `default "10"`.
        // Planning now checks the CommandArg variant: a Text literal is
        // rejected where a Number literal is required, even though the
        // string content "10" could be parsed as a valid Decimal.
        let mut engine = Engine::new();
        let result = engine.load(
            "spec t\nfact x: [number -> default \"10\"]\nrule r: x",
            SourceType::Labeled("t.lemma"),
        );
        assert!(
            result.is_err(),
            "must reject text literal \"10\" as default for number type"
        );
    }

    #[test]
    fn planning_rejects_invalid_boolean_default() {
        let mut engine = Engine::new();
        let result = engine.load(
            "spec t\nfact x: [boolean -> default \"maybe\"]\nrule r: x",
            SourceType::Labeled("t.lemma"),
        );
        assert!(
            result.is_err(),
            "must reject non-boolean default on boolean type"
        );
    }

    #[test]
    fn planning_rejects_invalid_named_type_default() {
        // Named type: the parser can't validate this, only planning can.
        let mut engine = Engine::new();
        let result = engine.load("spec t\ntype custom: number -> minimum 0\nfact x: [custom -> default \"abc\"]\nrule r: x", SourceType::Labeled("t.lemma",));
        assert!(
            result.is_err(),
            "must reject non-numeric default on named number type"
        );
    }

    #[test]
    fn planning_accepts_valid_number_default() {
        let mut engine = Engine::new();
        let result = engine.load(
            "spec t\nfact x: [number -> default 10]\nrule r: x",
            SourceType::Labeled("t.lemma"),
        );
        assert!(result.is_ok(), "must accept valid number default");
    }

    #[test]
    fn planning_accepts_valid_boolean_default() {
        let mut engine = Engine::new();
        let result = engine.load(
            "spec t\nfact x: [boolean -> default true]\nrule r: x",
            SourceType::Labeled("t.lemma"),
        );
        assert!(result.is_ok(), "must accept valid boolean default");
    }

    #[test]
    fn planning_accepts_valid_text_default() {
        let mut engine = Engine::new();
        let result = engine.load(
            "spec t\nfact x: [text -> default \"hello\"]\nrule r: x",
            SourceType::Labeled("t.lemma"),
        );
        assert!(result.is_ok(), "must accept valid text default");
    }
}