riffdb-errors 0.1.0

First-party RiffDB runtime crate (riffdb-errors)
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
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
#![forbid(unsafe_code)]

//! Transport-neutral, public-safe errors for RiffDB.
//!
//! Declared business outcomes are contract values and intentionally do not
//! appear in this crate. [`PublicError`] describes failures outside that
//! outcome algebra without retaining untrusted diagnostic text or internal
//! error sources.

mod replication;
pub use replication::ReplicationStreamErrorV3;

use std::error::Error;
use std::fmt;

use riffdb_types::{
    ContractLineage, ContractVersion, ExecutionFailureCode, FieldId, IncidentId, RequestId,
};

/// Version of the bounded application-semantic error envelope.
pub const APPLICATION_ERROR_ENVELOPE_VERSION: u32 = 1;
/// Maximum encoded application-error details accepted at a public boundary.
pub const MAX_APPLICATION_ERROR_BYTES: usize = 16 * 1024;
/// Maximum number of symbolic path segments in an application error.
pub const MAX_APPLICATION_SYMBOL_PATH_SEGMENTS: usize = 16;
/// Maximum bytes in one application operation or path symbol.
pub const MAX_APPLICATION_SYMBOL_BYTES: usize = 256;
/// Maximum number of closed remediation codes in one application error.
pub const MAX_APPLICATION_FIXES: usize = 8;
/// Maximum RiffQL source offset retained in a public error.
pub const MAX_APPLICATION_SOURCE_OFFSET: u64 = 262_144;

/// Closed application operation inventory used only for public-safe context.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ApplicationOperation {
    /// Describe a symbolic contract catalog.
    DescribeContract,
    /// Check RiffQL source.
    CheckQuery,
    /// Explain ad-hoc or named RiffQL.
    ExplainQuery,
    /// Execute ad-hoc or named RiffQL.
    ExecuteQuery,
    /// Compile and deploy a named-query module.
    DeployQueryModule,
    /// Compile and publish an immutable reactive module.
    DeployReactiveModule,
    /// Inspect a named-query module.
    GetQueryModule,
    /// Execute a symbolic command.
    ExecuteCommand,
    /// Execute a bounded command batch.
    BatchCommand,
    /// Execute one projected columnar query under a freshness policy.
    ExecuteProjectedQuery,
    /// Inspect authoritative vector evidence through symbolic contract names.
    InspectVectorState,
}

impl ApplicationOperation {
    /// Returns the stable application-facing operation name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::DescribeContract => "DescribeContract",
            Self::CheckQuery => "CheckQuery",
            Self::ExplainQuery => "ExplainQuery",
            Self::ExecuteQuery => "ExecuteQuery",
            Self::DeployQueryModule => "DeployQueryModule",
            Self::DeployReactiveModule => "DeployReactiveModule",
            Self::GetQueryModule => "GetQueryModule",
            Self::ExecuteCommand => "ExecuteCommand",
            Self::BatchCommand => "BatchCommand",
            Self::ExecuteProjectedQuery => "ExecuteProjectedQuery",
            Self::InspectVectorState => "InspectVectorState",
        }
    }
}

/// Closed stable code registry for application-semantic failures.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ApplicationErrorCode {
    /// Public message bytes failed structural validation.
    InvalidRequest,
    /// A typed application input failed validation.
    InputInvalid,
    /// Current policy denied the operation.
    AuthorizationDenied,
    /// Contract identity is absent, stale, or does not match.
    ContractMismatch,
    /// RiffQL could not be parsed, resolved, typed, or planned.
    QueryInvalid,
    /// A checked query cannot currently be loaded or executed.
    QueryUnavailable,
    /// The requested named-query module is absent or stale.
    ModuleUnavailable,
    /// A continuation cursor is invalid or stale.
    CursorInvalid,
    /// One complete authorized result exceeds a public bound.
    ResponseTooLarge,
    /// Authoritative storage is temporarily unavailable.
    StorageUnavailable,
    /// A durable mutation may have completed.
    OutcomeUnknown,
    /// The request was cancelled at a safe point.
    OperationCancelled,
    /// The request deadline elapsed.
    DeadlineExceeded,
    /// A redacted internal defect occurred.
    InternalDefect,
    /// An idempotency identity was reused with different input.
    IdempotencyKeyReuse,
    /// Deterministic command execution failed.
    CommandExecutionFailed,
    /// A formerly valid capability is revoked.
    CapabilityRevoked,
    /// A public peer violated the application protocol.
    ProtocolInvalid,
    /// Observed history predates a database restore.
    HistoryIncarnationMismatch,
    /// Requested history was retired by retention prune.
    HistoryPruned,
    /// The service is over capacity and rejected admission.
    Overloaded,
    /// Exact result-set providers cannot prove one common epoch.
    ProjectionDiverged,
    /// The exact snapshot bound to the request is no longer retained.
    SnapshotRetired,
    /// No servable exact snapshot satisfies the requested freshness floor.
    FreshnessUnsatisfied,
    /// A retained nearest plan predates the required compiler-owned source declaration.
    ProjectedSourceRequired,
    /// This node is a follower and cannot execute a write operation.
    FollowerMode,
    /// Durable source fencing permanently refuses new command admission.
    PrimaryFenced,
}

/// Complete v1 application error code registry in stable wire order.
pub const APPLICATION_ERROR_CODES: [ApplicationErrorCode; 27] = [
    ApplicationErrorCode::InvalidRequest,
    ApplicationErrorCode::InputInvalid,
    ApplicationErrorCode::AuthorizationDenied,
    ApplicationErrorCode::ContractMismatch,
    ApplicationErrorCode::QueryInvalid,
    ApplicationErrorCode::QueryUnavailable,
    ApplicationErrorCode::ModuleUnavailable,
    ApplicationErrorCode::CursorInvalid,
    ApplicationErrorCode::ResponseTooLarge,
    ApplicationErrorCode::StorageUnavailable,
    ApplicationErrorCode::OutcomeUnknown,
    ApplicationErrorCode::OperationCancelled,
    ApplicationErrorCode::DeadlineExceeded,
    ApplicationErrorCode::InternalDefect,
    ApplicationErrorCode::IdempotencyKeyReuse,
    ApplicationErrorCode::CommandExecutionFailed,
    ApplicationErrorCode::CapabilityRevoked,
    ApplicationErrorCode::ProtocolInvalid,
    ApplicationErrorCode::HistoryIncarnationMismatch,
    ApplicationErrorCode::HistoryPruned,
    ApplicationErrorCode::Overloaded,
    ApplicationErrorCode::ProjectionDiverged,
    ApplicationErrorCode::SnapshotRetired,
    ApplicationErrorCode::FreshnessUnsatisfied,
    ApplicationErrorCode::ProjectedSourceRequired,
    ApplicationErrorCode::FollowerMode,
    ApplicationErrorCode::PrimaryFenced,
];

impl ApplicationErrorCode {
    /// Maps the compatible kernel classification into the application registry.
    #[must_use]
    pub const fn from_public_kind(kind: PublicErrorKind) -> Self {
        match kind {
            PublicErrorKind::Validation => Self::InputInvalid,
            PublicErrorKind::IdempotencyKeyReuse => Self::IdempotencyKeyReuse,
            PublicErrorKind::AuthorizationDenied => Self::AuthorizationDenied,
            PublicErrorKind::ConcurrencyDeadlineExceeded => Self::DeadlineExceeded,
            PublicErrorKind::ContractMismatch => Self::ContractMismatch,
            PublicErrorKind::StorageUnavailable => Self::StorageUnavailable,
            PublicErrorKind::OutcomeUnknown => Self::OutcomeUnknown,
            PublicErrorKind::InternalDefect => Self::InternalDefect,
            PublicErrorKind::CommandExecutionFailed => Self::CommandExecutionFailed,
            PublicErrorKind::HistoryIncarnationMismatch => Self::HistoryIncarnationMismatch,
            PublicErrorKind::HistoryPruned => Self::HistoryPruned,
            PublicErrorKind::Overloaded => Self::Overloaded,
            PublicErrorKind::FollowerMode => Self::FollowerMode,
            PublicErrorKind::PrimaryFenced => Self::PrimaryFenced,
        }
    }

