type-bridge-contract 2.3.0

Versioned binding-neutral contract primitives for type-bridge
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
//! Versioned in-memory diagnostics for binding-neutral SDK execution.
//!
//! This module is deliberately separate from [`crate::diagnostic`]. The
//! existing diagnostic is part of canonical contract wires; an SDK execution
//! diagnostic is an in-memory engine value. It has no wire decoder. Hosts
//! receive it in one JSON form,
//! [`SdkDiagnosticJson`](crate::sdk_diagnostic::SdkDiagnosticJson), which every
//! binding that reports a diagnostic as data uses unchanged; the C ABI copies the
//! same values into typed accessors.
//!
//! Dynamic provider messages, credentials, endpoint or custom-root paths,
//! query values, and internal backtraces have no representation here. Stable
//! messages borrow implementation-owned static text. Codes and names are
//! bounded owned identifiers so canonical typed-query fields can cross this
//! seam without leaking storage or accepting free-form provider text. Dynamic
//! context remains limited to the closed typed detail vocabulary.

use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;

use serde::Serialize;
use serde::ser::{SerializeMap, Serializer};

use crate::capability::CapabilityId;
use crate::diagnostic::Diagnostic;
use crate::fingerprint::Fingerprint;
use crate::id::{RoleId, TypeId};
use crate::schema::OwnsFactId;
use crate::value::ValueTypeTag;

/// Maximum bytes in one stable execution-diagnostic code.
pub const MAX_SDK_DIAGNOSTIC_CODE_BYTES: usize = 128;
/// Maximum UTF-8 bytes in one stable execution-diagnostic message.
pub const MAX_SDK_DIAGNOSTIC_MESSAGE_BYTES: usize = 512;
/// Maximum bytes in one stable path name or detail key.
pub const MAX_SDK_DIAGNOSTIC_NAME_BYTES: usize = 128;
/// Maximum typed path segments in one execution diagnostic.
pub const MAX_SDK_DIAGNOSTIC_PATH_SEGMENTS: usize = 32;
/// Maximum typed details in one execution diagnostic.
pub const MAX_SDK_DIAGNOSTIC_DETAILS: usize = 32;
/// Maximum UTF-8 bytes in one query-owned diagnostic identity.
pub const MAX_SDK_QUERY_DIAGNOSTIC_IDENTITY_BYTES: usize = 512;
/// Maximum identities in one query diagnostic list detail.
pub const MAX_SDK_QUERY_DIAGNOSTIC_IDENTITY_LIST: usize = 32;

/// The version of the in-memory SDK execution-diagnostic contract.
///
/// The numeric value is projected explicitly by each binding. It is not a
/// Rust layout or a serialization discriminant.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct SdkDiagnosticVersion(u16);

impl SdkDiagnosticVersion {
    /// The first SDK execution-diagnostic contract.
    pub const V1: Self = Self(1);
    /// The version produced by constructors in this module.
    pub const CURRENT: Self = Self::V1;

    /// Return the stable positive version number.
    #[must_use]
    pub const fn get(self) -> u16 {
        self.0
    }
}

/// Stable binding-neutral SDK execution failure categories.
///
/// This is a new, forward-extensible category vocabulary. It intentionally
/// does not add variants to the released [`crate::diagnostic::DiagnosticCategory`].
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum SdkDiagnosticCategory {
    /// Caller input does not satisfy the generated SDK contract.
    InvalidInput,
    /// The selected runtime or provider cannot execute a required capability.
    UnsupportedCapability,
    /// A configured or implementation-defined resource ceiling was exceeded.
    ResourceLimit,
    /// Schema, projection, database, request, or result identity did not match.
    Integrity,
    /// The database provider could not complete an operation.
    Provider,
    /// Transaction lifecycle or commit certainty prevents a successful result.
    Transaction,
    /// The operation was cancelled before or during execution.
    Cancelled,
    /// TypeBridge failed internally without exposing implementation state.
    Internal,
}

impl SdkDiagnosticCategory {
    /// Return the stable language-neutral category spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::InvalidInput => "invalid_input",
            Self::UnsupportedCapability => "unsupported_capability",
            Self::ResourceLimit => "resource_limit",
            Self::Integrity => "integrity",
            Self::Provider => "provider",
            Self::Transaction => "transaction",
            Self::Cancelled => "cancelled",
            Self::Internal => "internal",
        }
    }
}

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

/// Why an SDK diagnostic component or bounded collection was rejected.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum SdkDiagnosticBuildError {
    /// A code was not canonical lowercase snake case or exceeded its ceiling.
    InvalidCode,
    /// A message was empty, oversized, multiline, path-like, or not trimmed.
    InvalidMessage,
    /// A path name or detail key was not canonical lowercase snake case.
    InvalidName,
    /// The typed path exceeded [`MAX_SDK_DIAGNOSTIC_PATH_SEGMENTS`].
    PathLimitExceeded,
    /// The detail map exceeded [`MAX_SDK_DIAGNOSTIC_DETAILS`].
    DetailLimitExceeded,
    /// The same stable detail key was attached more than once.
    DuplicateDetail,
}

impl fmt::Display for SdkDiagnosticBuildError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let message = match self {
            Self::InvalidCode => {
                "SDK diagnostic code must be bounded canonical lowercase snake case"
            }
            Self::InvalidMessage => {
                "SDK diagnostic message must be bounded, trimmed, single-line, and path-free static text"
            }
            Self::InvalidName => {
                "SDK diagnostic name must be bounded canonical lowercase snake case"
            }
            Self::PathLimitExceeded => "SDK diagnostic path exceeds its segment ceiling",
            Self::DetailLimitExceeded => "SDK diagnostic details exceed their entry ceiling",
            Self::DuplicateDetail => "SDK diagnostic detail key is duplicated",
        };
        formatter.write_str(message)
    }
}

impl Error for SdkDiagnosticBuildError {}

/// A validated stable machine-readable execution-diagnostic code.
///
/// Codes are bounded canonical identifiers. Lowering code must still admit
/// only engine-owned stable codes, never provider messages or query values.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct SdkDiagnosticCode(String);

impl SdkDiagnosticCode {
    /// Validate one implementation-owned code.
    pub fn new(value: impl Into<String>) -> Result<Self, SdkDiagnosticBuildError> {
        let value = value.into();
        if is_canonical_snake_name(&value, MAX_SDK_DIAGNOSTIC_CODE_BYTES) {
            Ok(Self(value))
        } else {
            Err(SdkDiagnosticBuildError::InvalidCode)
        }
    }

    /// Return the stable code spelling.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

/// A validated stable human-readable execution-diagnostic message.
///
/// The message is implementation-owned static text, not a formatting target.
/// Runtime context belongs only in [`SdkDiagnosticDetailValue`]. Path
/// separators and control characters are rejected so an endpoint, custom-root
/// path, or backtrace cannot be copied into this field.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct SdkDiagnosticMessage(&'static str);

impl SdkDiagnosticMessage {
    /// Validate one implementation-owned message.
    pub fn new(value: &'static str) -> Result<Self, SdkDiagnosticBuildError> {
        let valid = !value.is_empty()
            && value.len() <= MAX_SDK_DIAGNOSTIC_MESSAGE_BYTES
            && value.trim() == value
            && !value
                .chars()
                .any(|character| character.is_control() || matches!(character, '/' | '\\'));
        if valid {
            Ok(Self(value))
        } else {
            Err(SdkDiagnosticBuildError::InvalidMessage)
        }
    }

