turnframe-core 0.1.0

Pure types and the deterministic Flow Map workflow projector for Turnframe
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
//! Persistent interactions: cards, confirmations, selections (spec §15).
//!
//! An interaction is a durable, server-owned record. The client only ever
//! sends back an interaction id, an option id and the case revision it saw
//! (I7); the meaning of the click is the [`StoredInteractionAction`] persisted
//! with the option. [`validate_response`] is the pure gate every response
//! passes through before anything executes.

use std::time::Duration;

use chrono::{DateTime, Utc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::case::CaseRef;
use crate::command::{CommandOrigin, ResolutionChannel, RiskClass};
use crate::error::{InteractionError, InteractionSpecError};
use crate::hash::{Digest, HashError, canonical_digest};
use crate::ids::{
    AccountId, CaseRevision, ConversationId, InteractionId, OperationKey, OptionId, TurnId,
};
use crate::locale::LocalizedText;
use crate::reduce::CommandRef;
use crate::turn::{ActorContext, InteractionResponse};

/// The shape of an interaction (spec §15.2).
///
/// New card shapes are expected, so downstream matches need a wildcard arm.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum InteractionKind {
    /// Yes/no.
    Boolean,
    /// Pick one option.
    SingleSelect,
    /// Pick several options.
    MultiSelect,
    /// Free text.
    Freeform,
    /// Review a diff before applying.
    ReviewChanges,
    /// Confirm compiled commands.
    ConfirmCommand,
    /// Choose which case an act targets.
    SelectTarget,
    /// Resolve a validation error.
    ResolveValidationError,
    /// Re-authenticate.
    Reauthenticate,
    /// Sign externally.
    ExternalSignature,
}

impl InteractionKind {
    /// Every kind, in declaration order.
    pub const ALL: [Self; 10] = [
        Self::Boolean,
        Self::SingleSelect,
        Self::MultiSelect,
        Self::Freeform,
        Self::ReviewChanges,
        Self::ConfirmCommand,
        Self::SelectTarget,
        Self::ResolveValidationError,
        Self::Reauthenticate,
        Self::ExternalSignature,
    ];

    /// Returns `true` for cards whose answer authorizes commands.
    ///
    /// Such a card is never resolvable from typed text: the authorization must
    /// be the user's own deterministic answer (spec §15.7, §13.2 rule 8).
    #[must_use]
    pub fn authorizes_commands(self) -> bool {
        matches!(
            self,
            Self::ConfirmCommand
                | Self::ReviewChanges
                | Self::Reauthenticate
                | Self::ExternalSignature
        )
    }
}

/// Lifecycle status of an interaction (spec §15.4).
///
/// Deliberately exhaustive: the set is a closed state machine with an
/// [`ALL`](Self::ALL) table and a
/// [`can_transition`](Self::can_transition) rule for every pair, so code that
/// handles statuses must be forced by the compiler to consider all of them.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum InteractionStatus {
    /// Displayed and answerable.
    Active,
    /// An answer was accepted and its commands are executing.
    Resolving,
    /// The associated commands committed.
    Resolved,
    /// The user declined.
    Declined,
    /// The user dismissed it without answering.
    Dismissed,
    /// The case moved on; the card is no longer valid.
    Invalidated,
    /// The deadline passed.
    Expired,
    /// The associated commands failed.
    Failed,
}

impl InteractionStatus {
    /// Every status, in declaration order.
    pub const ALL: [Self; 8] = [
        Self::Active,
        Self::Resolving,
        Self::Resolved,
        Self::Declined,
        Self::Dismissed,
        Self::Invalidated,
        Self::Expired,
        Self::Failed,
    ];

    /// Returns `true` for statuses with no outgoing transition.
    #[must_use]
    pub fn is_terminal(self) -> bool {
        !matches!(self, Self::Active | Self::Resolving)
    }

    /// Returns `true` while the interaction still occupies the "one blocking
    /// interaction per case" slot (I5).
    #[must_use]
    pub fn is_open(self) -> bool {
        matches!(self, Self::Active | Self::Resolving)
    }

    /// The interaction state machine (spec §15.5).
    ///
    /// * `Active` may move to any other status.
    /// * `Resolving` may move to `Resolved`, `Failed`, or back to `Active` when
    ///   policy restores the card after a failed command.
    /// * Every other status is terminal.
    #[must_use]
    pub fn can_transition(from: Self, to: Self) -> bool {
        match from {
            Self::Active => to != Self::Active,
            Self::Resolving => matches!(to, Self::Resolved | Self::Failed | Self::Active),
            _ => false,
        }
    }
}

/// Whether an option accepts free text (spec §15.5).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum FreeformPolicy {
    /// No free text accepted.
    #[default]
    Forbidden,
    /// Free text accepted up to `max_len` characters.
    Optional {
        /// Maximum length in characters.
        max_len: usize,
    },
    /// Free text required, up to `max_len` characters.
    Required {
        /// Maximum length in characters.
        max_len: usize,
    },
}

impl FreeformPolicy {
    /// Returns `true` when free text may be supplied.
    #[must_use]
    pub fn allows(self) -> bool {
        !matches!(self, Self::Forbidden)
    }

    /// Returns `true` when free text must be supplied.
    #[must_use]
    pub fn requires(self) -> bool {
        matches!(self, Self::Required { .. })
    }

    /// Maximum accepted length, when free text is allowed.
    #[must_use]
    pub fn max_len(self) -> Option<usize> {
        match self {
            Self::Forbidden => None,
            Self::Optional { max_len } | Self::Required { max_len } => Some(max_len),
        }
    }
}

/// Whether and how typed text may resolve an interaction (spec §15.7).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum TextResolutionPolicy {
    /// Only the structured CTA resolves it (default for high-risk confirmations).
    #[default]
    Never,
    /// Understanding may read typed text as one of its options, for a low-risk card;
    /// the option id is still checked against the stored options.
    ModelInterpretedLowRisk,
}

impl TextResolutionPolicy {
    /// Returns `true` when typed text may be read as an option.
    #[must_use]
    pub fn allows_model_interpretation(&self) -> bool {
        matches!(self, Self::ModelInterpretedLowRisk)
    }

    /// Returns `true` when the policy admits the channel an answer arrived on.
    ///
    /// [`ResolutionChannel::Click`] is always admitted: the structured CTA
    /// resolves every card.
    #[must_use]
    pub fn admits(&self, channel: ResolutionChannel) -> bool {
        match channel {
            ResolutionChannel::Click => true,
            ResolutionChannel::ModelInterpreted => self.allows_model_interpretation(),
        }
    }
}

/// What a stored option authorizes when it is chosen (spec §15.3).
///
/// This is the half of [`StoredInteractionAction`] that policy cares about: an
/// origin records the class, not the payload, so
/// [`origin_satisfies`](crate::command::origin_satisfies) can tell a
/// confirmation from a clarification without loading the card again.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum ActionClass {
    /// Executes commands that were compiled and journaled with the card.
    ConfirmsCommands,
    /// Compiles and executes an operation named by the option.
    AppliesOperation,
    /// Answers the card without authorizing any command: a selection, a
    /// clarification, a decline, a dismissal, an application-defined action.
    NoCommands,
}

impl ActionClass {
    /// Returns `true` when choosing the option makes commands run.
    #[must_use]
    pub fn authorizes_commands(self) -> bool {
        matches!(self, Self::ConfirmsCommands | Self::AppliesOperation)
    }
}