    /// Returns the stable externally documented code.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::InvalidRequest => "RDB-APP-0001",
            Self::InputInvalid => "RDB-INPUT-0101",
            Self::AuthorizationDenied => "RDB-AUTH-0214",
            Self::ContractMismatch => "RDB-CONTRACT-0101",
            Self::QueryInvalid => "RDB-QUERY-0101",
            Self::QueryUnavailable => "RDB-QUERY-0102",
            Self::ModuleUnavailable => "RDB-MODULE-0101",
            Self::CursorInvalid => "RDB-CURSOR-0101",
            Self::ResponseTooLarge => "RDB-RESOURCE-0101",
            Self::StorageUnavailable => "RDB-STORAGE-0101",
            Self::OutcomeUnknown => "RDB-UNCERTAIN-0101",
            Self::OperationCancelled => "RDB-APP-0002",
            Self::DeadlineExceeded => "RDB-APP-0003",
            Self::InternalDefect => "RDB-INTERNAL-0001",
            Self::IdempotencyKeyReuse => "RDB-COMMAND-0101",
            Self::CommandExecutionFailed => "RDB-COMMAND-0102",
            Self::CapabilityRevoked => "RDB-AUTH-0215",
            Self::ProtocolInvalid => "RDB-PROTOCOL-0101",
            Self::HistoryIncarnationMismatch => "RDB-HISTORY-0101",
            Self::HistoryPruned => "RDB-HISTORY-0102",
            Self::Overloaded => "RDB-CAPACITY-0101",
            Self::ProjectionDiverged => "RDB-PROJECTION-0101",
            Self::SnapshotRetired => "RDB-PROJECTION-0102",
            Self::FreshnessUnsatisfied => "RDB-PROJECTION-0103",
            Self::ProjectedSourceRequired => "RDB-PROJECTION-0104",
            Self::FollowerMode => "RDB-REP-0101",
            Self::PrimaryFenced => "RDB-REP-0102",
        }
    }

    /// Returns the one registry-owned public message for this code.
    #[must_use]
    pub const fn safe_message(self) -> &'static str {
        match self {
            Self::InvalidRequest => "application request is structurally invalid",
            Self::InputInvalid => "application input is invalid",
            Self::AuthorizationDenied => "application operation is not authorized",
            Self::ContractMismatch => "application contract does not match",
            Self::QueryInvalid => "RiffQL query is invalid",
            Self::QueryUnavailable => "RiffQL query is unavailable",
            Self::ModuleUnavailable => "query module is unavailable",
            Self::CursorInvalid => "query cursor is invalid or stale",
            Self::ResponseTooLarge => "application result exceeds the service limit",
            Self::StorageUnavailable => "storage is temporarily unavailable",
            Self::OutcomeUnknown => "command outcome is not yet known",
            Self::OperationCancelled => "application request was cancelled",
            Self::DeadlineExceeded => "application request deadline elapsed",
            Self::InternalDefect => "an internal error occurred",
            Self::IdempotencyKeyReuse => {
                "idempotency key was reused with different application input"
            }
            Self::CommandExecutionFailed => "command execution failed",
            Self::CapabilityRevoked => "application capability is revoked",
            Self::ProtocolInvalid => "the RiffDB peer returned an invalid application response",
            Self::HistoryIncarnationMismatch => "observed history predates a database restore",
            Self::HistoryPruned => "requested history has been pruned",
            Self::Overloaded => "service is over capacity",
            Self::FollowerMode => "operation is unavailable in follower mode",
            Self::PrimaryFenced => "primary is durably fenced",
            Self::ProjectionDiverged => "query projections cannot prove one common snapshot",
            Self::SnapshotRetired => "the requested query snapshot has been retired",
            Self::FreshnessUnsatisfied => "no query snapshot satisfies the requested freshness",
            Self::ProjectedSourceRequired => {
                "nearest query requires a compiler-owned projected source"
            }
        }
    }

    /// Returns the closed category.
    #[must_use]
    pub const fn category(self) -> ApplicationErrorCategory {
        match self {
            Self::InvalidRequest | Self::InputInvalid => ApplicationErrorCategory::Input,
            Self::AuthorizationDenied | Self::CapabilityRevoked => {
                ApplicationErrorCategory::Authorization
            }
            Self::ContractMismatch => ApplicationErrorCategory::Contract,
            Self::QueryInvalid
            | Self::QueryUnavailable
            | Self::ProjectionDiverged
            | Self::SnapshotRetired
            | Self::FreshnessUnsatisfied => ApplicationErrorCategory::Query,
            Self::ProjectedSourceRequired => ApplicationErrorCategory::Query,
            Self::ModuleUnavailable => ApplicationErrorCategory::Module,
            Self::CursorInvalid => ApplicationErrorCategory::Cursor,
            Self::ResponseTooLarge => ApplicationErrorCategory::Resource,
            Self::StorageUnavailable => ApplicationErrorCategory::Storage,
            Self::OutcomeUnknown => ApplicationErrorCategory::Uncertainty,
            Self::OperationCancelled
            | Self::DeadlineExceeded
            | Self::FollowerMode
            | Self::PrimaryFenced => ApplicationErrorCategory::Control,
            Self::InternalDefect => ApplicationErrorCategory::Internal,
            Self::IdempotencyKeyReuse | Self::CommandExecutionFailed => {
                ApplicationErrorCategory::Command
            }
            Self::ProtocolInvalid => ApplicationErrorCategory::Protocol,
            Self::HistoryIncarnationMismatch | Self::HistoryPruned => {
                ApplicationErrorCategory::History
            }
            Self::Overloaded => ApplicationErrorCategory::Capacity,
        }
    }

    /// Returns deterministic recovery guidance.
    #[must_use]
    pub const fn recovery_action(self) -> ApplicationRecoveryAction {
        match self {
            Self::InvalidRequest
            | Self::InputInvalid
            | Self::QueryInvalid
            | Self::CursorInvalid
            | Self::ResponseTooLarge
            | Self::IdempotencyKeyReuse
            | Self::HistoryIncarnationMismatch
            | Self::HistoryPruned
            | Self::SnapshotRetired
            | Self::FollowerMode => ApplicationRecoveryAction::CorrectRequest,
            Self::ProjectedSourceRequired => ApplicationRecoveryAction::RefreshContract,
            Self::AuthorizationDenied | Self::CapabilityRevoked => {
                ApplicationRecoveryAction::ObtainPermission
            }
            Self::ContractMismatch | Self::QueryUnavailable | Self::ModuleUnavailable => {
                ApplicationRecoveryAction::RefreshContract
            }
            Self::StorageUnavailable
            | Self::DeadlineExceeded
            | Self::Overloaded
            | Self::ProjectionDiverged
            | Self::FreshnessUnsatisfied => ApplicationRecoveryAction::Retry,
            Self::OutcomeUnknown => ApplicationRecoveryAction::ResolveWithSameIdempotencyKey,
            Self::OperationCancelled => ApplicationRecoveryAction::None,
            Self::InternalDefect
            | Self::CommandExecutionFailed
            | Self::ProtocolInvalid
            | Self::PrimaryFenced => ApplicationRecoveryAction::ContactOperator,
        }
    }

    /// Returns the exact deterministic remediation set.
    #[must_use]
    pub const fn fixes(self) -> &'static [ApplicationFixCode] {
        match self {
            Self::InvalidRequest
            | Self::InputInvalid
            | Self::QueryInvalid
            | Self::HistoryIncarnationMismatch
            | Self::HistoryPruned => &[ApplicationFixCode::CorrectInput],
            Self::AuthorizationDenied | Self::CapabilityRevoked => {
                &[ApplicationFixCode::BindApplicationRole]
            }
            Self::ContractMismatch => &[ApplicationFixCode::RefreshContract],
            Self::QueryUnavailable | Self::ModuleUnavailable => {
                &[ApplicationFixCode::PinActiveModule]
            }
            Self::ProjectedSourceRequired => &[ApplicationFixCode::PinActiveModule],
            Self::CursorInvalid => &[ApplicationFixCode::RestartFromFirstPage],
            Self::SnapshotRetired => &[ApplicationFixCode::RestartFromFirstPage],
            Self::ResponseTooLarge | Self::IdempotencyKeyReuse => {
                &[ApplicationFixCode::CorrectInput]
            }
            Self::StorageUnavailable
            | Self::DeadlineExceeded
            | Self::Overloaded
            | Self::ProjectionDiverged
            | Self::FreshnessUnsatisfied => &[ApplicationFixCode::RetryLater],
            Self::OutcomeUnknown => &[ApplicationFixCode::ResolveWithSameIdempotencyKey],
            Self::InternalDefect => &[ApplicationFixCode::ContactOperatorWithIncident],
            Self::OperationCancelled
            | Self::CommandExecutionFailed
            | Self::ProtocolInvalid
            | Self::FollowerMode
            | Self::PrimaryFenced => &[],
        }
    }
}

/// Coarse application failure category.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ApplicationErrorCategory {
    /// Caller-controlled application input.
    Input,
    /// Authentication, role, or authorization policy.
    Authorization,
    /// Contract selection and compatibility.
    Contract,
    /// RiffQL compilation or execution.
    Query,
    /// Named-query module selection.
    Module,
    /// Cursor validation.
    Cursor,
    /// Public resource bounds.
    Resource,
    /// Authoritative storage availability.
    Storage,
    /// Mutation uncertainty.
    Uncertainty,
    /// Cancellation, deadline, or redacted defects.
    Internal,
    /// Peer protocol conformance.
    Protocol,
    /// Symbolic command admission or execution.
    Command,
    /// Cancellation and deadline control.
    Control,
    /// History incarnation observations.
    History,
    /// Admission capacity.
    Capacity,
}

impl ApplicationErrorCategory {
    /// Returns the stable machine name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Input => "input",
            Self::Authorization => "authorization",
            Self::Contract => "contract",
            Self::Query => "query",
            Self::Module => "module",
            Self::Cursor => "cursor",
            Self::Resource => "resource",
            Self::Storage => "storage",
            Self::Uncertainty => "uncertainty",
            Self::Internal => "internal",
            Self::Protocol => "protocol",
            Self::Command => "command",
            Self::Control => "control",
            Self::History => "history",
            Self::Capacity => "capacity",
        }
    }
}

/// Closed application recovery action.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ApplicationRecoveryAction {
    /// Correct the input before retrying.
    CorrectRequest,
    /// Retry according to caller policy.
    Retry,
    /// Resolve using the same idempotency identity.
    ResolveWithSameIdempotencyKey,
    /// Bind or obtain an application role.
    ObtainPermission,
    /// Refresh contract and module metadata.
    RefreshContract,
    /// Escalate with the incident identifier when present.
    ContactOperator,
    /// No recovery is prescribed.
    None,
}

