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
//! Task episode and counterfactual memory schemas (EE-380).
//!
//! Replay frozen task episodes with alternate memory interventions to
//! discover what would plausibly have prevented failures without mutating
//! durable memory state.
//!
//! Core concepts:
//!
//! * **Task episode**: A frozen snapshot of a task execution including
//!   inputs, context, actions, and outcome. Episodes are immutable once
//!   captured.
//! * **Intervention**: A hypothetical memory mutation (add, remove,
//!   strengthen, weaken) to test counterfactual scenarios.
//! * **Counterfactual run**: Replay an episode with one or more
//!   interventions applied, producing a hypothetical outcome.
//! * **Regret ledger**: A record of interventions that would have
//!   plausibly changed outcomes, with confidence scores.

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

fn normalized_episode_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
}

/// Schema version for task episode.
pub const TASK_EPISODE_SCHEMA_V1: &str = "ee.task_episode.v1";

/// Schema version for intervention.
pub const INTERVENTION_SCHEMA_V1: &str = "ee.intervention.v1";

/// Schema version for counterfactual run.
pub const COUNTERFACTUAL_RUN_SCHEMA_V1: &str = "ee.counterfactual_run.v1";

/// Schema version for regret ledger.
pub const REGRET_LEDGER_SCHEMA_V1: &str = "ee.regret_ledger.v1";

/// Schema version for regret entry.
pub const REGRET_ENTRY_SCHEMA_V1: &str = "ee.regret_entry.v1";

/// ID prefix for task episodes.
pub const EPISODE_ID_PREFIX: &str = "ep_";

/// ID prefix for interventions.
pub const INTERVENTION_ID_PREFIX: &str = "int_";

/// ID prefix for counterfactual runs.
pub const COUNTERFACTUAL_RUN_ID_PREFIX: &str = "cfr_";

/// ID prefix for regret entries.
pub const REGRET_ENTRY_ID_PREFIX: &str = "reg_";

/// A frozen snapshot of a task execution.
///
/// Episodes capture the complete context of a task at execution time,
/// including the input prompt, retrieved memories, actions taken, and
/// final outcome. They are immutable once captured and serve as the
/// baseline for counterfactual analysis.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct TaskEpisode {
    /// Schema identifier.
    pub schema: &'static str,
    /// Unique episode ID.
    pub id: String,
    /// Workspace where this episode occurred.
    pub workspace_id: Option<String>,
    /// Session ID if imported from CASS.
    pub session_id: Option<String>,
    /// The original task input/prompt.
    pub task_input: String,
    /// IDs of memories retrieved during this task.
    pub retrieved_memory_ids: Vec<String>,
    /// Context pack ID if one was generated.
    pub context_pack_id: Option<String>,
    /// Sequence of actions taken during the task.
    pub actions: Vec<EpisodeAction>,
    /// Final outcome of the task.
    pub outcome: EpisodeOutcome,
    /// Timestamp when task started (RFC 3339).
    pub started_at: String,
    /// Timestamp when task ended (RFC 3339).
    pub ended_at: Option<String>,
    /// Duration in milliseconds.
    pub duration_ms: Option<u64>,
    /// Agent that executed this task.
    pub agent: Option<String>,
    /// Hash of the frozen episode for integrity.
    pub episode_hash: Option<String>,
}

impl TaskEpisode {
    /// Create a new task episode.
    #[must_use]
    pub fn new(
        id: impl Into<String>,
        task_input: impl Into<String>,
        started_at: impl Into<String>,
    ) -> Self {
        Self {
            schema: TASK_EPISODE_SCHEMA_V1,
            id: id.into(),
            task_input: task_input.into(),
            started_at: started_at.into(),
            outcome: EpisodeOutcome::Unknown,
            ..Default::default()
        }
    }

    /// Set the workspace ID.
    #[must_use]
    pub fn with_workspace_id(mut self, id: impl Into<String>) -> Self {
        self.workspace_id = Some(id.into());
        self
    }

    /// Set the session ID.
    #[must_use]
    pub fn with_session_id(mut self, id: impl Into<String>) -> Self {
        self.session_id = Some(id.into());
        self
    }

    /// Set the context pack ID.
    #[must_use]
    pub fn with_context_pack_id(mut self, id: impl Into<String>) -> Self {
        self.context_pack_id = Some(id.into());
        self
    }

    /// Add a retrieved memory ID.
    pub fn add_retrieved_memory(&mut self, id: impl Into<String>) {
        self.retrieved_memory_ids.push(id.into());
    }

    /// Add an action.
    pub fn add_action(&mut self, action: EpisodeAction) {
        self.actions.push(action);
    }

    /// Set the outcome.
    #[must_use]
    pub fn with_outcome(mut self, outcome: EpisodeOutcome) -> Self {
        self.outcome = outcome;
        self
    }

    /// Set the ended timestamp.
    #[must_use]
    pub fn with_ended_at(mut self, ts: impl Into<String>) -> Self {
        self.ended_at = Some(ts.into());
        self
    }

    /// Set the duration.
    #[must_use]
    pub fn with_duration_ms(mut self, ms: u64) -> Self {
        self.duration_ms = Some(ms);
        self
    }

    /// Set the agent.
    #[must_use]
    pub fn with_agent(mut self, agent: impl Into<String>) -> Self {
        self.agent = Some(agent.into());
        self
    }

    /// Set the episode hash.
    #[must_use]
    pub fn with_episode_hash(mut self, hash: impl Into<String>) -> Self {
        self.episode_hash = Some(hash.into());
        self
    }
}

/// An action taken during a task episode.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EpisodeAction {
    /// Action sequence number within the episode.
    pub sequence: u32,
    /// Type of action (tool_call, edit, command, etc.).
    pub action_type: ActionType,
    /// Brief description of the action.
    pub description: String,
    /// Timestamp (RFC 3339).
    pub timestamp: String,
    /// Whether the action succeeded.
    pub succeeded: bool,
    /// Error message if action failed.
    pub error: Option<String>,
}

impl EpisodeAction {
    /// Create a new action.
    #[must_use]
    pub fn new(
        sequence: u32,
        action_type: ActionType,
        description: impl Into<String>,
        timestamp: impl Into<String>,
    ) -> Self {
        Self {
            sequence,
            action_type,
            description: description.into(),
            timestamp: timestamp.into(),
            succeeded: true,
            error: None,
        }
    }

    /// Mark as failed with error.
    #[must_use]
    pub fn with_error(mut self, err: impl Into<String>) -> Self {
        self.succeeded = false;
        self.error = Some(err.into());
        self
    }
}