/// The server-side meaning of an option (spec §15.3). Never supplied by the client.
///
/// Applications add meanings through [`Self::Custom`] and the library adds
/// variants, so downstream matches need a wildcard arm.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum StoredInteractionAction {
    /// Execute commands that were compiled and journaled when the card was made.
    ConfirmCommands {
        /// The commands.
        command_refs: Vec<CommandRef>,
    },
    /// Drop the pending commands.
    DeclineCommands,
    /// Bind an ambiguous act to this case.
    SelectTarget {
        /// The chosen case.
        case_ref: CaseRef,
    },
    /// Answer a clarification with a stable key.
    ResolveClarification {
        /// Application-defined answer key.
        answer_key: String,
    },
    /// Compile and execute an operation when clicked (the option is the origin).
    ApplyOperation {
        /// Operation to compile through the workflow.
        operation: OperationKey,
        /// Arguments for the operation.
        arguments: serde_json::Value,
        /// Where the option's free text goes in those arguments, as a JSON
        /// pointer (RFC 6901), for a card that asks for a VALUE rather than a
        /// choice.
        ///
        /// `None` is every card that only offers options, which is all of them
        /// until one asks a question whose answer is a word.
        ///
        /// # Why a card at all, when the user could just type
        ///
        /// Because a question in prose is not a state: the next message arrives as
        /// free text, and what to do with it is a guess among every operation that
        /// accepts a name. Asked on a card, the question is the state: the answer
        /// arrives bound to the case and to the operation, and nothing is chosen.
        ///
        /// A JSON pointer into the operation's arguments.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        freeform_argument: Option<String>,
    },
    /// Drop the pending commands, and record that the card was answered.
    ///
    /// # The trace a "no" could not leave
    ///
    /// A confirmation must carry an option that declines, and both declining
    /// actions end the card without effect. So the only shape a "no" could take
    /// wrote nothing — and a workflow whose next sentence depends on whether the
    /// user has already answered could not tell that they had.
    ///
    /// A send confirmation offered "Send" and "Edit". The user pressed Edit;
    /// nothing was written, so the projection was unchanged, so the phase's own
    /// instruction to the writing stage was served again, and the reply was word
    /// for word the sentence the user had just answered. The writer was obeying.
    ///
    /// The runtime already remembers the answer well enough not to raise the
    /// card again, and that memory decides whether the **card** is rendered. It
    /// does not reach what the workflow tells the stage that speaks, which is
    /// where the repetition lives.
    ///
    /// # What it is not
    ///
    /// It does not run what it declined. The journaled commands are dropped
    /// exactly as [`Self::DeclineCommands`] drops them, [`Self::declines`] is
    /// true of it, and it satisfies the requirement that a confirmation offer a
    /// way to say no. What it adds is one operation, named by the server that
    /// wrote the card, compiled through `compile_act` and validated like any
    /// other — so a workflow that records nothing is unaffected, and one that
    /// records something cannot smuggle a confirmation through this door,
    /// because no pending command executes on it.
    ///
    /// The operation is the domain's bookkeeping, so its `command_policy` had
    /// better not ask for a confirmation of its own.
    DeclineAndRecord {
        /// Operation to compile through the workflow, on the case the card
        /// belongs to.
        operation: OperationKey,
    },
    /// Close the card without effect.
    Dismiss,
    /// Application-defined action.
    Custom {
        /// Application key.
        key: String,
        /// Application payload.
        payload: serde_json::Value,
    },
}

impl StoredInteractionAction {
    /// What choosing this option authorizes.
    ///
    /// [`Self::Custom`] is deliberately [`ActionClass::NoCommands`]: an
    /// application-defined action cannot be a confirmation, because the library
    /// cannot know what it does.
    #[must_use]
    pub fn action_class(&self) -> ActionClass {
        match self {
            Self::ConfirmCommands { .. } => ActionClass::ConfirmsCommands,
            Self::ApplyOperation { .. } => ActionClass::AppliesOperation,
            // It compiles an operation, and it is still not a confirmation:
            // what it authorizes is the record of a refusal, on the path where
            // nothing pending runs.
            Self::DeclineCommands
            | Self::DeclineAndRecord { .. }
            | Self::SelectTarget { .. }
            | Self::ResolveClarification { .. }
            | Self::Dismiss
            | Self::Custom { .. } => ActionClass::NoCommands,
        }
    }

    /// Returns `true` when choosing this option ends the card without effect.
    #[must_use]
    pub fn declines(&self) -> bool {
        matches!(
            self,
            Self::DeclineCommands | Self::DeclineAndRecord { .. } | Self::Dismiss
        )
    }

    /// The operation a decline records, when it records one.
    #[must_use]
    pub fn records(&self) -> Option<&OperationKey> {
        match self {
            Self::DeclineAndRecord { operation } => Some(operation),
            _ => None,
        }
    }
}

/// Visual emphasis of an option, for clients.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OptionStyle {
    /// The suggested action.
    Primary,
    /// A neutral action.
    #[default]
    Secondary,
    /// A destructive or declining action.
    Danger,
}

/// A stored option (spec §15.3).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InteractionOption {
    /// Identifier echoed by the client.
    pub id: OptionId,
    /// Label copy.
    pub label: LocalizedText,
    /// Server-side meaning.
    pub action: StoredInteractionAction,
    /// Whether free text may accompany the click.
    #[serde(default)]
    pub freeform_policy: FreeformPolicy,
    /// Visual emphasis.
    #[serde(default)]
    pub style: OptionStyle,
}

impl InteractionOption {
    /// Builds an option that forbids free text with secondary style.
    #[must_use]
    pub fn new(
        id: impl Into<OptionId>,
        label: impl Into<LocalizedText>,
        action: StoredInteractionAction,
    ) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            action,
            freeform_policy: FreeformPolicy::Forbidden,
            style: OptionStyle::Secondary,
        }
    }

    /// Sets the free-form policy.
    #[must_use]
    pub fn with_freeform(mut self, policy: FreeformPolicy) -> Self {
        self.freeform_policy = policy;
        self
    }

    /// Sets the style.
    #[must_use]
    pub fn with_style(mut self, style: OptionStyle) -> Self {
        self.style = style;
        self
    }

    /// The client-facing projection (no action).
    #[must_use]
    pub fn view(&self) -> InteractionOptionView {
        InteractionOptionView {
            id: self.id.clone(),
            label: self.label.clone(),
            freeform_policy: self.freeform_policy,
            style: self.style,
        }
    }
}

/// One side of a field change: absent, or an explicit JSON value.
///
/// `Option<serde_json::Value>` cannot express this: with
/// `skip_serializing_if = "Option::is_none"` an explicit `Some(Value::Null)` —
/// "this field is being cleared" — is written as a missing key and reads back
/// as `None`, so a review card that clears a field fails
/// [`Interaction::verify_payload_hash`] after a round trip through any JSON
/// store and its confirmation can never match. `FieldValue` keeps the two
/// apart: [`Self::Absent`] omits the key, [`Self::Present`] writes the value,
/// `null` included.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum FieldValue {
    /// The field is not part of this side of the change.
    #[default]
    Absent,
    /// An explicit value. [`serde_json::Value::Null`] means "cleared".
    Present(serde_json::Value),
}

impl FieldValue {
    /// A present value.
    #[must_use]
    pub fn present(value: impl Into<serde_json::Value>) -> Self {
        Self::Present(value.into())
    }

    /// An explicit JSON `null`: the field is being cleared.
    #[must_use]
    pub fn cleared() -> Self {
        Self::Present(serde_json::Value::Null)
    }

    /// Returns `true` when the field is not part of this side.
    #[must_use]
    pub fn is_absent(&self) -> bool {
        matches!(self, Self::Absent)
    }

    /// The value, when present.
    #[must_use]
    pub fn value(&self) -> Option<&serde_json::Value> {
        match self {
            Self::Absent => None,
            Self::Present(value) => Some(value),
        }
    }
}

impl From<serde_json::Value> for FieldValue {
    fn from(value: serde_json::Value) -> Self {
        Self::Present(value)
    }
}

impl Serialize for FieldValue {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        // `Absent` is skipped by the container; serializing it standalone still
        // has to produce something, and `null` is the closest reading.
        match self {
            Self::Absent => serializer.serialize_unit(),
            Self::Present(value) => value.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for FieldValue {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // Only called when the key is present, so an explicit `null` arrives
        // here and stays `Present(Null)`; a missing key uses `Default`.
        serde_json::Value::deserialize(deserializer).map(Self::Present)
    }
}

/// One line of a review card: a field before and after the proposed change.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReviewDiffEntry {
    /// Stable field path.
    pub field: String,
    /// Label copy.
    pub label: LocalizedText,
    /// Current value.
    #[serde(default, skip_serializing_if = "FieldValue::is_absent")]
    pub before: FieldValue,
    /// Proposed value.
    #[serde(default, skip_serializing_if = "FieldValue::is_absent")]
    pub after: FieldValue,
}