impl ApplicationRecoveryAction {
    /// Returns the stable machine name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::CorrectRequest => "correct_request",
            Self::Retry => "retry",
            Self::ResolveWithSameIdempotencyKey => "resolve_with_same_idempotency_key",
            Self::ObtainPermission => "obtain_permission",
            Self::RefreshContract => "refresh_contract",
            Self::ContactOperator => "contact_operator",
            Self::None => "none",
        }
    }
}

/// Closed machine-actionable remediation.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ApplicationFixCode {
    /// Correct the typed input or query source.
    CorrectInput,
    /// Remove a result field not visible to the application role.
    RemoveForbiddenOutput,
    /// Bind the symbolic application role.
    BindApplicationRole,
    /// Refresh exact contract metadata.
    RefreshContract,
    /// Pin or redeploy the active named-query module.
    PinActiveModule,
    /// Declare a bounded index that satisfies the diagnostic.
    AddBoundedIndex,
    /// Discard a stale cursor and restart.
    RestartFromFirstPage,
    /// Retry later using bounded caller policy.
    RetryLater,
    /// Resolve or retry with the exact same idempotency identity.
    ResolveWithSameIdempotencyKey,
    /// Contact an operator and include only the opaque incident ID.
    ContactOperatorWithIncident,
}

impl ApplicationFixCode {
    /// Returns the stable machine name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::CorrectInput => "correct_input",
            Self::RemoveForbiddenOutput => "remove_forbidden_output",
            Self::BindApplicationRole => "bind_application_role",
            Self::RefreshContract => "refresh_contract",
            Self::PinActiveModule => "pin_active_module",
            Self::AddBoundedIndex => "add_bounded_index",
            Self::RestartFromFirstPage => "restart_from_first_page",
            Self::RetryLater => "retry_later",
            Self::ResolveWithSameIdempotencyKey => "resolve_with_same_idempotency_key",
            Self::ContactOperatorWithIncident => "contact_operator_with_incident",
        }
    }
}

/// Checked half-open source span in submitted RiffQL.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ApplicationSourceSpan {
    start: u64,
    end: u64,
}

impl ApplicationSourceSpan {
    /// Constructs a bounded ordered source span.
    pub const fn new(start: u64, end: u64) -> Option<Self> {
        if start <= end && end <= MAX_APPLICATION_SOURCE_OFFSET {
            Some(Self { start, end })
        } else {
            None
        }
    }

    /// Inclusive start byte offset.
    #[must_use]
    pub const fn start(self) -> u64 {
        self.start
    }

    /// Exclusive end byte offset.
    #[must_use]
    pub const fn end(self) -> u64 {
        self.end
    }
}

/// Bounded symbolic context for one application failure.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ApplicationErrorContext {
    contract: Option<(ContractLineage, ContractVersion)>,
    operation_symbol: Option<String>,
    symbol_path: Vec<String>,
    source_span: Option<ApplicationSourceSpan>,
    trace_id: Option<RequestId>,
}

impl ApplicationErrorContext {
    /// Constructs empty context for a failure that has no honest symbol.
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            contract: None,
            operation_symbol: None,
            symbol_path: Vec::new(),
            source_span: None,
            trace_id: None,
        }
    }

    /// Adds exact contract identity already visible to the caller.
    #[must_use]
    pub fn with_contract(mut self, lineage: ContractLineage, version: ContractVersion) -> Self {
        self.contract = Some((lineage, version));
        self
    }

    /// Adds one checked caller-visible query, module, command, or role symbol.
    pub fn with_operation_symbol(
        mut self,
        symbol: String,
    ) -> Result<Self, ApplicationErrorContextError> {
        validate_application_symbol(&symbol)?;
        self.operation_symbol = Some(symbol);
        Ok(self)
    }

    /// Adds a bounded checked caller-visible symbol path.
    pub fn with_symbol_path(
        mut self,
        symbols: Vec<String>,
    ) -> Result<Self, ApplicationErrorContextError> {
        if symbols.len() > MAX_APPLICATION_SYMBOL_PATH_SEGMENTS {
            return Err(ApplicationErrorContextError);
        }
        for symbol in &symbols {
            validate_application_symbol(symbol)?;
        }
        self.symbol_path = symbols;
        Ok(self)
    }

    /// Adds a checked source span.
    #[must_use]
    pub const fn with_source_span(mut self, source_span: ApplicationSourceSpan) -> Self {
        self.source_span = Some(source_span);
        self
    }

    /// Adds the request identity as the safe end-to-end trace identity.
    #[must_use]
    pub const fn with_trace_id(mut self, trace_id: RequestId) -> Self {
        self.trace_id = Some(trace_id);
        self
    }

    /// Exact selected contract, when safely known.
    #[must_use]
    pub const fn contract(&self) -> Option<&(ContractLineage, ContractVersion)> {
        self.contract.as_ref()
    }

    /// Caller-visible operation symbol, when safely known.
    #[must_use]
    pub fn operation_symbol(&self) -> Option<&str> {
        self.operation_symbol.as_deref()
    }

    /// Caller-visible symbolic path.
    #[must_use]
    pub fn symbol_path(&self) -> &[String] {
        &self.symbol_path
    }

    /// Source span, when safely known.
    #[must_use]
    pub const fn source_span(&self) -> Option<ApplicationSourceSpan> {
        self.source_span
    }

    /// Opaque request/trace identity.
    #[must_use]
    pub const fn trace_id(&self) -> Option<RequestId> {
        self.trace_id
    }
}

fn validate_application_symbol(symbol: &str) -> Result<(), ApplicationErrorContextError> {
    if symbol.is_empty()
        || symbol.len() > MAX_APPLICATION_SYMBOL_BYTES
        || !symbol
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
    {
        return Err(ApplicationErrorContextError);
    }
    Ok(())
}

/// A symbolic context rejected before it could reach a public error.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ApplicationErrorContextError;

impl fmt::Display for ApplicationErrorContextError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("application error context is invalid")
    }
}

impl Error for ApplicationErrorContextError {}

/// One fully checked bounded application-semantic failure.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ApplicationError {
    code: ApplicationErrorCode,
    operation: ApplicationOperation,
    context: ApplicationErrorContext,
    incident_id: Option<IncidentId>,
}

impl ApplicationError {
    /// Constructs one registry-owned error with already checked context.
    #[must_use]
    pub const fn new(
        code: ApplicationErrorCode,
        operation: ApplicationOperation,
        context: ApplicationErrorContext,
        incident_id: Option<IncidentId>,
    ) -> Self {
        Self {
            code,
            operation,
            context,
            incident_id,
        }
    }

    /// Lifts one compatible kernel failure into symbolic application context.
    ///
    /// Kernel validation paths are intentionally not copied because they carry
    /// compiler IDs rather than application symbols.
    #[must_use]
    pub fn from_public_error(
        error: &PublicError,
        operation: ApplicationOperation,
        context: ApplicationErrorContext,
    ) -> Self {
        Self::new(
            error
                .application_code_hint()
                .unwrap_or_else(|| ApplicationErrorCode::from_public_kind(error.kind())),
            operation,
            context,
            error.incident_id().copied(),
        )
    }

    /// Stable code.
    #[must_use]
    pub const fn code(&self) -> ApplicationErrorCode {
        self.code
    }

    /// Application operation.
    #[must_use]
    pub const fn operation(&self) -> ApplicationOperation {
        self.operation
    }

    /// Checked safe context.
    #[must_use]
    pub const fn context(&self) -> &ApplicationErrorContext {
        &self.context
    }

    /// Opaque incident identity.
    #[must_use]
    pub const fn incident_id(&self) -> Option<&IncidentId> {
        self.incident_id.as_ref()
    }

    /// Closed category.
    #[must_use]
    pub const fn category(&self) -> ApplicationErrorCategory {
        self.code.category()
    }

    /// Stable public message.
    #[must_use]
    pub const fn safe_message(&self) -> &'static str {
        self.code.safe_message()
    }

    /// Recovery action.
    #[must_use]
    pub const fn recovery_action(&self) -> ApplicationRecoveryAction {
        self.code.recovery_action()
    }

    /// Deterministic remediation codes.
    #[must_use]
    pub const fn fixes(&self) -> &'static [ApplicationFixCode] {
        self.code.fixes()
    }
}

impl fmt::Display for ApplicationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{}: {} [{}]",
            self.code.as_str(),
            self.safe_message(),
            self.operation.as_str()
        )?;
        if let Some(symbol) = self.context.operation_symbol() {
            write!(formatter, " {symbol}")?;
        }
        if let Some(incident_id) = &self.incident_id {
            write!(formatter, " (incident {incident_id})")?;
        }
        Ok(())
    }
}

impl Error for ApplicationError {}

/// Consumer-owned source for fresh opaque incident identifiers.
///
/// Production providers live at the server composition boundary. Core error
/// handling receives only this synchronous port and must fail closed when it
/// cannot obtain an identifier.
pub trait IncidentIdSource: Send + Sync {
    /// Returns one fresh checked UUIDv7 incident identifier.
    fn next_incident_id(&self) -> Result<IncidentId, IncidentIdSourceError>;
}

/// A bounded, public-safe failure to obtain a fresh incident identifier.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct IncidentIdSourceError;

impl fmt::Display for IncidentIdSourceError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("incident identifier source failed")
    }
}

impl Error for IncidentIdSourceError {}

/// The maximum number of validation issues returned for one request.
pub const MAX_VALIDATION_ISSUES: usize = 16;

/// The maximum number of segments in one validation path.
pub const MAX_VALIDATION_PATH_SEGMENTS: usize = 16;