    /// Return the stable message text.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        self.0
    }
}

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

/// A validated stable argument name or detail key.
///
/// Names are bounded canonical identifiers. Dynamic schema identities use the
/// typed path and detail variants instead of being flattened into names.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct SdkDiagnosticName(String);

impl SdkDiagnosticName {
    /// Validate one implementation-owned name.
    pub fn new(value: impl Into<String>) -> Result<Self, SdkDiagnosticBuildError> {
        let value = value.into();
        if is_canonical_snake_name(&value, MAX_SDK_DIAGNOSTIC_NAME_BYTES) {
            Ok(Self(value))
        } else {
            Err(SdkDiagnosticBuildError::InvalidName)
        }
    }

    /// Return the stable name spelling.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

/// A bounded query-owned identity retained by a structured SDK diagnostic.
///
/// This is not a free-text diagnostic channel. The constructor accepts only a
/// single-line, whitespace-free identifier shape and rejects path separators,
/// control characters, and unbounded text. Query lowering additionally admits
/// identities only for closed, case-specific detail keys.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct SdkQueryDiagnosticIdentity(String);

impl SdkQueryDiagnosticIdentity {
    /// Validate one bounded query identity.
    pub fn new(value: impl Into<String>) -> Result<Self, SdkDiagnosticBuildError> {
        let value = value.into();
        let valid = !value.is_empty()
            && value.len() <= MAX_SDK_QUERY_DIAGNOSTIC_IDENTITY_BYTES
            && !value.chars().any(|character| {
                character.is_control()
                    || character.is_whitespace()
                    || matches!(character, '/' | '\\' | '@')
            });
        if valid {
            Ok(Self(value))
        } else {
            Err(SdkDiagnosticBuildError::InvalidName)
        }
    }

    /// Return the exact validated identity spelling.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

/// The exact canonical typed-query failure category retained inside an SDK
/// diagnostic whose outer category is binding-neutral.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum SdkQueryDiagnosticCategory {
    /// The immutable query plan is invalid.
    InvalidPlan,
    /// A terminal cardinality contract was not satisfied.
    Cardinality,
    /// The provider lacks a required query capability.
    UnsupportedCapability,
    /// Request-relevant schema changed after validation.
    StaleSchema,
    /// A query processing ceiling was crossed.
    ResourceLimit,
    /// Cooperative cancellation interrupted query processing.
    Cancelled,
    /// The provider failed before complete evidence was available.
    Provider,
    /// Provider evidence did not match the validated invocation.
    ResultDecode,
}

impl SdkQueryDiagnosticCategory {
    /// Return the canonical typed-query category spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::InvalidPlan => "invalid_plan",
            Self::Cardinality => "cardinality",
            Self::UnsupportedCapability => "unsupported_capability",
            Self::StaleSchema => "stale_schema",
            Self::ResourceLimit => "resource_limit",
            Self::Cancelled => "cancelled",
            Self::Provider => "provider",
            Self::ResultDecode => "result_decode",
        }
    }
}

/// One closed structural location within a typed query request or result.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum SdkQueryDiagnosticPathKind {
    /// The request envelope.
    Request,
    /// The graph plan.
    Plan,
    /// The selected terminal operation.
    Operation,
    /// The predicate tree.
    Predicate,
    /// The declared output shape.
    Output,
    /// Provider solution or hydration evidence.
    ProviderEvidence,
    /// The validated result envelope.
    Result,
}

impl SdkQueryDiagnosticPathKind {
    /// Return the stable structural spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Request => "request",
            Self::Plan => "plan",
            Self::Operation => "operation",
            Self::Predicate => "predicate",
            Self::Output => "output",
            Self::ProviderEvidence => "provider_evidence",
            Self::Result => "result",
        }
    }
}

fn is_canonical_snake_name(value: impl AsRef<str>, maximum_bytes: usize) -> bool {
    let value = value.as_ref();
    let bytes = value.as_bytes();
    if bytes.is_empty()
        || bytes.len() > maximum_bytes
        || !bytes[0].is_ascii_lowercase()
        || !bytes[bytes.len() - 1].is_ascii_lowercase() && !bytes[bytes.len() - 1].is_ascii_digit()
    {
        return false;
    }

    let mut previous_was_underscore = false;
    for byte in bytes {
        if *byte == b'_' {
            if previous_was_underscore {
                return false;
            }
            previous_was_underscore = true;
        } else if byte.is_ascii_lowercase() || byte.is_ascii_digit() {
            previous_was_underscore = false;
        } else {
            return false;
        }
    }
    true
}

/// One typed location within an SDK operation input or projected model.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum SdkDiagnosticPathSegment {
    /// A stable SDK operation argument.
    Argument(SdkDiagnosticName),
    /// A zero-based item position in a bounded input collection.
    Index(u64),
    /// A canonical schema type identity.
    Type(TypeId),
    /// A canonical direct ownership-fact identity.
    Field(OwnsFactId),
    /// A canonical relation-qualified role identity.
    Role(RoleId),
    /// A structural typed-query request or result location.
    Query(SdkQueryDiagnosticPathKind),
    /// A plan-local typed-query binding ordinal.
    QueryBinding(u16),
    /// A descriptor-qualified, binding-facing typed-query field identity.
    QueryField {
        /// Kind-qualified registry descriptor identity.
        owner: SdkQueryDiagnosticIdentity,
        /// Binding-facing field name.
        name: SdkQueryDiagnosticIdentity,
    },
    /// A descriptor-qualified typed-query role identity.
    QueryRole {
        /// Kind-qualified registry descriptor identity.
        owner: SdkQueryDiagnosticIdentity,
        /// Binding-facing role name.
        name: SdkQueryDiagnosticIdentity,
    },
    /// A plan-local typed-query role-edge ordinal.
    QueryRoleEdge(u16),
    /// A zero-based positional typed-query output slot.
    QueryOutputSlot(u64),
    /// A declared generated typed-query output member.
    QueryOutputName(SdkQueryDiagnosticIdentity),
    /// An object field retained from one authenticated contract diagnostic.
    ContractField(SdkQueryDiagnosticIdentity),
    /// A typed identifier retained from one authenticated contract diagnostic.
    ContractIdentity(SdkQueryDiagnosticIdentity),
}

/// A provider operation class safe to expose across SDK boundaries.
///
/// Provider-specific error text, codes, endpoints, and query text are not
/// retained. Commit is intentionally absent: failed commits use
/// [`SdkCommitFailureOutcome`] so their durability certainty cannot be lost.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum SdkProviderOperation {
    /// Establish or verify a direct database connection.
    Connect,
    /// Read or install schema authority.
    Schema,
    /// Open a read transaction.
    OpenReadTransaction,
    /// Open a write transaction.
    OpenWriteTransaction,
    /// Execute a read operation.
    Read,
    /// Execute a write operation before commit.
    Write,
    /// Roll back a write transaction.
    Rollback,
    /// Close a provider-owned resource.
    Close,
}