impl ReviewDiffEntry {
    /// Builds an entry with both sides absent.
    #[must_use]
    pub fn new(field: impl Into<String>, label: impl Into<LocalizedText>) -> Self {
        Self {
            field: field.into(),
            label: label.into(),
            before: FieldValue::Absent,
            after: FieldValue::Absent,
        }
    }

    /// Sets the current value.
    #[must_use]
    pub fn with_before(mut self, before: FieldValue) -> Self {
        self.before = before;
        self
    }

    /// Sets the proposed value.
    #[must_use]
    pub fn with_after(mut self, after: FieldValue) -> Self {
        self.after = after;
        self
    }
}

/// Immutable content of an interaction (spec §15.1).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InteractionPayload {
    /// Title copy.
    pub title: LocalizedText,
    /// Body copy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<LocalizedText>,
    /// Stored options.
    #[serde(default)]
    pub options: Vec<InteractionOption>,
    /// Diff entries for review cards.
    #[serde(default)]
    pub review_entries: Vec<ReviewDiffEntry>,
    /// Prompt for free-form interactions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub freeform_prompt: Option<LocalizedText>,
    /// Application metadata (rendering hints, preview hash...).
    #[serde(default)]
    pub metadata: serde_json::Value,
}

impl InteractionPayload {
    /// Builds a payload with only a title.
    #[must_use]
    pub fn new(title: impl Into<LocalizedText>) -> Self {
        Self {
            title: title.into(),
            body: None,
            options: Vec::new(),
            review_entries: Vec::new(),
            freeform_prompt: None,
            metadata: serde_json::Value::Null,
        }
    }

    /// Sets the body.
    #[must_use]
    pub fn with_body(mut self, body: impl Into<LocalizedText>) -> Self {
        self.body = Some(body.into());
        self
    }

    /// Appends an option.
    #[must_use]
    pub fn with_option(mut self, option: InteractionOption) -> Self {
        self.options.push(option);
        self
    }

    /// Appends a review entry.
    #[must_use]
    pub fn with_review_entry(mut self, entry: ReviewDiffEntry) -> Self {
        self.review_entries.push(entry);
        self
    }

    /// Sets metadata.
    #[must_use]
    pub fn with_metadata(mut self, metadata: serde_json::Value) -> Self {
        self.metadata = metadata;
        self
    }

    /// BLAKE3 over the canonical JSON of the payload. Stored on the interaction
    /// and embedded in [`CommandOrigin::ConfirmedInteraction`] so a command can
    /// prove which content the user confirmed.
    pub fn hash(&self) -> Result<Digest, HashError> {
        canonical_digest(self)
    }

    /// Finds a stored option.
    #[must_use]
    pub fn option(&self, id: &OptionId) -> Option<&InteractionOption> {
        self.options.iter().find(|o| &o.id == id)
    }

    /// Identifiers of all options.
    #[must_use]
    pub fn option_ids(&self) -> Vec<OptionId> {
        self.options.iter().map(|o| o.id.clone()).collect()
    }

    /// Sets the free-form prompt.
    #[must_use]
    pub fn with_freeform_prompt(mut self, prompt: impl Into<LocalizedText>) -> Self {
        self.freeform_prompt = Some(prompt.into());
        self
    }

    /// Checks that a card of this `kind` can actually be answered (I6).
    ///
    /// A user-owned phase whose card carries no usable option is a dead end:
    /// the case blocks on an answer nobody can give. The rules are:
    ///
    /// * option ids are unique, whatever the kind;
    /// * `Boolean` has exactly two options;
    /// * `SingleSelect`, `SelectTarget` and `ResolveValidationError` have at
    ///   least one option;
    /// * `ConfirmCommand` and `ReviewChanges` have at least one option that
    ///   authorizes commands **and** one that declines, so refusing is always
    ///   possible; `ReviewChanges` also has at least one diff entry;
    /// * `Reauthenticate` and `ExternalSignature` have at least one option that
    ///   authorizes commands, since their whole purpose is to carry that
    ///   authority;
    /// * `Freeform` has a prompt and an option that requires free text;
    /// * `MultiSelect` is refused outright: the input protocol carries one
    ///   option id ([`InteractionResponse::option_id`]), so a persisted
    ///   multi-select card could only ever be answered as a single select.
    pub fn validate_for(&self, kind: InteractionKind) -> Result<(), InteractionSpecError> {
        let mut seen = std::collections::BTreeSet::new();
        for option in &self.options {
            if !seen.insert(&option.id) {
                return Err(InteractionSpecError::DuplicateOptionId {
                    option_id: option.id.clone(),
                });
            }
        }
        let authorizing = self
            .options
            .iter()
            .filter(|o| o.action.action_class().authorizes_commands())
            .count();
        let declining = self.options.iter().filter(|o| o.action.declines()).count();
        let required_freeform = self
            .options
            .iter()
            .filter(|o| o.freeform_policy.requires())
            .count();
        let require_options = |expected: usize| {
            if self.options.len() < expected {
                Err(InteractionSpecError::NotEnoughOptions {
                    interaction_kind: kind,
                    required: expected,
                    found: self.options.len(),
                })
            } else {
                Ok(())
            }
        };
        match kind {
            InteractionKind::MultiSelect => {
                return Err(InteractionSpecError::UnsupportedKind {
                    interaction_kind: kind,
                });
            }
            InteractionKind::Boolean => {
                if self.options.len() != 2 {
                    return Err(InteractionSpecError::NotEnoughOptions {
                        interaction_kind: kind,
                        required: 2,
                        found: self.options.len(),
                    });
                }
            }
            InteractionKind::SingleSelect
            | InteractionKind::SelectTarget
            | InteractionKind::ResolveValidationError => require_options(1)?,
            InteractionKind::ConfirmCommand | InteractionKind::ReviewChanges => {
                require_options(2)?;
                if authorizing == 0 {
                    return Err(InteractionSpecError::MissingAuthorizingOption {
                        interaction_kind: kind,
                    });
                }
                if declining == 0 {
                    return Err(InteractionSpecError::MissingDeclineOption {
                        interaction_kind: kind,
                    });
                }
                if kind == InteractionKind::ReviewChanges && self.review_entries.is_empty() {
                    return Err(InteractionSpecError::MissingReviewEntries);
                }
            }
            InteractionKind::Reauthenticate | InteractionKind::ExternalSignature => {
                require_options(1)?;
                if authorizing == 0 {
                    return Err(InteractionSpecError::MissingAuthorizingOption {
                        interaction_kind: kind,
                    });
                }
            }
            InteractionKind::Freeform => {
                require_options(1)?;
                if self.freeform_prompt.is_none() {
                    return Err(InteractionSpecError::MissingFreeformPrompt);
                }
                if required_freeform == 0 {
                    return Err(InteractionSpecError::MissingFreeformOption);
                }
            }
        }
        Ok(())
    }
}

/// What a reducer or workflow asks the engine to create (spec §13.3, I6).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InteractionSpec {
    /// Stable key within a turn/plan (e.g. `"select_target:acts[1]"`). Two
    /// specs with the same key describe the same interaction.
    pub key: String,
    /// Case the interaction belongs to; its revision is the bound revision.
    pub case_ref: CaseRef,
    /// Shape.
    pub kind: InteractionKind,
    /// Whether it owns unqualified answers for the case (I5).
    pub blocking: bool,
    /// Content.
    pub payload: InteractionPayload,
    /// Time to live, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_in: Option<Duration>,
    /// Whether typed text may resolve it.
    #[serde(default)]
    pub text_resolution: TextResolutionPolicy,
    /// Highest risk class of the commands an answer to this card authorizes.
    ///
    /// The default is [`RiskClass::Irreversible`], so a card that forgets to
    /// declare it is treated as consequential and can never be resolved from
    /// typed text (spec §13.2 rule 8, §15.7).
    #[serde(default = "RiskClass::conservative")]
    pub confirms_risk: RiskClass,
    /// `true` when the interaction is invalidated by a case revision change.
    pub binds_to_revision: bool,
}