/// A protocol-neutral classification for a public failure.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ErrorClass {
    /// The submitted request is invalid and must be corrected.
    InvalidArgument,
    /// The request conflicts with previously admitted state.
    Conflict,
    /// The principal is not permitted to perform the operation.
    PermissionDenied,
    /// The operation did not complete before its deadline.
    DeadlineExceeded,
    /// The request targets a contract state that is no longer current.
    FailedPrecondition,
    /// A required service is temporarily unavailable.
    Unavailable,
    /// The caller must resolve an uncertain command result.
    Uncertain,
    /// The server encountered a defect that is not safe to disclose.
    Internal,
}

/// Safe, protocol-neutral recovery guidance for a public failure.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum RecoveryAction {
    /// Correct the request before submitting it again.
    CorrectRequest,
    /// Retry the operation according to the caller's retry policy.
    Retry,
    /// Resolve or retry the command with the original idempotency key.
    ResolveWithSameIdempotencyKey,
    /// Obtain an appropriate permission before retrying.
    ObtainPermission,
    /// Refresh contract metadata and rebuild the request.
    RefreshContract,
    /// Escalate the incident to an operator.
    ContactOperator,
}

/// Closed emergency failure when an internal incident cannot be identified.
///
/// This value is intentionally distinct from [`PublicError`]: an internal
/// public error requires a real fresh [`IncidentId`]. It carries no identifier,
/// arbitrary text, diagnostic source, or protected operation result.
///
/// ```compile_fail
/// use riffdb_errors::{EmergencyInternalFailure, IncidentIdSourceError, PublicError};
///
/// let emergency = EmergencyInternalFailure::from(IncidentIdSourceError);
/// let _: PublicError = emergency.into();
/// ```
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct EmergencyInternalFailure {
    _private: (),
}

impl EmergencyInternalFailure {
    /// Returns the only fixed message safe at an emergency transport boundary.
    #[must_use]
    pub const fn safe_message(self) -> &'static str {
        "an internal error occurred"
    }

    /// Returns the protocol-neutral emergency classification.
    #[must_use]
    pub const fn class(self) -> ErrorClass {
        ErrorClass::Internal
    }

    /// Returns the only safe recovery guidance for this readiness failure.
    #[must_use]
    pub const fn recovery_action(self) -> RecoveryAction {
        RecoveryAction::ContactOperator
    }
}

impl From<IncidentIdSourceError> for EmergencyInternalFailure {
    fn from(_: IncidentIdSourceError) -> Self {
        Self { _private: () }
    }
}

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

impl fmt::Debug for EmergencyInternalFailure {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("EmergencyInternalFailure")
    }
}

impl Error for EmergencyInternalFailure {}

/// The closed set of failures that RiffDB may expose to an untrusted caller.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum PublicErrorKind {
    /// A request failed bounded validation.
    Validation,
    /// An idempotency identity was reused with different canonical input.
    IdempotencyKeyReuse,
    /// Authorization denied the operation.
    AuthorizationDenied,
    /// Logical conflict acquisition exceeded its deadline, or the fixed v1
    /// command reevaluation budget was exhausted.
    ConcurrencyDeadlineExceeded,
    /// The requested contract version or plan is not current.
    ContractMismatch,
    /// Authoritative storage is temporarily unavailable.
    StorageUnavailable,
    /// A submitted command may have completed, but its outcome is not known.
    OutcomeUnknown,
    /// An internal defect occurred and details were retained only internally.
    InternalDefect,
    /// Deterministic evaluation failed before an application commit was formed.
    CommandExecutionFailed,
    /// Observed history predates a database restore.
    HistoryIncarnationMismatch,
    /// Requested history was retired by retention prune.
    HistoryPruned,
    /// The service is over capacity and rejected admission.
    Overloaded,
    /// This node is a follower and cannot execute a write operation.
    FollowerMode,
    /// Durable source fencing permanently refuses new command admission.
    PrimaryFenced,
}

impl PublicErrorKind {
    /// Returns the stable ASCII identifier exposed by every transport.
    #[must_use]
    pub const fn code(self) -> &'static str {
        match self {
            Self::Validation => "validation_failed",
            Self::IdempotencyKeyReuse => "idempotency_key_reuse",
            Self::AuthorizationDenied => "authorization_denied",
            Self::ConcurrencyDeadlineExceeded => "concurrency_deadline_exceeded",
            Self::ContractMismatch => "contract_mismatch",
            Self::StorageUnavailable => "storage_unavailable",
            Self::OutcomeUnknown => "outcome_unknown",
            Self::InternalDefect => "internal_defect",
            Self::CommandExecutionFailed => "command_execution_failed",
            Self::HistoryIncarnationMismatch => "history_incarnation_mismatch",
            Self::HistoryPruned => "history_pruned",
            Self::Overloaded => "overloaded",
            Self::FollowerMode => "follower_mode",
            Self::PrimaryFenced => "primary_fenced",
        }
    }

    /// Returns the stable, caller-safe ASCII message for this failure.
    #[must_use]
    pub const fn safe_message(self) -> &'static str {
        match self {
            Self::Validation => "request validation failed",
            Self::IdempotencyKeyReuse => "idempotency key was reused with different input",
            Self::AuthorizationDenied => "operation is not authorized",
            Self::ConcurrencyDeadlineExceeded => "concurrency deadline exceeded",
            Self::ContractMismatch => "contract version or plan does not match",
            Self::StorageUnavailable => "storage is temporarily unavailable",
            Self::OutcomeUnknown => "command outcome is not yet known",
            Self::InternalDefect => "an internal error occurred",
            Self::CommandExecutionFailed => "command execution failed",
            Self::HistoryIncarnationMismatch => "observed history predates a database restore",
            Self::HistoryPruned => "requested history has been pruned",
            Self::Overloaded => "service is over capacity",
            Self::FollowerMode => "operation is unavailable in follower mode",
            Self::PrimaryFenced => "primary is durably fenced",
        }
    }

    /// Returns the protocol-neutral class for this failure.
    #[must_use]
    pub const fn class(self) -> ErrorClass {
        match self {
            Self::Validation => ErrorClass::InvalidArgument,
            Self::IdempotencyKeyReuse => ErrorClass::Conflict,
            Self::AuthorizationDenied => ErrorClass::PermissionDenied,
            Self::ConcurrencyDeadlineExceeded => ErrorClass::DeadlineExceeded,
            Self::ContractMismatch
            | Self::HistoryIncarnationMismatch
            | Self::HistoryPruned
            | Self::FollowerMode
            | Self::PrimaryFenced => ErrorClass::FailedPrecondition,
            Self::StorageUnavailable | Self::Overloaded => ErrorClass::Unavailable,
            Self::OutcomeUnknown => ErrorClass::Uncertain,
            Self::InternalDefect => ErrorClass::Internal,
            Self::CommandExecutionFailed => ErrorClass::FailedPrecondition,
        }
    }

    /// Returns the one authoritative public status code for this kind.
    ///
    /// Server encoding and client validation must both use this mapping. Do not
    /// re-derive the wire code from [`Self::class`] alone: some kinds deliberately
    /// diverge (for example, overload keeps class [`ErrorClass::Unavailable`] while
    /// carrying [`PublicErrorStatusCode::ResourceExhausted`]).
    ///
    /// This match is the sole wire-code authority and must remain exhaustive over
    /// every [`PublicErrorKind`] variant.
    #[must_use]
    pub const fn status_code(self) -> PublicErrorStatusCode {
        match self {
            Self::Validation => PublicErrorStatusCode::InvalidArgument,
            Self::IdempotencyKeyReuse => PublicErrorStatusCode::AlreadyExists,
            Self::AuthorizationDenied => PublicErrorStatusCode::PermissionDenied,
            Self::ConcurrencyDeadlineExceeded => PublicErrorStatusCode::DeadlineExceeded,
            Self::ContractMismatch
            | Self::CommandExecutionFailed
            | Self::HistoryIncarnationMismatch
            | Self::HistoryPruned
            | Self::FollowerMode
            | Self::PrimaryFenced => PublicErrorStatusCode::FailedPrecondition,
            Self::StorageUnavailable => PublicErrorStatusCode::Unavailable,
            Self::Overloaded => PublicErrorStatusCode::ResourceExhausted,
            Self::OutcomeUnknown => PublicErrorStatusCode::Unknown,
            Self::InternalDefect => PublicErrorStatusCode::Internal,
        }
    }

    /// Returns safe recovery guidance for this failure.
    #[must_use]
    pub const fn recovery_action(self) -> RecoveryAction {
        match self {
            Self::Validation
            | Self::IdempotencyKeyReuse
            | Self::HistoryIncarnationMismatch
            | Self::HistoryPruned
            | Self::FollowerMode => RecoveryAction::CorrectRequest,
            Self::AuthorizationDenied => RecoveryAction::ObtainPermission,
            Self::ConcurrencyDeadlineExceeded | Self::StorageUnavailable | Self::Overloaded => {
                RecoveryAction::Retry
            }
            Self::ContractMismatch => RecoveryAction::RefreshContract,
            Self::OutcomeUnknown => RecoveryAction::ResolveWithSameIdempotencyKey,
            Self::InternalDefect | Self::CommandExecutionFailed | Self::PrimaryFenced => {
                RecoveryAction::ContactOperator
            }
        }
    }
}

