eidetic-engine 0.15.2

Durable, local-first, explainable memory for coding agents.
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
//! Causal memory credit and uplift schema contracts (EE-450).
//!
//! These records distinguish mere exposure from plausible influence, replay
//! support, and experiment-backed uplift. They are schema contracts for later
//! `ee causal` commands; defining them here does not promote, demote, or mutate
//! durable memory.

use std::fmt;
use std::str::FromStr;

use serde_json::{Value as JsonValue, json};

use super::decision::DecisionPlane;

// ============================================================================
// Schema Constants
// ============================================================================

/// Schema for a memory/artifact exposure to an agent decision.
pub const CAUSAL_EXPOSURE_SCHEMA_V1: &str = "ee.causal.exposure.v1";

/// Schema for the decision trace used by causal credit analysis.
pub const DECISION_TRACE_SCHEMA_V1: &str = "ee.causal.decision_trace.v1";

/// Schema for a bounded uplift estimate.
pub const UPLIFT_ESTIMATE_SCHEMA_V1: &str = "ee.causal.uplift_estimate.v1";

/// Schema for a confounder that can explain apparent uplift.
pub const CONFOUNDER_SCHEMA_V1: &str = "ee.causal.confounder.v1";

/// Schema for a dry-run-first promotion plan.
pub const PROMOTION_PLAN_SCHEMA_V1: &str = "ee.causal.promotion_plan.v1";

/// Schema for the causal schema catalog.
pub const CAUSAL_SCHEMA_CATALOG_V1: &str = "ee.causal.schemas.v1";

/// Schema for causal trace reports.
pub const CAUSAL_TRACE_SCHEMA_V1: &str = "ee.causal.trace.v1";

const JSON_SCHEMA_DRAFT_2020_12: &str = "https://json-schema.org/draft/2020-12/schema";

fn bounded_unit(value: f64) -> f64 {
    if value.is_finite() {
        value.clamp(0.0, 1.0)
    } else {
        0.0
    }
}

fn bounded_delta(value: f64) -> f64 {
    if value.is_finite() {
        value.clamp(-1.0, 1.0)
    } else {
        0.0
    }
}

fn rounded_metric(value: f64) -> f64 {
    if value.is_finite() {
        (value * 1000.0).round() / 1000.0
    } else {
        0.0
    }
}

fn normalized_causal_token(input: &str) -> String {
    let trimmed = input.trim();
    let mut normalized = String::with_capacity(trimmed.len());
    let mut previous_was_lowercase = false;
    let mut previous_was_separator = false;

    for character in trimmed.chars() {
        match character {
            '-' | '_' => {
                if !normalized.is_empty() && !previous_was_separator {
                    normalized.push('_');
                }
                previous_was_lowercase = false;
                previous_was_separator = true;
            }
            character if character.is_ascii_uppercase() => {
                if previous_was_lowercase && !previous_was_separator {
                    normalized.push('_');
                }
                normalized.push(character.to_ascii_lowercase());
                previous_was_lowercase = false;
                previous_was_separator = false;
            }
            character => {
                normalized.push(character.to_ascii_lowercase());
                previous_was_lowercase = character.is_ascii_lowercase();
                previous_was_separator = false;
            }
        }
    }

    normalized
}

// ============================================================================
// Stable Wire Enums
// ============================================================================

/// How an artifact was exposed to an agent decision.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum CausalExposureChannel {
    ContextPack,
    SearchResult,
    WhyExplanation,
    AgentDocs,
    Procedure,
    ManualReference,
}

impl CausalExposureChannel {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ContextPack => "context_pack",
            Self::SearchResult => "search_result",
            Self::WhyExplanation => "why_explanation",
            Self::AgentDocs => "agent_docs",
            Self::Procedure => "procedure",
            Self::ManualReference => "manual_reference",
        }
    }

    #[must_use]
    pub const fn all() -> [Self; 6] {
        [
            Self::ContextPack,
            Self::SearchResult,
            Self::WhyExplanation,
            Self::AgentDocs,
            Self::Procedure,
            Self::ManualReference,
        ]
    }
}

impl fmt::Display for CausalExposureChannel {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for CausalExposureChannel {
    type Err = ParseCausalValueError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_causal_token(input).as_str() {
            "context_pack" => Ok(Self::ContextPack),
            "search_result" => Ok(Self::SearchResult),
            "why_explanation" => Ok(Self::WhyExplanation),
            "agent_docs" => Ok(Self::AgentDocs),
            "procedure" => Ok(Self::Procedure),
            "manual_reference" => Ok(Self::ManualReference),
            _ => Err(ParseCausalValueError::new(
                "causal_exposure_channel",
                input,
                "context_pack, search_result, why_explanation, agent_docs, procedure, manual_reference",
            )),
        }
    }
}

/// What the decision did with exposed evidence.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum DecisionTraceOutcome {
    Used,
    Ignored,
    Deferred,
    Rejected,
    Unsafe,
}

impl DecisionTraceOutcome {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Used => "used",
            Self::Ignored => "ignored",
            Self::Deferred => "deferred",
            Self::Rejected => "rejected",
            Self::Unsafe => "unsafe",
        }
    }

    #[must_use]
    pub const fn all() -> [Self; 5] {
        [
            Self::Used,
            Self::Ignored,
            Self::Deferred,
            Self::Rejected,
            Self::Unsafe,
        ]
    }
}

impl fmt::Display for DecisionTraceOutcome {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for DecisionTraceOutcome {
    type Err = ParseCausalValueError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_causal_token(input).as_str() {
            "used" => Ok(Self::Used),
            "ignored" => Ok(Self::Ignored),
            "deferred" => Ok(Self::Deferred),
            "rejected" => Ok(Self::Rejected),
            "unsafe" => Ok(Self::Unsafe),
            _ => Err(ParseCausalValueError::new(
                "decision_trace_outcome",
                input,
                "used, ignored, deferred, rejected, unsafe",
            )),
        }
    }
}

/// Evidence strength behind a causal estimate or promotion plan.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum CausalEvidenceStrength {
    ExposureOnly,
    Correlational,
    ReplaySupported,
    ExperimentSupported,
    Rejected,
}

/// How a causal evidence ledger edge was produced.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum CausalEvidenceMethod {
    Manual,
    GraphInferred,
    CassDerived,
}

impl CausalEvidenceMethod {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Manual => "manual",
            Self::GraphInferred => "graph-inferred",
            Self::CassDerived => "cass-derived",
        }
    }

    #[must_use]
    pub const fn all() -> [Self; 3] {
        [Self::Manual, Self::GraphInferred, Self::CassDerived]
    }
}

impl fmt::Display for CausalEvidenceMethod {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for CausalEvidenceMethod {
    type Err = ParseCausalValueError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_causal_token(input).as_str() {
            "manual" => Ok(Self::Manual),
            "graph_inferred" => Ok(Self::GraphInferred),
            "cass_derived" => Ok(Self::CassDerived),
            _ => Err(ParseCausalValueError::new(
                "causal_evidence_method",
                input,
                "manual, graph-inferred, cass-derived",
            )),
        }
    }
}