impl InteractionSpec {
    /// Builds a blocking, revision-bound spec with `Never` text resolution and
    /// the conservative [`RiskClass::Irreversible`] confirmation risk.
    #[must_use]
    pub fn new(
        key: impl Into<String>,
        case_ref: CaseRef,
        kind: InteractionKind,
        payload: InteractionPayload,
    ) -> Self {
        Self {
            key: key.into(),
            case_ref,
            kind,
            blocking: true,
            payload,
            expires_in: None,
            text_resolution: TextResolutionPolicy::Never,
            confirms_risk: RiskClass::conservative(),
            binds_to_revision: true,
        }
    }

    /// Declares the highest risk class an answer authorizes.
    #[must_use]
    pub fn with_confirms_risk(mut self, risk: RiskClass) -> Self {
        self.confirms_risk = risk;
        self
    }

    /// Checks that the card can be answered and that its text-resolution
    /// policy is allowed for what it confirms.
    ///
    /// Beyond [`InteractionPayload::validate_for`], any policy other than
    /// [`TextResolutionPolicy::Never`] is refused when the card authorizes
    /// commands above [`RiskClass::ReversibleLowRisk`] or is one of the
    /// authorizing kinds ([`InteractionKind::authorizes_commands`]): a
    /// confirmation inferred from prose is not a confirmation.
    pub fn validate(&self) -> Result<(), InteractionSpecError> {
        self.payload.validate_for(self.kind)?;
        if self.text_resolution != TextResolutionPolicy::Never
            && (self.confirms_risk > RiskClass::ReversibleLowRisk
                || self.kind.authorizes_commands())
        {
            return Err(InteractionSpecError::TextResolutionNotAllowed {
                interaction_kind: self.kind,
                confirms_risk: self.confirms_risk,
            });
        }
        Ok(())
    }

    /// Marks the spec non-blocking.
    #[must_use]
    pub fn non_blocking(mut self) -> Self {
        self.blocking = false;
        self
    }

    /// Sets the text resolution policy.
    #[must_use]
    pub fn with_text_resolution(mut self, policy: TextResolutionPolicy) -> Self {
        self.text_resolution = policy;
        self
    }

    /// Sets the time to live.
    #[must_use]
    pub fn expires_in(mut self, ttl: Duration) -> Self {
        self.expires_in = Some(ttl);
        self
    }

    /// Makes the interaction survive revision changes.
    #[must_use]
    pub fn revision_independent(mut self) -> Self {
        self.binds_to_revision = false;
        self
    }
}

/// A persisted interaction (spec §15.1).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Interaction {
    /// Identifier.
    pub id: InteractionId,
    /// Owning tenant.
    pub account_id: AccountId,
    /// Owning conversation.
    pub conversation_id: ConversationId,
    /// Case and the revision the card was rendered against (the bound revision).
    pub case_ref: CaseRef,
    /// Turn that created it.
    pub created_by_turn: TurnId,
    /// Shape.
    pub kind: InteractionKind,
    /// Whether it owns unqualified answers for the case.
    pub blocking: bool,
    /// Immutable content.
    pub payload: InteractionPayload,
    /// Hash of `payload` at creation.
    pub payload_hash: Digest,
    /// Lifecycle status.
    pub status: InteractionStatus,
    /// `true` when a revision change does not invalidate it.
    pub revision_independent: bool,
    /// Whether typed text may resolve it.
    pub text_resolution: TextResolutionPolicy,
    /// Highest risk class of the commands an answer authorizes. Conservative
    /// ([`RiskClass::Irreversible`]) when a stored record predates the field.
    #[serde(default = "RiskClass::conservative")]
    pub confirms_risk: RiskClass,
    /// Creation time.
    pub created_at: DateTime<Utc>,
    /// Expiry, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,
    /// Resolution time, if resolved.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved_at: Option<DateTime<Utc>>,
    /// Option chosen, if resolved.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved_option_id: Option<OptionId>,
}

impl Interaction {
    /// Materializes a spec into a new `Active` interaction, computing the
    /// payload hash and the expiry.
    ///
    /// Fails closed: a card that cannot be answered
    /// ([`InteractionSpec::validate`]) or whose time to live cannot be applied
    /// is never persisted. Silently dropping an out-of-range TTL would produce
    /// a card that never expires, which is a fail-open on a safety timeout.
    pub fn from_spec(
        spec: InteractionSpec,
        id: InteractionId,
        account_id: AccountId,
        conversation_id: ConversationId,
        created_by_turn: TurnId,
        now: DateTime<Utc>,
    ) -> Result<Self, InteractionError> {
        spec.validate()?;
        let payload_hash = spec.payload.hash().map_err(|_| InteractionError::Hash)?;
        let expires_at = spec
            .expires_in
            .map(|ttl| {
                chrono::Duration::from_std(ttl)
                    .ok()
                    .and_then(|ttl| now.checked_add_signed(ttl))
                    .ok_or(InteractionError::InvalidTtl)
            })
            .transpose()?;
        Ok(Self {
            id,
            account_id,
            conversation_id,
            case_ref: spec.case_ref,
            created_by_turn,
            kind: spec.kind,
            blocking: spec.blocking,
            payload: spec.payload,
            payload_hash,
            status: InteractionStatus::Active,
            revision_independent: !spec.binds_to_revision,
            text_resolution: spec.text_resolution,
            confirms_risk: spec.confirms_risk,
            created_at: now,
            expires_at,
            resolved_at: None,
            resolved_option_id: None,
        })
    }

    /// The revision the card is bound to, or `None` when revision independent.
    #[must_use]
    pub fn bound_revision(&self) -> Option<CaseRevision> {
        (!self.revision_independent).then_some(self.case_ref.expected_revision)
    }

    /// Returns `true` when `now` is past the expiry.
    #[must_use]
    pub fn is_expired(&self, now: DateTime<Utc>) -> bool {
        self.expires_at.is_some_and(|at| at <= now)
    }

    /// Recomputes the payload hash and compares it with the stored one.
    pub fn verify_payload_hash(&self) -> Result<bool, HashError> {
        Ok(self.payload.hash()? == self.payload_hash)
    }

    /// Applies a status transition, refusing illegal ones.
    pub fn transition(&mut self, to: InteractionStatus) -> Result<(), InteractionError> {
        if !InteractionStatus::can_transition(self.status, to) {
            return Err(InteractionError::InvalidTransition {
                interaction_id: self.id,
                from: self.status,
                to,
            });
        }
        self.status = to;
        Ok(())
    }

    /// Records the chosen option and moves to `Resolving`.
    pub fn begin_resolution(
        &mut self,
        option_id: OptionId,
        now: DateTime<Utc>,
    ) -> Result<(), InteractionError> {
        self.transition(InteractionStatus::Resolving)?;
        self.resolved_option_id = Some(option_id);
        self.resolved_at = Some(now);
        Ok(())
    }

    /// The client-facing projection without server actions.
    #[must_use]
    pub fn view(&self) -> InteractionView {
        InteractionView {
            id: self.id,
            kind: self.kind,
            status: self.status,
            blocking: self.blocking,
            case_ref: self.case_ref.clone(),
            title: self.payload.title.clone(),
            body: self.payload.body.clone(),
            options: self
                .payload
                .options
                .iter()
                .map(InteractionOption::view)
                .collect(),
            review_entries: self.payload.review_entries.clone(),
            freeform_prompt: self.payload.freeform_prompt.clone(),
            metadata: self.payload.metadata.clone(),
            expires_at: self.expires_at,
        }
    }
}

/// Client-facing option: no server action.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InteractionOptionView {
    /// Identifier to echo back.
    pub id: OptionId,
    /// Label copy.
    pub label: LocalizedText,
    /// Whether free text may accompany the click.
    pub freeform_policy: FreeformPolicy,
    /// Visual emphasis.
    pub style: OptionStyle,
}