impl SdkProviderOperation {
    /// Return the stable language-neutral operation spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Connect => "connect",
            Self::Schema => "schema",
            Self::OpenReadTransaction => "open_read_transaction",
            Self::OpenWriteTransaction => "open_write_transaction",
            Self::Read => "read",
            Self::Write => "write",
            Self::Rollback => "rollback",
            Self::Close => "close",
        }
    }
}

/// Durability certainty for a failed transaction commit.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum SdkCommitFailureOutcome {
    /// The provider proves that the transaction did not commit.
    DefinitelyAborted,
    /// The provider cannot determine whether the transaction committed.
    Unknown,
}

impl SdkCommitFailureOutcome {
    /// Return the stable language-neutral outcome spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::DefinitelyAborted => "definitely_aborted",
            Self::Unknown => "unknown",
        }
    }
}

/// One bounded typed SDK execution-diagnostic detail value.
///
/// There is deliberately no free-text or byte-string variant. Every dynamic
/// value is either a bounded canonical identity or a non-sensitive scalar
/// classification.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum SdkDiagnosticDetailValue {
    /// A boolean contract fact.
    Boolean(bool),
    /// A non-negative item or occurrence count.
    Count(u64),
    /// A non-negative byte count.
    ByteCount(u64),
    /// A canonical capability identity.
    Capability(CapabilityId),
    /// A canonical scalar-domain identity.
    ValueType(ValueTypeTag),
    /// A canonical schema type identity.
    Type(TypeId),
    /// A canonical direct ownership-fact identity.
    Field(OwnsFactId),
    /// A canonical relation-qualified role identity.
    Role(RoleId),
    /// A complete bounded, domain-separated fingerprint.
    Fingerprint(Fingerprint),
    /// A redacted provider operation classification.
    ProviderOperation(SdkProviderOperation),
    /// A classified failed-commit outcome.
    CommitOutcome(SdkCommitFailureOutcome),
    /// A signed bound or scalar diagnostic value.
    Signed(i64),
    /// The exact canonical typed-query category.
    QueryCategory(SdkQueryDiagnosticCategory),
    /// One bounded typed-query identity admitted for a closed detail key.
    QueryIdentity(SdkQueryDiagnosticIdentity),
    /// A bounded ordered list of typed-query identities.
    QueryIdentityList(Vec<SdkQueryDiagnosticIdentity>),
}

/// Raw presence of one binding-supplied projection-evidence slot.
///
/// This closed value records presence only. It does not parse evidence bytes,
/// infer package provenance, or classify arbitrary evidence collections.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum SdkProjectionEvidenceSlotPresence {
    /// The binding received no bytes for the required slot.
    Absent,
    /// The binding received one or more bytes for the slot.
    Present,
}

/// Schema context for a staged failure, supplied from the executing plan only.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct FailureContext {
    /// Possible owning type; never parsed from provider text.
    pub owner: Option<TypeId>,
    /// Possible ownership fact; never parsed from provider text.
    pub attribute: Option<OwnsFactId>,
}
impl FailureContext {
    /// Context naming the possible owning type and ownership fact.
    #[must_use]
    pub const fn new(owner: Option<TypeId>, attribute: Option<OwnsFactId>) -> Self {
        Self { owner, attribute }
    }
}

/// One stable, binding-neutral SDK execution failure.
///
/// This value is versioned but intentionally has no wire representation. A
/// binding must copy its accessor results into that binding's owned diagnostic
/// handle and must not expose this Rust layout.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SdkExecutionDiagnostic {
    failure: Option<Box<crate::failure::Failure>>,
    version: SdkDiagnosticVersion,
    category: SdkDiagnosticCategory,
    code: SdkDiagnosticCode,
    message: SdkDiagnosticMessage,
    path: Vec<SdkDiagnosticPathSegment>,
    details: BTreeMap<SdkDiagnosticName, SdkDiagnosticDetailValue>,
}

impl SdkExecutionDiagnostic {
    fn stable(
        category: SdkDiagnosticCategory,
        code: SdkDiagnosticCode,
        message: SdkDiagnosticMessage,
    ) -> Self {
        Self {
            failure: None,
            version: SdkDiagnosticVersion::CURRENT,
            category,
            code,
            message,
            path: Vec::new(),
            details: BTreeMap::new(),
        }
    }

    /// Construct a stable invalid-input diagnostic.
    #[must_use]
    pub fn invalid_input(code: SdkDiagnosticCode, message: SdkDiagnosticMessage) -> Self {
        Self::stable(SdkDiagnosticCategory::InvalidInput, code, message)
    }

    /// Construct a stable unsupported-capability diagnostic.
    #[must_use]
    pub fn unsupported_capability(code: SdkDiagnosticCode, message: SdkDiagnosticMessage) -> Self {
        Self::stable(SdkDiagnosticCategory::UnsupportedCapability, code, message)
    }

    /// Construct a stable resource-limit diagnostic.
    #[must_use]
    pub fn resource_limit(code: SdkDiagnosticCode, message: SdkDiagnosticMessage) -> Self {
        Self::stable(SdkDiagnosticCategory::ResourceLimit, code, message)
    }

    /// Construct a stable integrity diagnostic.
    #[must_use]
    pub fn integrity(code: SdkDiagnosticCode, message: SdkDiagnosticMessage) -> Self {
        Self::stable(SdkDiagnosticCategory::Integrity, code, message)
    }

    /// Construct the fixed generated-package projection-evidence diagnostic.
    ///
    /// Callers may append the exact rejected evidence index and validated
    /// evidence identity, plus closed typed count or provenance details. The
    /// root argument is fixed here so every binding exposes the same path.
    #[must_use]
    pub fn projection_evidence_mismatch() -> Self {
        Self::stable(
            SdkDiagnosticCategory::Integrity,
            static_code("projection_evidence_mismatch"),
            static_message(
                "Generated projection evidence does not match the verified schema package",
            ),
        )
        .try_at(SdkDiagnosticPathSegment::Argument(static_name(
            "projection_evidence",
        )))
        .expect("the fixed projection-evidence diagnostic path is bounded")
    }

    /// Construct the fixed diagnostic for one required projection-evidence
    /// identity that is absent from its expected position.
    ///
    /// The caller supplies a validated contract identity and whether the
    /// rejected package was foreign. The occurrence counts are fixed by the
    /// missing-evidence case: exactly one occurrence was expected and none was
    /// present. Other mismatch shapes must use
    /// [`Self::projection_evidence_mismatch`] and attach their own exact typed
    /// metadata rather than relabeling them as missing evidence.
    #[must_use]
    pub fn projection_evidence_missing(
        index: u64,
        identity: SdkQueryDiagnosticIdentity,
        foreign_package: bool,
    ) -> Self {
        Self::projection_evidence_mismatch()
            .try_at(SdkDiagnosticPathSegment::Index(index))
            .and_then(|diagnostic| {
                diagnostic.try_at(SdkDiagnosticPathSegment::ContractIdentity(identity))
            })
            .expect("the fixed missing-evidence diagnostic path is bounded")
            .with_static_detail(
                static_name("actual_occurrence_count"),
                SdkDiagnosticDetailValue::Count(0),
            )
            .with_static_detail(
                static_name("expected_occurrence_count"),
                SdkDiagnosticDetailValue::Count(1),
            )
            .with_static_detail(
                static_name("foreign_package"),
                SdkDiagnosticDetailValue::Boolean(foreign_package),
            )
    }