/// Type of action in a task episode.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum ActionType {
    /// A tool was called.
    ToolCall,
    /// A file was edited.
    Edit,
    /// A command was run.
    Command,
    /// A search was performed.
    Search,
    /// Memory was retrieved.
    Retrieval,
    /// Output was generated.
    Output,
    /// Unknown or other action.
    #[default]
    Other,
}

impl ActionType {
    /// Stable string representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ToolCall => "tool_call",
            Self::Edit => "edit",
            Self::Command => "command",
            Self::Search => "search",
            Self::Retrieval => "retrieval",
            Self::Output => "output",
            Self::Other => "other",
        }
    }
}

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

impl FromStr for ActionType {
    type Err = ParseActionTypeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match normalized_episode_token(s).as_str() {
            "tool_call" => Ok(Self::ToolCall),
            "edit" => Ok(Self::Edit),
            "command" => Ok(Self::Command),
            "search" => Ok(Self::Search),
            "retrieval" => Ok(Self::Retrieval),
            "output" => Ok(Self::Output),
            "other" => Ok(Self::Other),
            _ => Err(ParseActionTypeError {
                input: s.to_owned(),
            }),
        }
    }
}

/// Error parsing an action type.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseActionTypeError {
    input: String,
}

impl fmt::Display for ParseActionTypeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown action type `{}`; expected tool_call, edit, command, search, retrieval, output, or other",
            self.input
        )
    }
}

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

/// Outcome of a task episode.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum EpisodeOutcome {
    /// Task completed successfully.
    Success,
    /// Task failed.
    Failure,
    /// Task was cancelled.
    Cancelled,
    /// Task timed out.
    Timeout,
    /// Task outcome is unknown.
    #[default]
    Unknown,
}

impl EpisodeOutcome {
    /// Stable string representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Success => "success",
            Self::Failure => "failure",
            Self::Cancelled => "cancelled",
            Self::Timeout => "timeout",
            Self::Unknown => "unknown",
        }
    }

    /// Whether the outcome is considered negative (failure, cancelled, timeout).
    #[must_use]
    pub const fn is_negative(self) -> bool {
        matches!(self, Self::Failure | Self::Cancelled | Self::Timeout)
    }
}

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

impl FromStr for EpisodeOutcome {
    type Err = ParseEpisodeOutcomeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match normalized_episode_token(s).as_str() {
            "success" => Ok(Self::Success),
            "failure" => Ok(Self::Failure),
            "cancelled" => Ok(Self::Cancelled),
            "timeout" => Ok(Self::Timeout),
            "unknown" => Ok(Self::Unknown),
            _ => Err(ParseEpisodeOutcomeError {
                input: s.to_owned(),
            }),
        }
    }
}

/// Error parsing an episode outcome.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseEpisodeOutcomeError {
    input: String,
}

impl fmt::Display for ParseEpisodeOutcomeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown episode outcome `{}`; expected success, failure, cancelled, timeout, or unknown",
            self.input
        )
    }
}

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

/// A hypothetical memory mutation for counterfactual analysis.
///
/// Interventions are applied to episodes to test "what if" scenarios
/// without mutating actual memory state.
#[derive(Clone, Debug, PartialEq)]
pub struct Intervention {
    /// Schema identifier.
    pub schema: &'static str,
    /// Unique intervention ID.
    pub id: String,
    /// Type of intervention.
    pub intervention_type: InterventionType,
    /// Target memory ID (for add/remove/modify).
    pub target_memory_id: Option<String>,
    /// Hypothetical memory content (for add/replace).
    pub hypothetical_content: Option<String>,
    /// Score adjustment (for strengthen/weaken).
    pub score_delta: Option<f64>,
    /// Brief description of the intervention.
    pub description: String,
    /// Rationale for this intervention.
    pub rationale: Option<String>,
    /// Timestamp when intervention was created (RFC 3339).
    pub created_at: String,
    /// Who created this intervention.
    pub created_by: Option<String>,
}

impl Intervention {
    /// Create a new intervention.
    #[must_use]
    pub fn new(
        id: impl Into<String>,
        intervention_type: InterventionType,
        description: impl Into<String>,
        created_at: impl Into<String>,
    ) -> Self {
        Self {
            schema: INTERVENTION_SCHEMA_V1,
            id: id.into(),
            intervention_type,
            description: description.into(),
            created_at: created_at.into(),
            target_memory_id: None,
            hypothetical_content: None,
            score_delta: None,
            rationale: None,
            created_by: None,
        }
    }

    /// Set the target memory ID.
    #[must_use]
    pub fn with_target_memory(mut self, id: impl Into<String>) -> Self {
        self.target_memory_id = Some(id.into());
        self
    }

    /// Set hypothetical content.
    #[must_use]
    pub fn with_hypothetical_content(mut self, content: impl Into<String>) -> Self {
        self.hypothetical_content = Some(content.into());
        self
    }

    /// Set score delta.
    #[must_use]
    pub fn with_score_delta(mut self, delta: f64) -> Self {
        self.score_delta = Some(delta);
        self
    }

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

    /// Set creator.
    #[must_use]
    pub fn with_created_by(mut self, by: impl Into<String>) -> Self {
        self.created_by = Some(by.into());
        self
    }
}

/// Type of memory intervention.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum InterventionType {
    /// Add a hypothetical memory that didn't exist.
    AddMemory,
    /// Remove a memory that was present.
    RemoveMemory,
    /// Replace memory content.
    ReplaceContent,
    /// Increase memory scores (utility, confidence, relevance).
    Strengthen,
    /// Decrease memory scores.
    Weaken,
    /// Change memory retrieval ranking.
    Rerank,
}

impl InterventionType {
    /// Stable string representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::AddMemory => "add_memory",
            Self::RemoveMemory => "remove_memory",
            Self::ReplaceContent => "replace_content",
            Self::Strengthen => "strengthen",
            Self::Weaken => "weaken",
            Self::Rerank => "rerank",
        }
    }
}

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

impl FromStr for InterventionType {
    type Err = ParseInterventionTypeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match normalized_episode_token(s).as_str() {
            "add_memory" => Ok(Self::AddMemory),
            "remove_memory" => Ok(Self::RemoveMemory),
            "replace_content" => Ok(Self::ReplaceContent),
            "strengthen" => Ok(Self::Strengthen),
            "weaken" => Ok(Self::Weaken),
            "rerank" => Ok(Self::Rerank),
            _ => Err(ParseInterventionTypeError {
                input: s.to_owned(),
            }),
        }
    }
}