/// Client-facing projection of an interaction (spec §18.1).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InteractionView {
    /// Identifier.
    pub id: InteractionId,
    /// Shape.
    pub kind: InteractionKind,
    /// Status.
    pub status: InteractionStatus,
    /// Whether it blocks the case.
    pub blocking: bool,
    /// Case and bound revision the client must echo back.
    pub case_ref: CaseRef,
    /// Title copy.
    pub title: LocalizedText,
    /// Body copy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<LocalizedText>,
    /// Options without actions.
    pub options: Vec<InteractionOptionView>,
    /// Diff entries.
    #[serde(default)]
    pub review_entries: Vec<ReviewDiffEntry>,
    /// Free-form prompt.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub freeform_prompt: Option<LocalizedText>,
    /// Application metadata.
    #[serde(default)]
    pub metadata: serde_json::Value,
    /// Expiry.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,
}

/// Why a response was not accepted (spec §15.5).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum InteractionRejection {
    /// Wrong id, account or conversation. Deliberately indistinguishable so a
    /// guessed id reveals nothing about other tenants (spec §25.4).
    #[error("interaction not found")]
    NotFound,
    /// The interaction is not `Active`.
    #[error("interaction is not active ({status:?})")]
    NotActive {
        /// Current status.
        status: InteractionStatus,
    },
    /// The interaction was already resolved; the original option is returned so
    /// the caller can replay the original result (I14).
    #[error("interaction already resolved")]
    AlreadyResolved {
        /// The option chosen originally.
        option_id: Option<OptionId>,
    },
    /// The interaction expired.
    #[error("interaction expired")]
    Expired,
    /// The case moved past the bound revision, or the client echoed another one.
    #[error("interaction stale: bound {bound_revision}, current {current_revision}")]
    Stale {
        /// Revision the card was rendered against.
        bound_revision: CaseRevision,
        /// Revision now.
        current_revision: CaseRevision,
    },
    /// The option id is not stored on the interaction.
    #[error("unknown option")]
    UnknownOption,
    /// Free text was supplied but the option forbids it.
    #[error("freeform input not allowed")]
    FreeformNotAllowed,
    /// The option requires free text and none was supplied.
    #[error("freeform input required")]
    FreeformRequired,
    /// Free text exceeds the option's limit.
    #[error("freeform input exceeds {max_len} characters")]
    FreeformTooLong {
        /// The limit.
        max_len: usize,
    },
    /// The stored payload no longer hashes to the stored `payload_hash`, so the
    /// option's meaning is not the one the user saw.
    #[error("interaction payload does not match its stored hash")]
    PayloadCorrupt,
    /// The answer arrived on a channel the card's
    /// [`TextResolutionPolicy`] does not admit (e.g. an interpreted "yes" on a
    /// card that only the CTA resolves).
    #[error("interaction cannot be resolved through the {channel:?} channel")]
    ChannelNotAllowed {
        /// The channel the answer arrived on.
        channel: ResolutionChannel,
    },
}

/// A response that passed every §15.5 rule.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcceptedResponse {
    /// The interaction.
    pub interaction_id: InteractionId,
    /// Case and bound revision.
    pub case_ref: CaseRef,
    /// Shape of the card that was answered.
    pub kind: InteractionKind,
    /// The chosen option.
    pub option_id: OptionId,
    /// Server-side meaning of the option.
    pub action: StoredInteractionAction,
    /// How the answer reached the server.
    pub channel: ResolutionChannel,
    /// Free text, when permitted and supplied.
    pub freeform_input: Option<String>,
    /// Hash of the payload the user saw.
    pub payload_hash: Digest,
}

impl AcceptedResponse {
    /// The command origin this response authorizes (I12), or `None` when it
    /// authorizes nothing.
    ///
    /// Only an option that actually confirms or applies commands mints an
    /// origin. Picking a case on a `SelectTarget` card, answering a
    /// clarification or dismissing a card resolves the interaction without
    /// authorizing anything: the runtime must re-run policy for the original
    /// act and raise a fresh confirmation when one is required, instead of
    /// treating the click as consent.
    #[must_use]
    pub fn origin(&self) -> Option<CommandOrigin> {
        let action_class = self.action.action_class();
        action_class
            .authorizes_commands()
            .then(|| CommandOrigin::ConfirmedInteraction {
                interaction_id: self.interaction_id,
                payload_hash: self.payload_hash.clone(),
                interaction_kind: self.kind,
                action_class,
                channel: self.channel,
            })
    }
}