impl CausalEvidenceStrength {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ExposureOnly => "exposure_only",
            Self::Correlational => "correlational",
            Self::ReplaySupported => "replay_supported",
            Self::ExperimentSupported => "experiment_supported",
            Self::Rejected => "rejected",
        }
    }

    #[must_use]
    pub const fn all() -> [Self; 5] {
        [
            Self::ExposureOnly,
            Self::Correlational,
            Self::ReplaySupported,
            Self::ExperimentSupported,
            Self::Rejected,
        ]
    }
}

impl fmt::Display for CausalEvidenceStrength {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for CausalEvidenceStrength {
    type Err = ParseCausalValueError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_causal_token(input).as_str() {
            "exposure_only" => Ok(Self::ExposureOnly),
            "correlational" => Ok(Self::Correlational),
            "replay_supported" => Ok(Self::ReplaySupported),
            "experiment_supported" => Ok(Self::ExperimentSupported),
            "rejected" => Ok(Self::Rejected),
            _ => Err(ParseCausalValueError::new(
                "causal_evidence_strength",
                input,
                "exposure_only, correlational, replay_supported, experiment_supported, rejected",
            )),
        }
    }
}

/// Direction of the estimated causal uplift.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum UpliftDirection {
    Positive,
    Negative,
    Neutral,
    Unknown,
}

impl UpliftDirection {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Positive => "positive",
            Self::Negative => "negative",
            Self::Neutral => "neutral",
            Self::Unknown => "unknown",
        }
    }

    #[must_use]
    pub const fn all() -> [Self; 4] {
        [Self::Positive, Self::Negative, Self::Neutral, Self::Unknown]
    }

    #[must_use]
    pub fn from_uplift(uplift: f64) -> Self {
        if !uplift.is_finite() {
            Self::Unknown
        } else if uplift > 0.001 {
            Self::Positive
        } else if uplift < -0.001 {
            Self::Negative
        } else {
            Self::Neutral
        }
    }
}

impl fmt::Display for UpliftDirection {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for UpliftDirection {
    type Err = ParseCausalValueError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_causal_token(input).as_str() {
            "positive" => Ok(Self::Positive),
            "negative" => Ok(Self::Negative),
            "neutral" => Ok(Self::Neutral),
            "unknown" => Ok(Self::Unknown),
            _ => Err(ParseCausalValueError::new(
                "uplift_direction",
                input,
                "positive, negative, neutral, unknown",
            )),
        }
    }
}

/// Common confounder classes for uplift analysis.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ConfounderKind {
    SelectionBias,
    TaskDifficulty,
    AgentSkill,
    TimeTrend,
    ToolingChange,
    ExternalIntervention,
}

impl ConfounderKind {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SelectionBias => "selection_bias",
            Self::TaskDifficulty => "task_difficulty",
            Self::AgentSkill => "agent_skill",
            Self::TimeTrend => "time_trend",
            Self::ToolingChange => "tooling_change",
            Self::ExternalIntervention => "external_intervention",
        }
    }

    #[must_use]
    pub const fn all() -> [Self; 6] {
        [
            Self::SelectionBias,
            Self::TaskDifficulty,
            Self::AgentSkill,
            Self::TimeTrend,
            Self::ToolingChange,
            Self::ExternalIntervention,
        ]
    }
}

impl fmt::Display for ConfounderKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for ConfounderKind {
    type Err = ParseCausalValueError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_causal_token(input).as_str() {
            "selection_bias" => Ok(Self::SelectionBias),
            "task_difficulty" => Ok(Self::TaskDifficulty),
            "agent_skill" => Ok(Self::AgentSkill),
            "time_trend" => Ok(Self::TimeTrend),
            "tooling_change" => Ok(Self::ToolingChange),
            "external_intervention" => Ok(Self::ExternalIntervention),
            _ => Err(ParseCausalValueError::new(
                "confounder_kind",
                input,
                "selection_bias, task_difficulty, agent_skill, time_trend, tooling_change, external_intervention",
            )),
        }
    }
}

/// Planned action for a promotion plan.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum PromotionAction {
    Promote,
    Hold,
    Demote,
    Archive,
    Quarantine,
}

impl PromotionAction {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Promote => "promote",
            Self::Hold => "hold",
            Self::Demote => "demote",
            Self::Archive => "archive",
            Self::Quarantine => "quarantine",
        }
    }

    #[must_use]
    pub const fn all() -> [Self; 5] {
        [
            Self::Promote,
            Self::Hold,
            Self::Demote,
            Self::Archive,
            Self::Quarantine,
        ]
    }
}

impl fmt::Display for PromotionAction {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for PromotionAction {
    type Err = ParseCausalValueError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_causal_token(input).as_str() {
            "promote" => Ok(Self::Promote),
            "hold" => Ok(Self::Hold),
            "demote" => Ok(Self::Demote),
            "archive" => Ok(Self::Archive),
            "quarantine" => Ok(Self::Quarantine),
            _ => Err(ParseCausalValueError::new(
                "promotion_action",
                input,
                "promote, hold, demote, archive, quarantine",
            )),
        }
    }
}

/// Lifecycle status for a promotion plan.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum PromotionPlanStatus {
    Proposed,
    DryRunReady,
    Approved,
    Applied,
    Rejected,
    Superseded,
}

impl PromotionPlanStatus {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Proposed => "proposed",
            Self::DryRunReady => "dry_run_ready",
            Self::Approved => "approved",
            Self::Applied => "applied",
            Self::Rejected => "rejected",
            Self::Superseded => "superseded",
        }
    }

    #[must_use]
    pub const fn all() -> [Self; 6] {
        [
            Self::Proposed,
            Self::DryRunReady,
            Self::Approved,
            Self::Applied,
            Self::Rejected,
            Self::Superseded,
        ]
    }
}

impl fmt::Display for PromotionPlanStatus {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for PromotionPlanStatus {
    type Err = ParseCausalValueError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_causal_token(input).as_str() {
            "proposed" => Ok(Self::Proposed),
            "dry_run_ready" => Ok(Self::DryRunReady),
            "approved" => Ok(Self::Approved),
            "applied" => Ok(Self::Applied),
            "rejected" => Ok(Self::Rejected),
            "superseded" => Ok(Self::Superseded),
            _ => Err(ParseCausalValueError::new(
                "promotion_plan_status",
                input,
                "proposed, dry_run_ready, approved, applied, rejected, superseded",
            )),
        }
    }
}

/// Error returned when a stable causal wire value cannot be parsed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseCausalValueError {
    field: &'static str,
    value: String,
    expected: &'static str,
}

impl ParseCausalValueError {
    #[must_use]
    pub fn new(field: &'static str, value: impl Into<String>, expected: &'static str) -> Self {
        Self {
            field,
            value: value.into(),
            expected,
        }
    }