    /// Classify a rejected package by the raw presence of its detached
    /// semantic-schema-fingerprint evidence.
    ///
    /// The detached semantic fingerprint is the first item in the current
    /// generated-package admission evidence, so an absent slot has canonical
    /// index zero and identity `semantic_schema_fingerprint`. Absence alone
    /// never proves a foreign package. A present slot deliberately retains the
    /// generic mismatch because malformed, noncanonical, stale, forged, or
    /// otherwise conflicting bytes cannot honestly be narrowed by presence.
    #[must_use]
    pub fn classify_detached_semantic_schema_fingerprint_rejection(
        presence: SdkProjectionEvidenceSlotPresence,
    ) -> Self {
        match presence {
            SdkProjectionEvidenceSlotPresence::Absent => Self::projection_evidence_missing(
                0,
                SdkQueryDiagnosticIdentity::new("semantic_schema_fingerprint")
                    .expect("the fixed projection-evidence identity is canonical"),
                false,
            ),
            SdkProjectionEvidenceSlotPresence::Present => Self::projection_evidence_mismatch(),
        }
    }

    /// Construct the fixed generated-token package-brand diagnostic.
    ///
    /// Operation owners append the exact model, field, role, or query path at
    /// which a token from another installed package was rejected.
    #[must_use]
    pub fn generated_token_package_mismatch() -> Self {
        Self::stable(
            SdkDiagnosticCategory::Integrity,
            static_code("generated_token_package_mismatch"),
            static_message("The generated token belongs to a different installed schema package"),
        )
    }

    /// Construct a redacted provider diagnostic.
    ///
    /// The constructor accepts only a closed operation class. In particular,
    /// it cannot receive provider error text, credentials, endpoints, paths,
    /// query text, or query values.
    #[must_use]
    pub fn provider_failure(operation: SdkProviderOperation) -> Self {
        Self::stable(
            SdkDiagnosticCategory::Provider,
            static_code("provider_operation_failed"),
            static_message("The database provider could not complete the requested operation"),
        )
        .with_static_detail(
            static_name("operation"),
            SdkDiagnosticDetailValue::ProviderOperation(operation),
        )
    }

    /// Construct a classified, redacted commit-failure diagnostic.
    ///
    /// The exact provider message is deliberately discarded. An unknown
    /// outcome requires state reconciliation before any retry.
    #[must_use]
    pub fn commit_failure(outcome: SdkCommitFailureOutcome) -> Self {
        let (code, message) = match outcome {
            SdkCommitFailureOutcome::DefinitelyAborted => (
                "commit_definitely_aborted",
                "The provider proves that the transaction did not commit",
            ),
            SdkCommitFailureOutcome::Unknown => (
                "commit_outcome_unknown",
                "The transaction commit outcome is unknown and state must be reconciled before retry",
            ),
        };
        Self::stable(
            SdkDiagnosticCategory::Transaction,
            static_code(code),
            static_message(message),
        )
        .with_static_detail(
            static_name("commit_outcome"),
            SdkDiagnosticDetailValue::CommitOutcome(outcome),
        )
    }

    /// Construct the released diagnostic for a typed provider failure.
    ///
    /// The code stays on the released vocabulary: an indeterminate commit is
    /// `commit_outcome_unknown`, a commit rejection `commit_definitely_aborted`
    /// and a query rejection `provider_operation_failed` for a `write`. The
    /// typed failure is added through [`Self::with_failure`].
    #[must_use]
    pub fn from_failure(failure: &crate::failure::Failure, context: FailureContext) -> Self {
        use crate::failure::{Failure, Phase};
        let released = match failure {
            Failure::Indeterminate { .. } => Self::commit_failure(SdkCommitFailureOutcome::Unknown),
            Failure::Rejected {
                phase: Phase::Commit,
                ..
            } => Self::commit_failure(SdkCommitFailureOutcome::DefinitelyAborted),
            Failure::Rejected {
                phase: Phase::Query,
                ..
            } => Self::provider_failure(SdkProviderOperation::Write),
        };
        released.with_failure(failure, context)
    }

    /// Attach a typed provider failure to a released diagnostic.
    ///
    /// Code, category, message and existing details are kept. The additive
    /// details are `retry_safe`, `phase`, `code` (provider code), `rejection`
    /// (reason), `lock_kind` and `annotation`; the staged index and schema
    /// context extend the path. [`Self::failure_from_host_json`] reads them
    /// back.
    #[must_use]
    pub fn with_failure(
        mut self,
        failure: &crate::failure::Failure,
        context: FailureContext,
    ) -> Self {
        use crate::failure::Failure;
        self.failure = Some(Box::new(failure.clone()));
        let mut diagnostic = self.with_static_detail(
            static_name(FAILURE_RETRY_SAFE_DETAIL),
            SdkDiagnosticDetailValue::Boolean(failure.retry_safe()),
        );
        let host = failure.host_json();
        for (key, name) in FAILURE_IDENTITY_DETAILS {
            if let Some(value) = host[key].as_str() {
                diagnostic = diagnostic.with_static_detail(
                    static_name(name),
                    SdkDiagnosticDetailValue::QueryIdentity(
                        SdkQueryDiagnosticIdentity::new(value)
                            .expect("closed failure vocabulary is a bounded identity"),
                    ),
                );
            }
        }
        if let Failure::Rejected {
            op_index: Some(index),
            ..
        } = failure
        {
            diagnostic
                .path
                .push(SdkDiagnosticPathSegment::Index(u64::from(*index)));
        }
        if let Some(owner) = context.owner {
            diagnostic.path.push(SdkDiagnosticPathSegment::Type(owner));
        }
        if let Some(field) = context.attribute {
            diagnostic.path.push(SdkDiagnosticPathSegment::Field(field));
        }
        diagnostic
    }

    /// The typed failure a diagnostic's host form carries in the details
    /// [`Self::with_failure`] adds, with the staged index from its path.
    ///
    /// This is how a signed remote reply keeps the failure the server
    /// classified: `None` unless the details name a complete, consistent
    /// failure ([`crate::failure::Failure::from_host_json`]).
    #[must_use]
    pub fn failure_from_host_json(
        diagnostic: &serde_json::Value,
    ) -> Option<crate::failure::Failure> {
        let details = diagnostic.get("details")?;
        let detail = |name: &str, kind: &str| {
            let value = details.get(name)?;
            (value.get("kind")?.as_str()? == kind).then(|| value.get("value").cloned())?
        };
        let mut host = serde_json::Map::new();
        host.insert(
            "retry_safe".into(),
            detail(FAILURE_RETRY_SAFE_DETAIL, "boolean")?,
        );
        for (key, name) in FAILURE_IDENTITY_DETAILS {
            if details.get(name).is_some() {
                host.insert(key.into(), detail(name, "query_identity")?);
            }
        }
        let index = diagnostic
            .get("path")
            .and_then(serde_json::Value::as_array)
            .and_then(|path| {
                path.iter().find_map(|segment| {
                    (segment.get("kind")?.as_str()? == "index")
                        .then(|| segment.get("value").cloned())?
                })
            });
        if let Some(index) = index {
            host.insert("op_index".into(), index);
        }
        crate::failure::Failure::from_host_json(&serde_json::Value::Object(host))
    }