/// Authoritative status code carried for a public error on the gRPC wire.
///
/// Transport adapters map this closed set to their native status type. It is
/// intentionally separate from [`ErrorClass`]: class is the protocol-neutral
/// classification, while this value is the exact wire status both server and
/// client must agree on.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum PublicErrorStatusCode {
    /// The submitted request is invalid and must be corrected.
    InvalidArgument,
    /// The request conflicts with previously admitted state.
    AlreadyExists,
    /// The principal is not permitted to perform the operation.
    PermissionDenied,
    /// The operation did not complete before its deadline.
    DeadlineExceeded,
    /// The request targets state that is no longer current.
    FailedPrecondition,
    /// Capacity or resource bounds rejected the request without execution.
    ResourceExhausted,
    /// A required service is temporarily unavailable.
    Unavailable,
    /// The caller must resolve an uncertain command result.
    Unknown,
    /// The server encountered a defect that is not safe to disclose.
    Internal,
}

/// A stable, caller-safe explanation for one validation failure.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ValidationCode {
    /// A required value was not provided.
    MissingRequiredValue,
    /// A value has the wrong contract type.
    TypeMismatch,
    /// A value has an invalid representation.
    InvalidValue,
    /// A numeric or temporal value is outside its allowed range.
    OutOfRange,
    /// A string or byte value exceeds its allowed length.
    TooLong,
    /// A collection exceeds its allowed item count.
    TooManyItems,
    /// A submitted field is not part of the active contract.
    UnknownField,
    /// A submitted record contains a field more than once.
    DuplicateField,
}

impl ValidationCode {
    /// Returns the stable ASCII identifier exposed by every transport.
    #[must_use]
    pub const fn code(self) -> &'static str {
        match self {
            Self::MissingRequiredValue => "missing_required_value",
            Self::TypeMismatch => "type_mismatch",
            Self::InvalidValue => "invalid_value",
            Self::OutOfRange => "out_of_range",
            Self::TooLong => "too_long",
            Self::TooManyItems => "too_many_items",
            Self::UnknownField => "unknown_field",
            Self::DuplicateField => "duplicate_field",
        }
    }

    /// Returns a stable public-safe description of the validation failure.
    #[must_use]
    pub const fn safe_message(self) -> &'static str {
        match self {
            Self::MissingRequiredValue => "required value is missing",
            Self::TypeMismatch => "value has the wrong type",
            Self::InvalidValue => "value is invalid",
            Self::OutOfRange => "value is outside the allowed range",
            Self::TooLong => "value exceeds the allowed length",
            Self::TooManyItems => "collection has too many items",
            Self::UnknownField => "field is not defined by the active contract",
            Self::DuplicateField => "field occurs more than once",
        }
    }
}

/// One non-secret location component in a validation issue.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ValidationPathSegment {
    /// A compiler-assigned field identifier.
    Field(FieldId),
    /// A zero-based list position.
    ListIndex(u32),
}

/// A bounded path to a value that failed validation.
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
pub struct ValidationPath {
    segments: Vec<ValidationPathSegment>,
}

impl ValidationPath {
    /// Creates the root path, used when an issue applies to the whole request.
    #[must_use]
    pub const fn root() -> Self {
        Self {
            segments: Vec::new(),
        }
    }

    /// Creates a checked validation path.
    pub fn new(segments: Vec<ValidationPathSegment>) -> Result<Self, ValidationPathError> {
        if segments.len() > MAX_VALIDATION_PATH_SEGMENTS {
            return Err(ValidationPathError::TooManySegments);
        }
        Ok(Self { segments })
    }

    /// Returns the path components in root-to-leaf order.
    #[must_use]
    pub fn segments(&self) -> &[ValidationPathSegment] {
        &self.segments
    }
}

/// A failure to construct a bounded validation path.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ValidationPathError {
    /// More than [`MAX_VALIDATION_PATH_SEGMENTS`] were supplied.
    TooManySegments,
}

impl fmt::Display for ValidationPathError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("validation path has too many segments")
    }
}

impl Error for ValidationPathError {}

/// One stable validation code associated with a structured path.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ValidationIssue {
    code: ValidationCode,
    path: ValidationPath,
}

impl ValidationIssue {
    /// Creates a validation issue without accepting caller-controlled text.
    #[must_use]
    pub const fn new(code: ValidationCode, path: ValidationPath) -> Self {
        Self { code, path }
    }

    /// Returns the stable validation code.
    #[must_use]
    pub const fn code(&self) -> ValidationCode {
        self.code
    }

    /// Returns the structured location of the invalid value.
    #[must_use]
    pub const fn path(&self) -> &ValidationPath {
        &self.path
    }
}

/// A non-empty bounded collection of validation issues.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ValidationIssues {
    issues: Vec<ValidationIssue>,
}

impl ValidationIssues {
    /// Creates a checked collection of validation issues.
    pub fn new(issues: Vec<ValidationIssue>) -> Result<Self, ValidationIssuesError> {
        if issues.is_empty() {
            return Err(ValidationIssuesError::Empty);
        }
        if issues.len() > MAX_VALIDATION_ISSUES {
            return Err(ValidationIssuesError::TooManyIssues);
        }
        Ok(Self { issues })
    }

    /// Creates a collection containing exactly one issue.
    #[must_use]
    pub fn one(issue: ValidationIssue) -> Self {
        Self {
            issues: vec![issue],
        }
    }

    /// Returns the validation issues in deterministic producer order.
    #[must_use]
    pub fn as_slice(&self) -> &[ValidationIssue] {
        &self.issues
    }
}

/// A failure to construct a bounded collection of validation issues.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ValidationIssuesError {
    /// At least one validation issue is required.
    Empty,
    /// More than [`MAX_VALIDATION_ISSUES`] were supplied.
    TooManyIssues,
}

impl fmt::Display for ValidationIssuesError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Empty => "validation issue collection is empty",
            Self::TooManyIssues => "validation issue collection has too many entries",
        })
    }
}

impl Error for ValidationIssuesError {}

/// Structured, caller-safe detail for a public failure.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PublicErrorDetails {
    /// The failure does not expose structured detail.
    None,
    /// Bounded validation failures.
    Validation(ValidationIssues),
    /// The authoritative contract version active at the time of rejection.
    ContractMismatch {
        /// The contract version the caller must refresh to.
        active_contract_version: ContractVersion,
    },
    /// A closed deterministic evaluation failure code.
    CommandExecutionFailed {
        /// The arithmetic or fixed resource-limit failure classification.
        code: ExecutionFailureCode,
    },
}

/// A failure safe to display, serialize, or map at a public transport boundary.
///
/// This type cannot carry arbitrary messages or an error source. Construction
/// is restricted to named constructors so its kind and details cannot disagree.
/// The optional incident identifier is an opaque correlation value, not a
/// diagnostic.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PublicError {
    kind: PublicErrorKind,
    details: PublicErrorDetails,
    incident_id: Option<IncidentId>,
    application_code_hint: Option<ApplicationErrorCode>,
}

impl PublicError {
    const fn contextless(kind: PublicErrorKind) -> Self {
        Self {
            kind,
            details: PublicErrorDetails::None,
            incident_id: None,
            application_code_hint: None,
        }
    }

    /// Creates a bounded validation failure.
    #[must_use]
    pub const fn validation(issues: ValidationIssues) -> Self {
        Self {
            kind: PublicErrorKind::Validation,
            details: PublicErrorDetails::Validation(issues),
            incident_id: None,
            application_code_hint: None,
        }
    }

    /// Creates an idempotency-key-reuse failure.
    #[must_use]
    pub const fn idempotency_key_reuse() -> Self {
        Self::contextless(PublicErrorKind::IdempotencyKeyReuse)
    }

    /// Creates an authorization-denied failure.
    #[must_use]
    pub const fn authorization_denied() -> Self {
        Self::contextless(PublicErrorKind::AuthorizationDenied)
    }

    /// Creates the shared failure for a logical-conflict deadline or exhausted
    /// fixed v1 command reevaluation budget.
    #[must_use]
    pub const fn concurrency_deadline_exceeded() -> Self {
        Self::contextless(PublicErrorKind::ConcurrencyDeadlineExceeded)
    }

    /// Creates a contract mismatch and identifies the active version.
    #[must_use]
    pub const fn contract_mismatch(active_contract_version: ContractVersion) -> Self {
        Self {
            kind: PublicErrorKind::ContractMismatch,
            details: PublicErrorDetails::ContractMismatch {
                active_contract_version,
            },
            incident_id: None,
            application_code_hint: None,
        }
    }

    /// Creates a storage-unavailable failure.
    #[must_use]
    pub const fn storage_unavailable() -> Self {
        Self::contextless(PublicErrorKind::StorageUnavailable)
    }

    /// Creates an uncertain-outcome failure.
    #[must_use]
    pub const fn outcome_unknown() -> Self {
        Self::contextless(PublicErrorKind::OutcomeUnknown)
    }

    /// Creates a deterministic command-execution failure.
    #[must_use]
    pub const fn command_execution_failed(code: ExecutionFailureCode) -> Self {
        Self {
            kind: PublicErrorKind::CommandExecutionFailed,
            details: PublicErrorDetails::CommandExecutionFailed { code },
            incident_id: None,
            application_code_hint: None,
        }
    }

    /// Creates a redacted internal-defect failure with its incident identifier.
    #[must_use]
    pub const fn internal_defect(incident_id: IncidentId) -> Self {
        Self {
            kind: PublicErrorKind::InternalDefect,
            details: PublicErrorDetails::None,
            incident_id: Some(incident_id),
            application_code_hint: None,
        }
    }

    /// Creates a history-incarnation mismatch failure.
    #[must_use]
    pub const fn history_incarnation_mismatch() -> Self {
        Self::contextless(PublicErrorKind::HistoryIncarnationMismatch)
    }

    /// Creates a history-pruned failure (RDB-HISTORY-0102).
    #[must_use]
    pub const fn history_pruned() -> Self {
        Self::contextless(PublicErrorKind::HistoryPruned)
    }