/// Error parsing an intervention type.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseInterventionTypeError {
    input: String,
}

impl fmt::Display for ParseInterventionTypeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown intervention type `{}`; expected add_memory, remove_memory, replace_content, strengthen, weaken, or rerank",
            self.input
        )
    }
}

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

/// A counterfactual replay of an episode with interventions applied.
#[derive(Clone, Debug, PartialEq)]
pub struct CounterfactualRun {
    /// Schema identifier.
    pub schema: &'static str,
    /// Unique run ID.
    pub id: String,
    /// Episode being replayed.
    pub episode_id: String,
    /// Interventions applied to this run.
    pub intervention_ids: Vec<String>,
    /// Hypothetical outcome after interventions.
    pub hypothetical_outcome: EpisodeOutcome,
    /// Confidence that the outcome would have changed (0.0-1.0).
    pub confidence: f64,
    /// Method used for counterfactual analysis.
    pub method: CounterfactualMethod,
    /// Analysis notes.
    pub analysis: Option<String>,
    /// Timestamp when run was executed (RFC 3339).
    pub executed_at: String,
    /// Duration of analysis in milliseconds.
    pub analysis_duration_ms: Option<u64>,
}

impl CounterfactualRun {
    /// Create a new counterfactual run.
    #[must_use]
    pub fn new(
        id: impl Into<String>,
        episode_id: impl Into<String>,
        hypothetical_outcome: EpisodeOutcome,
        confidence: f64,
        method: CounterfactualMethod,
        executed_at: impl Into<String>,
    ) -> Self {
        Self {
            schema: COUNTERFACTUAL_RUN_SCHEMA_V1,
            id: id.into(),
            episode_id: episode_id.into(),
            intervention_ids: Vec::new(),
            hypothetical_outcome,
            confidence,
            method,
            analysis: None,
            executed_at: executed_at.into(),
            analysis_duration_ms: None,
        }
    }

    /// Add an intervention.
    pub fn add_intervention(&mut self, id: impl Into<String>) {
        self.intervention_ids.push(id.into());
    }

    /// Set analysis notes.
    #[must_use]
    pub fn with_analysis(mut self, analysis: impl Into<String>) -> Self {
        self.analysis = Some(analysis.into());
        self
    }

    /// Set analysis duration.
    #[must_use]
    pub fn with_analysis_duration_ms(mut self, ms: u64) -> Self {
        self.analysis_duration_ms = Some(ms);
        self
    }
}

/// Method used for counterfactual analysis.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum CounterfactualMethod {
    /// Deterministic replay with modified inputs.
    DeterministicReplay,
    /// Heuristic estimation based on memory impact.
    HeuristicEstimate,
    /// LLM-based what-if reasoning.
    LlmReasoning,
    /// Human expert judgment.
    HumanJudgment,
    /// Method unknown or not specified.
    #[default]
    Unknown,
}

impl CounterfactualMethod {
    /// Stable string representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::DeterministicReplay => "deterministic_replay",
            Self::HeuristicEstimate => "heuristic_estimate",
            Self::LlmReasoning => "llm_reasoning",
            Self::HumanJudgment => "human_judgment",
            Self::Unknown => "unknown",
        }
    }
}

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

impl FromStr for CounterfactualMethod {
    type Err = ParseCounterfactualMethodError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match normalized_episode_token(s).as_str() {
            "deterministic_replay" => Ok(Self::DeterministicReplay),
            "heuristic_estimate" => Ok(Self::HeuristicEstimate),
            "llm_reasoning" => Ok(Self::LlmReasoning),
            "human_judgment" => Ok(Self::HumanJudgment),
            "unknown" => Ok(Self::Unknown),
            _ => Err(ParseCounterfactualMethodError {
                input: s.to_owned(),
            }),
        }
    }
}

/// Error parsing a counterfactual method.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseCounterfactualMethodError {
    input: String,
}

impl fmt::Display for ParseCounterfactualMethodError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown counterfactual method `{}`; expected deterministic_replay, heuristic_estimate, llm_reasoning, human_judgment, or unknown",
            self.input
        )
    }
}

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

/// A ledger of regret entries recording what interventions would have helped.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RegretLedger {
    /// Schema identifier.
    pub schema: &'static str,
    /// Workspace this ledger belongs to.
    pub workspace_id: Option<String>,
    /// All regret entries.
    pub entries: Vec<RegretEntry>,
    /// Summary statistics.
    pub summary: Option<RegretSummary>,
    /// Timestamp when ledger was last updated (RFC 3339).
    pub updated_at: String,
}

impl RegretLedger {
    /// Create a new regret ledger.
    #[must_use]
    pub fn new(updated_at: impl Into<String>) -> Self {
        Self {
            schema: REGRET_LEDGER_SCHEMA_V1,
            updated_at: updated_at.into(),
            ..Default::default()
        }
    }

    /// Set the workspace ID.
    #[must_use]
    pub fn with_workspace_id(mut self, id: impl Into<String>) -> Self {
        self.workspace_id = Some(id.into());
        self
    }

    /// Add a regret entry.
    pub fn add_entry(&mut self, entry: RegretEntry) {
        self.entries.push(entry);
    }

    /// Set summary statistics.
    #[must_use]
    pub fn with_summary(mut self, summary: RegretSummary) -> Self {
        self.summary = Some(summary);
        self
    }
}

/// A single entry in the regret ledger.
#[derive(Clone, Debug, PartialEq)]
pub struct RegretEntry {
    /// Schema identifier.
    pub schema: &'static str,
    /// Unique entry ID.
    pub id: String,
    /// Episode that experienced regret.
    pub episode_id: String,
    /// Counterfactual run that identified this regret.
    pub counterfactual_run_id: String,
    /// Intervention that would have helped.
    pub intervention_id: String,
    /// Estimated regret (impact of not having the intervention).
    pub regret_score: f64,
    /// Confidence in the regret estimate.
    pub confidence: f64,
    /// Category of regret.
    pub category: RegretCategory,
    /// Whether this regret led to an actual memory promotion.
    pub promoted: bool,
    /// Memory ID if a promotion occurred.
    pub promoted_memory_id: Option<String>,
    /// Timestamp when entry was created (RFC 3339).
    pub created_at: String,
}