    /// Typed provider failure when constructed from the runtime's classification.
    #[must_use]
    pub fn failure(&self) -> Option<&crate::failure::Failure> {
        self.failure.as_deref()
    }

    /// Details in lexical key order without those [`Self::with_failure`]
    /// added: the released detail set.
    ///
    /// A binding whose released ABI fixes the detail set, such as C ABI 1.6,
    /// projects these instead of [`Self::details`]; the typed failure stays
    /// available through [`Self::failure`].
    pub fn released_details(
        &self,
    ) -> impl Iterator<Item = (&SdkDiagnosticName, &SdkDiagnosticDetailValue)> {
        let typed = self.failure.is_some();
        self.details.iter().filter(move |(key, _)| {
            let key = key.as_str();
            !(typed
                && (key == FAILURE_RETRY_SAFE_DETAIL
                    || FAILURE_IDENTITY_DETAILS
                        .iter()
                        .any(|(_, name)| *name == key)))
        })
    }

    /// Typed commit outcome, including the released umbrella constructors.
    #[must_use]
    pub fn commit_outcome(&self) -> Option<SdkCommitFailureOutcome> {
        self.details.values().find_map(|value| match value {
            SdkDiagnosticDetailValue::CommitOutcome(outcome) => Some(*outcome),
            _ => None,
        })
    }

    /// Construct a stable transaction-lifecycle diagnostic.
    ///
    /// Dynamic transaction or provider text cannot enter this constructor;
    /// callers supply only implementation-owned stable code and message text.
    #[must_use]
    pub fn transaction_failure(code: SdkDiagnosticCode, message: SdkDiagnosticMessage) -> Self {
        Self::stable(SdkDiagnosticCategory::Transaction, code, message)
    }

    /// Construct a typed-query diagnostic while retaining its exact canonical
    /// query category inside the binding-neutral SDK envelope.
    ///
    /// The message is selected from a closed redacted vocabulary. Dynamic
    /// provider text, query operands, and transport context cannot enter this
    /// constructor.
    #[must_use]
    pub fn query_failure(category: SdkQueryDiagnosticCategory, code: SdkDiagnosticCode) -> Self {
        let (outer, message) = match category {
            SdkQueryDiagnosticCategory::InvalidPlan => (
                SdkDiagnosticCategory::InvalidInput,
                "The typed query plan does not satisfy the generated query contract",
            ),
            SdkQueryDiagnosticCategory::Cardinality => (
                SdkDiagnosticCategory::InvalidInput,
                "The typed query result does not satisfy the requested cardinality",
            ),
            SdkQueryDiagnosticCategory::UnsupportedCapability => (
                SdkDiagnosticCategory::UnsupportedCapability,
                "The provider cannot execute a capability required by this typed query",
            ),
            SdkQueryDiagnosticCategory::StaleSchema => (
                SdkDiagnosticCategory::Integrity,
                "The typed query schema authority changed after request validation",
            ),
            SdkQueryDiagnosticCategory::ResourceLimit => (
                SdkDiagnosticCategory::ResourceLimit,
                "The typed query exceeded a binding neutral execution limit",
            ),
            SdkQueryDiagnosticCategory::Cancelled => (
                SdkDiagnosticCategory::Cancelled,
                "The typed query was cancelled during execution",
            ),
            SdkQueryDiagnosticCategory::Provider => (
                SdkDiagnosticCategory::Provider,
                "The database provider could not complete the typed query",
            ),
            SdkQueryDiagnosticCategory::ResultDecode => (
                SdkDiagnosticCategory::Integrity,
                "Typed query evidence does not match the validated request invocation",
            ),
        };
        Self::stable(outer, code, static_message(message)).with_static_detail(
            static_name("query_category"),
            SdkDiagnosticDetailValue::QueryCategory(category),
        )
    }

    /// Construct the fixed diagnostic for pre-dispatch cancellation.
    #[must_use]
    pub fn cancelled_before_dispatch() -> Self {
        Self::stable(
            SdkDiagnosticCategory::Cancelled,
            static_code("cancelled_before_dispatch"),
            static_message("The operation was cancelled before provider dispatch"),
        )
    }

    /// Construct the fixed data-operation cancellation diagnostic.
    #[must_use]
    pub fn data_operation_cancelled() -> Self {
        Self::stable(
            SdkDiagnosticCategory::Cancelled,
            static_code("provider_cancelled"),
            static_message("The data operation was cancelled"),
        )
    }

    /// Construct the fixed absolute data-operation deadline diagnostic.
    #[must_use]
    pub fn data_operation_deadline_exceeded() -> Self {
        Self::stable(
            SdkDiagnosticCategory::ResourceLimit,
            static_code("transaction_deadline_exceeded"),
            static_message("The data operation exceeded its absolute execution deadline"),
        )
    }

    /// Construct the fixed canonical projected-codec cancellation diagnostic.
    #[must_use]
    pub fn projected_codec_cancelled() -> Self {
        Self::stable(
            SdkDiagnosticCategory::Cancelled,
            static_code("projected_codec_cancelled"),
            static_message("Canonical projected codec work was cancelled before publication"),
        )
    }

    /// Construct the fixed canonical projected-codec deadline diagnostic.
    #[must_use]
    pub fn projected_codec_deadline_exceeded() -> Self {
        Self::resource_limit(
            static_code("projected_codec_deadline_exceeded"),
            static_message("Canonical projected codec work exceeded its absolute deadline"),
        )
    }

    fn projected_codec_limit(code: &'static str) -> Self {
        Self::resource_limit(
            static_code(code),
            static_message("Canonical projected codec work exceeded a tightened resource limit"),
        )
    }

    /// Construct the fixed canonical projected-codec input-byte limit diagnostic.
    #[must_use]
    pub fn projected_codec_input_limit() -> Self {
        Self::projected_codec_limit("projected_codec_input_limit")
    }

    /// Construct the fixed canonical projected-codec output-byte limit diagnostic.
    #[must_use]
    pub fn projected_codec_output_limit() -> Self {
        Self::projected_codec_limit("projected_codec_output_limit")
    }

    /// Construct the fixed canonical projected-codec member limit diagnostic.
    #[must_use]
    pub fn projected_codec_member_limit() -> Self {
        Self::projected_codec_limit("projected_codec_member_limit")
    }

    /// Construct the fixed canonical projected-codec depth limit diagnostic.
    #[must_use]
    pub fn projected_codec_depth_limit() -> Self {
        Self::projected_codec_limit("projected_codec_depth_limit")
    }

    /// Construct the fixed declared-schema mismatch diagnostic without payload data.
    #[must_use]
    pub fn projected_record_schema_mismatch() -> Self {
        Self::invalid_input(
            static_code("projected_record_schema_mismatch"),
            static_message("Canonical projected record schema identity does not match the package"),
        )
        .try_at(SdkDiagnosticPathSegment::ContractField(
            SdkQueryDiagnosticIdentity::new("declared_schema_identity")
                .expect("the fixed projected record schema path is canonical"),
        ))
        .expect("the fixed projected record schema path is bounded")
    }