    #[must_use]
    pub const fn field(&self) -> &'static str {
        self.field
    }

    #[must_use]
    pub fn value(&self) -> &str {
        &self.value
    }

    #[must_use]
    pub const fn expected(&self) -> &'static str {
        self.expected
    }
}

impl fmt::Display for ParseCausalValueError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "invalid {} value '{}'; expected one of: {}",
            self.field, self.value, self.expected
        )
    }
}

impl std::error::Error for ParseCausalValueError {}

// ============================================================================
// Domain Records
// ============================================================================

/// Exposure of a memory or artifact to an agent decision.
#[derive(Clone, Debug, PartialEq)]
pub struct CausalExposure {
    pub schema: &'static str,
    pub exposure_id: String,
    pub artifact_id: String,
    pub artifact_kind: String,
    pub decision_id: String,
    pub channel: CausalExposureChannel,
    pub exposed_at: String,
    pub rank: Option<u32>,
    pub policy_id: Option<String>,
    pub context_pack_id: Option<String>,
    pub trace_id: Option<String>,
    pub evidence_ids: Vec<String>,
}

impl CausalExposure {
    #[must_use]
    pub fn new(
        exposure_id: impl Into<String>,
        artifact_id: impl Into<String>,
        artifact_kind: impl Into<String>,
        decision_id: impl Into<String>,
        channel: CausalExposureChannel,
        exposed_at: impl Into<String>,
    ) -> Self {
        Self {
            schema: CAUSAL_EXPOSURE_SCHEMA_V1,
            exposure_id: exposure_id.into(),
            artifact_id: artifact_id.into(),
            artifact_kind: artifact_kind.into(),
            decision_id: decision_id.into(),
            channel,
            exposed_at: exposed_at.into(),
            rank: None,
            policy_id: None,
            context_pack_id: None,
            trace_id: None,
            evidence_ids: Vec::new(),
        }
    }

    #[must_use]
    pub const fn with_rank(mut self, rank: u32) -> Self {
        self.rank = Some(rank);
        self
    }

    #[must_use]
    pub fn with_policy(mut self, policy_id: impl Into<String>) -> Self {
        self.policy_id = Some(policy_id.into());
        self
    }

    #[must_use]
    pub fn with_context_pack(mut self, context_pack_id: impl Into<String>) -> Self {
        self.context_pack_id = Some(context_pack_id.into());
        self
    }

    #[must_use]
    pub fn with_trace(mut self, trace_id: impl Into<String>) -> Self {
        self.trace_id = Some(trace_id.into());
        self
    }

    #[must_use]
    pub fn with_evidence(mut self, evidence_id: impl Into<String>) -> Self {
        self.evidence_ids.push(evidence_id.into());
        self
    }

    #[must_use]
    pub fn data_json(&self) -> JsonValue {
        json!({
            "schema": self.schema,
            "exposureId": self.exposure_id,
            "artifactId": self.artifact_id,
            "artifactKind": self.artifact_kind,
            "decisionId": self.decision_id,
            "channel": self.channel.as_str(),
            "exposedAt": self.exposed_at,
            "rank": self.rank,
            "policyId": self.policy_id,
            "contextPackId": self.context_pack_id,
            "traceId": self.trace_id,
            "evidenceIds": self.evidence_ids,
        })
    }
}

/// Decision trace tying exposures to the action actually taken.
#[derive(Clone, Debug, PartialEq)]
pub struct CausalDecisionTrace {
    pub schema: &'static str,
    pub decision_id: String,
    pub trace_id: String,
    pub plane: DecisionPlane,
    pub decided_at: String,
    pub outcome: DecisionTraceOutcome,
    pub agent: String,
    pub task_id: Option<String>,
    pub policy_id: Option<String>,
    pub exposed_artifact_ids: Vec<String>,
    pub selected_artifact_ids: Vec<String>,
    pub rejected_artifact_ids: Vec<String>,
    pub rationale: String,
    pub evidence_ids: Vec<String>,
}

impl CausalDecisionTrace {
    #[must_use]
    pub fn new(
        decision_id: impl Into<String>,
        trace_id: impl Into<String>,
        plane: DecisionPlane,
        decided_at: impl Into<String>,
        agent: impl Into<String>,
        rationale: impl Into<String>,
    ) -> Self {
        Self {
            schema: DECISION_TRACE_SCHEMA_V1,
            decision_id: decision_id.into(),
            trace_id: trace_id.into(),
            plane,
            decided_at: decided_at.into(),
            outcome: DecisionTraceOutcome::Deferred,
            agent: agent.into(),
            task_id: None,
            policy_id: None,
            exposed_artifact_ids: Vec::new(),
            selected_artifact_ids: Vec::new(),
            rejected_artifact_ids: Vec::new(),
            rationale: rationale.into(),
            evidence_ids: Vec::new(),
        }
    }

    #[must_use]
    pub const fn with_outcome(mut self, outcome: DecisionTraceOutcome) -> Self {
        self.outcome = outcome;
        self
    }

    #[must_use]
    pub fn with_task(mut self, task_id: impl Into<String>) -> Self {
        self.task_id = Some(task_id.into());
        self
    }

    #[must_use]
    pub fn with_policy(mut self, policy_id: impl Into<String>) -> Self {
        self.policy_id = Some(policy_id.into());
        self
    }

    #[must_use]
    pub fn with_exposed_artifact(mut self, artifact_id: impl Into<String>) -> Self {
        self.exposed_artifact_ids.push(artifact_id.into());
        self
    }

    #[must_use]
    pub fn with_selected_artifact(mut self, artifact_id: impl Into<String>) -> Self {
        self.selected_artifact_ids.push(artifact_id.into());
        self
    }

    #[must_use]
    pub fn with_rejected_artifact(mut self, artifact_id: impl Into<String>) -> Self {
        self.rejected_artifact_ids.push(artifact_id.into());
        self
    }

    #[must_use]
    pub fn with_evidence(mut self, evidence_id: impl Into<String>) -> Self {
        self.evidence_ids.push(evidence_id.into());
        self
    }

    #[must_use]
    pub fn data_json(&self) -> JsonValue {
        json!({
            "schema": self.schema,
            "decisionId": self.decision_id,
            "traceId": self.trace_id,
            "plane": self.plane.as_str(),
            "decidedAt": self.decided_at,
            "outcome": self.outcome.as_str(),
            "agent": self.agent,
            "taskId": self.task_id,
            "policyId": self.policy_id,
            "exposedArtifactIds": self.exposed_artifact_ids,
            "selectedArtifactIds": self.selected_artifact_ids,
            "rejectedArtifactIds": self.rejected_artifact_ids,
            "rationale": self.rationale,
            "evidenceIds": self.evidence_ids,
        })
    }
}

/// Bounded estimate of the change associated with artifact exposure.
#[derive(Clone, Debug, PartialEq)]
pub struct UpliftEstimate {
    pub schema: &'static str,
    pub estimate_id: String,
    pub artifact_id: String,
    pub decision_id: String,
    pub baseline_success_rate: f64,
    pub observed_success_rate: f64,
    pub uplift: f64,
    pub direction: UpliftDirection,
    pub confidence: f64,
    pub sample_size: u32,
    pub evidence_strength: CausalEvidenceStrength,
    pub method: String,
    pub exposure_ids: Vec<String>,
    pub confounder_ids: Vec<String>,
    pub estimated_at: String,
}