impl RegretEntry {
    /// Create a new regret entry.
    #[must_use]
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: impl Into<String>,
        episode_id: impl Into<String>,
        counterfactual_run_id: impl Into<String>,
        intervention_id: impl Into<String>,
        regret_score: f64,
        confidence: f64,
        category: RegretCategory,
        created_at: impl Into<String>,
    ) -> Self {
        Self {
            schema: REGRET_ENTRY_SCHEMA_V1,
            id: id.into(),
            episode_id: episode_id.into(),
            counterfactual_run_id: counterfactual_run_id.into(),
            intervention_id: intervention_id.into(),
            regret_score,
            confidence,
            category,
            promoted: false,
            promoted_memory_id: None,
            created_at: created_at.into(),
        }
    }

    /// Mark as promoted with memory ID.
    #[must_use]
    pub fn with_promotion(mut self, memory_id: impl Into<String>) -> Self {
        self.promoted = true;
        self.promoted_memory_id = Some(memory_id.into());
        self
    }
}

/// Category of regret.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum RegretCategory {
    /// Missing knowledge that would have helped.
    MissingKnowledge,
    /// Stale or outdated information was used.
    StaleInformation,
    /// Relevant memory was not retrieved.
    RetrievalFailure,
    /// Retrieved but not used effectively.
    UnderutilizedMemory,
    /// Wrong information was used.
    Misinformation,
    /// Uncategorized regret.
    #[default]
    Other,
}

impl RegretCategory {
    /// Stable string representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MissingKnowledge => "missing_knowledge",
            Self::StaleInformation => "stale_information",
            Self::RetrievalFailure => "retrieval_failure",
            Self::UnderutilizedMemory => "underutilized_memory",
            Self::Misinformation => "misinformation",
            Self::Other => "other",
        }
    }
}

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

impl FromStr for RegretCategory {
    type Err = ParseRegretCategoryError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match normalized_episode_token(s).as_str() {
            "missing_knowledge" => Ok(Self::MissingKnowledge),
            "stale_information" => Ok(Self::StaleInformation),
            "retrieval_failure" => Ok(Self::RetrievalFailure),
            "underutilized_memory" => Ok(Self::UnderutilizedMemory),
            "misinformation" => Ok(Self::Misinformation),
            "other" => Ok(Self::Other),
            _ => Err(ParseRegretCategoryError {
                input: s.to_owned(),
            }),
        }
    }
}

/// Error parsing a regret category.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseRegretCategoryError {
    input: String,
}

impl fmt::Display for ParseRegretCategoryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown regret category `{}`; expected missing_knowledge, stale_information, retrieval_failure, underutilized_memory, misinformation, or other",
            self.input
        )
    }
}

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

/// Summary statistics for a regret ledger.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct RegretSummary {
    /// Total number of entries.
    pub total_entries: u32,
    /// Number that led to promotions.
    pub promoted_count: u32,
    /// Entries by category.
    pub by_category: Vec<(RegretCategory, u32)>,
    /// Average regret score.
    pub average_regret: Option<String>,
    /// Average confidence.
    pub average_confidence: Option<String>,
}

impl RegretSummary {
    /// Create a new summary.
    #[must_use]
    pub fn new(total_entries: u32, promoted_count: u32) -> Self {
        Self {
            total_entries,
            promoted_count,
            ..Default::default()
        }
    }

    /// Add a category count.
    pub fn add_category_count(&mut self, category: RegretCategory, count: u32) {
        self.by_category.push((category, count));
    }

    /// Set average regret (as string to avoid float comparison issues).
    #[must_use]
    pub fn with_average_regret(mut self, avg: impl Into<String>) -> Self {
        self.average_regret = Some(avg.into());
        self
    }

    /// Set average confidence.
    #[must_use]
    pub fn with_average_confidence(mut self, avg: impl Into<String>) -> Self {
        self.average_confidence = Some(avg.into());
        self
    }
}

/// Schema version for counterfactual claims.
pub const COUNTERFACTUAL_CLAIM_SCHEMA_V1: &str = "ee.counterfactual_claim.v1";

/// Schema version for regret delta.
pub const REGRET_DELTA_SCHEMA_V1: &str = "ee.regret_delta.v1";

/// ID prefix for counterfactual claims.
pub const COUNTERFACTUAL_CLAIM_ID_PREFIX: &str = "cfc_";

/// Type of counterfactual claim.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum CounterfactualClaimType {
    /// Memory would have been surfaced if retrieval parameters differed.
    WouldHaveSurfaced,
    /// Quantified difference in outcome between actual and hypothetical runs.
    RegretDelta,
    /// Memory existed but was not retrieved for the task.
    MissedRetrieval,
    /// Memory was retrieved but with insufficient rank/score.
    InsufficientRank,
}

impl CounterfactualClaimType {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::WouldHaveSurfaced => "would_have_surfaced",
            Self::RegretDelta => "regret_delta",
            Self::MissedRetrieval => "missed_retrieval",
            Self::InsufficientRank => "insufficient_rank",
        }
    }

    #[must_use]
    pub const fn all() -> [Self; 4] {
        [
            Self::WouldHaveSurfaced,
            Self::RegretDelta,
            Self::MissedRetrieval,
            Self::InsufficientRank,
        ]
    }
}

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

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseCounterfactualClaimTypeError {
    input: String,
}

impl ParseCounterfactualClaimTypeError {
    pub fn input(&self) -> &str {
        &self.input
    }
}

impl fmt::Display for ParseCounterfactualClaimTypeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown counterfactual claim type `{}`; expected would_have_surfaced, regret_delta, missed_retrieval, or insufficient_rank",
            self.input
        )
    }
}

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

impl FromStr for CounterfactualClaimType {
    type Err = ParseCounterfactualClaimTypeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match normalized_episode_token(s).as_str() {
            "would_have_surfaced" => Ok(Self::WouldHaveSurfaced),
            "regret_delta" => Ok(Self::RegretDelta),
            "missed_retrieval" => Ok(Self::MissedRetrieval),
            "insufficient_rank" => Ok(Self::InsufficientRank),
            other => Err(ParseCounterfactualClaimTypeError {
                input: other.to_owned(),
            }),
        }
    }
}

/// A claim about what would have happened under counterfactual conditions.
///
/// These claims connect counterfactual replay analysis to actionable
/// evidence about memory system improvements.
#[derive(Clone, Debug, PartialEq)]
pub struct CounterfactualClaim {
    /// Schema identifier.
    pub schema: &'static str,
    /// Unique claim ID.
    pub id: String,
    /// Type of counterfactual claim.
    pub claim_type: CounterfactualClaimType,
    /// Episode this claim is about.
    pub episode_id: String,
    /// Counterfactual run that generated this claim.
    pub counterfactual_run_id: String,
    /// Memory ID involved in the claim (if applicable).
    pub memory_id: Option<String>,
    /// Human-readable description of the claim.
    pub description: String,
    /// Confidence that the claim is valid (0.0-1.0).
    pub confidence: f64,
    /// Evidence supporting this claim.
    pub evidence: Vec<String>,
    /// Suggested action based on this claim.
    pub suggested_action: Option<String>,
    /// When this claim was generated (RFC 3339).
    pub created_at: String,
}