    /// Construct the fixed rejection for mutating a decoded detached snapshot.
    #[must_use]
    pub fn projected_snapshot_detached() -> Self {
        Self::invalid_input(
            static_code("projected_snapshot_detached"),
            static_message(
                "A decoded canonical snapshot is detached and cannot authorize a mutation",
            ),
        )
    }

    /// Construct a redacted internal failure with no implementation details.
    #[must_use]
    pub fn internal_failure() -> Self {
        Self::stable(
            SdkDiagnosticCategory::Internal,
            static_code("internal_failure"),
            static_message("The operation failed inside the TypeBridge runtime"),
        )
    }

    /// Append one typed path segment, enforcing the path ceiling.
    pub fn try_at(
        mut self,
        segment: SdkDiagnosticPathSegment,
    ) -> Result<Self, SdkDiagnosticBuildError> {
        if self.path.len() == MAX_SDK_DIAGNOSTIC_PATH_SEGMENTS {
            return Err(SdkDiagnosticBuildError::PathLimitExceeded);
        }
        self.path.push(segment);
        Ok(self)
    }

    /// Prepend a bounded typed path while preserving the complete diagnostic.
    ///
    /// Execution layers use this when a validated child value fails beneath a
    /// containing argument or collection item. The original category, code,
    /// message, path suffix, and typed details remain unchanged.
    pub fn try_with_path_prefix<I>(mut self, prefix: I) -> Result<Self, SdkDiagnosticBuildError>
    where
        I: IntoIterator<Item = SdkDiagnosticPathSegment>,
    {
        let mut bounded = Vec::new();
        for segment in prefix {
            if bounded.len().saturating_add(self.path.len()) == MAX_SDK_DIAGNOSTIC_PATH_SEGMENTS {
                return Err(SdkDiagnosticBuildError::PathLimitExceeded);
            }
            bounded.push(segment);
        }
        for segment in bounded.into_iter().rev() {
            self.path.insert(0, segment);
        }
        Ok(self)
    }

    /// Attach one typed detail, enforcing uniqueness and the detail ceiling.
    pub fn try_with_detail(
        mut self,
        key: SdkDiagnosticName,
        value: SdkDiagnosticDetailValue,
    ) -> Result<Self, SdkDiagnosticBuildError> {
        if self.details.contains_key(&key) {
            return Err(SdkDiagnosticBuildError::DuplicateDetail);
        }
        if self.details.len() == MAX_SDK_DIAGNOSTIC_DETAILS {
            return Err(SdkDiagnosticBuildError::DetailLimitExceeded);
        }
        self.details.insert(key, value);
        Ok(self)
    }

    fn with_static_detail(
        mut self,
        key: SdkDiagnosticName,
        value: SdkDiagnosticDetailValue,
    ) -> Self {
        let replaced = self.details.insert(key, value);
        debug_assert!(replaced.is_none());
        self
    }

    /// Return the in-memory diagnostic contract version.
    #[must_use]
    pub const fn version(&self) -> SdkDiagnosticVersion {
        self.version
    }

    /// Return the stable category.
    #[must_use]
    pub const fn category(&self) -> SdkDiagnosticCategory {
        self.category
    }

    /// Return the validated stable code.
    #[must_use]
    pub const fn code(&self) -> &SdkDiagnosticCode {
        &self.code
    }

    /// Return the validated stable message.
    #[must_use]
    pub const fn message(&self) -> SdkDiagnosticMessage {
        self.message
    }

    /// Return the ordered typed path.
    #[must_use]
    pub fn path(&self) -> &[SdkDiagnosticPathSegment] {
        &self.path
    }

    /// Return deterministic typed details in lexical key order.
    #[must_use]
    pub const fn details(&self) -> &BTreeMap<SdkDiagnosticName, SdkDiagnosticDetailValue> {
        &self.details
    }
}

impl fmt::Display for SdkExecutionDiagnostic {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{} [{}]: {}",
            self.category, self.code, self.message
        )
    }
}

impl Error for SdkExecutionDiagnostic {}

impl SdkExecutionDiagnostic {
    /// Map a canonical codec ceiling refusal to its projected-codec
    /// resource-limit diagnostic.
    ///
    /// `input` says whether the refused bytes were being decoded (input) or
    /// encoded (output). Returns `None` for any other contract diagnostic,
    /// which the caller reports unchanged.
    #[must_use]
    pub fn from_canonical_limit(diagnostic: &Diagnostic, input: bool) -> Option<Self> {
        match diagnostic.code().as_str() {
            "canonical_json_too_deep" => Some(Self::projected_codec_depth_limit()),
            "canonical_collection_too_large" => Some(Self::projected_codec_member_limit()),
            "canonical_json_too_large" | "canonical_string_too_large" if input => {
                Some(Self::projected_codec_input_limit())
            }
            "canonical_json_too_large" | "canonical_string_too_large" => {
                Some(Self::projected_codec_output_limit())
            }
            _ => None,
        }
    }

    /// Borrow the canonical host JSON form of this diagnostic.
    #[must_use]
    pub const fn host_json(&self) -> SdkDiagnosticJson<'_> {
        SdkDiagnosticJson(self)
    }
}

/// The one JSON form in which an [`SdkExecutionDiagnostic`] reaches a host.
///
/// ```json
/// {
///   "version": 1,
///   "category": "invalid_plan",
///   "sdk_category": "invalid_input",
///   "query_category": "invalid_plan",
///   "code": "group_key_cap_exceeded",
///   "message": "...",
///   "path": [{"kind": "operation"}, {"kind": "index", "value": 2}],
///   "details": {"maximum": {"kind": "count", "value": "16"}}
/// }
/// ```
///
/// - `category` is the typed-query category when the diagnostic carries
///   one, else the SDK category; `sdk_category` is always the SDK category;
///   `query_category` is the typed-query category or `null`. The
///   `query_category` detail is not repeated under `details`.
/// - Each path segment is `{"kind", "value"}`; structural query segments
///   (`request`, `plan`, `operation`, ...) have no `value`.
/// - Each detail is `{"kind", "value"}`. `count`, `byte_count`, and
///   `signed` values are decimal strings: their Rust types (`u64`, `i64`)
///   exceed the 2^53 integers a JavaScript number holds exactly.
/// - Path positions (`index`, `output_slot`, `binding`, `role_edge`) are
///   JSON numbers: they index collections bounded by the canonical codec
///   ceilings, far below 2^53.
#[derive(Clone, Copy, Debug)]
pub struct SdkDiagnosticJson<'a>(&'a SdkExecutionDiagnostic);

impl Serialize for SdkDiagnosticJson<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let diagnostic = self.0;
        let query_category = diagnostic
            .details()
            .values()
            .find_map(|detail| match detail {
                SdkDiagnosticDetailValue::QueryCategory(category) => Some(category.as_str()),
                _ => None,
            });
        let sdk_category = diagnostic.category().as_str();
        let mut map = serializer.serialize_map(Some(8))?;
        map.serialize_entry("version", &diagnostic.version().get())?;
        map.serialize_entry("category", query_category.unwrap_or(sdk_category))?;
        map.serialize_entry("sdk_category", sdk_category)?;
        map.serialize_entry("query_category", &query_category)?;
        map.serialize_entry("code", diagnostic.code().as_str())?;
        map.serialize_entry("message", diagnostic.message().as_str())?;
        map.serialize_entry("path", &PathJson(diagnostic.path()))?;
        map.serialize_entry("details", &DetailsJson(diagnostic.details()))?;
        map.end()
    }
}