impl UpliftEstimate {
    #[must_use]
    pub fn new(
        estimate_id: impl Into<String>,
        artifact_id: impl Into<String>,
        decision_id: impl Into<String>,
        method: impl Into<String>,
        estimated_at: impl Into<String>,
    ) -> Self {
        Self {
            schema: UPLIFT_ESTIMATE_SCHEMA_V1,
            estimate_id: estimate_id.into(),
            artifact_id: artifact_id.into(),
            decision_id: decision_id.into(),
            baseline_success_rate: 0.0,
            observed_success_rate: 0.0,
            uplift: 0.0,
            direction: UpliftDirection::Neutral,
            confidence: 0.0,
            sample_size: 0,
            evidence_strength: CausalEvidenceStrength::ExposureOnly,
            method: method.into(),
            exposure_ids: Vec::new(),
            confounder_ids: Vec::new(),
            estimated_at: estimated_at.into(),
        }
    }

    #[must_use]
    pub fn with_rates(mut self, baseline_success_rate: f64, observed_success_rate: f64) -> Self {
        self.baseline_success_rate = bounded_unit(baseline_success_rate);
        self.observed_success_rate = bounded_unit(observed_success_rate);
        self.uplift = bounded_delta(self.observed_success_rate - self.baseline_success_rate);
        self.direction = UpliftDirection::from_uplift(self.uplift);
        self
    }

    #[must_use]
    pub fn with_confidence(mut self, confidence: f64) -> Self {
        self.confidence = bounded_unit(confidence);
        self
    }

    #[must_use]
    pub const fn with_sample_size(mut self, sample_size: u32) -> Self {
        self.sample_size = sample_size;
        self
    }

    #[must_use]
    pub const fn with_evidence_strength(mut self, strength: CausalEvidenceStrength) -> Self {
        self.evidence_strength = strength;
        self
    }

    #[must_use]
    pub fn with_exposure(mut self, exposure_id: impl Into<String>) -> Self {
        self.exposure_ids.push(exposure_id.into());
        self
    }

    #[must_use]
    pub fn with_confounder(mut self, confounder_id: impl Into<String>) -> Self {
        self.confounder_ids.push(confounder_id.into());
        self
    }

    #[must_use]
    pub fn data_json(&self) -> JsonValue {
        json!({
            "schema": self.schema,
            "estimateId": self.estimate_id,
            "artifactId": self.artifact_id,
            "decisionId": self.decision_id,
            "baselineSuccessRate": rounded_metric(self.baseline_success_rate),
            "observedSuccessRate": rounded_metric(self.observed_success_rate),
            "uplift": rounded_metric(self.uplift),
            "direction": self.direction.as_str(),
            "confidence": rounded_metric(self.confidence),
            "sampleSize": self.sample_size,
            "evidenceStrength": self.evidence_strength.as_str(),
            "method": self.method,
            "exposureIds": self.exposure_ids,
            "confounderIds": self.confounder_ids,
            "estimatedAt": self.estimated_at,
        })
    }
}

/// Confounder that may explain apparent causal uplift.
#[derive(Clone, Debug, PartialEq)]
pub struct CausalConfounder {
    pub schema: &'static str,
    pub confounder_id: String,
    pub kind: ConfounderKind,
    pub description: String,
    pub severity: f64,
    pub mitigation: String,
    pub affected_artifact_ids: Vec<String>,
    pub affected_decision_ids: Vec<String>,
    pub evidence_ids: Vec<String>,
}

impl CausalConfounder {
    #[must_use]
    pub fn new(
        confounder_id: impl Into<String>,
        kind: ConfounderKind,
        description: impl Into<String>,
        mitigation: impl Into<String>,
    ) -> Self {
        Self {
            schema: CONFOUNDER_SCHEMA_V1,
            confounder_id: confounder_id.into(),
            kind,
            description: description.into(),
            severity: 0.0,
            mitigation: mitigation.into(),
            affected_artifact_ids: Vec::new(),
            affected_decision_ids: Vec::new(),
            evidence_ids: Vec::new(),
        }
    }

    #[must_use]
    pub fn with_severity(mut self, severity: f64) -> Self {
        self.severity = bounded_unit(severity);
        self
    }

    #[must_use]
    pub fn with_affected_artifact(mut self, artifact_id: impl Into<String>) -> Self {
        self.affected_artifact_ids.push(artifact_id.into());
        self
    }

    #[must_use]
    pub fn with_affected_decision(mut self, decision_id: impl Into<String>) -> Self {
        self.affected_decision_ids.push(decision_id.into());
        self
    }

    #[must_use]
    pub fn with_evidence(mut self, evidence_id: impl Into<String>) -> Self {
        self.evidence_ids.push(evidence_id.into());
        self
    }

    #[must_use]
    pub fn data_json(&self) -> JsonValue {
        json!({
            "schema": self.schema,
            "confounderId": self.confounder_id,
            "kind": self.kind.as_str(),
            "description": self.description,
            "severity": rounded_metric(self.severity),
            "mitigation": self.mitigation,
            "affectedArtifactIds": self.affected_artifact_ids,
            "affectedDecisionIds": self.affected_decision_ids,
            "evidenceIds": self.evidence_ids,
        })
    }
}

/// Dry-run-first plan for changing an artifact's memory posture.
#[derive(Clone, Debug, PartialEq)]
pub struct PromotionPlan {
    pub schema: &'static str,
    pub plan_id: String,
    pub artifact_id: String,
    pub action: PromotionAction,
    pub status: PromotionPlanStatus,
    pub evidence_strength: CausalEvidenceStrength,
    pub minimum_uplift: f64,
    pub estimated_uplift: f64,
    pub required_evidence_ids: Vec<String>,
    pub blocking_confounder_ids: Vec<String>,
    pub dry_run_first: bool,
    pub audit_ids: Vec<String>,
    pub created_at: String,
}

impl PromotionPlan {
    #[must_use]
    pub fn new(
        plan_id: impl Into<String>,
        artifact_id: impl Into<String>,
        action: PromotionAction,
        created_at: impl Into<String>,
    ) -> Self {
        Self {
            schema: PROMOTION_PLAN_SCHEMA_V1,
            plan_id: plan_id.into(),
            artifact_id: artifact_id.into(),
            action,
            status: PromotionPlanStatus::Proposed,
            evidence_strength: CausalEvidenceStrength::ExposureOnly,
            minimum_uplift: 0.0,
            estimated_uplift: 0.0,
            required_evidence_ids: Vec::new(),
            blocking_confounder_ids: Vec::new(),
            dry_run_first: true,
            audit_ids: Vec::new(),
            created_at: created_at.into(),
        }
    }

    #[must_use]
    pub const fn with_status(mut self, status: PromotionPlanStatus) -> Self {
        self.status = status;
        self
    }