impl CounterfactualClaim {
    /// Create a new counterfactual claim.
    #[must_use]
    pub fn new(
        id: impl Into<String>,
        claim_type: CounterfactualClaimType,
        episode_id: impl Into<String>,
        counterfactual_run_id: impl Into<String>,
        description: impl Into<String>,
        confidence: f64,
        created_at: impl Into<String>,
    ) -> Self {
        Self {
            schema: COUNTERFACTUAL_CLAIM_SCHEMA_V1,
            id: id.into(),
            claim_type,
            episode_id: episode_id.into(),
            counterfactual_run_id: counterfactual_run_id.into(),
            memory_id: None,
            description: description.into(),
            confidence,
            evidence: Vec::new(),
            suggested_action: None,
            created_at: created_at.into(),
        }
    }

    /// Create a "would have surfaced" claim.
    #[must_use]
    pub fn would_have_surfaced(
        id: impl Into<String>,
        episode_id: impl Into<String>,
        counterfactual_run_id: impl Into<String>,
        memory_id: impl Into<String>,
        confidence: f64,
        created_at: impl Into<String>,
    ) -> Self {
        let memory_id_str = memory_id.into();
        Self {
            schema: COUNTERFACTUAL_CLAIM_SCHEMA_V1,
            id: id.into(),
            claim_type: CounterfactualClaimType::WouldHaveSurfaced,
            episode_id: episode_id.into(),
            counterfactual_run_id: counterfactual_run_id.into(),
            memory_id: Some(memory_id_str.clone()),
            description: format!(
                "Memory {} would have been surfaced under alternate retrieval parameters",
                memory_id_str
            ),
            confidence,
            evidence: Vec::new(),
            suggested_action: Some(format!(
                "Consider adjusting retrieval parameters to surface memory {}",
                memory_id_str
            )),
            created_at: created_at.into(),
        }
    }

    /// Create a "regret delta" claim.
    #[must_use]
    pub fn regret_delta(
        id: impl Into<String>,
        episode_id: impl Into<String>,
        counterfactual_run_id: impl Into<String>,
        delta: &RegretDelta,
        created_at: impl Into<String>,
    ) -> Self {
        Self {
            schema: COUNTERFACTUAL_CLAIM_SCHEMA_V1,
            id: id.into(),
            claim_type: CounterfactualClaimType::RegretDelta,
            episode_id: episode_id.into(),
            counterfactual_run_id: counterfactual_run_id.into(),
            memory_id: None,
            description: format!(
                "Outcome would have changed from {} to {} with regret delta {:.3}",
                delta.actual_outcome, delta.hypothetical_outcome, delta.delta_score
            ),
            confidence: delta.confidence,
            evidence: Vec::new(),
            suggested_action: if delta.delta_score > 0.5 {
                Some("High-impact improvement opportunity identified".to_owned())
            } else {
                None
            },
            created_at: created_at.into(),
        }
    }

    /// Set memory ID.
    #[must_use]
    pub fn with_memory_id(mut self, memory_id: impl Into<String>) -> Self {
        self.memory_id = Some(memory_id.into());
        self
    }

    /// Add evidence.
    pub fn add_evidence(&mut self, evidence: impl Into<String>) {
        self.evidence.push(evidence.into());
    }

    /// Set suggested action.
    #[must_use]
    pub fn with_suggested_action(mut self, action: impl Into<String>) -> Self {
        self.suggested_action = Some(action.into());
        self
    }
}

/// Quantified difference between actual and hypothetical outcomes.
///
/// The delta measures how much better or worse the outcome would have
/// been under different memory retrieval conditions.
#[derive(Clone, Debug, PartialEq)]
pub struct RegretDelta {
    /// Schema identifier.
    pub schema: &'static str,
    /// Unique delta ID.
    pub id: String,
    /// Episode being analyzed.
    pub episode_id: String,
    /// Counterfactual run that generated this delta.
    pub counterfactual_run_id: String,
    /// Actual outcome of the episode.
    pub actual_outcome: EpisodeOutcome,
    /// Hypothetical outcome under intervention.
    pub hypothetical_outcome: EpisodeOutcome,
    /// Normalized delta score (-1.0 to 1.0, positive = improvement).
    pub delta_score: f64,
    /// Confidence in the delta estimate (0.0-1.0).
    pub confidence: f64,
    /// Breakdown of contributing factors.
    pub contributing_factors: Vec<String>,
    /// When this delta was computed (RFC 3339).
    pub computed_at: String,
}