    /// Creates the typed follower-mode refusal before any write is admitted.
    #[must_use]
    pub const fn follower_mode() -> Self {
        Self::contextless(PublicErrorKind::FollowerMode)
    }

    /// Creates the durable primary-fence refusal before command admission.
    /// This outcome never recommends retrying or clearing the fence.
    #[must_use]
    pub const fn primary_fenced() -> Self {
        Self::contextless(PublicErrorKind::PrimaryFenced)
    }

    /// Creates an overload / capacity rejection failure.
    #[must_use]
    pub const fn overloaded() -> Self {
        Self::contextless(PublicErrorKind::Overloaded)
    }

    /// Adds an opaque incident identifier for trusted diagnostic correlation.
    #[must_use]
    pub const fn with_incident_id(mut self, incident_id: IncidentId) -> Self {
        self.incident_id = Some(incident_id);
        self
    }

    /// Attaches a stricter symbolic classification for the application surface.
    ///
    /// The compatible kernel serializer deliberately ignores this hint.
    pub fn with_application_code_hint(
        mut self,
        code: ApplicationErrorCode,
    ) -> Result<Self, ApplicationErrorHintError> {
        let compatible = match self.kind {
            PublicErrorKind::Validation => matches!(
                code,
                ApplicationErrorCode::InvalidRequest
                    | ApplicationErrorCode::InputInvalid
                    | ApplicationErrorCode::QueryInvalid
                    | ApplicationErrorCode::QueryUnavailable
                    | ApplicationErrorCode::ModuleUnavailable
                    | ApplicationErrorCode::CursorInvalid
                    | ApplicationErrorCode::ProjectionDiverged
                    | ApplicationErrorCode::SnapshotRetired
                    | ApplicationErrorCode::FreshnessUnsatisfied
                    | ApplicationErrorCode::ProjectedSourceRequired
            ),
            PublicErrorKind::AuthorizationDenied => matches!(
                code,
                ApplicationErrorCode::AuthorizationDenied | ApplicationErrorCode::CapabilityRevoked
            ),
            PublicErrorKind::ContractMismatch => code == ApplicationErrorCode::ContractMismatch,
            PublicErrorKind::StorageUnavailable => code == ApplicationErrorCode::StorageUnavailable,
            PublicErrorKind::OutcomeUnknown => code == ApplicationErrorCode::OutcomeUnknown,
            PublicErrorKind::InternalDefect => code == ApplicationErrorCode::InternalDefect,
            PublicErrorKind::IdempotencyKeyReuse => {
                code == ApplicationErrorCode::IdempotencyKeyReuse
            }
            PublicErrorKind::ConcurrencyDeadlineExceeded => {
                code == ApplicationErrorCode::DeadlineExceeded
            }
            PublicErrorKind::CommandExecutionFailed => {
                code == ApplicationErrorCode::CommandExecutionFailed
            }
            PublicErrorKind::HistoryIncarnationMismatch => {
                code == ApplicationErrorCode::HistoryIncarnationMismatch
            }
            PublicErrorKind::HistoryPruned => code == ApplicationErrorCode::HistoryPruned,
            PublicErrorKind::Overloaded => code == ApplicationErrorCode::Overloaded,
            PublicErrorKind::FollowerMode => code == ApplicationErrorCode::FollowerMode,
            PublicErrorKind::PrimaryFenced => code == ApplicationErrorCode::PrimaryFenced,
        };
        if !compatible {
            return Err(ApplicationErrorHintError);
        }
        self.application_code_hint = Some(code);
        Ok(self)
    }

    /// Returns the stricter application-only classification, when present.
    #[must_use]
    pub const fn application_code_hint(&self) -> Option<ApplicationErrorCode> {
        self.application_code_hint
    }

    /// Returns the closed failure kind.
    #[must_use]
    pub const fn kind(&self) -> PublicErrorKind {
        self.kind
    }

    /// Returns the stable public code.
    #[must_use]
    pub const fn code(&self) -> &'static str {
        self.kind.code()
    }

    /// Returns the stable public-safe message.
    #[must_use]
    pub const fn safe_message(&self) -> &'static str {
        self.kind.safe_message()
    }

    /// Returns the protocol-neutral failure class.
    #[must_use]
    pub const fn class(&self) -> ErrorClass {
        self.kind.class()
    }

    /// Returns the authoritative public status code for this error.
    #[must_use]
    pub const fn status_code(&self) -> PublicErrorStatusCode {
        self.kind.status_code()
    }

    /// Returns safe recovery guidance.
    #[must_use]
    pub const fn recovery_action(&self) -> RecoveryAction {
        self.kind.recovery_action()
    }

    /// Returns structured, caller-safe detail for this failure.
    #[must_use]
    pub const fn details(&self) -> &PublicErrorDetails {
        &self.details
    }

    /// Returns the opaque incident identifier, when one is available.
    #[must_use]
    pub const fn incident_id(&self) -> Option<&IncidentId> {
        self.incident_id.as_ref()
    }
}

/// An application hint did not refine the compatible kernel classification.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ApplicationErrorHintError;

impl fmt::Display for ApplicationErrorHintError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("application error hint is incompatible")
    }
}

impl Error for ApplicationErrorHintError {}

impl fmt::Display for PublicError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}: {}", self.code(), self.safe_message())?;
        if let Some(incident_id) = &self.incident_id {
            write!(formatter, " (incident {incident_id})")?;
        }
        Ok(())
    }
}

impl Error for PublicError {}

/// What a defect puts in doubt (ADR-0250).
///
/// The scope is a judgment made where the defect is raised, because that is the
/// only place that knows it. A supervision sink receives a boxed source and can
/// recover nothing from it, so a defect that does not carry its scope is
/// indistinguishable from every other, and a process-level breaker fed by all of
/// them counts requests as though they were process faults.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DefectScope {
    /// The process's own state is in doubt: a contained panic, an omitted
    /// terminal audit, a lower-integrity failure. These feed the runtime's
    /// defect breaker.
    Process,
    /// This request could not be completed, and nothing follows about the next
    /// one. These never stop the runtime, however often a caller repeats them.
    Request,
}

/// An internal failure retaining its source for trusted tracing.
///
/// Its default [`fmt::Display`] and [`fmt::Debug`] representations are
/// redacted. Converting this type into [`PublicError`] deliberately discards
/// the source.
pub struct InternalError {
    incident_id: IncidentId,
    scope: DefectScope,
    source: Box<dyn Error + Send + Sync + 'static>,
}

impl InternalError {
    /// Creates an internal failure associated with an opaque incident.
    ///
    /// There is deliberately no scope default and no second constructor that
    /// omits it: a new defect path must decide what its defect implies rather
    /// than inherit an answer nobody made (ADR-0250 decision 1).
    pub fn new(
        incident_id: IncidentId,
        scope: DefectScope,
        source: impl Error + Send + Sync + 'static,
    ) -> Self {
        Self {
            incident_id,
            scope,
            source: Box::new(source),
        }
    }

    /// Returns what this defect puts in doubt.
    #[must_use]
    pub const fn scope(&self) -> DefectScope {
        self.scope
    }

    /// Returns the opaque identifier used to correlate trusted diagnostics.
    #[must_use]
    pub const fn incident_id(&self) -> &IncidentId {
        &self.incident_id
    }

    /// Converts this internal failure into a redacted public failure.
    #[must_use]
    pub fn into_public(self) -> PublicError {
        PublicError::internal_defect(self.incident_id)
    }
}

impl fmt::Display for InternalError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "internal defect (incident {})", self.incident_id)
    }
}

impl fmt::Debug for InternalError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("InternalError")
            .field("incident_id", &self.incident_id)
            .field("source", &"[REDACTED]")
            .finish()
    }
}

impl Error for InternalError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(self.source.as_ref())
    }
}

impl From<InternalError> for PublicError {
    fn from(error: InternalError) -> Self {
        error.into_public()
    }
}

#[cfg(test)]
mod tests {
    use std::fmt::Write as _;

    use super::*;

    const KINDS: [PublicErrorKind; 14] = [
        PublicErrorKind::Validation,
        PublicErrorKind::IdempotencyKeyReuse,
        PublicErrorKind::AuthorizationDenied,
        PublicErrorKind::ConcurrencyDeadlineExceeded,
        PublicErrorKind::ContractMismatch,
        PublicErrorKind::StorageUnavailable,
        PublicErrorKind::OutcomeUnknown,
        PublicErrorKind::InternalDefect,
        PublicErrorKind::CommandExecutionFailed,
        PublicErrorKind::HistoryIncarnationMismatch,
        PublicErrorKind::HistoryPruned,
        PublicErrorKind::Overloaded,
        PublicErrorKind::FollowerMode,
        PublicErrorKind::PrimaryFenced,
    ];

    const VALIDATION_CODES: [ValidationCode; 8] = [
        ValidationCode::MissingRequiredValue,
        ValidationCode::TypeMismatch,
        ValidationCode::InvalidValue,
        ValidationCode::OutOfRange,
        ValidationCode::TooLong,
        ValidationCode::TooManyItems,
        ValidationCode::UnknownField,
        ValidationCode::DuplicateField,
    ];

    #[derive(Debug)]
    struct SecretSource;