    #[must_use]
    pub const fn with_evidence_strength(mut self, strength: CausalEvidenceStrength) -> Self {
        self.evidence_strength = strength;
        self
    }

    #[must_use]
    pub fn with_minimum_uplift(mut self, uplift: f64) -> Self {
        self.minimum_uplift = bounded_delta(uplift);
        self
    }

    #[must_use]
    pub fn with_estimated_uplift(mut self, uplift: f64) -> Self {
        self.estimated_uplift = bounded_delta(uplift);
        self
    }

    #[must_use]
    pub fn with_required_evidence(mut self, evidence_id: impl Into<String>) -> Self {
        self.required_evidence_ids.push(evidence_id.into());
        self
    }

    #[must_use]
    pub fn with_blocking_confounder(mut self, confounder_id: impl Into<String>) -> Self {
        self.blocking_confounder_ids.push(confounder_id.into());
        self
    }

    #[must_use]
    pub const fn without_dry_run_first(mut self) -> Self {
        self.dry_run_first = false;
        self
    }

    #[must_use]
    pub fn with_audit_id(mut self, audit_id: impl Into<String>) -> Self {
        self.audit_ids.push(audit_id.into());
        self
    }

    #[must_use]
    pub fn data_json(&self) -> JsonValue {
        json!({
            "schema": self.schema,
            "planId": self.plan_id,
            "artifactId": self.artifact_id,
            "action": self.action.as_str(),
            "status": self.status.as_str(),
            "evidenceStrength": self.evidence_strength.as_str(),
            "minimumUplift": rounded_metric(self.minimum_uplift),
            "estimatedUplift": rounded_metric(self.estimated_uplift),
            "requiredEvidenceIds": self.required_evidence_ids,
            "blockingConfounderIds": self.blocking_confounder_ids,
            "dryRunFirst": self.dry_run_first,
            "auditIds": self.audit_ids,
            "createdAt": self.created_at,
        })
    }
}

// ============================================================================
// Schema Catalog
// ============================================================================

/// Field descriptor used by the causal schema catalog.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CausalFieldSchema {
    pub name: &'static str,
    pub type_name: &'static str,
    pub required: bool,
    pub description: &'static str,
}

impl CausalFieldSchema {
    #[must_use]
    pub const fn new(
        name: &'static str,
        type_name: &'static str,
        required: bool,
        description: &'static str,
    ) -> Self {
        Self {
            name,
            type_name,
            required,
            description,
        }
    }
}

/// Stable JSON-schema-like catalog entry for causal records.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CausalObjectSchema {
    pub schema_name: &'static str,
    pub schema_uri: &'static str,
    pub kind: &'static str,
    pub title: &'static str,
    pub description: &'static str,
    pub fields: &'static [CausalFieldSchema],
}

impl CausalObjectSchema {
    #[must_use]
    pub fn required_count(&self) -> usize {
        self.fields.iter().filter(|field| field.required).count()
    }
}

const CAUSAL_EXPOSURE_FIELDS: &[CausalFieldSchema] = &[
    CausalFieldSchema::new("schema", "string", true, "Schema identifier."),
    CausalFieldSchema::new("exposureId", "string", true, "Stable exposure identifier."),
    CausalFieldSchema::new(
        "artifactId",
        "string",
        true,
        "Exposed memory or artifact identifier.",
    ),
    CausalFieldSchema::new("artifactKind", "string", true, "Exposed artifact category."),
    CausalFieldSchema::new(
        "decisionId",
        "string",
        true,
        "Decision that received the exposure.",
    ),
    CausalFieldSchema::new("channel", "string", true, "Exposure channel."),
    CausalFieldSchema::new("exposedAt", "string", true, "RFC 3339 exposure timestamp."),
    CausalFieldSchema::new(
        "rank",
        "integer|null",
        false,
        "Rank or slot when exposure was ordered.",
    ),
    CausalFieldSchema::new(
        "policyId",
        "string|null",
        false,
        "Policy active when exposed.",
    ),
    CausalFieldSchema::new(
        "contextPackId",
        "string|null",
        false,
        "Context pack containing the exposure.",
    ),
    CausalFieldSchema::new(
        "traceId",
        "string|null",
        false,
        "Trace linking related decisions.",
    ),
    CausalFieldSchema::new(
        "evidenceIds",
        "array<string>",
        true,
        "Evidence supporting exposure capture.",
    ),
];

const DECISION_TRACE_FIELDS: &[CausalFieldSchema] = &[
    CausalFieldSchema::new("schema", "string", true, "Schema identifier."),
    CausalFieldSchema::new("decisionId", "string", true, "Stable decision identifier."),
    CausalFieldSchema::new(
        "traceId",
        "string",
        true,
        "Trace linking exposures and outcomes.",
    ),
    CausalFieldSchema::new("plane", "string", true, "Decision plane."),
    CausalFieldSchema::new("decidedAt", "string", true, "RFC 3339 decision timestamp."),
    CausalFieldSchema::new(
        "outcome",
        "string",
        true,
        "How the decision treated exposed evidence.",
    ),
    CausalFieldSchema::new(
        "agent",
        "string",
        true,
        "Agent, harness, or tool that made the decision.",
    ),
    CausalFieldSchema::new(
        "taskId",
        "string|null",
        false,
        "Task or run associated with the decision.",
    ),
    CausalFieldSchema::new(
        "policyId",
        "string|null",
        false,
        "Policy that governed the decision.",
    ),
    CausalFieldSchema::new(
        "exposedArtifactIds",
        "array<string>",
        true,
        "Artifacts available to the decision.",
    ),
    CausalFieldSchema::new(
        "selectedArtifactIds",
        "array<string>",
        true,
        "Artifacts actually used.",
    ),
    CausalFieldSchema::new(
        "rejectedArtifactIds",
        "array<string>",
        true,
        "Artifacts rejected or ignored.",
    ),
    CausalFieldSchema::new(
        "rationale",
        "string",
        true,
        "Decision rationale or explanation.",
    ),
    CausalFieldSchema::new(
        "evidenceIds",
        "array<string>",
        true,
        "Evidence supporting the trace.",
    ),
];