struct PathJson<'a>(&'a [SdkDiagnosticPathSegment]);

impl Serialize for PathJson<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_seq(self.0.iter().map(SegmentJson))
    }
}

struct SegmentJson<'a>(&'a SdkDiagnosticPathSegment);

#[derive(Serialize)]
struct OwnedName<'a> {
    owner: &'a str,
    name: &'a str,
}

impl Serialize for SegmentJson<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self.0 {
            SdkDiagnosticPathSegment::Argument(name) => {
                tagged(serializer, "argument", name.as_str())
            }
            SdkDiagnosticPathSegment::Index(index) => tagged(serializer, "index", index),
            SdkDiagnosticPathSegment::Type(id) => tagged(serializer, "type", id),
            SdkDiagnosticPathSegment::Field(id) => tagged(serializer, "field", id),
            SdkDiagnosticPathSegment::Role(id) => tagged(serializer, "role", id),
            SdkDiagnosticPathSegment::Query(kind) => {
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry("kind", kind.as_str())?;
                map.end()
            }
            SdkDiagnosticPathSegment::QueryBinding(binding) => {
                tagged(serializer, "binding", binding)
            }
            SdkDiagnosticPathSegment::QueryField { owner, name } => tagged(
                serializer,
                "field",
                &OwnedName {
                    owner: owner.as_str(),
                    name: name.as_str(),
                },
            ),
            SdkDiagnosticPathSegment::QueryRole { owner, name } => tagged(
                serializer,
                "role",
                &OwnedName {
                    owner: owner.as_str(),
                    name: name.as_str(),
                },
            ),
            SdkDiagnosticPathSegment::QueryRoleEdge(edge) => tagged(serializer, "role_edge", edge),
            SdkDiagnosticPathSegment::QueryOutputSlot(slot) => {
                tagged(serializer, "output_slot", slot)
            }
            SdkDiagnosticPathSegment::QueryOutputName(name) => {
                tagged(serializer, "output_name", name.as_str())
            }
            SdkDiagnosticPathSegment::ContractField(name) => {
                tagged(serializer, "contract_field", name.as_str())
            }
            SdkDiagnosticPathSegment::ContractIdentity(name) => {
                tagged(serializer, "contract_identity", name.as_str())
            }
        }
    }
}

struct DetailsJson<'a>(&'a BTreeMap<SdkDiagnosticName, SdkDiagnosticDetailValue>);

impl Serialize for DetailsJson<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_map(
            self.0
                .iter()
                .filter(|(_, value)| !matches!(value, SdkDiagnosticDetailValue::QueryCategory(_)))
                .map(|(name, value)| (name.as_str(), DetailJson(value))),
        )
    }
}

struct DetailJson<'a>(&'a SdkDiagnosticDetailValue);

impl Serialize for DetailJson<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self.0 {
            SdkDiagnosticDetailValue::Boolean(value) => tagged(serializer, "boolean", value),
            SdkDiagnosticDetailValue::Count(value) => {
                tagged(serializer, "count", &value.to_string())
            }
            SdkDiagnosticDetailValue::ByteCount(value) => {
                tagged(serializer, "byte_count", &value.to_string())
            }
            SdkDiagnosticDetailValue::Signed(value) => {
                tagged(serializer, "signed", &value.to_string())
            }
            SdkDiagnosticDetailValue::QueryIdentity(value) => {
                tagged(serializer, "query_identity", value.as_str())
            }
            SdkDiagnosticDetailValue::QueryIdentityList(values) => tagged(
                serializer,
                "query_identity_list",
                &values
                    .iter()
                    .map(SdkQueryDiagnosticIdentity::as_str)
                    .collect::<Vec<_>>(),
            ),
            SdkDiagnosticDetailValue::Capability(value) => {
                tagged(serializer, "text", value.as_str())
            }
            SdkDiagnosticDetailValue::ValueType(value) => {
                tagged(serializer, "text", value.as_str())
            }
            SdkDiagnosticDetailValue::Type(value) => tagged(serializer, "text", value),
            SdkDiagnosticDetailValue::Field(value) => tagged(serializer, "text", value),
            SdkDiagnosticDetailValue::Role(value) => tagged(serializer, "text", value),
            SdkDiagnosticDetailValue::Fingerprint(value) => tagged(serializer, "text", value),
            SdkDiagnosticDetailValue::ProviderOperation(value) => {
                tagged(serializer, "text", value.as_str())
            }
            SdkDiagnosticDetailValue::CommitOutcome(value) => {
                tagged(serializer, "text", value.as_str())
            }
            SdkDiagnosticDetailValue::QueryCategory(value) => {
                tagged(serializer, "text", value.as_str())
            }
        }
    }
}

fn tagged<S: Serializer, V: Serialize + ?Sized>(
    serializer: S,
    kind: &str,
    value: &V,
) -> Result<S::Ok, S::Error> {
    let mut map = serializer.serialize_map(Some(2))?;
    map.serialize_entry("kind", kind)?;
    map.serialize_entry("value", value)?;
    map.end()
}

fn static_code(value: &'static str) -> SdkDiagnosticCode {
    SdkDiagnosticCode::new(value).expect("static SDK diagnostic code is canonical")
}

fn static_message(value: &'static str) -> SdkDiagnosticMessage {
    SdkDiagnosticMessage::new(value).expect("static SDK diagnostic message is valid")
}

/// Boolean detail [`SdkExecutionDiagnostic::with_failure`] always adds.
const FAILURE_RETRY_SAFE_DETAIL: &str = "retry_safe";

/// Identity details [`SdkExecutionDiagnostic::with_failure`] adds when the
/// failure has them, as (`Failure::host_json` key, detail name).
const FAILURE_IDENTITY_DETAILS: [(&str, &str); 5] = [
    ("phase", "phase"),
    ("code", "code"),
    ("reason", "rejection"),
    ("lock_kind", "lock_kind"),
    ("annotation", "annotation"),
];