/// Pure validation of a client response against the stored interaction
/// (spec §15.5).
///
/// Checks, in order: identity (id, account, conversation → `NotFound`),
/// status (`AlreadyResolved` / `NotActive`), expiry, revision binding
/// (`Stale`), payload integrity (`PayloadCorrupt`), the resolution channel
/// against the stored [`TextResolutionPolicy`] (`ChannelNotAllowed`), option
/// existence (`UnknownOption`), free-form rules.
///
/// `channel` says how the answer arrived: [`ResolutionChannel::Click`] for a
/// structured client response, the text channels when the runtime resolved
/// typed text to an option. It is carried into the accepted response and from
/// there into the [`CommandOrigin`], because an inferred "yes" and a click are
/// not the same authority (I12, I20).
pub fn validate_response(
    interaction: &Interaction,
    response: &InteractionResponse,
    channel: ResolutionChannel,
    actor: &ActorContext,
    conversation_id: &ConversationId,
    current_revision: CaseRevision,
    now: DateTime<Utc>,
) -> Result<AcceptedResponse, InteractionRejection> {
    if response.interaction_id != interaction.id
        || actor.account_id != interaction.account_id
        || *conversation_id != interaction.conversation_id
    {
        return Err(InteractionRejection::NotFound);
    }
    match interaction.status {
        InteractionStatus::Active => {}
        InteractionStatus::Resolved => {
            return Err(InteractionRejection::AlreadyResolved {
                option_id: interaction.resolved_option_id.clone(),
            });
        }
        status => return Err(InteractionRejection::NotActive { status }),
    }
    if interaction.is_expired(now) {
        return Err(InteractionRejection::Expired);
    }
    if let Some(bound) = interaction.bound_revision()
        && (response.expected_case_revision != bound || current_revision != bound)
    {
        return Err(InteractionRejection::Stale {
            bound_revision: bound,
            current_revision,
        });
    }
    // The stored payload is what the user saw and what the origin's hash will
    // claim; if the two disagree, the option's meaning is not the one that was
    // shown, so nothing may execute (I19, §15.5).
    if !matches!(interaction.verify_payload_hash(), Ok(true)) {
        return Err(InteractionRejection::PayloadCorrupt);
    }
    if !interaction.text_resolution.admits(channel) {
        return Err(InteractionRejection::ChannelNotAllowed { channel });
    }
    let option = interaction
        .payload
        .option(&response.option_id)
        .ok_or(InteractionRejection::UnknownOption)?;
    let freeform_input = match (&response.freeform_input, option.freeform_policy) {
        (Some(_), FreeformPolicy::Forbidden) => {
            return Err(InteractionRejection::FreeformNotAllowed);
        }
        (None, FreeformPolicy::Required { .. }) => {
            return Err(InteractionRejection::FreeformRequired);
        }
        (
            Some(text),
            FreeformPolicy::Optional { max_len } | FreeformPolicy::Required { max_len },
        ) => {
            if text.chars().count() > max_len {
                return Err(InteractionRejection::FreeformTooLong { max_len });
            }
            // Blank text is no text: required free text must carry content.
            if text.trim().is_empty() {
                if option.freeform_policy.requires() {
                    return Err(InteractionRejection::FreeformRequired);
                }
                None
            } else {
                Some(text.clone())
            }
        }
        (None, _) => None,
    };
    Ok(AcceptedResponse {
        interaction_id: interaction.id,
        case_ref: interaction.case_ref.clone(),
        kind: interaction.kind,
        option_id: option.id.clone(),
        action: option.action.clone(),
        channel,
        freeform_input,
        payload_hash: interaction.payload_hash.clone(),
    })
}

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

    fn now() -> DateTime<Utc> {
        DateTime::from_timestamp(1_700_000_000, 0).unwrap()
    }

    fn confirm_option() -> InteractionOption {
        InteractionOption::new(
            "confirm",
            "Confirm",
            StoredInteractionAction::ApplyOperation {
                operation: OperationKey::from("trip.rebook"),
                arguments: serde_json::Value::Null,
                freeform_argument: None,
            },
        )
    }

    fn decline_option() -> InteractionOption {
        InteractionOption::new("no", "Cancel", StoredInteractionAction::DeclineCommands)
    }

    fn payload() -> InteractionPayload {
        InteractionPayload::new("Rebook this flight?")
            .with_option(confirm_option())
            .with_option(decline_option())
            .with_option(
                InteractionOption::new("note", "Add a note", StoredInteractionAction::Dismiss)
                    .with_freeform(FreeformPolicy::Optional { max_len: 5 }),
            )
            .with_option(
                InteractionOption::new("why", "Explain", StoredInteractionAction::Dismiss)
                    .with_freeform(FreeformPolicy::Required { max_len: 100 }),
            )
    }

    fn spec() -> InteractionSpec {
        InteractionSpec::new(
            "send",
            CaseRef::new("trip", "i1", CaseRevision(12)),
            InteractionKind::ConfirmCommand,
            payload(),
        )
    }

    fn interaction() -> Interaction {
        Interaction::from_spec(
            spec(),
            InteractionId::nil(),
            AccountId::from("acct"),
            ConversationId::nil(),
            TurnId::nil(),
            now(),
        )
        .unwrap()
    }

    fn response(option: &str) -> InteractionResponse {
        InteractionResponse {
            interaction_id: InteractionId::nil(),
            option_id: OptionId::from(option),
            expected_case_revision: CaseRevision(12),
            freeform_input: None,
        }
    }

    fn actor() -> ActorContext {
        ActorContext::new("acct", "u1")
    }

    fn validate(
        i: &Interaction,
        r: &InteractionResponse,
    ) -> Result<AcceptedResponse, InteractionRejection> {
        validate_response(
            i,
            r,
            ResolutionChannel::Click,
            &actor(),
            &ConversationId::nil(),
            CaseRevision(12),
            now(),
        )
    }

    #[test]
    fn happy_path_yields_confirmed_origin() {
        let i = interaction();
        let accepted = validate(&i, &response("confirm")).unwrap();
        assert_eq!(accepted.option_id, OptionId::from("confirm"));
        assert_eq!(
            accepted.origin(),
            Some(CommandOrigin::ConfirmedInteraction {
                interaction_id: i.id,
                payload_hash: i.payload_hash.clone(),
                interaction_kind: InteractionKind::ConfirmCommand,
                action_class: ActionClass::AppliesOperation,
                channel: ResolutionChannel::Click,
            })
        );
        assert!(crate::command::origin_satisfies(
            &accepted.origin().unwrap(),
            &crate::command::CommandPolicy::conservative()
        ));
    }

    #[test]
    fn an_option_that_authorizes_nothing_mints_no_origin() {
        let i = interaction();
        // Declining and dismissing resolve the card without authorizing a
        // command; the runtime must not treat either as consent.
        for option in ["no", "note"] {
            let accepted = validate(&i, &response(option)).unwrap();
            assert_eq!(accepted.origin(), None, "{option}");
        }
        let selection = Interaction::from_spec(
            InteractionSpec::new(
                "which",
                CaseRef::new("trip", "i1", CaseRevision(12)),
                InteractionKind::SelectTarget,
                InteractionPayload::new("Which trip?").with_option(InteractionOption::new(
                    "a",
                    "Trip A",
                    StoredInteractionAction::SelectTarget {
                        case_ref: CaseRef::new("trip", "a", CaseRevision(1)),
                    },
                )),
            ),
            InteractionId::nil(),
            AccountId::from("acct"),
            ConversationId::nil(),
            TurnId::nil(),
            now(),
        )
        .unwrap();
        let accepted = validate(&selection, &response("a")).unwrap();
        assert_eq!(accepted.origin(), None);
    }

    #[test]
    fn wrong_account_and_conversation_are_indistinguishable() {
        let i = interaction();
        let other_actor = ActorContext::new("other", "u1");
        let err_account = validate_response(
            &i,
            &response("confirm"),
            ResolutionChannel::Click,
            &other_actor,
            &ConversationId::nil(),
            CaseRevision(12),
            now(),
        )
        .unwrap_err();
        let err_conv = validate_response(
            &i,
            &response("confirm"),
            ResolutionChannel::Click,
            &actor(),
            &ConversationId::new(),
            CaseRevision(12),
            now(),
        )
        .unwrap_err();
        let mut r = response("confirm");
        r.interaction_id = InteractionId::new();
        let err_id = validate(&i, &r).unwrap_err();
        assert_eq!(err_account, InteractionRejection::NotFound);
        assert_eq!(err_conv, InteractionRejection::NotFound);
        assert_eq!(err_id, InteractionRejection::NotFound);
    }

    #[test]
    fn identity_is_checked_before_status_and_expiry() {
        // A foreign tenant must not learn that the card exists, whatever state
        // it is in.
        let mut resolved = interaction();
        resolved
            .begin_resolution(OptionId::from("confirm"), now())
            .unwrap();
        resolved.transition(InteractionStatus::Resolved).unwrap();
        let mut expired = interaction();
        expired.expires_at = Some(now() - chrono::Duration::seconds(1));
        for card in [&resolved, &expired] {
            let err = validate_response(
                card,
                &response("confirm"),
                ResolutionChannel::Click,
                &ActorContext::new("other", "u1"),
                &ConversationId::nil(),
                CaseRevision(12),
                now(),
            )
            .unwrap_err();
            assert_eq!(err, InteractionRejection::NotFound);
        }
    }

    #[test]
    fn unknown_option_rejected() {
        assert_eq!(
            validate(&interaction(), &response("nope")).unwrap_err(),
            InteractionRejection::UnknownOption
        );
    }

    #[test]
    fn freeform_rules() {
        let i = interaction();
        let mut r = response("confirm");
        r.freeform_input = Some("x".into());
        assert_eq!(
            validate(&i, &r).unwrap_err(),
            InteractionRejection::FreeformNotAllowed
        );
        let mut r = response("note");
        r.freeform_input = Some("toolong".into());
        assert_eq!(
            validate(&i, &r).unwrap_err(),
            InteractionRejection::FreeformTooLong { max_len: 5 }
        );
        r.freeform_input = Some("exact".into());
        assert_eq!(
            validate(&i, &r).unwrap().freeform_input.as_deref(),
            Some("exact"),
            "a string of exactly max_len characters is accepted"
        );
        r.freeform_input = Some("ok".into());
        assert_eq!(
            validate(&i, &r).unwrap().freeform_input.as_deref(),
            Some("ok")
        );
        assert!(validate(&i, &response("note")).is_ok());
        assert_eq!(
            validate(&i, &response("why")).unwrap_err(),
            InteractionRejection::FreeformRequired
        );
    }

    #[test]
    fn blank_text_does_not_satisfy_a_required_freeform() {
        let i = interaction();
        for blank in ["", "   ", "\n\t "] {
            let mut r = response("why");
            r.freeform_input = Some(blank.into());
            assert_eq!(
                validate(&i, &r).unwrap_err(),
                InteractionRejection::FreeformRequired,
                "{blank:?}"
            );
        }
        // Blank optional text is simply no text.
        let mut r = response("note");
        r.freeform_input = Some("  ".into());
        assert_eq!(validate(&i, &r).unwrap().freeform_input, None);
    }

    #[test]
    fn a_tampered_payload_is_refused() {
        let mut i = interaction();
        i.payload.options[0].action = StoredInteractionAction::ApplyOperation {
            operation: OperationKey::from("trip.withdraw"),
            arguments: serde_json::Value::Null,
            freeform_argument: None,
        };
        assert!(!i.verify_payload_hash().unwrap());
        assert_eq!(
            validate(&i, &response("confirm")).unwrap_err(),
            InteractionRejection::PayloadCorrupt
        );
    }

    #[test]
    fn a_card_only_answers_on_the_channels_it_admits() {
        let i = interaction();
        let channel = ResolutionChannel::ModelInterpreted;
        let err = validate_response(
            &i,
            &response("confirm"),
            channel,
            &actor(),
            &ConversationId::nil(),
            CaseRevision(12),
            now(),
        )
        .unwrap_err();
        assert_eq!(err, InteractionRejection::ChannelNotAllowed { channel });
        let mut aliased = Interaction::from_spec(
            InteractionSpec::new(
                "pick",
                CaseRef::new("trip", "i1", CaseRevision(12)),
                InteractionKind::SingleSelect,
                InteractionPayload::new("Which?").with_option(InteractionOption::new(
                    "a",
                    "A",
                    StoredInteractionAction::ResolveClarification {
                        answer_key: "a".into(),
                    },
                )),
            )
            .with_confirms_risk(RiskClass::ReversibleLowRisk)
            .with_text_resolution(TextResolutionPolicy::Never),
            InteractionId::nil(),
            AccountId::from("acct"),
            ConversationId::nil(),
            TurnId::nil(),
            now(),
        )
        .unwrap();
        aliased.text_resolution = TextResolutionPolicy::ModelInterpretedLowRisk;
        let accepted = validate_response(
            &aliased,
            &response("a"),
            ResolutionChannel::ModelInterpreted,
            &actor(),
            &ConversationId::nil(),
            CaseRevision(12),
            now(),
        )
        .unwrap();
        assert_eq!(accepted.channel, ResolutionChannel::ModelInterpreted);
        assert_eq!(
            accepted.origin(),
            None,
            "a clarification authorizes nothing"
        );
    }

    #[test]
    fn stale_revision_rejected_both_ways() {
        let i = interaction();
        let mut r = response("confirm");
        r.expected_case_revision = CaseRevision(11);
        assert_eq!(
            validate(&i, &r).unwrap_err(),
            InteractionRejection::Stale {
                bound_revision: CaseRevision(12),
                current_revision: CaseRevision(12)
            }
        );
        let err = validate_response(
            &i,
            &response("confirm"),
            ResolutionChannel::Click,
            &actor(),
            &ConversationId::nil(),
            CaseRevision(13),
            now(),
        )
        .unwrap_err();
        assert_eq!(
            err,
            InteractionRejection::Stale {
                bound_revision: CaseRevision(12),
                current_revision: CaseRevision(13)
            }
        );
        let mut independent = interaction();
        independent.revision_independent = true;
        assert!(
            validate_response(
                &independent,
                &response("confirm"),
                ResolutionChannel::Click,
                &actor(),
                &ConversationId::nil(),
                CaseRevision(99),
                now(),
            )
            .is_ok()
        );
    }

    #[test]
    fn already_resolved_returns_original_option() {
        let mut i = interaction();
        i.begin_resolution(OptionId::from("confirm"), now())
            .unwrap();
        i.transition(InteractionStatus::Resolved).unwrap();
        assert_eq!(
            validate(&i, &response("confirm")).unwrap_err(),
            InteractionRejection::AlreadyResolved {
                option_id: Some(OptionId::from("confirm"))
            }
        );
    }

    #[test]
    fn expired_and_not_active() {
        let mut i = interaction();
        i.expires_at = Some(now() - chrono::Duration::seconds(1));
        assert_eq!(
            validate(&i, &response("confirm")).unwrap_err(),
            InteractionRejection::Expired
        );
        let mut i = interaction();
        i.status = InteractionStatus::Invalidated;
        assert_eq!(
            validate(&i, &response("confirm")).unwrap_err(),
            InteractionRejection::NotActive {
                status: InteractionStatus::Invalidated
            }
        );
        let mut i = interaction();
        i.status = InteractionStatus::Resolving;
        assert!(matches!(
            validate(&i, &response("confirm")).unwrap_err(),
            InteractionRejection::NotActive { .. }
        ));
    }

    #[test]
    fn state_machine_table() {
        use InteractionStatus as S;
        let allowed: &[(S, S)] = &[
            (S::Active, S::Resolving),
            (S::Active, S::Resolved),
            (S::Active, S::Declined),
            (S::Active, S::Dismissed),
            (S::Active, S::Invalidated),
            (S::Active, S::Expired),
            (S::Active, S::Failed),
            (S::Resolving, S::Resolved),
            (S::Resolving, S::Failed),
            (S::Resolving, S::Active),
        ];
        for from in S::ALL {
            for to in S::ALL {
                let expected = allowed.contains(&(from, to));
                assert_eq!(S::can_transition(from, to), expected, "{from:?} -> {to:?}");
            }
        }
        for terminal in [
            S::Resolved,
            S::Declined,
            S::Dismissed,
            S::Invalidated,
            S::Expired,
            S::Failed,
        ] {
            assert!(terminal.is_terminal());
            assert!(!terminal.is_open());
        }
    }

    #[test]
    fn transition_refuses_what_the_table_forbids() {
        let mut i = interaction();
        i.transition(InteractionStatus::Resolving).unwrap();
        i.transition(InteractionStatus::Resolved).unwrap();
        let err = i.transition(InteractionStatus::Active).unwrap_err();
        assert!(matches!(
            err,
            InteractionError::InvalidTransition {
                from: InteractionStatus::Resolved,
                to: InteractionStatus::Active,
                ..
            }
        ));
        // `begin_resolution` refuses too, instead of recording the option.
        let mut done = interaction();
        done.status = InteractionStatus::Expired;
        assert!(
            done.begin_resolution(OptionId::from("confirm"), now())
                .is_err()
        );
        assert_eq!(done.resolved_option_id, None);
    }

    #[test]
    fn view_hides_actions() {
        let json = serde_json::to_value(interaction().view()).unwrap();
        assert!(json["options"][0].get("action").is_none());
        assert_eq!(json["options"][0]["id"], "confirm");
    }

    #[test]
    fn a_card_must_be_answerable_for_its_kind() {
        let title_only = InteractionPayload::new("Anything?");
        for kind in InteractionKind::ALL {
            assert!(
                title_only.validate_for(kind).is_err(),
                "{kind:?} accepted a card with no options"
            );
        }
        let boolean = InteractionPayload::new("Ready?")
            .with_option(InteractionOption::new(
                "yes",
                "Yes",
                StoredInteractionAction::ConfirmCommands {
                    command_refs: vec![],
                },
            ))
            .with_option(decline_option());
        assert_eq!(boolean.validate_for(InteractionKind::Boolean), Ok(()));
        let three = boolean.clone().with_option(InteractionOption::new(
            "maybe",
            "Maybe",
            StoredInteractionAction::Dismiss,
        ));
        assert!(matches!(
            three.validate_for(InteractionKind::Boolean),
            Err(InteractionSpecError::NotEnoughOptions { .. })
        ));
        // A confirmation the user cannot refuse is not a confirmation.
        let no_decline = InteractionPayload::new("Send?")
            .with_option(confirm_option())
            .with_option(InteractionOption::new(
                "later",
                "Later",
                StoredInteractionAction::ResolveClarification {
                    answer_key: "later".into(),
                },
            ));
        assert!(matches!(
            no_decline.validate_for(InteractionKind::ConfirmCommand),
            Err(InteractionSpecError::MissingDeclineOption { .. })
        ));
        let no_authority = InteractionPayload::new("Send?")
            .with_option(decline_option())
            .with_option(InteractionOption::new(
                "dismiss",
                "Close",
                StoredInteractionAction::Dismiss,
            ));
        assert!(matches!(
            no_authority.validate_for(InteractionKind::ConfirmCommand),
            Err(InteractionSpecError::MissingAuthorizingOption { .. })
        ));
        // A review card with nothing to review.
        assert!(matches!(
            boolean.validate_for(InteractionKind::ReviewChanges),
            Err(InteractionSpecError::MissingReviewEntries)
        ));
        let review = boolean.clone().with_review_entry(
            ReviewDiffEntry::new("total", "Total")
                .with_after(FieldValue::present(serde_json::Value::from(10))),
        );
        assert_eq!(review.validate_for(InteractionKind::ReviewChanges), Ok(()));
        // Free-form cards need somewhere to type.
        let freeform_option =
            InteractionOption::new("text", "Send", StoredInteractionAction::Dismiss)
                .with_freeform(FreeformPolicy::Required { max_len: 200 });
        let no_prompt = InteractionPayload::new("Note").with_option(freeform_option.clone());
        assert!(matches!(
            no_prompt.validate_for(InteractionKind::Freeform),
            Err(InteractionSpecError::MissingFreeformPrompt)
        ));
        let no_field = InteractionPayload::new("Note")
            .with_freeform_prompt("Write the note")
            .with_option(decline_option());
        assert!(matches!(
            no_field.validate_for(InteractionKind::Freeform),
            Err(InteractionSpecError::MissingFreeformOption)
        ));
        let good = InteractionPayload::new("Note")
            .with_freeform_prompt("Write the note")
            .with_option(freeform_option);
        assert_eq!(good.validate_for(InteractionKind::Freeform), Ok(()));
        // Duplicate ids make the answer ambiguous.
        let duplicated = InteractionPayload::new("Pick")
            .with_option(InteractionOption::new(
                "a",
                "A",
                StoredInteractionAction::Dismiss,
            ))
            .with_option(InteractionOption::new(
                "a",
                "A again",
                StoredInteractionAction::Dismiss,
            ));
        assert!(matches!(
            duplicated.validate_for(InteractionKind::SingleSelect),
            Err(InteractionSpecError::DuplicateOptionId { .. })
        ));
    }

    #[test]
    fn multi_select_cannot_be_persisted() {
        // The input protocol carries one option id, so a stored multi-select
        // card could only ever be answered as a single select.
        let payload = InteractionPayload::new("Pick some")
            .with_option(InteractionOption::new(
                "a",
                "A",
                StoredInteractionAction::Dismiss,
            ))
            .with_option(InteractionOption::new(
                "b",
                "B",
                StoredInteractionAction::Dismiss,
            ));
        assert!(matches!(
            payload.validate_for(InteractionKind::MultiSelect),
            Err(InteractionSpecError::UnsupportedKind {
                interaction_kind: InteractionKind::MultiSelect
            })
        ));
        let spec = InteractionSpec::new(
            "pick",
            CaseRef::new("trip", "i1", CaseRevision(1)),
            InteractionKind::MultiSelect,
            payload,
        );
        assert!(matches!(
            Interaction::from_spec(
                spec,
                InteractionId::nil(),
                AccountId::from("acct"),
                ConversationId::nil(),
                TurnId::nil(),
                now()
            ),
            Err(InteractionError::InvalidSpec(_))
        ));
    }

    #[test]
    fn a_confirming_card_may_never_be_resolved_from_text() {
        let base = spec();
        let policy = TextResolutionPolicy::ModelInterpretedLowRisk;
        let risky = base.clone().with_text_resolution(policy.clone());
        assert!(
            matches!(
                risky.validate(),
                Err(InteractionSpecError::TextResolutionNotAllowed { .. })
            ),
            "a ConfirmCommand card is authorizing whatever its risk"
        );
        // Even a low-risk kind is refused while it confirms something
        // consequential.
        let mut low_kind = base.clone().with_text_resolution(policy);
        low_kind.kind = InteractionKind::SingleSelect;
        low_kind.payload = InteractionPayload::new("Which?").with_option(InteractionOption::new(
            "a",
            "A",
            StoredInteractionAction::Dismiss,
        ));
        assert!(matches!(
            low_kind.validate(),
            Err(InteractionSpecError::TextResolutionNotAllowed { .. })
        ));
        assert_eq!(
            low_kind
                .with_confirms_risk(RiskClass::ReversibleLowRisk)
                .validate(),
            Ok(())
        );
        assert_eq!(base.validate(), Ok(()));
        assert_eq!(
            spec().confirms_risk,
            RiskClass::Irreversible,
            "a card that declares nothing is treated as consequential"
        );
    }

    #[test]
    fn an_unusable_time_to_live_is_an_error_not_an_immortal_card() {
        let ttl = spec().expires_in(Duration::from_secs(60));
        let card = Interaction::from_spec(
            ttl,
            InteractionId::nil(),
            AccountId::from("acct"),
            ConversationId::nil(),
            TurnId::nil(),
            now(),
        )
        .unwrap();
        assert_eq!(card.expires_at, Some(now() + chrono::Duration::seconds(60)));
        assert!(!card.is_expired(now()));
        assert!(card.is_expired(now() + chrono::Duration::seconds(61)));
        let absurd = spec().expires_in(Duration::from_secs(u64::MAX));
        assert!(matches!(
            Interaction::from_spec(
                absurd,
                InteractionId::nil(),
                AccountId::from("acct"),
                ConversationId::nil(),
                TurnId::nil(),
                now()
            ),
            Err(InteractionError::InvalidTtl)
        ));
    }

    #[test]
    fn an_explicit_null_survives_the_round_trip() {
        let entry = ReviewDiffEntry::new("traveler.email", "Email")
            .with_before(FieldValue::present(serde_json::Value::from("a@b.it")))
            .with_after(FieldValue::cleared());
        let json = serde_json::to_value(&entry).unwrap();
        assert_eq!(json["after"], serde_json::Value::Null);
        let back: ReviewDiffEntry = serde_json::from_value(json).unwrap();
        assert_eq!(back, entry);
        assert_eq!(back.after, FieldValue::Present(serde_json::Value::Null));

        let absent = ReviewDiffEntry::new("traveler.email", "Email");
        let json = serde_json::to_value(&absent).unwrap();
        assert!(json.get("after").is_none(), "an absent side omits the key");
        assert_eq!(
            serde_json::from_value::<ReviewDiffEntry>(json).unwrap(),
            absent
        );

        // The whole point: a card that clears a field still verifies after a
        // round trip through a JSON store, so its confirmation can match.
        let payload = InteractionPayload::new("Clear the email?")
            .with_option(confirm_option())
            .with_option(decline_option())
            .with_review_entry(entry);
        let card = Interaction::from_spec(
            InteractionSpec::new(
                "clear",
                CaseRef::new("trip", "i1", CaseRevision(1)),
                InteractionKind::ReviewChanges,
                payload,
            ),
            InteractionId::nil(),
            AccountId::from("acct"),
            ConversationId::nil(),
            TurnId::nil(),
            now(),
        )
        .unwrap();
        assert!(card.verify_payload_hash().unwrap());
        let reloaded: Interaction =
            serde_json::from_str(&serde_json::to_string(&card).unwrap()).unwrap();
        assert_eq!(reloaded, card);
        assert!(reloaded.verify_payload_hash().unwrap());
    }

    #[test]
    fn action_classes_follow_the_stored_action() {
        assert_eq!(
            StoredInteractionAction::ConfirmCommands {
                command_refs: vec![]
            }
            .action_class(),
            ActionClass::ConfirmsCommands
        );
        assert_eq!(
            StoredInteractionAction::ApplyOperation {
                operation: OperationKey::from("x"),
                arguments: serde_json::Value::Null,
                freeform_argument: None,
            }
            .action_class(),
            ActionClass::AppliesOperation
        );
        for action in [
            StoredInteractionAction::DeclineCommands,
            StoredInteractionAction::Dismiss,
            StoredInteractionAction::SelectTarget {
                case_ref: CaseRef::new("w", "c", CaseRevision(1)),
            },
            StoredInteractionAction::ResolveClarification {
                answer_key: "k".into(),
            },
            StoredInteractionAction::Custom {
                key: "k".into(),
                payload: serde_json::Value::Null,
            },
        ] {
            assert_eq!(action.action_class(), ActionClass::NoCommands);
            assert!(!action.action_class().authorizes_commands());
        }
        assert!(InteractionKind::ConfirmCommand.authorizes_commands());
        assert!(InteractionKind::ExternalSignature.authorizes_commands());
        assert!(!InteractionKind::SelectTarget.authorizes_commands());
        assert_eq!(
            ConfirmationPolicy::ExplicitClick.interaction_kind(),
            Some(InteractionKind::ConfirmCommand)
        );
    }
}