const UPLIFT_ESTIMATE_FIELDS: &[CausalFieldSchema] = &[
    CausalFieldSchema::new("schema", "string", true, "Schema identifier."),
    CausalFieldSchema::new(
        "estimateId",
        "string",
        true,
        "Stable uplift estimate identifier.",
    ),
    CausalFieldSchema::new(
        "artifactId",
        "string",
        true,
        "Artifact whose influence is estimated.",
    ),
    CausalFieldSchema::new(
        "decisionId",
        "string",
        true,
        "Decision or decision class being estimated.",
    ),
    CausalFieldSchema::new(
        "baselineSuccessRate",
        "number",
        true,
        "Baseline outcome rate from 0.0 to 1.0.",
    ),
    CausalFieldSchema::new(
        "observedSuccessRate",
        "number",
        true,
        "Observed outcome rate from 0.0 to 1.0.",
    ),
    CausalFieldSchema::new(
        "uplift",
        "number",
        true,
        "Observed minus baseline rate from -1.0 to 1.0.",
    ),
    CausalFieldSchema::new(
        "direction",
        "string",
        true,
        "Direction of the uplift estimate.",
    ),
    CausalFieldSchema::new("confidence", "number", true, "Confidence from 0.0 to 1.0."),
    CausalFieldSchema::new(
        "sampleSize",
        "integer",
        true,
        "Number of observations used.",
    ),
    CausalFieldSchema::new(
        "evidenceStrength",
        "string",
        true,
        "Strength of causal evidence.",
    ),
    CausalFieldSchema::new("method", "string", true, "Deterministic estimation method."),
    CausalFieldSchema::new(
        "exposureIds",
        "array<string>",
        true,
        "Exposure records used by the estimate.",
    ),
    CausalFieldSchema::new(
        "confounderIds",
        "array<string>",
        true,
        "Known confounders considered.",
    ),
    CausalFieldSchema::new(
        "estimatedAt",
        "string",
        true,
        "RFC 3339 estimate timestamp.",
    ),
];

const CONFOUNDER_FIELDS: &[CausalFieldSchema] = &[
    CausalFieldSchema::new("schema", "string", true, "Schema identifier."),
    CausalFieldSchema::new(
        "confounderId",
        "string",
        true,
        "Stable confounder identifier.",
    ),
    CausalFieldSchema::new("kind", "string", true, "Confounder class."),
    CausalFieldSchema::new(
        "description",
        "string",
        true,
        "Why this can explain apparent uplift.",
    ),
    CausalFieldSchema::new("severity", "number", true, "Severity from 0.0 to 1.0."),
    CausalFieldSchema::new(
        "mitigation",
        "string",
        true,
        "How to control or account for the confounder.",
    ),
    CausalFieldSchema::new(
        "affectedArtifactIds",
        "array<string>",
        true,
        "Artifacts affected by this confounder.",
    ),
    CausalFieldSchema::new(
        "affectedDecisionIds",
        "array<string>",
        true,
        "Decisions affected by this confounder.",
    ),
    CausalFieldSchema::new(
        "evidenceIds",
        "array<string>",
        true,
        "Evidence supporting the confounder.",
    ),
];

const PROMOTION_PLAN_FIELDS: &[CausalFieldSchema] = &[
    CausalFieldSchema::new("schema", "string", true, "Schema identifier."),
    CausalFieldSchema::new(
        "planId",
        "string",
        true,
        "Stable promotion plan identifier.",
    ),
    CausalFieldSchema::new(
        "artifactId",
        "string",
        true,
        "Artifact targeted by the plan.",
    ),
    CausalFieldSchema::new("action", "string", true, "Planned memory posture action."),
    CausalFieldSchema::new("status", "string", true, "Promotion plan lifecycle status."),
    CausalFieldSchema::new(
        "evidenceStrength",
        "string",
        true,
        "Evidence strength required by the plan.",
    ),
    CausalFieldSchema::new(
        "minimumUplift",
        "number",
        true,
        "Minimum uplift threshold from -1.0 to 1.0.",
    ),
    CausalFieldSchema::new(
        "estimatedUplift",
        "number",
        true,
        "Current estimated uplift from -1.0 to 1.0.",
    ),
    CausalFieldSchema::new(
        "requiredEvidenceIds",
        "array<string>",
        true,
        "Evidence required before applying the plan.",
    ),
    CausalFieldSchema::new(
        "blockingConfounderIds",
        "array<string>",
        true,
        "Confounders blocking promotion.",
    ),
    CausalFieldSchema::new(
        "dryRunFirst",
        "boolean",
        true,
        "Whether dry-run verification is required before mutation.",
    ),
    CausalFieldSchema::new(
        "auditIds",
        "array<string>",
        true,
        "Audit records attached to the plan.",
    ),
    CausalFieldSchema::new("createdAt", "string", true, "RFC 3339 creation timestamp."),
];

#[must_use]
pub const fn causal_schemas() -> [CausalObjectSchema; 5] {
    [
        CausalObjectSchema {
            schema_name: CAUSAL_EXPOSURE_SCHEMA_V1,
            schema_uri: "urn:ee:schema:causal-exposure:v1",
            kind: "causal_exposure",
            title: "CausalExposure",
            description: "Exposure of a memory or artifact to an agent decision.",
            fields: CAUSAL_EXPOSURE_FIELDS,
        },
        CausalObjectSchema {
            schema_name: DECISION_TRACE_SCHEMA_V1,
            schema_uri: "urn:ee:schema:causal-decision-trace:v1",
            kind: "decision_trace",
            title: "CausalDecisionTrace",
            description: "Decision trace tying exposed artifacts to selected and rejected evidence.",
            fields: DECISION_TRACE_FIELDS,
        },
        CausalObjectSchema {
            schema_name: UPLIFT_ESTIMATE_SCHEMA_V1,
            schema_uri: "urn:ee:schema:causal-uplift-estimate:v1",
            kind: "uplift_estimate",
            title: "UpliftEstimate",
            description: "Bounded estimate of outcome change associated with an artifact exposure.",
            fields: UPLIFT_ESTIMATE_FIELDS,
        },
        CausalObjectSchema {
            schema_name: CONFOUNDER_SCHEMA_V1,
            schema_uri: "urn:ee:schema:causal-confounder:v1",
            kind: "confounder",
            title: "CausalConfounder",
            description: "Alternative explanation that can weaken or block causal claims.",
            fields: CONFOUNDER_FIELDS,
        },
        CausalObjectSchema {
            schema_name: PROMOTION_PLAN_SCHEMA_V1,
            schema_uri: "urn:ee:schema:causal-promotion-plan:v1",
            kind: "promotion_plan",
            title: "PromotionPlan",
            description: "Dry-run-first plan for promotion, demotion, archive, or quarantine decisions.",
            fields: PROMOTION_PLAN_FIELDS,
        },
    ]
}