fn static_name(value: &'static str) -> SdkDiagnosticName {
    SdkDiagnosticName::new(value).expect("static SDK diagnostic name is canonical")
}

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

    #[test]
    fn signed_failure_details_round_trip_every_phase_and_reason() {
        use crate::failure::{AnnotationKind, Code, Failure, LockKind, Phase, Reason};
        let reasons = [
            Reason::Conflict {
                lock: LockKind::Exclusive,
            },
            Reason::Conflict {
                lock: LockKind::RequireDeletedKey,
            },
            Reason::Conflict {
                lock: LockKind::DeletingRequiredKey,
            },
            Reason::Conflict {
                lock: LockKind::Unknown,
            },
            Reason::Cardinality,
            Reason::Unique,
            Reason::Constraint {
                annotation: AnnotationKind::Abstract,
            },
            Reason::Constraint {
                annotation: AnnotationKind::Regex,
            },
            Reason::Constraint {
                annotation: AnnotationKind::Range,
            },
            Reason::Constraint {
                annotation: AnnotationKind::Values,
            },
            Reason::Constraint {
                annotation: AnnotationKind::Distinct,
            },
            Reason::Constraint {
                annotation: AnnotationKind::Unknown,
            },
            Reason::Other {
                code: Code::new("TSV7").expect("code"),
            },
        ];
        let mut failures = vec![
            Failure::Indeterminate { code: None },
            Failure::Indeterminate {
                code: Code::new("SRV9"),
            },
        ];
        for phase in [Phase::Query, Phase::Commit] {
            for reason in &reasons {
                for op_index in [None, Some(3)] {
                    failures.push(Failure::Rejected {
                        phase,
                        reason: reason.clone(),
                        op_index,
                    });
                }
            }
        }
        for failure in failures {
            let diagnostic =
                SdkExecutionDiagnostic::from_failure(&failure, FailureContext::default());
            let host = serde_json::to_value(diagnostic.host_json()).expect("host json");
            assert_eq!(
                SdkExecutionDiagnostic::failure_from_host_json(&host),
                Some(failure.clone()),
                "{host}"
            );
            assert_eq!(Failure::from_host_json(&failure.host_json()), Some(failure));
            // The released detail set never shows the additive failure details.
            assert!(
                diagnostic
                    .released_details()
                    .all(|(name, _)| name.as_str() != "phase" && name.as_str() != "retry_safe")
            );
        }
    }

    #[test]
    fn signed_failure_details_refuse_an_incomplete_or_inconsistent_failure() {
        use crate::failure::Failure;
        let unique = Failure::Rejected {
            phase: crate::failure::Phase::Query,
            reason: crate::failure::Reason::Unique,
            op_index: Some(0),
        };
        let host = unique.host_json();
        for (key, value) in [
            ("phase", serde_json::Value::Null),
            ("phase", "staging".into()),
            ("retry_safe", serde_json::Value::Null),
            ("code", "CNT5".into()),
            ("lock_kind", "exclusive".into()),
            ("reason", "duplicate".into()),
        ] {
            let mut changed = host.clone();
            changed[key] = value;
            assert_eq!(Failure::from_host_json(&changed), None, "{changed}");
        }
        // A diagnostic without the additive details carries no failure.
        let plain = serde_json::to_value(
            SdkExecutionDiagnostic::provider_failure(SdkProviderOperation::Write).host_json(),
        )
        .expect("host json");
        assert_eq!(SdkExecutionDiagnostic::failure_from_host_json(&plain), None);
    }

    #[test]
    fn generated_package_diagnostics_have_fixed_binding_neutral_vocabulary() {
        let evidence = SdkExecutionDiagnostic::projection_evidence_mismatch();
        assert_eq!(evidence.category(), SdkDiagnosticCategory::Integrity);
        assert_eq!(evidence.code().as_str(), "projection_evidence_mismatch");
        assert_eq!(
            evidence.message().as_str(),
            "Generated projection evidence does not match the verified schema package",
        );
        assert!(matches!(
            evidence.path(),
            [SdkDiagnosticPathSegment::Argument(name)]
                if name.as_str() == "projection_evidence"
        ));
        assert!(evidence.details().is_empty());

        let token = SdkExecutionDiagnostic::generated_token_package_mismatch();
        assert_eq!(token.category(), SdkDiagnosticCategory::Integrity);
        assert_eq!(token.code().as_str(), "generated_token_package_mismatch");
        assert_eq!(
            token.message().as_str(),
            "The generated token belongs to a different installed schema package",
        );
        assert!(token.path().is_empty());
        assert!(token.details().is_empty());
    }

    #[test]
    fn detached_semantic_fingerprint_classifier_matches_models_representative() {
        let missing =
            SdkExecutionDiagnostic::classify_detached_semantic_schema_fingerprint_rejection(
                SdkProjectionEvidenceSlotPresence::Absent,
            );
        assert_eq!(missing.category(), SdkDiagnosticCategory::Integrity);
        assert_eq!(missing.code().as_str(), "projection_evidence_mismatch");
        assert!(matches!(
            missing.path(),
            [
                SdkDiagnosticPathSegment::Argument(argument),
                SdkDiagnosticPathSegment::Index(0),
                SdkDiagnosticPathSegment::ContractIdentity(identity),
            ] if argument.as_str() == "projection_evidence"
                && identity.as_str() == "semantic_schema_fingerprint"
        ));
        assert_eq!(
            missing
                .details()
                .iter()
                .map(|(name, value)| (name.as_str(), value))
                .collect::<Vec<_>>(),
            vec![
                (
                    "actual_occurrence_count",
                    &SdkDiagnosticDetailValue::Count(0),
                ),
                (
                    "expected_occurrence_count",
                    &SdkDiagnosticDetailValue::Count(1),
                ),
                ("foreign_package", &SdkDiagnosticDetailValue::Boolean(false),),
            ],
        );

        let present =
            SdkExecutionDiagnostic::classify_detached_semantic_schema_fingerprint_rejection(
                SdkProjectionEvidenceSlotPresence::Present,
            );
        assert_eq!(
            present,
            SdkExecutionDiagnostic::projection_evidence_mismatch()
        );
    }

    #[test]
    fn projected_codec_diagnostics_match_the_closed_serialization_algebra() {
        for (diagnostic, category, code) in [
            (
                SdkExecutionDiagnostic::projected_codec_cancelled(),
                SdkDiagnosticCategory::Cancelled,
                "projected_codec_cancelled",
            ),
            (
                SdkExecutionDiagnostic::projected_codec_input_limit(),
                SdkDiagnosticCategory::ResourceLimit,
                "projected_codec_input_limit",
            ),
            (
                SdkExecutionDiagnostic::projected_codec_output_limit(),
                SdkDiagnosticCategory::ResourceLimit,
                "projected_codec_output_limit",
            ),
            (
                SdkExecutionDiagnostic::projected_codec_member_limit(),
                SdkDiagnosticCategory::ResourceLimit,
                "projected_codec_member_limit",
            ),
            (
                SdkExecutionDiagnostic::projected_codec_depth_limit(),
                SdkDiagnosticCategory::ResourceLimit,
                "projected_codec_depth_limit",
            ),
        ] {
            assert_eq!(diagnostic.category(), category);
            assert_eq!(diagnostic.code().as_str(), code);
            assert!(diagnostic.path().is_empty());
            assert!(diagnostic.details().is_empty());
        }

        let mismatch = SdkExecutionDiagnostic::projected_record_schema_mismatch();
        assert_eq!(mismatch.category(), SdkDiagnosticCategory::InvalidInput);
        assert_eq!(mismatch.code().as_str(), "projected_record_schema_mismatch");
        assert!(matches!(
            mismatch.path(),
            [SdkDiagnosticPathSegment::ContractField(field)]
                if field.as_str() == "declared_schema_identity"
        ));
        assert!(mismatch.details().is_empty());

        let detached = SdkExecutionDiagnostic::projected_snapshot_detached();
        assert_eq!(detached.category(), SdkDiagnosticCategory::InvalidInput);
        assert_eq!(detached.code().as_str(), "projected_snapshot_detached");
        assert!(detached.path().is_empty());
        assert!(detached.details().is_empty());
    }
}