impl RegretDelta {
    /// Create a new regret delta.
    #[must_use]
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: impl Into<String>,
        episode_id: impl Into<String>,
        counterfactual_run_id: impl Into<String>,
        actual_outcome: EpisodeOutcome,
        hypothetical_outcome: EpisodeOutcome,
        delta_score: f64,
        confidence: f64,
        computed_at: impl Into<String>,
    ) -> Self {
        Self {
            schema: REGRET_DELTA_SCHEMA_V1,
            id: id.into(),
            episode_id: episode_id.into(),
            counterfactual_run_id: counterfactual_run_id.into(),
            actual_outcome,
            hypothetical_outcome,
            delta_score,
            confidence,
            contributing_factors: Vec::new(),
            computed_at: computed_at.into(),
        }
    }

    /// Compute delta score from outcome transition.
    #[must_use]
    pub fn compute_score(actual: EpisodeOutcome, hypothetical: EpisodeOutcome) -> f64 {
        let actual_value = Self::outcome_value(actual);
        let hypothetical_value = Self::outcome_value(hypothetical);
        hypothetical_value - actual_value
    }

    /// Get numerical value for outcome (higher = better).
    #[must_use]
    pub const fn outcome_value(outcome: EpisodeOutcome) -> f64 {
        match outcome {
            EpisodeOutcome::Success => 1.0,
            EpisodeOutcome::Cancelled => 0.3,
            EpisodeOutcome::Timeout => 0.2,
            EpisodeOutcome::Unknown => 0.0,
            EpisodeOutcome::Failure => -0.5,
        }
    }

    /// Add a contributing factor.
    pub fn add_contributing_factor(&mut self, factor: impl Into<String>) {
        self.contributing_factors.push(factor.into());
    }

    /// Check if this delta represents an improvement.
    #[must_use]
    pub fn is_improvement(&self) -> bool {
        self.delta_score > 0.0
    }

    /// Check if this delta is significant (above threshold).
    #[must_use]
    pub fn is_significant(&self, threshold: f64) -> bool {
        self.delta_score.abs() >= threshold && self.confidence >= 0.5
    }
}

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

    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 episode_schema_versions_are_stable() -> TestResult {
        ensure(TASK_EPISODE_SCHEMA_V1, "ee.task_episode.v1", "episode")?;
        ensure(INTERVENTION_SCHEMA_V1, "ee.intervention.v1", "intervention")?;
        ensure(
            COUNTERFACTUAL_RUN_SCHEMA_V1,
            "ee.counterfactual_run.v1",
            "cfr",
        )?;
        ensure(REGRET_LEDGER_SCHEMA_V1, "ee.regret_ledger.v1", "ledger")?;
        ensure(REGRET_ENTRY_SCHEMA_V1, "ee.regret_entry.v1", "entry")
    }

    #[test]
    fn task_episode_builder() -> TestResult {
        let mut ep = TaskEpisode::new("ep_001", "Fix the bug", "2026-04-30T12:00:00Z")
            .with_workspace_id("ws_001")
            .with_session_id("sess_001")
            .with_context_pack_id("pack_001")
            .with_outcome(EpisodeOutcome::Success)
            .with_ended_at("2026-04-30T12:05:00Z")
            .with_duration_ms(300000)
            .with_agent("claude-code");

        ep.add_retrieved_memory("mem_001");
        ep.add_action(EpisodeAction::new(
            1,
            ActionType::Edit,
            "Edit file",
            "2026-04-30T12:01:00Z",
        ));

        ensure(ep.schema, TASK_EPISODE_SCHEMA_V1, "schema")?;
        ensure(ep.task_input, "Fix the bug".to_string(), "task")?;
        ensure(ep.outcome, EpisodeOutcome::Success, "outcome")?;
        ensure(ep.retrieved_memory_ids.len(), 1, "memories")?;
        ensure(ep.actions.len(), 1, "actions")
    }

    #[test]
    fn action_type_strings_are_stable() -> TestResult {
        ensure(ActionType::ToolCall.as_str(), "tool_call", "tool_call")?;
        ensure(ActionType::Edit.as_str(), "edit", "edit")?;
        ensure(ActionType::Command.as_str(), "command", "command")?;
        ensure(ActionType::Search.as_str(), "search", "search")?;
        ensure(ActionType::Retrieval.as_str(), "retrieval", "retrieval")?;
        ensure(ActionType::Output.as_str(), "output", "output")?;
        ensure(ActionType::Other.as_str(), "other", "other")
    }

    #[test]
    fn action_type_round_trip() -> TestResult {
        for at in [
            ActionType::ToolCall,
            ActionType::Edit,
            ActionType::Command,
            ActionType::Search,
            ActionType::Retrieval,
            ActionType::Output,
            ActionType::Other,
        ] {
            let parsed = ActionType::from_str(at.as_str());
            ensure(parsed, Ok(at), at.as_str())?;
        }
        Ok(())
    }

    #[test]
    fn action_type_rejects_invalid() {
        assert!(ActionType::from_str("invalid").is_err());
    }

    #[test]
    fn episode_outcome_strings_are_stable() -> TestResult {
        ensure(EpisodeOutcome::Success.as_str(), "success", "success")?;
        ensure(EpisodeOutcome::Failure.as_str(), "failure", "failure")?;
        ensure(EpisodeOutcome::Cancelled.as_str(), "cancelled", "cancelled")?;
        ensure(EpisodeOutcome::Timeout.as_str(), "timeout", "timeout")?;
        ensure(EpisodeOutcome::Unknown.as_str(), "unknown", "unknown")
    }

    #[test]
    fn episode_outcome_round_trip() -> TestResult {
        for eo in [
            EpisodeOutcome::Success,
            EpisodeOutcome::Failure,
            EpisodeOutcome::Cancelled,
            EpisodeOutcome::Timeout,
            EpisodeOutcome::Unknown,
        ] {
            let parsed = EpisodeOutcome::from_str(eo.as_str());
            ensure(parsed, Ok(eo), eo.as_str())?;
        }
        Ok(())
    }

    #[test]
    fn episode_outcome_is_negative() -> TestResult {
        ensure(EpisodeOutcome::Success.is_negative(), false, "success")?;
        ensure(EpisodeOutcome::Failure.is_negative(), true, "failure")?;
        ensure(EpisodeOutcome::Cancelled.is_negative(), true, "cancelled")?;
        ensure(EpisodeOutcome::Timeout.is_negative(), true, "timeout")?;
        ensure(EpisodeOutcome::Unknown.is_negative(), false, "unknown")
    }

    #[test]
    fn intervention_builder() -> TestResult {
        let int = Intervention::new(
            "int_001",
            InterventionType::AddMemory,
            "Add missing rule",
            "2026-04-30T12:00:00Z",
        )
        .with_target_memory("mem_001")
        .with_hypothetical_content("Always run tests")
        .with_rationale("Would have prevented test failure")
        .with_created_by("analyst");

        ensure(int.schema, INTERVENTION_SCHEMA_V1, "schema")?;
        ensure(int.intervention_type, InterventionType::AddMemory, "type")?;
        ensure(int.target_memory_id, Some("mem_001".to_string()), "target")
    }

    #[test]
    fn intervention_type_strings_are_stable() -> TestResult {
        ensure(InterventionType::AddMemory.as_str(), "add_memory", "add")?;
        ensure(
            InterventionType::RemoveMemory.as_str(),
            "remove_memory",
            "remove",
        )?;
        ensure(
            InterventionType::ReplaceContent.as_str(),
            "replace_content",
            "replace",
        )?;
        ensure(
            InterventionType::Strengthen.as_str(),
            "strengthen",
            "strengthen",
        )?;
        ensure(InterventionType::Weaken.as_str(), "weaken", "weaken")?;
        ensure(InterventionType::Rerank.as_str(), "rerank", "rerank")
    }

    #[test]
    fn intervention_type_round_trip() -> TestResult {
        for it in [
            InterventionType::AddMemory,
            InterventionType::RemoveMemory,
            InterventionType::ReplaceContent,
            InterventionType::Strengthen,
            InterventionType::Weaken,
            InterventionType::Rerank,
        ] {
            let parsed = InterventionType::from_str(it.as_str());
            ensure(parsed, Ok(it), it.as_str())?;
        }
        Ok(())
    }

    #[test]
    fn counterfactual_run_builder() -> TestResult {
        let mut cfr = CounterfactualRun::new(
            "cfr_001",
            "ep_001",
            EpisodeOutcome::Success,
            0.85,
            CounterfactualMethod::DeterministicReplay,
            "2026-04-30T12:00:00Z",
        )
        .with_analysis("Adding the rule would have prevented failure")
        .with_analysis_duration_ms(500);

        cfr.add_intervention("int_001");

        ensure(cfr.schema, COUNTERFACTUAL_RUN_SCHEMA_V1, "schema")?;
        ensure(cfr.hypothetical_outcome, EpisodeOutcome::Success, "outcome")?;
        ensure(cfr.intervention_ids.len(), 1, "interventions")
    }

    #[test]
    fn counterfactual_method_strings_are_stable() -> TestResult {
        ensure(
            CounterfactualMethod::DeterministicReplay.as_str(),
            "deterministic_replay",
            "replay",
        )?;
        ensure(
            CounterfactualMethod::HeuristicEstimate.as_str(),
            "heuristic_estimate",
            "heuristic",
        )?;
        ensure(
            CounterfactualMethod::LlmReasoning.as_str(),
            "llm_reasoning",
            "llm",
        )?;
        ensure(
            CounterfactualMethod::HumanJudgment.as_str(),
            "human_judgment",
            "human",
        )?;
        ensure(CounterfactualMethod::Unknown.as_str(), "unknown", "unknown")
    }

    #[test]
    fn counterfactual_method_round_trip() -> TestResult {
        for cm in [
            CounterfactualMethod::DeterministicReplay,
            CounterfactualMethod::HeuristicEstimate,
            CounterfactualMethod::LlmReasoning,
            CounterfactualMethod::HumanJudgment,
            CounterfactualMethod::Unknown,
        ] {
            let parsed = CounterfactualMethod::from_str(cm.as_str());
            ensure(parsed, Ok(cm), cm.as_str())?;
        }
        Ok(())
    }

    #[test]
    fn regret_ledger_builder() -> TestResult {
        let mut ledger = RegretLedger::new("2026-04-30T12:00:00Z")
            .with_workspace_id("ws_001")
            .with_summary(RegretSummary::new(10, 3));

        ledger.add_entry(RegretEntry::new(
            "reg_001",
            "ep_001",
            "cfr_001",
            "int_001",
            0.7,
            0.85,
            RegretCategory::MissingKnowledge,
            "2026-04-30T12:00:00Z",
        ));

        ensure(ledger.schema, REGRET_LEDGER_SCHEMA_V1, "schema")?;
        ensure(ledger.entries.len(), 1, "entries")
    }

    #[test]
    fn regret_entry_builder() -> TestResult {
        let entry = RegretEntry::new(
            "reg_001",
            "ep_001",
            "cfr_001",
            "int_001",
            0.7,
            0.85,
            RegretCategory::RetrievalFailure,
            "2026-04-30T12:00:00Z",
        )
        .with_promotion("mem_new_001");

        ensure(entry.schema, REGRET_ENTRY_SCHEMA_V1, "schema")?;
        ensure(entry.promoted, true, "promoted")?;
        ensure(entry.category, RegretCategory::RetrievalFailure, "category")
    }

    #[test]
    fn regret_category_strings_are_stable() -> TestResult {
        ensure(
            RegretCategory::MissingKnowledge.as_str(),
            "missing_knowledge",
            "missing",
        )?;
        ensure(
            RegretCategory::StaleInformation.as_str(),
            "stale_information",
            "stale",
        )?;
        ensure(
            RegretCategory::RetrievalFailure.as_str(),
            "retrieval_failure",
            "retrieval",
        )?;
        ensure(
            RegretCategory::UnderutilizedMemory.as_str(),
            "underutilized_memory",
            "underutilized",
        )?;
        ensure(
            RegretCategory::Misinformation.as_str(),
            "misinformation",
            "misinformation",
        )?;
        ensure(RegretCategory::Other.as_str(), "other", "other")
    }

    #[test]
    fn regret_category_round_trip() -> TestResult {
        for rc in [
            RegretCategory::MissingKnowledge,
            RegretCategory::StaleInformation,
            RegretCategory::RetrievalFailure,
            RegretCategory::UnderutilizedMemory,
            RegretCategory::Misinformation,
            RegretCategory::Other,
        ] {
            let parsed = RegretCategory::from_str(rc.as_str());
            ensure(parsed, Ok(rc), rc.as_str())?;
        }
        Ok(())
    }

    #[test]
    fn regret_summary_builder() -> TestResult {
        let mut summary = RegretSummary::new(100, 25)
            .with_average_regret("0.65")
            .with_average_confidence("0.80");

        summary.add_category_count(RegretCategory::MissingKnowledge, 40);
        summary.add_category_count(RegretCategory::RetrievalFailure, 30);

        ensure(summary.total_entries, 100, "total")?;
        ensure(summary.promoted_count, 25, "promoted")?;
        ensure(summary.by_category.len(), 2, "categories")
    }

    #[test]
    fn counterfactual_claim_schema_versions_are_stable() -> TestResult {
        ensure(
            COUNTERFACTUAL_CLAIM_SCHEMA_V1,
            "ee.counterfactual_claim.v1",
            "claim",
        )?;
        ensure(REGRET_DELTA_SCHEMA_V1, "ee.regret_delta.v1", "delta")
    }

    #[test]
    fn counterfactual_claim_type_strings_are_stable() -> TestResult {
        ensure(
            CounterfactualClaimType::WouldHaveSurfaced.as_str(),
            "would_have_surfaced",
            "surfaced",
        )?;
        ensure(
            CounterfactualClaimType::RegretDelta.as_str(),
            "regret_delta",
            "delta",
        )?;
        ensure(
            CounterfactualClaimType::MissedRetrieval.as_str(),
            "missed_retrieval",
            "missed",
        )?;
        ensure(
            CounterfactualClaimType::InsufficientRank.as_str(),
            "insufficient_rank",
            "rank",
        )
    }

    #[test]
    fn counterfactual_claim_type_round_trip() -> TestResult {
        for ct in CounterfactualClaimType::all() {
            let parsed = CounterfactualClaimType::from_str(ct.as_str());
            ensure(parsed, Ok(ct), ct.as_str())?;
        }
        Ok(())
    }

    #[test]
    fn episode_enums_accept_operator_spelling_variants() -> TestResult {
        ensure(
            ActionType::from_str(" Tool-Call "),
            Ok(ActionType::ToolCall),
            "action type alias",
        )?;
        ensure(
            ActionType::from_str("toolCall"),
            Ok(ActionType::ToolCall),
            "camel action type alias",
        )?;
        ensure(
            EpisodeOutcome::from_str("FAILURE"),
            Ok(EpisodeOutcome::Failure),
            "outcome alias",
        )?;
        ensure(
            InterventionType::from_str("replace-content"),
            Ok(InterventionType::ReplaceContent),
            "intervention alias",
        )?;
        ensure(
            InterventionType::from_str("removeMemory"),
            Ok(InterventionType::RemoveMemory),
            "camel intervention alias",
        )?;
        ensure(
            CounterfactualMethod::from_str(" Human-Judgment "),
            Ok(CounterfactualMethod::HumanJudgment),
            "method alias",
        )?;
        ensure(
            CounterfactualMethod::from_str("humanJudgment"),
            Ok(CounterfactualMethod::HumanJudgment),
            "camel method alias",
        )?;
        ensure(
            RegretCategory::from_str("retrieval-failure"),
            Ok(RegretCategory::RetrievalFailure),
            "regret category alias",
        )?;
        ensure(
            RegretCategory::from_str("staleInformation"),
            Ok(RegretCategory::StaleInformation),
            "camel regret category alias",
        )?;
        ensure(
            CounterfactualClaimType::from_str("INSUFFICIENT_RANK"),
            Ok(CounterfactualClaimType::InsufficientRank),
            "claim type alias",
        )?;
        ensure(
            CounterfactualClaimType::from_str("wouldHaveSurfaced"),
            Ok(CounterfactualClaimType::WouldHaveSurfaced),
            "camel claim type alias",
        )
    }

    #[test]
    fn counterfactual_claim_would_have_surfaced() -> TestResult {
        let claim = CounterfactualClaim::would_have_surfaced(
            "cfc_001",
            "ep_001",
            "cfr_001",
            "mem_001",
            0.85,
            "2026-04-30T12:00:00Z",
        );

        ensure(claim.schema, COUNTERFACTUAL_CLAIM_SCHEMA_V1, "schema")?;
        ensure(
            claim.claim_type,
            CounterfactualClaimType::WouldHaveSurfaced,
            "type",
        )?;
        ensure(claim.memory_id, Some("mem_001".to_string()), "memory")?;
        ensure(claim.confidence, 0.85, "confidence")?;
        ensure(claim.suggested_action.is_some(), true, "has action")
    }

    #[test]
    fn counterfactual_claim_regret_delta() -> TestResult {
        let delta = RegretDelta::new(
            "rd_001",
            "ep_001",
            "cfr_001",
            EpisodeOutcome::Failure,
            EpisodeOutcome::Success,
            1.5,
            0.9,
            "2026-04-30T12:00:00Z",
        );

        let claim = CounterfactualClaim::regret_delta(
            "cfc_002",
            "ep_001",
            "cfr_001",
            &delta,
            "2026-04-30T12:00:00Z",
        );

        ensure(claim.schema, COUNTERFACTUAL_CLAIM_SCHEMA_V1, "schema")?;
        ensure(
            claim.claim_type,
            CounterfactualClaimType::RegretDelta,
            "type",
        )?;
        ensure(claim.confidence, 0.9, "confidence")?;
        ensure(
            claim.suggested_action.is_some(),
            true,
            "has action for high delta",
        )
    }

    #[test]
    fn regret_delta_compute_score() -> TestResult {
        let failure_to_success =
            RegretDelta::compute_score(EpisodeOutcome::Failure, EpisodeOutcome::Success);
        ensure(failure_to_success, 1.5, "failure->success")?;

        let success_to_failure =
            RegretDelta::compute_score(EpisodeOutcome::Success, EpisodeOutcome::Failure);
        ensure(success_to_failure, -1.5, "success->failure")?;

        let no_change =
            RegretDelta::compute_score(EpisodeOutcome::Success, EpisodeOutcome::Success);
        ensure(no_change, 0.0, "no change")
    }

    #[test]
    fn regret_delta_is_improvement() -> TestResult {
        let mut delta = RegretDelta::new(
            "rd_001",
            "ep_001",
            "cfr_001",
            EpisodeOutcome::Failure,
            EpisodeOutcome::Success,
            1.5,
            0.9,
            "2026-04-30T12:00:00Z",
        );
        ensure(delta.is_improvement(), true, "positive is improvement")?;

        delta.delta_score = -0.5;
        ensure(delta.is_improvement(), false, "negative is not improvement")?;

        delta.delta_score = 0.0;
        ensure(delta.is_improvement(), false, "zero is not improvement")
    }

    #[test]
    fn regret_delta_is_significant() -> TestResult {
        let mut delta = RegretDelta::new(
            "rd_001",
            "ep_001",
            "cfr_001",
            EpisodeOutcome::Failure,
            EpisodeOutcome::Success,
            0.8,
            0.7,
            "2026-04-30T12:00:00Z",
        );
        ensure(delta.is_significant(0.5), true, "high delta high conf")?;

        delta.confidence = 0.3;
        ensure(delta.is_significant(0.5), false, "low confidence")?;

        delta.confidence = 0.7;
        delta.delta_score = 0.2;
        ensure(delta.is_significant(0.5), false, "low delta")
    }

    #[test]
    fn regret_delta_builder() -> TestResult {
        let mut delta = RegretDelta::new(
            "rd_001",
            "ep_001",
            "cfr_001",
            EpisodeOutcome::Failure,
            EpisodeOutcome::Success,
            1.0,
            0.85,
            "2026-04-30T12:00:00Z",
        );

        delta.add_contributing_factor("Memory boost");
        delta.add_contributing_factor("Better context");

        ensure(delta.schema, REGRET_DELTA_SCHEMA_V1, "schema")?;
        ensure(delta.contributing_factors.len(), 2, "factors")
    }

    #[test]
    fn counterfactual_claim_builder() -> TestResult {
        let mut claim = CounterfactualClaim::new(
            "cfc_001",
            CounterfactualClaimType::MissedRetrieval,
            "ep_001",
            "cfr_001",
            "Memory was not retrieved",
            0.75,
            "2026-04-30T12:00:00Z",
        )
        .with_memory_id("mem_001")
        .with_suggested_action("Adjust retrieval threshold");

        claim.add_evidence("Memory existed in index");
        claim.add_evidence("Query matched memory");

        ensure(claim.schema, COUNTERFACTUAL_CLAIM_SCHEMA_V1, "schema")?;
        ensure(claim.evidence.len(), 2, "evidence count")
    }
}