#[must_use]
pub fn causal_schema_catalog_json() -> String {
    let schemas = causal_schemas();
    let mut output = String::from("{\n");
    output.push_str(&format!("  \"schema\": \"{CAUSAL_SCHEMA_CATALOG_V1}\",\n"));
    output.push_str("  \"schemas\": [\n");
    for (schema_index, schema) in schemas.iter().enumerate() {
        output.push_str("    {\n");
        output.push_str(&format!(
            "      \"$schema\": \"{JSON_SCHEMA_DRAFT_2020_12}\",\n"
        ));
        output.push_str("      \"$id\": ");
        push_json_string(&mut output, schema.schema_uri);
        output.push_str(",\n");
        output.push_str("      \"eeSchema\": ");
        push_json_string(&mut output, schema.schema_name);
        output.push_str(",\n");
        output.push_str("      \"kind\": ");
        push_json_string(&mut output, schema.kind);
        output.push_str(",\n");
        output.push_str("      \"title\": ");
        push_json_string(&mut output, schema.title);
        output.push_str(",\n");
        output.push_str("      \"description\": ");
        push_json_string(&mut output, schema.description);
        output.push_str(",\n");
        output.push_str("      \"type\": \"object\",\n");
        output.push_str("      \"required\": [\n");
        let mut emitted_required = 0;
        for field in schema.fields {
            if field.required {
                emitted_required += 1;
                output.push_str("        ");
                push_json_string(&mut output, field.name);
                if emitted_required == schema.required_count() {
                    output.push('\n');
                } else {
                    output.push_str(",\n");
                }
            }
        }
        output.push_str("      ],\n");
        output.push_str("      \"fields\": [\n");
        for (field_index, field) in schema.fields.iter().enumerate() {
            output.push_str("        {\"name\": ");
            push_json_string(&mut output, field.name);
            output.push_str(", \"type\": ");
            push_json_string(&mut output, field.type_name);
            output.push_str(", \"required\": ");
            output.push_str(if field.required { "true" } else { "false" });
            output.push_str(", \"description\": ");
            push_json_string(&mut output, field.description);
            if field_index + 1 == schema.fields.len() {
                output.push_str("}\n");
            } else {
                output.push_str("},\n");
            }
        }
        output.push_str("      ],\n");
        output.push_str("      \"additionalProperties\": false\n");
        if schema_index + 1 == schemas.len() {
            output.push_str("    }\n");
        } else {
            output.push_str("    },\n");
        }
    }
    output.push_str("  ]\n");
    output.push_str("}\n");
    output
}