    impl fmt::Display for SecretSource {
        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("secret-canary-internal-context")
        }
    }

    impl Error for SecretSource {}

    #[test]
    fn application_error_registry_matches_the_checked_fixture() {
        let mut rendered = "code\tcategory\trecovery_action\tfixes\tmessage\n".to_owned();
        for code in APPLICATION_ERROR_CODES {
            let fixes = code
                .fixes()
                .iter()
                .map(|fix| fix.as_str())
                .collect::<Vec<_>>()
                .join(",");
            writeln!(
                rendered,
                "{}\t{}\t{}\t{}\t{}",
                code.as_str(),
                code.category().as_str(),
                code.recovery_action().as_str(),
                fixes,
                code.safe_message()
            )
            .expect("string");
        }
        assert_eq!(
            rendered,
            include_str!("../../../fixtures/application-errors/registry-v1.tsv")
        );
    }

    #[test]
    fn application_hints_only_refine_compatible_kernel_failures() {
        let validation = PublicError::validation(ValidationIssues::one(ValidationIssue::new(
            ValidationCode::InvalidValue,
            ValidationPath::root(),
        )));
        let cursor = validation
            .clone()
            .with_application_code_hint(ApplicationErrorCode::CursorInvalid)
            .expect("compatible cursor refinement");
        assert_eq!(
            cursor.application_code_hint(),
            Some(ApplicationErrorCode::CursorInvalid)
        );
        assert_eq!(
            validation.with_application_code_hint(ApplicationErrorCode::StorageUnavailable),
            Err(ApplicationErrorHintError)
        );
        assert_eq!(
            PublicError::authorization_denied()
                .with_application_code_hint(ApplicationErrorCode::QueryInvalid),
            Err(ApplicationErrorHintError)
        );
    }

    fn incident_id() -> IncidentId {
        let mut bytes = [0x42; 16];
        bytes[6] = 0x72;
        bytes[8] = 0x82;
        IncidentId::from_bytes(bytes).expect("fixture is a valid UUIDv7")
    }

    fn issue() -> ValidationIssue {
        ValidationIssue::new(
            ValidationCode::TypeMismatch,
            ValidationPath::new(vec![
                ValidationPathSegment::Field(FieldId::new(7).expect("field ID is nonzero")),
                ValidationPathSegment::ListIndex(3),
            ])
            .expect("fixture path is bounded"),
        )
    }

    #[test]
    fn codes_messages_classes_and_recovery_actions_are_stable() {
        let expected = [
            (
                "validation_failed",
                "request validation failed",
                ErrorClass::InvalidArgument,
                RecoveryAction::CorrectRequest,
            ),
            (
                "idempotency_key_reuse",
                "idempotency key was reused with different input",
                ErrorClass::Conflict,
                RecoveryAction::CorrectRequest,
            ),
            (
                "authorization_denied",
                "operation is not authorized",
                ErrorClass::PermissionDenied,
                RecoveryAction::ObtainPermission,
            ),
            (
                "concurrency_deadline_exceeded",
                "concurrency deadline exceeded",
                ErrorClass::DeadlineExceeded,
                RecoveryAction::Retry,
            ),
            (
                "contract_mismatch",
                "contract version or plan does not match",
                ErrorClass::FailedPrecondition,
                RecoveryAction::RefreshContract,
            ),
            (
                "storage_unavailable",
                "storage is temporarily unavailable",
                ErrorClass::Unavailable,
                RecoveryAction::Retry,
            ),
            (
                "outcome_unknown",
                "command outcome is not yet known",
                ErrorClass::Uncertain,
                RecoveryAction::ResolveWithSameIdempotencyKey,
            ),
            (
                "internal_defect",
                "an internal error occurred",
                ErrorClass::Internal,
                RecoveryAction::ContactOperator,
            ),
            (
                "command_execution_failed",
                "command execution failed",
                ErrorClass::FailedPrecondition,
                RecoveryAction::ContactOperator,
            ),
            (
                "history_incarnation_mismatch",
                "observed history predates a database restore",
                ErrorClass::FailedPrecondition,
                RecoveryAction::CorrectRequest,
            ),
            (
                "history_pruned",
                "requested history has been pruned",
                ErrorClass::FailedPrecondition,
                RecoveryAction::CorrectRequest,
            ),
            (
                "overloaded",
                "service is over capacity",
                ErrorClass::Unavailable,
                RecoveryAction::Retry,
            ),
            (
                "follower_mode",
                "operation is unavailable in follower mode",
                ErrorClass::FailedPrecondition,
                RecoveryAction::CorrectRequest,
            ),
            (
                "primary_fenced",
                "primary is durably fenced",
                ErrorClass::FailedPrecondition,
                RecoveryAction::ContactOperator,
            ),
        ];

        assert_eq!(KINDS.len(), 14);
        assert_eq!(KINDS[9], PublicErrorKind::HistoryIncarnationMismatch);
        assert_eq!(KINDS[10], PublicErrorKind::HistoryPruned);
        assert_eq!(KINDS[11], PublicErrorKind::Overloaded);
        assert_eq!(APPLICATION_ERROR_CODES.len(), 27);
        assert_eq!(
            APPLICATION_ERROR_CODES[18],
            ApplicationErrorCode::HistoryIncarnationMismatch
        );
        assert_eq!(
            APPLICATION_ERROR_CODES[19],
            ApplicationErrorCode::HistoryPruned
        );
        assert_eq!(
            APPLICATION_ERROR_CODES[20],
            ApplicationErrorCode::Overloaded
        );
        assert_eq!(
            APPLICATION_ERROR_CODES[21],
            ApplicationErrorCode::ProjectionDiverged
        );
        assert_eq!(
            APPLICATION_ERROR_CODES[22],
            ApplicationErrorCode::SnapshotRetired
        );
        assert_eq!(
            APPLICATION_ERROR_CODES[23],
            ApplicationErrorCode::FreshnessUnsatisfied
        );
        assert_eq!(
            APPLICATION_ERROR_CODES[24],
            ApplicationErrorCode::ProjectedSourceRequired
        );

        for (kind, (code, message, class, recovery_action)) in KINDS.into_iter().zip(expected) {
            assert_eq!(kind.code(), code);
            assert_eq!(kind.safe_message(), message);
            assert_eq!(kind.class(), class);
            assert_eq!(kind.recovery_action(), recovery_action);
            assert!(code.is_ascii());
            assert!(message.is_ascii());
        }
    }

    #[test]
    fn every_kind_has_an_authoritative_wire_status_code() {
        let expected = [
            PublicErrorStatusCode::InvalidArgument,
            PublicErrorStatusCode::AlreadyExists,
            PublicErrorStatusCode::PermissionDenied,
            PublicErrorStatusCode::DeadlineExceeded,
            PublicErrorStatusCode::FailedPrecondition,
            PublicErrorStatusCode::Unavailable,
            PublicErrorStatusCode::Unknown,
            PublicErrorStatusCode::Internal,
            PublicErrorStatusCode::FailedPrecondition,
            PublicErrorStatusCode::FailedPrecondition,
            PublicErrorStatusCode::FailedPrecondition,
            PublicErrorStatusCode::ResourceExhausted,
            PublicErrorStatusCode::FailedPrecondition,
        ];
        for (kind, expected_code) in KINDS.into_iter().zip(expected) {
            assert_eq!(kind.status_code(), expected_code);
            assert_eq!(PublicError::contextless(kind).status_code(), expected_code);
        }
        assert_eq!(PublicErrorKind::Overloaded.class(), ErrorClass::Unavailable);
        assert_eq!(
            PublicErrorKind::Overloaded.status_code(),
            PublicErrorStatusCode::ResourceExhausted
        );
    }

    #[test]
    fn staged_public_constructors_are_contextless_and_registry_aligned() {
        let mismatch = PublicError::history_incarnation_mismatch();
        assert_eq!(mismatch.kind(), PublicErrorKind::HistoryIncarnationMismatch);
        assert_eq!(mismatch.details(), &PublicErrorDetails::None);
        assert_eq!(mismatch.incident_id(), None);
        assert_eq!(
            ApplicationErrorCode::from_public_kind(mismatch.kind()),
            ApplicationErrorCode::HistoryIncarnationMismatch
        );

        let pruned = PublicError::history_pruned();
        assert_eq!(pruned.kind(), PublicErrorKind::HistoryPruned);
        assert_eq!(pruned.details(), &PublicErrorDetails::None);
        assert_eq!(pruned.incident_id(), None);
        assert_eq!(
            ApplicationErrorCode::from_public_kind(pruned.kind()),
            ApplicationErrorCode::HistoryPruned
        );

        let overloaded = PublicError::overloaded();
        assert_eq!(overloaded.kind(), PublicErrorKind::Overloaded);
        assert_eq!(overloaded.details(), &PublicErrorDetails::None);
        assert_eq!(overloaded.incident_id(), None);
        assert_eq!(
            ApplicationErrorCode::from_public_kind(overloaded.kind()),
            ApplicationErrorCode::Overloaded
        );
    }

    #[test]
    fn concurrency_deadline_error_represents_both_v1_retryable_causes() {
        #[derive(Clone, Copy)]
        enum Cause {
            LogicalConflictDeadline,
            ReevaluationBudgetExhausted,
        }

        const fn public_error_for(cause: Cause) -> PublicError {
            match cause {
                Cause::LogicalConflictDeadline | Cause::ReevaluationBudgetExhausted => {
                    PublicError::concurrency_deadline_exceeded()
                }
            }
        }

        for cause in [
            Cause::LogicalConflictDeadline,
            Cause::ReevaluationBudgetExhausted,
        ] {
            let error = public_error_for(cause);
            assert_eq!(error.kind(), PublicErrorKind::ConcurrencyDeadlineExceeded);
            assert_eq!(error.kind().code(), "concurrency_deadline_exceeded");
            assert_eq!(error.kind().safe_message(), "concurrency deadline exceeded");
            assert_eq!(error.kind().class(), ErrorClass::DeadlineExceeded);
            assert_eq!(error.kind().recovery_action(), RecoveryAction::Retry);
            assert_eq!(error.details(), &PublicErrorDetails::None);
        }
    }

    #[test]
    fn validation_codes_and_messages_are_stable_and_safe() {
        let expected = [
            ("missing_required_value", "required value is missing"),
            ("type_mismatch", "value has the wrong type"),
            ("invalid_value", "value is invalid"),
            ("out_of_range", "value is outside the allowed range"),
            ("too_long", "value exceeds the allowed length"),
            ("too_many_items", "collection has too many items"),
            (
                "unknown_field",
                "field is not defined by the active contract",
            ),
            ("duplicate_field", "field occurs more than once"),
        ];

        for (code, (stable_code, stable_message)) in VALIDATION_CODES.into_iter().zip(expected) {
            assert_eq!(code.code(), stable_code);
            assert_eq!(code.safe_message(), stable_message);
            assert!(stable_code.is_ascii());
            assert!(stable_message.is_ascii());
        }
    }

    #[test]
    fn validation_paths_are_structured_and_bounded() {
        let boundary =
            vec![
                ValidationPathSegment::Field(FieldId::new(1).expect("field ID is nonzero"));
                MAX_VALIDATION_PATH_SEGMENTS
            ];
        let path = ValidationPath::new(boundary).expect("boundary is accepted");
        assert_eq!(path.segments().len(), MAX_VALIDATION_PATH_SEGMENTS);
        assert!(ValidationPath::root().segments().is_empty());

        let above_boundary =
            vec![ValidationPathSegment::ListIndex(0); MAX_VALIDATION_PATH_SEGMENTS + 1];
        assert_eq!(
            ValidationPath::new(above_boundary),
            Err(ValidationPathError::TooManySegments)
        );
    }

    #[test]
    fn validation_issue_collections_are_non_empty_and_bounded() {
        assert_eq!(
            ValidationIssues::new(Vec::new()),
            Err(ValidationIssuesError::Empty)
        );

        let issues = ValidationIssues::new(vec![issue(); MAX_VALIDATION_ISSUES])
            .expect("boundary is accepted");
        assert_eq!(issues.as_slice().len(), MAX_VALIDATION_ISSUES);

        assert_eq!(
            ValidationIssues::new(vec![issue(); MAX_VALIDATION_ISSUES + 1]),
            Err(ValidationIssuesError::TooManyIssues)
        );
    }

    #[test]
    fn named_constructors_enforce_kind_and_detail_consistency() {
        let validation = PublicError::validation(ValidationIssues::one(issue()));
        assert_eq!(validation.kind(), PublicErrorKind::Validation);
        assert!(matches!(
            validation.details(),
            PublicErrorDetails::Validation(issues) if issues.as_slice().len() == 1
        ));

        let active_version = ContractVersion::new(41).expect("contract version is nonzero");
        let mismatch = PublicError::contract_mismatch(active_version);
        assert_eq!(mismatch.kind(), PublicErrorKind::ContractMismatch);
        assert_eq!(
            mismatch.details(),
            &PublicErrorDetails::ContractMismatch {
                active_contract_version: active_version,
            }
        );

        let contextless = [
            PublicError::idempotency_key_reuse(),
            PublicError::authorization_denied(),
            PublicError::concurrency_deadline_exceeded(),
            PublicError::storage_unavailable(),
            PublicError::outcome_unknown(),
        ];
        let expected = [
            PublicErrorKind::IdempotencyKeyReuse,
            PublicErrorKind::AuthorizationDenied,
            PublicErrorKind::ConcurrencyDeadlineExceeded,
            PublicErrorKind::StorageUnavailable,
            PublicErrorKind::OutcomeUnknown,
        ];
        for (error, kind) in contextless.into_iter().zip(expected) {
            assert_eq!(error.kind(), kind);
            assert_eq!(error.details(), &PublicErrorDetails::None);
            assert_eq!(error.incident_id(), None);
        }

        let execution =
            PublicError::command_execution_failed(ExecutionFailureCode::ArithmeticFault);
        assert_eq!(execution.kind(), PublicErrorKind::CommandExecutionFailed);
        assert_eq!(
            execution.details(),
            &PublicErrorDetails::CommandExecutionFailed {
                code: ExecutionFailureCode::ArithmeticFault,
            }
        );
        assert_eq!(execution.incident_id(), None);
    }

    #[test]
    fn public_error_never_exposes_a_source() {
        let error = PublicError::storage_unavailable();

        assert!(error.source().is_none());
    }

    #[test]
    fn internal_conversion_redacts_secret_source_everywhere_public() {
        let internal = InternalError::new(incident_id(), DefectScope::Process, SecretSource);
        assert!(internal.source().is_some());
        assert!(!internal.to_string().contains("secret-canary"));
        assert!(!format!("{internal:?}").contains("SecretSource"));
        assert_eq!(
            internal.source().map(ToString::to_string).as_deref(),
            Some("secret-canary-internal-context")
        );

        let public = PublicError::from(internal);
        let display = public.to_string();
        let debug = format!("{public:?}");

        assert_eq!(public.kind(), PublicErrorKind::InternalDefect);
        assert_eq!(public.details(), &PublicErrorDetails::None);
        assert_eq!(public.incident_id(), Some(&incident_id()));
        assert!(public.source().is_none());
        assert!(!display.contains("secret-canary"));
        assert!(!debug.contains("secret-canary"));
        assert!(!display.contains("SecretSource"));
        assert!(!debug.contains("SecretSource"));
    }

    #[test]
    fn validation_details_cannot_carry_secret_canaries() {
        let error = PublicError::validation(ValidationIssues::one(issue()));
        let display = error.to_string();
        let debug = format!("{error:?}");

        assert!(!display.contains("secret-canary"));
        assert!(!debug.contains("secret-canary"));
        assert_eq!(display, "validation_failed: request validation failed");
    }

    #[test]
    fn public_display_contains_only_stable_fields() {
        let error = PublicError::internal_defect(incident_id());

        assert_eq!(
            error.to_string(),
            "internal_defect: an internal error occurred (incident 42424242-4242-7242-8242-424242424242)"
        );
    }

    /// ADR-0118 sweep anchor: the public error surface is structurally
    /// incapable of echoing a secret-classified field's VALUE, because no
    /// details shape carries caller or stored text at all — locations are
    /// stable IDs, messages are `&'static str`. This match is exhaustive on
    /// purpose: a new details variant carrying dynamic payload must red here
    /// and be reviewed against the secret-field guarantee before it ships.
    #[test]
    fn public_error_details_shapes_carry_no_dynamic_payload_for_secret_fields() {
        let error = PublicError::validation(ValidationIssues::one(issue()));
        // The channel is live: the diagnostic names the field's stable ID…
        let PublicErrorDetails::Validation(issues) = error.details() else {
            panic!("validation details expected");
        };
        assert_eq!(
            issues.as_slice()[0].path().segments()[0],
            ValidationPathSegment::Field(FieldId::new(7).expect("nonzero field"))
        );
        // …while every details shape is closed over value-free payloads.
        for details in [
            PublicErrorDetails::None,
            error.details().clone(),
            PublicErrorDetails::ContractMismatch {
                active_contract_version: ContractVersion::new(3).expect("nonzero version"),
            },
            PublicErrorDetails::CommandExecutionFailed {
                code: ExecutionFailureCode::ArithmeticFault,
            },
        ] {
            match details {
                PublicErrorDetails::None => {}
                PublicErrorDetails::Validation(issues) => {
                    for issue in issues.as_slice() {
                        for segment in issue.path().segments() {
                            match segment {
                                ValidationPathSegment::Field(_)
                                | ValidationPathSegment::ListIndex(_) => {}
                            }
                        }
                    }
                }
                PublicErrorDetails::ContractMismatch {
                    active_contract_version: _,
                } => {}
                PublicErrorDetails::CommandExecutionFailed { code: _ } => {}
            }
        }
    }

    #[test]
    fn incident_source_is_synchronous_fallible_and_has_no_fallback() {
        struct FixedSource(IncidentId);

        impl IncidentIdSource for FixedSource {
            fn next_incident_id(&self) -> Result<IncidentId, IncidentIdSourceError> {
                Ok(self.0)
            }
        }

        struct FailingSource;

        impl IncidentIdSource for FailingSource {
            fn next_incident_id(&self) -> Result<IncidentId, IncidentIdSourceError> {
                Err(IncidentIdSourceError)
            }
        }

        assert_eq!(
            FixedSource(incident_id()).next_incident_id(),
            Ok(incident_id())
        );
        assert_eq!(FailingSource.next_incident_id(), Err(IncidentIdSourceError));
        assert_eq!(
            IncidentIdSourceError.to_string(),
            "incident identifier source failed"
        );
    }

    #[test]
    fn emergency_internal_failure_has_no_identifier_or_disclosive_source() {
        let failure = EmergencyInternalFailure::from(IncidentIdSourceError);

        assert_eq!(failure.safe_message(), "an internal error occurred");
        assert_eq!(failure.class(), ErrorClass::Internal);
        assert_eq!(failure.recovery_action(), RecoveryAction::ContactOperator);
        assert_eq!(failure.to_string(), "an internal error occurred");
        assert_eq!(format!("{failure:?}"), "EmergencyInternalFailure");
        assert!(failure.source().is_none());
        assert!(!failure.to_string().contains("incident"));
    }
}