fn push_json_string(output: &mut String, value: &str) {
    output.push('"');
    for character in value.chars() {
        match character {
            '"' => output.push_str("\\\""),
            '\\' => output.push_str("\\\\"),
            '\n' => output.push_str("\\n"),
            '\r' => output.push_str("\\r"),
            '\t' => output.push_str("\\t"),
            other if (other as u32) < 0x20 => {
                use std::fmt::Write;
                let _ = write!(output, "\\u{:04x}", other as u32);
            }
            other => output.push(other),
        }
    }
    output.push('"');
}

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

    const CAUSAL_SCHEMA_GOLDEN: &str =
        include_str!("../../tests/fixtures/golden/models/causal_schemas.json.golden");

    type TestResult = Result<(), String>;

    fn ensure<T: std::fmt::Debug + PartialEq>(actual: T, expected: T, ctx: &str) -> TestResult {
        if actual == expected {
            Ok(())
        } else {
            Err(format!("{ctx}: expected {expected:?}, got {actual:?}"))
        }
    }

    #[test]
    fn causal_schema_constants_are_stable() -> TestResult {
        ensure(CAUSAL_TRACE_SCHEMA_V1, "ee.causal.trace.v1", "trace report")?;
        ensure(
            CAUSAL_EXPOSURE_SCHEMA_V1,
            "ee.causal.exposure.v1",
            "exposure",
        )?;
        ensure(
            DECISION_TRACE_SCHEMA_V1,
            "ee.causal.decision_trace.v1",
            "decision trace",
        )?;
        ensure(
            UPLIFT_ESTIMATE_SCHEMA_V1,
            "ee.causal.uplift_estimate.v1",
            "uplift",
        )?;
        ensure(
            CONFOUNDER_SCHEMA_V1,
            "ee.causal.confounder.v1",
            "confounder",
        )?;
        ensure(
            PROMOTION_PLAN_SCHEMA_V1,
            "ee.causal.promotion_plan.v1",
            "promotion plan",
        )?;
        ensure(CAUSAL_SCHEMA_CATALOG_V1, "ee.causal.schemas.v1", "catalog")
    }

    #[test]
    fn stable_wire_enums_round_trip() -> TestResult {
        for channel in CausalExposureChannel::all() {
            ensure(
                CausalExposureChannel::from_str(channel.as_str()),
                Ok(channel),
                "channel",
            )?;
        }
        for outcome in DecisionTraceOutcome::all() {
            ensure(
                DecisionTraceOutcome::from_str(outcome.as_str()),
                Ok(outcome),
                "outcome",
            )?;
        }
        for method in CausalEvidenceMethod::all() {
            ensure(
                CausalEvidenceMethod::from_str(method.as_str()),
                Ok(method),
                "method",
            )?;
        }
        for strength in CausalEvidenceStrength::all() {
            ensure(
                CausalEvidenceStrength::from_str(strength.as_str()),
                Ok(strength),
                "strength",
            )?;
        }
        for direction in UpliftDirection::all() {
            ensure(
                UpliftDirection::from_str(direction.as_str()),
                Ok(direction),
                "direction",
            )?;
        }
        for kind in ConfounderKind::all() {
            ensure(
                ConfounderKind::from_str(kind.as_str()),
                Ok(kind),
                "confounder kind",
            )?;
        }
        for action in PromotionAction::all() {
            ensure(
                PromotionAction::from_str(action.as_str()),
                Ok(action),
                "action",
            )?;
        }
        for status in PromotionPlanStatus::all() {
            ensure(
                PromotionPlanStatus::from_str(status.as_str()),
                Ok(status),
                "status",
            )?;
        }
        ensure(
            PromotionAction::from_str("ship").map_err(|error| error.field()),
            Err("promotion_action"),
            "invalid action field",
        )
    }

    #[test]
    fn stable_wire_enums_accept_operator_spelling_variants() -> TestResult {
        ensure(
            CausalExposureChannel::from_str(" Context-Pack "),
            Ok(CausalExposureChannel::ContextPack),
            "channel alias",
        )?;
        ensure(
            CausalExposureChannel::from_str("contextPack"),
            Ok(CausalExposureChannel::ContextPack),
            "channel camelCase alias",
        )?;
        ensure(
            CausalExposureChannel::from_str("ManualReference"),
            Ok(CausalExposureChannel::ManualReference),
            "channel PascalCase alias",
        )?;
        ensure(
            DecisionTraceOutcome::from_str("USED"),
            Ok(DecisionTraceOutcome::Used),
            "outcome alias",
        )?;
        ensure(
            CausalEvidenceMethod::from_str("graph_inferred"),
            Ok(CausalEvidenceMethod::GraphInferred),
            "method alias",
        )?;
        ensure(
            CausalEvidenceMethod::from_str("GraphInferred"),
            Ok(CausalEvidenceMethod::GraphInferred),
            "method PascalCase alias",
        )?;
        ensure(
            CausalEvidenceStrength::from_str("Replay-Supported"),
            Ok(CausalEvidenceStrength::ReplaySupported),
            "strength alias",
        )?;
        ensure(
            CausalEvidenceStrength::from_str("experimentSupported"),
            Ok(CausalEvidenceStrength::ExperimentSupported),
            "strength camelCase alias",
        )?;
        ensure(
            UpliftDirection::from_str(" Positive "),
            Ok(UpliftDirection::Positive),
            "direction alias",
        )?;
        ensure(
            ConfounderKind::from_str("tooling-change"),
            Ok(ConfounderKind::ToolingChange),
            "confounder alias",
        )?;
        ensure(
            ConfounderKind::from_str("ExternalIntervention"),
            Ok(ConfounderKind::ExternalIntervention),
            "confounder PascalCase alias",
        )?;
        ensure(
            PromotionAction::from_str("QUARANTINE"),
            Ok(PromotionAction::Quarantine),
            "action alias",
        )?;
        ensure(
            PromotionPlanStatus::from_str("dry-run-ready"),
            Ok(PromotionPlanStatus::DryRunReady),
            "status alias",
        )?;
        ensure(
            PromotionPlanStatus::from_str("dryRunReady"),
            Ok(PromotionPlanStatus::DryRunReady),
            "status camelCase alias",
        )
    }

    #[test]
    fn causal_record_builders_set_schemas_and_defaults() -> TestResult {
        let exposure = CausalExposure::new(
            "cxp-001",
            "mem-release",
            "memory",
            "dec-001",
            CausalExposureChannel::ContextPack,
            "2026-04-30T12:00:00Z",
        )
        .with_rank(2)
        .with_policy("policy-default")
        .with_context_pack("pack-001")
        .with_trace("trace-001")
        .with_evidence("ev-001");
        ensure(
            exposure.schema,
            CAUSAL_EXPOSURE_SCHEMA_V1,
            "exposure schema",
        )?;
        ensure(exposure.rank, Some(2), "rank")?;

        let trace = CausalDecisionTrace::new(
            "dec-001",
            "trace-001",
            DecisionPlane::Packing,
            "2026-04-30T12:01:00Z",
            "codex",
            "Selected release memory for the pack.",
        )
        .with_outcome(DecisionTraceOutcome::Used)
        .with_task("task-001")
        .with_policy("policy-default")
        .with_exposed_artifact("mem-release")
        .with_selected_artifact("mem-release")
        .with_rejected_artifact("mem-old")
        .with_evidence("ev-002");
        ensure(trace.schema, DECISION_TRACE_SCHEMA_V1, "trace schema")?;
        ensure(trace.outcome, DecisionTraceOutcome::Used, "trace outcome")?;

        let estimate = UpliftEstimate::new(
            "uplift-001",
            "mem-release",
            "dec-001",
            "replay_fixture",
            "2026-04-30T12:02:00Z",
        )
        .with_rates(0.25, 0.7)
        .with_confidence(2.0)
        .with_sample_size(8)
        .with_evidence_strength(CausalEvidenceStrength::ReplaySupported)
        .with_exposure("cxp-001")
        .with_confounder("conf-001");
        ensure(
            estimate.schema,
            UPLIFT_ESTIMATE_SCHEMA_V1,
            "estimate schema",
        )?;
        ensure(estimate.confidence, 1.0, "confidence clamp")?;
        ensure(estimate.uplift, 0.44999999999999996, "uplift")?;
        ensure(estimate.direction, UpliftDirection::Positive, "direction")?;

        let confounder = CausalConfounder::new(
            "conf-001",
            ConfounderKind::TaskDifficulty,
            "Release tasks in the sample were easier than baseline.",
            "Stratify future estimates by task difficulty.",
        )
        .with_severity(1.7)
        .with_affected_artifact("mem-release")
        .with_affected_decision("dec-001")
        .with_evidence("ev-003");
        ensure(confounder.schema, CONFOUNDER_SCHEMA_V1, "confounder schema")?;
        ensure(confounder.severity, 1.0, "severity clamp")?;

        let plan = PromotionPlan::new(
            "prom-001",
            "mem-release",
            PromotionAction::Promote,
            "2026-04-30T12:03:00Z",
        )
        .with_status(PromotionPlanStatus::DryRunReady)
        .with_evidence_strength(CausalEvidenceStrength::ReplaySupported)
        .with_minimum_uplift(-2.0)
        .with_estimated_uplift(0.45)
        .with_required_evidence("ev-004")
        .with_blocking_confounder("conf-001")
        .with_audit_id("audit-001");
        ensure(plan.schema, PROMOTION_PLAN_SCHEMA_V1, "plan schema")?;
        ensure(plan.dry_run_first, true, "dry-run-first default")?;
        ensure(plan.minimum_uplift, -1.0, "minimum uplift clamp")
    }

    #[test]
    fn data_json_uses_stable_wire_names() -> TestResult {
        let estimate = UpliftEstimate::new(
            "uplift-001",
            "mem-release",
            "dec-001",
            "replay_fixture",
            "2026-04-30T12:02:00Z",
        )
        .with_rates(0.33333, 0.77777)
        .with_confidence(0.81234)
        .with_evidence_strength(CausalEvidenceStrength::ReplaySupported);

        let json = estimate.data_json();
        ensure(
            json.get("schema").and_then(serde_json::Value::as_str),
            Some(UPLIFT_ESTIMATE_SCHEMA_V1),
            "schema",
        )?;
        ensure(
            json.get("evidenceStrength")
                .and_then(serde_json::Value::as_str),
            Some("replay_supported"),
            "evidence strength",
        )?;
        ensure(
            json.get("uplift").and_then(serde_json::Value::as_f64),
            Some(0.444),
            "rounded uplift",
        )?;
        ensure(
            json.get("direction").and_then(serde_json::Value::as_str),
            Some("positive"),
            "direction",
        )
    }

    #[test]
    fn causal_schema_catalog_order_is_stable() -> TestResult {
        let schemas = causal_schemas();
        ensure(schemas.len(), 5, "schema count")?;
        ensure(
            schemas[0].schema_name,
            CAUSAL_EXPOSURE_SCHEMA_V1,
            "exposure",
        )?;
        ensure(
            schemas[1].schema_name,
            DECISION_TRACE_SCHEMA_V1,
            "decision trace",
        )?;
        ensure(schemas[2].schema_name, UPLIFT_ESTIMATE_SCHEMA_V1, "uplift")?;
        ensure(schemas[3].schema_name, CONFOUNDER_SCHEMA_V1, "confounder")?;
        ensure(
            schemas[4].schema_name,
            PROMOTION_PLAN_SCHEMA_V1,
            "promotion plan",
        )
    }

    #[test]
    fn causal_schema_catalog_matches_golden_fixture() {
        assert_eq!(causal_schema_catalog_json(), CAUSAL_SCHEMA_GOLDEN);
    }

    #[test]
    fn causal_schema_catalog_is_valid_json() -> TestResult {
        let parsed: serde_json::Value = serde_json::from_str(CAUSAL_SCHEMA_GOLDEN)
            .map_err(|error| format!("causal schema golden must be valid JSON: {error}"))?;
        ensure(
            parsed.get("schema").and_then(serde_json::Value::as_str),
            Some(CAUSAL_SCHEMA_CATALOG_V1),
            "catalog schema",
        )?;
        let schemas = parsed
            .get("schemas")
            .and_then(serde_json::Value::as_array)
            .ok_or_else(|| "schemas must be an array".to_string())?;
        ensure(schemas.len(), 5, "catalog length")
    }
}