type-bridge 2.2.2

Public client SDK for TypeBridge
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
//! Error handling for the public TypeBridge client.

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

use type_bridge_contract::sdk_diagnostic::{
    SdkDiagnosticCategory, SdkDiagnosticDetailValue, SdkDiagnosticPathSegment,
    SdkExecutionDiagnostic, SdkProjectionEvidenceSlotPresence, SdkQueryDiagnosticCategory,
    SdkQueryDiagnosticPathKind,
};
use type_bridge_orm::match_request::MatchError;
use type_bridge_orm::{
    ProjectedCrudCompatibilityCause, ProjectedCrudCompatibilityFailure,
    ProjectedCrudCompatibilityStage,
};

use crate::hooks::{CrudOperation, ModelKind};

/// Stable public classification for TypeBridge client failures.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ErrorCategory {
    /// Connection establishment or connectivity failed.
    Connection,
    /// Generated or installed schema authority failed verification.
    Schema,
    /// Generated input or provider evidence failed model validation.
    ModelValidation,
    /// Generated package or provider evidence failed an integrity contract.
    Integrity,
    /// A typed query was invalid before provider execution.
    QueryAuthoring,
    /// The provider failed while executing an accepted query.
    QueryExecution,
    /// A transaction lifecycle operation failed.
    Transaction,
    /// A remote envelope, reply, transport, or integrity contract failed.
    Remote,
    /// The selected provider or remote executor lacks a required capability.
    Capability,
    /// A canonical client, provider, or remote resource ceiling was exceeded.
    ResourceLimit,
    /// Cooperative cancellation interrupted the operation.
    Cancelled,
    /// A requested entity or schema element was not found.
    NotFound,
    /// A generated-model lifecycle hook rejected or failed an operation.
    Lifecycle,
    /// An underlying database operation failed outside a narrower category.
    Database,
    /// A client invariant failed outside the stable categories above.
    Other,
}

impl ErrorCategory {
    /// Return the stable language-neutral category spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Connection => "connection",
            Self::Schema => "schema",
            Self::ModelValidation => "model_validation",
            Self::Integrity => "integrity",
            Self::QueryAuthoring => "query_authoring",
            Self::QueryExecution => "query_execution",
            Self::Transaction => "transaction",
            Self::Remote => "remote",
            Self::Capability => "capability",
            Self::ResourceLimit => "resource_limit",
            Self::Cancelled => "cancelled",
            Self::NotFound => "not_found",
            Self::Lifecycle => "lifecycle",
            Self::Database => "database",
            Self::Other => "other",
        }
    }
}

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

/// Stage at which generated-model evidence failed validation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ModelValidationPhase {
    /// Generated constructor input failed before provider execution.
    Input,
    /// Provider row evidence failed while hydrating a generated model.
    Hydration,
}

/// One typed value from a structured engine or remote diagnostic.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ErrorDetail {
    /// Textual context.
    Text(String),
    /// A signed integer.
    Long(i64),
    /// A boolean fact.
    Boolean(bool),
    /// An ordered list of text values.
    TextList(Vec<String>),
    /// The exact canonical typed-query category.
    QueryCategory(QueryDiagnosticCategory),
    /// One bounded canonical query or contract identity.
    QueryIdentity(String),
    /// An ordered bounded list of canonical query or contract identities.
    QueryIdentityList(Vec<String>),
}

/// Stable public typed-query diagnostic categories.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum QueryDiagnosticCategory {
    /// 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 authority changed.
    StaleSchema,
    /// A query resource ceiling was crossed.
    ResourceLimit,
    /// Cooperative cancellation interrupted execution.
    Cancelled,
    /// The provider failed before complete evidence was available.
    Provider,
    /// Result evidence did not match the validated invocation.
    ResultDecode,
}

/// Stable structural locations within a typed query request or result.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum QueryDiagnosticPathKind {
    /// 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,
}

/// One typed segment from a structured engine or remote diagnostic path.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ErrorPathSegment {
    /// A named public operation argument.
    Argument(String),
    /// A named field in the rejected contract.
    Field(String),
    /// An indexed member in the rejected contract.
    Index(u64),
    /// A schema or query identifier.
    Identifier(String),
    /// A structural typed-query request or result location.
    Query(QueryDiagnosticPathKind),
    /// A plan-local typed-query binding ordinal.
    QueryBinding(u16),
    /// A descriptor-qualified binding-facing query field.
    QueryField {
        /// Kind-qualified registry descriptor identity.
        owner: String,
        /// Binding-facing field name.
        name: String,
    },
    /// A descriptor-qualified query role.
    QueryRole {
        /// Kind-qualified registry descriptor identity.
        owner: String,
        /// Binding-facing role name.
        name: String,
    },
    /// A plan-local typed-query role-edge ordinal.
    QueryRoleEdge(u16),
    /// A zero-based positional query output slot.
    QueryOutputSlot(u64),
    /// A declared generated query output member.
    QueryOutputName(String),
    /// An object field retained from an authenticated contract diagnostic.
    ContractField(String),
    /// An identity retained from an authenticated contract diagnostic.
    ContractIdentity(String),
}

/// Complete typed metadata supplied by one structured engine or remote
/// diagnostic.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ErrorDiagnostic {
    path: Vec<ErrorPathSegment>,
    details: BTreeMap<String, ErrorDetail>,
}

impl ErrorDiagnostic {
    /// Return the typed diagnostic path.
    #[must_use]
    pub fn path(&self) -> &[ErrorPathSegment] {
        &self.path
    }

    /// Return the deterministic typed detail map.
    #[must_use]
    pub fn details(&self) -> &BTreeMap<String, ErrorDetail> {
        &self.details
    }
}

/// Primary error type for the TypeBridge client SDK.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// Generated-model evidence did not match the installed schema projection.
    #[error("Model validation failed during {phase:?}: {message}")]
    ModelValidation {
        /// Validation stage at which the evidence failed.
        phase: ModelValidationPhase,
        /// Stable language-neutral failure code.
        code: String,
        /// Canonical path to the rejected value or model evidence.
        path: Vec<String>,
        /// Human-readable failure summary.
        message: String,
        /// Optional underlying error that caused the validation failure.
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// A structured engine or remote-contract failure mapped into stable
    /// client-owned categories, codes, and paths.
    #[error("{category} error [{code}]: {message}")]
    Classified {
        /// Stable public error category.
        category: ErrorCategory,
        /// Model-validation phase when applicable to this failure.
        phase: Option<ModelValidationPhase>,
        /// Stable language-neutral failure code.
        code: String,
        /// Canonical flattened path to the rejected contract member.
        path: Vec<String>,
        /// Typed engine or remote diagnostic metadata, when supplied.
        diagnostic: Option<Box<ErrorDiagnostic>>,
        /// Human-readable failure summary.
        message: String,
        /// Optional underlying error that caused the classified failure.
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Schema verification or installation failed.
    #[error("Schema verification failed: {message}")]
    SchemaVerification {
        /// Human-readable schema verification failure summary.
        message: String,
        /// Optional underlying schema decoding or installation error.
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Connection to the database failed.
    #[error("Connection error: {message}")]
    Connection {
        /// Human-readable connection failure summary.
        message: String,
        /// Optional underlying transport or provider error.
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Database query or operation failed.
    #[error("Query execution error: {message}")]
    QueryExecution {
        /// Human-readable query execution failure summary.
        message: String,
        /// Optional underlying provider or remote execution error.
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Database transaction failed.
    #[error("Transaction error: {message}")]
    Transaction {
        /// Human-readable transaction failure summary.
        message: String,
        /// Optional underlying provider transaction error.
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Requested schema element or database entity was not found.
    #[error("Entity not found: {message}")]
    NotFound {
        /// Human-readable description of the missing resource.
        message: String,
        /// Optional underlying lookup error.
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Underlying database error.
    #[error("Database error: {message}")]
    Database {
        /// Human-readable database failure summary.
        message: String,
        /// Optional underlying database driver error.
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Client request or execution error.
    #[error("Client error: {message}")]
    Other {
        /// Human-readable client failure summary.
        message: String,
        /// Optional underlying error outside the narrower variants.
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },
}

impl Error {
    pub(crate) fn from_contract_diagnostic(
        error: type_bridge_contract::diagnostic::Diagnostic,
    ) -> Self {
        use type_bridge_contract::diagnostic::DiagnosticCategory;

        let category = match error.category() {
            DiagnosticCategory::InvalidContract => ErrorCategory::Other,
            DiagnosticCategory::UnsupportedCapability => ErrorCategory::Capability,
            DiagnosticCategory::ResourceLimit => ErrorCategory::ResourceLimit,
            DiagnosticCategory::Cancelled => ErrorCategory::Cancelled,
            DiagnosticCategory::Integrity => ErrorCategory::Integrity,
        };
        let code = error.code().as_str().to_owned();
        let message = error.to_string();
        Self::classified_with_diagnostic(
            category,
            None,
            code,
            Vec::new(),
            None,
            message,
            Some(Box::new(error)),
        )
    }

    #[allow(dead_code)]
    pub(crate) fn model_validation(
        phase: ModelValidationPhase,
        code: impl Into<String>,
        path: Vec<String>,
        message: impl Into<String>,
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    ) -> Self {
        Self::ModelValidation {
            phase,
            code: code.into(),
            path,
            message: message.into(),
            source,
        }
    }

    pub(crate) fn classified(
        category: ErrorCategory,
        phase: Option<ModelValidationPhase>,
        code: impl Into<String>,
        path: Vec<String>,
        message: impl Into<String>,
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    ) -> Self {
        Self::classified_with_diagnostic(category, phase, code, path, None, message, source)
    }

    pub(crate) fn projection_evidence_rejection(
        presence: SdkProjectionEvidenceSlotPresence,
    ) -> Self {
        let error = SdkExecutionDiagnostic::classify_detached_semantic_schema_fingerprint_rejection(
            presence,
        );
        let code = error.code().as_str().to_owned();
        let message = error.message().as_str().to_owned();
        let path = error.path().iter().map(flatten_sdk_path).collect();
        let diagnostic = ErrorDiagnostic {
            path: error
                .path()
                .iter()
                .map(|segment| match segment {
                    SdkDiagnosticPathSegment::Argument(value) => {
                        ErrorPathSegment::Argument(value.as_str().to_owned())
                    }
                    other => typed_sdk_path(other),
                })
                .collect(),
            details: error
                .details()
                .iter()
                .map(|(name, value)| (name.as_str().to_owned(), flatten_sdk_detail(value)))
                .collect(),
        };
        Self::classified_with_diagnostic(
            ErrorCategory::Integrity,
            None,
            code,
            path,
            Some(diagnostic),
            message,
            Some(Box::new(error)),
        )
    }

    fn classified_with_diagnostic(
        category: ErrorCategory,
        phase: Option<ModelValidationPhase>,
        code: impl Into<String>,
        path: Vec<String>,
        diagnostic: Option<ErrorDiagnostic>,
        message: impl Into<String>,
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    ) -> Self {
        Self::Classified {
            category,
            phase,
            code: code.into(),
            path,
            diagnostic: diagnostic.map(Box::new),
            message: message.into(),
            source,
        }
    }

    /// Construct one application-owned remote transport failure.
    ///
    /// Transport implementations should use a stable lowercase snake-case
    /// code so callers can handle the failure without parsing its message.
    #[must_use]
    pub fn remote(
        code: impl Into<String>,
        message: impl Into<String>,
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    ) -> Self {
        Self::classified(
            ErrorCategory::Remote,
            None,
            code,
            Vec::new(),
            message,
            source,
        )
    }

    pub(crate) fn from_match(error: MatchError, phase: ModelValidationPhase) -> Self {
        Self::from_sdk_execution(type_bridge_orm::lower_match_error(&error), phase)
    }

    pub(crate) fn from_sdk_execution(
        error: SdkExecutionDiagnostic,
        model_phase: ModelValidationPhase,
    ) -> Self {
        let code = error.code().as_str().to_owned();
        let message = error.message().as_str().to_owned();
        let path = error.path().iter().map(flatten_sdk_path).collect();
        let diagnostic_path = error.path().iter().map(typed_sdk_path).collect();
        let details = error
            .details()
            .iter()
            .map(|(name, value)| (name.as_str().to_owned(), flatten_sdk_detail(value)))
            .collect();
        let diagnostic = ErrorDiagnostic {
            path: diagnostic_path,
            details,
        };
        if let Some(query_category) = sdk_query_category(&error) {
            let (category, phase) = match query_category {
                SdkQueryDiagnosticCategory::InvalidPlan => (ErrorCategory::QueryAuthoring, None),
                SdkQueryDiagnosticCategory::Cardinality
                | SdkQueryDiagnosticCategory::ResultDecode => {
                    (ErrorCategory::ModelValidation, Some(model_phase))
                }
                SdkQueryDiagnosticCategory::UnsupportedCapability => {
                    (ErrorCategory::Capability, None)
                }
                SdkQueryDiagnosticCategory::StaleSchema => (ErrorCategory::Schema, None),
                SdkQueryDiagnosticCategory::ResourceLimit => (ErrorCategory::ResourceLimit, None),
                SdkQueryDiagnosticCategory::Cancelled => (ErrorCategory::Cancelled, None),
                SdkQueryDiagnosticCategory::Provider => (ErrorCategory::QueryExecution, None),
                _ => (ErrorCategory::Other, None),
            };
            return Self::classified_with_diagnostic(
                category,
                phase,
                code,
                path,
                Some(diagnostic),
                message,
                Some(Box::new(error)),
            );
        }
        match error.category() {
            SdkDiagnosticCategory::InvalidInput | SdkDiagnosticCategory::Integrity => {
                Self::ModelValidation {
                    phase: model_phase,
                    code,
                    path,
                    message,
                    source: Some(Box::new(error)),
                }
            }
            SdkDiagnosticCategory::Provider => Self::QueryExecution {
                message,
                source: Some(Box::new(error)),
            },
            SdkDiagnosticCategory::Transaction => Self::Transaction {
                message,
                source: Some(Box::new(error)),
            },
            SdkDiagnosticCategory::UnsupportedCapability => Self::classified_with_diagnostic(
                ErrorCategory::Capability,
                None,
                code,
                path,
                Some(diagnostic),
                message,
                Some(Box::new(error)),
            ),
            SdkDiagnosticCategory::ResourceLimit => Self::classified_with_diagnostic(
                ErrorCategory::ResourceLimit,
                None,
                code,
                path,
                Some(diagnostic),
                message,
                Some(Box::new(error)),
            ),
            SdkDiagnosticCategory::Cancelled => Self::classified_with_diagnostic(
                ErrorCategory::Cancelled,
                None,
                code,
                path,
                Some(diagnostic),
                message,
                Some(Box::new(error)),
            ),
            SdkDiagnosticCategory::Internal => Self::classified_with_diagnostic(
                ErrorCategory::Other,
                None,
                code,
                path,
                Some(diagnostic),
                message,
                Some(Box::new(error)),
            ),
            _ => Self::Other {
                message,
                source: Some(Box::new(error)),
            },
        }
    }

    #[cfg(feature = "typedb")]
    pub(crate) fn from_direct_connection(error: SdkExecutionDiagnostic) -> Self {
        let category = match error.category() {
            SdkDiagnosticCategory::InvalidInput | SdkDiagnosticCategory::Provider => {
                ErrorCategory::Connection
            }
            SdkDiagnosticCategory::Integrity => ErrorCategory::Integrity,
            SdkDiagnosticCategory::UnsupportedCapability => ErrorCategory::Capability,
            SdkDiagnosticCategory::ResourceLimit => ErrorCategory::ResourceLimit,
            SdkDiagnosticCategory::Cancelled => ErrorCategory::Cancelled,
            SdkDiagnosticCategory::Transaction | SdkDiagnosticCategory::Internal => {
                ErrorCategory::Other
            }
            _ => ErrorCategory::Other,
        };
        let code = error.code().as_str().to_owned();
        let message = error.message().as_str().to_owned();
        let path = error.path().iter().map(flatten_sdk_path).collect();
        let diagnostic = ErrorDiagnostic {
            path: error.path().iter().map(typed_sdk_path).collect(),
            details: error
                .details()
                .iter()
                .map(|(name, value)| (name.as_str().to_owned(), flatten_sdk_detail(value)))
                .collect(),
        };
        Self::classified_with_diagnostic(
            category,
            None,
            code,
            path,
            Some(diagnostic),
            message,
            Some(Box::new(error)),
        )
    }

    pub(crate) fn from_projected_batch(
        error: SdkExecutionDiagnostic,
        model_phase: ModelValidationPhase,
    ) -> Self {
        let (category, phase) = match error.category() {
            SdkDiagnosticCategory::InvalidInput => {
                (ErrorCategory::ModelValidation, Some(model_phase))
            }
            SdkDiagnosticCategory::Integrity => (ErrorCategory::Integrity, Some(model_phase)),
            SdkDiagnosticCategory::Provider => (ErrorCategory::QueryExecution, None),
            SdkDiagnosticCategory::Transaction => (ErrorCategory::Transaction, None),
            SdkDiagnosticCategory::UnsupportedCapability => (ErrorCategory::Capability, None),
            SdkDiagnosticCategory::ResourceLimit => (ErrorCategory::ResourceLimit, None),
            SdkDiagnosticCategory::Cancelled => (ErrorCategory::Cancelled, None),
            SdkDiagnosticCategory::Internal => (ErrorCategory::Other, None),
            _ => (ErrorCategory::Other, None),
        };
        let code = error.code().as_str().to_owned();
        let message = error.message().as_str().to_owned();
        let path = error.path().iter().map(flatten_sdk_path).collect();
        let diagnostic = ErrorDiagnostic {
            path: error
                .path()
                .iter()
                .map(typed_projected_batch_path)
                .collect(),
            details: error
                .details()
                .iter()
                .map(|(name, value)| (name.as_str().to_owned(), flatten_sdk_detail(value)))
                .collect(),
        };
        Self::classified_with_diagnostic(
            category,
            phase,
            code,
            path,
            Some(diagnostic),
            message,
            Some(Box::new(error)),
        )
    }

    pub(crate) fn with_projected_batch_row(self, ordinal: u64) -> Self {
        let row_path = [
            ErrorPathSegment::Argument("rows".to_owned()),
            ErrorPathSegment::Index(ordinal),
        ];
        match self {
            Self::ModelValidation {
                phase,
                code,
                mut path,
                message,
                source,
            } => {
                let mut typed_path = Vec::with_capacity(path.len().saturating_add(2));
                typed_path.extend(row_path);
                for segment in &path {
                    append_generated_path_segment(&mut typed_path, segment);
                }
                path.insert(0, format!("[{ordinal}]"));
                path.insert(0, "rows".to_owned());
                Self::classified_with_diagnostic(
                    ErrorCategory::ModelValidation,
                    Some(phase),
                    code,
                    path,
                    Some(ErrorDiagnostic {
                        path: typed_path,
                        details: BTreeMap::new(),
                    }),
                    message,
                    source,
                )
            }
            Self::Classified {
                category,
                phase,
                code,
                mut path,
                diagnostic,
                message,
                source,
            } => {
                path.insert(0, format!("[{ordinal}]"));
                path.insert(0, "rows".to_owned());
                let mut diagnostic = diagnostic.map_or_else(
                    || ErrorDiagnostic {
                        path: Vec::new(),
                        details: BTreeMap::new(),
                    },
                    |diagnostic| *diagnostic,
                );
                diagnostic.path.splice(0..0, row_path);
                Self::classified_with_diagnostic(
                    category,
                    phase,
                    code,
                    path,
                    Some(diagnostic),
                    message,
                    source,
                )
            }
            other => other,
        }
    }

    pub(crate) fn from_projected_crud(
        error: ProjectedCrudCompatibilityFailure,
        kind: ModelKind,
        operation: Option<CrudOperation>,
    ) -> Self {
        let (diagnostic, stage, cause) = error.into_parts();
        let code = diagnostic.code().as_str();

        if code == "mutation_rehydration_missing" {
            let message = match (kind, operation) {
                (ModelKind::Entity, Some(CrudOperation::Update)) => {
                    "updated entity was not returned"
                }
                (ModelKind::Entity, _) => "written entity was not returned",
                (ModelKind::Relation, _) => "written relation was not returned",
            };
            return Self::model_validation(
                ModelValidationPhase::Hydration,
                "missing_post_write_row",
                vec!["iid".into()],
                message,
                None,
            );
        }
        if code == "relation_hydration_ambiguous" {
            return Self::model_validation(
                ModelValidationPhase::Hydration,
                "ambiguous_provider_row",
                vec!["iid".into()],
                "provider returned multiple coalesced rows for one exact IID",
                None,
            );
        }
        if code == "hydrated_type_mismatch" {
            let message = match kind {
                ModelKind::Entity => "provider entity row has the wrong exact concrete type",
                ModelKind::Relation => "provider relation row has the wrong exact concrete type",
            };
            return Self::model_validation(
                ModelValidationPhase::Hydration,
                "wrong_concrete_type",
                vec!["type".into()],
                message,
                None,
            );
        }
        if code == "hydrated_iid_missing" {
            let message = match kind {
                ModelKind::Entity => "provider entity row omitted its IID",
                ModelKind::Relation => "provider relation row omitted its IID",
            };
            return Self::model_validation(
                ModelValidationPhase::Hydration,
                "missing_iid",
                vec!["iid".into()],
                message,
                None,
            );
        }
        if code == "hydrated_iid_mismatch" {
            let message = match kind {
                ModelKind::Entity => "provider entity row contains a noncanonical IID",
                ModelKind::Relation => "provider relation row contains a noncanonical IID",
            };
            return Self::model_validation(
                ModelValidationPhase::Hydration,
                "noncanonical_iid",
                vec!["iid".into()],
                message,
                None,
            );
        }
        if kind == ModelKind::Relation
            && code == "noncanonical_iid"
            && diagnostic
                .path()
                .iter()
                .any(|segment| matches!(segment, SdkDiagnosticPathSegment::Role(_)))
        {
            return Self::model_validation(
                ModelValidationPhase::Input,
                "noncanonical_player_iid",
                projected_role_path(&diagnostic, "iid"),
                "relation reference IID must be canonical",
                None,
            );
        }
        if kind == ModelKind::Relation
            && diagnostic
                .path()
                .iter()
                .any(|segment| matches!(segment, SdkDiagnosticPathSegment::Role(_)))
            && matches!(
                cause.as_ref(),
                Some(ProjectedCrudCompatibilityCause::Orm(
                    type_bridge_orm::OrmError::Hydration { .. }
                ))
            )
        {
            return Self::model_validation(
                ModelValidationPhase::Hydration,
                "invalid_player_attributes",
                projected_role_path(&diagnostic, "attributes"),
                "provider role player attributes are outside the projected descriptor",
                cause.and_then(projected_cause_source),
            );
        }
        if kind == ModelKind::Relation
            && code == "runtime_projection_mismatch"
            && diagnostic
                .path()
                .iter()
                .any(|segment| matches!(segment, SdkDiagnosticPathSegment::Role(_)))
        {
            return Self::model_validation(
                ModelValidationPhase::Hydration,
                "invalid_player_attributes",
                projected_role_path(&diagnostic, "attributes"),
                "provider role player attributes are outside the projected descriptor",
                cause.and_then(projected_cause_source),
            );
        }
        if kind == ModelKind::Relation {
            let mapped = match code {
                "hydrated_player_iid_missing" => Some((
                    "missing_player_iid",
                    "iid",
                    "provider role player omitted its IID",
                )),
                "hydrated_player_iid_invalid" => Some((
                    "noncanonical_player_iid",
                    "iid",
                    "provider role player contains a noncanonical IID",
                )),
                "hydrated_player_type_missing" => Some((
                    "missing_player_type",
                    "type",
                    "provider role player omitted its concrete type",
                )),
                "hydrated_role_player_not_accepted" => Some((
                    "player_not_allowed",
                    "type",
                    "provider role player type is outside the role",
                )),
                "projected_player_type_ambiguous" => Some((
                    "invalid_installed_projection",
                    "type",
                    "projected player authority is ambiguous",
                )),
                _ => None,
            };
            if let Some((legacy_code, suffix, message)) = mapped {
                return Self::model_validation(
                    ModelValidationPhase::Hydration,
                    legacy_code,
                    projected_role_path(&diagnostic, suffix),
                    message,
                    None,
                );
            }
        }

        if let Some(cause) = cause {
            return match cause {
                ProjectedCrudCompatibilityCause::Orm(error) => {
                    if stage == ProjectedCrudCompatibilityStage::Hydration {
                        Self::from_orm_hydration(error)
                    } else {
                        Self::from_orm(error)
                    }
                }
                ProjectedCrudCompatibilityCause::Commit(error) => {
                    Self::from_orm(error.into_orm_error())
                }
            };
        }
        Self::from_sdk_execution(
            diagnostic,
            if stage == ProjectedCrudCompatibilityStage::Hydration {
                ModelValidationPhase::Hydration
            } else {
                ModelValidationPhase::Input
            },
        )
    }

    pub(crate) fn from_hook(error: crate::hooks::HookError) -> Self {
        let code = match error {
            crate::hooks::HookError::Rejected { .. } => "lifecycle_hook_rejected",
            crate::hooks::HookError::Internal { .. } => "lifecycle_hook_failed",
        };
        Self::classified(
            ErrorCategory::Lifecycle,
            None,
            code,
            Vec::new(),
            error.to_string(),
            Some(Box::new(error)),
        )
    }

    #[allow(dead_code)]
    pub(crate) fn from_orm(err: type_bridge_orm::OrmError) -> Self {
        match err {
            type_bridge_orm::OrmError::Match(error) => {
                Self::from_match(error, ModelValidationPhase::Input)
            }
            error @ type_bridge_orm::OrmError::Connection(_) => Self::Connection {
                message: error.to_string(),
                source: Some(Box::new(error)),
            },
            error @ type_bridge_orm::OrmError::QueryExecution(_) => Self::QueryExecution {
                message: error.to_string(),
                source: Some(Box::new(error)),
            },
            error @ type_bridge_orm::OrmError::Transaction(_) => Self::Transaction {
                message: error.to_string(),
                source: Some(Box::new(error)),
            },
            error @ type_bridge_orm::OrmError::NotFound(_) => Self::NotFound {
                message: error.to_string(),
                source: Some(Box::new(error)),
            },
            error @ type_bridge_orm::OrmError::Hydration { .. } => Self::ModelValidation {
                phase: ModelValidationPhase::Hydration,
                code: "invalid_provider_evidence".into(),
                path: vec![],
                message: error.to_string(),
                source: Some(Box::new(error)),
            },
            error => Self::Database {
                message: error.to_string(),
                source: Some(Box::new(error)),
            },
        }
    }

    pub(crate) fn from_orm_hydration(err: type_bridge_orm::OrmError) -> Self {
        match err {
            type_bridge_orm::OrmError::Match(error) => {
                Self::from_match(error, ModelValidationPhase::Hydration)
            }
            error => Self::from_orm(error),
        }
    }

    /// Return the stable public failure category.
    #[must_use]
    pub const fn category(&self) -> ErrorCategory {
        match self {
            Self::ModelValidation { .. } => ErrorCategory::ModelValidation,
            Self::Classified { category, .. } => *category,
            Self::SchemaVerification { .. } => ErrorCategory::Schema,
            Self::Connection { .. } => ErrorCategory::Connection,
            Self::QueryExecution { .. } => ErrorCategory::QueryExecution,
            Self::Transaction { .. } => ErrorCategory::Transaction,
            Self::NotFound { .. } => ErrorCategory::NotFound,
            Self::Database { .. } => ErrorCategory::Database,
            Self::Other { .. } => ErrorCategory::Other,
        }
    }

    /// Return the exact common SDK diagnostic category, when this error
    /// directly retains one.
    ///
    /// This is an additive, lossless view for generated manager and projected
    /// batch diagnostics. [`Self::category`] remains the released Rust
    /// compatibility classification and may intentionally map SDK
    /// `invalid_input` to [`ErrorCategory::ModelValidation`].
    #[must_use]
    pub fn sdk_category(&self) -> Option<&'static str> {
        StdError::source(self)
            .and_then(|source| source.downcast_ref::<SdkExecutionDiagnostic>())
            .map(|diagnostic| diagnostic.category().as_str())
    }

    /// Return the error message string.
    #[must_use]
    pub fn message(&self) -> &str {
        match self {
            Self::ModelValidation { message, .. }
            | Self::Classified { message, .. }
            | Self::SchemaVerification { message, .. }
            | Self::Connection { message, .. }
            | Self::QueryExecution { message, .. }
            | Self::Transaction { message, .. }
            | Self::NotFound { message, .. }
            | Self::Database { message, .. }
            | Self::Other { message, .. } => message,
        }
    }

    /// Return the stable machine-readable failure code, when available.
    #[must_use]
    pub fn code(&self) -> Option<&str> {
        match self {
            Self::ModelValidation { code, .. } | Self::Classified { code, .. } => Some(code),
            _ => None,
        }
    }

    /// Return the owned structured diagnostic path, when available.
    #[must_use]
    pub fn path(&self) -> Option<&[String]> {
        match self {
            Self::ModelValidation { path, .. } | Self::Classified { path, .. } => Some(path),
            _ => None,
        }
    }

    /// Return the typed diagnostic path, when the source supplied one.
    ///
    /// [`Self::path`] remains available as the compatibility-oriented textual
    /// projection of the same path.
    #[must_use]
    pub fn diagnostic_path(&self) -> Option<&[ErrorPathSegment]> {
        match self {
            Self::Classified { diagnostic, .. } => diagnostic.as_deref().map(ErrorDiagnostic::path),
            _ => None,
        }
    }

    /// Return deterministic typed diagnostic details, when available.
    #[must_use]
    pub fn details(&self) -> Option<&BTreeMap<String, ErrorDetail>> {
        match self {
            Self::Classified { diagnostic, .. } => {
                diagnostic.as_deref().map(ErrorDiagnostic::details)
            }
            _ => None,
        }
    }

    /// Return the model-validation phase, when applicable.
    #[must_use]
    pub const fn model_validation_phase(&self) -> Option<ModelValidationPhase> {
        match self {
            Self::ModelValidation { phase, .. } => Some(*phase),
            Self::Classified { phase, .. } => *phase,
            _ => None,
        }
    }
}

fn flatten_sdk_path(segment: &SdkDiagnosticPathSegment) -> String {
    match segment {
        SdkDiagnosticPathSegment::Argument(value) => value.as_str().to_owned(),
        SdkDiagnosticPathSegment::Index(value) => format!("[{value}]"),
        SdkDiagnosticPathSegment::Type(_) => "type".into(),
        SdkDiagnosticPathSegment::Field(value) => value.attribute().label().as_str().to_owned(),
        SdkDiagnosticPathSegment::Role(value) => value.label().as_str().to_owned(),
        SdkDiagnosticPathSegment::Query(value) => value.as_str().to_owned(),
        SdkDiagnosticPathSegment::QueryBinding(value) => format!("binding[{value}]"),
        SdkDiagnosticPathSegment::QueryField { owner, name } => {
            format!("{}.{}", owner.as_str(), name.as_str())
        }
        SdkDiagnosticPathSegment::QueryRole { owner, name } => {
            format!("{}.{}", owner.as_str(), name.as_str())
        }
        SdkDiagnosticPathSegment::QueryRoleEdge(value) => format!("role_edge[{value}]"),
        SdkDiagnosticPathSegment::QueryOutputSlot(value) => format!("output[{value}]"),
        SdkDiagnosticPathSegment::QueryOutputName(value)
        | SdkDiagnosticPathSegment::ContractField(value)
        | SdkDiagnosticPathSegment::ContractIdentity(value) => value.as_str().to_owned(),
        _ => "diagnostic".into(),
    }
}

fn projected_role_path(diagnostic: &SdkExecutionDiagnostic, suffix: &'static str) -> Vec<String> {
    let role = diagnostic.path().iter().find_map(|segment| {
        let SdkDiagnosticPathSegment::Role(role) = segment else {
            return None;
        };
        Some(role.label().as_str())
    });
    let index = diagnostic.path().iter().find_map(|segment| {
        let SdkDiagnosticPathSegment::Index(index) = segment else {
            return None;
        };
        Some(*index)
    });
    let head = match (role, index) {
        (Some(role), Some(index)) => format!("{role}[{index}]"),
        (Some(role), None) => role.to_owned(),
        _ => "roles".to_owned(),
    };
    vec![head, suffix.to_owned()]
}

fn projected_cause_source(
    cause: ProjectedCrudCompatibilityCause,
) -> Option<Box<dyn StdError + Send + Sync + 'static>> {
    match cause {
        ProjectedCrudCompatibilityCause::Orm(error) => Some(Box::new(error)),
        ProjectedCrudCompatibilityCause::Commit(error) => Some(Box::new(error)),
    }
}

fn typed_sdk_path(segment: &SdkDiagnosticPathSegment) -> ErrorPathSegment {
    match segment {
        SdkDiagnosticPathSegment::Argument(value) => {
            ErrorPathSegment::Field(value.as_str().to_owned())
        }
        SdkDiagnosticPathSegment::Index(value) => ErrorPathSegment::Index(*value),
        SdkDiagnosticPathSegment::Type(value) => ErrorPathSegment::Identifier(format!(
            "{}:{}",
            match value.kind() {
                type_bridge_contract::id::TypeKind::Entity => "entity",
                type_bridge_contract::id::TypeKind::Relation => "relation",
                type_bridge_contract::id::TypeKind::Attribute => "attribute",
                type_bridge_contract::id::TypeKind::Struct => "struct",
            },
            value.label().as_str()
        )),
        SdkDiagnosticPathSegment::Field(value) => ErrorPathSegment::Identifier(format!(
            "{}:{}",
            value.owner().label().as_str(),
            value.attribute().label().as_str()
        )),
        SdkDiagnosticPathSegment::Role(value) => ErrorPathSegment::Identifier(format!(
            "{}:{}",
            value.declaring_relation().as_str(),
            value.label().as_str()
        )),
        SdkDiagnosticPathSegment::Query(value) => {
            ErrorPathSegment::Query(acceptance_path_kind(*value))
        }
        SdkDiagnosticPathSegment::QueryBinding(value) => ErrorPathSegment::QueryBinding(*value),
        SdkDiagnosticPathSegment::QueryField { owner, name } => ErrorPathSegment::QueryField {
            owner: owner.as_str().to_owned(),
            name: name.as_str().to_owned(),
        },
        SdkDiagnosticPathSegment::QueryRole { owner, name } => ErrorPathSegment::QueryRole {
            owner: owner.as_str().to_owned(),
            name: name.as_str().to_owned(),
        },
        SdkDiagnosticPathSegment::QueryRoleEdge(value) => ErrorPathSegment::QueryRoleEdge(*value),
        SdkDiagnosticPathSegment::QueryOutputSlot(value) => {
            ErrorPathSegment::QueryOutputSlot(*value)
        }
        SdkDiagnosticPathSegment::QueryOutputName(value) => {
            ErrorPathSegment::QueryOutputName(value.as_str().to_owned())
        }
        SdkDiagnosticPathSegment::ContractField(value) => {
            ErrorPathSegment::ContractField(value.as_str().to_owned())
        }
        SdkDiagnosticPathSegment::ContractIdentity(value) => {
            ErrorPathSegment::ContractIdentity(value.as_str().to_owned())
        }
        _ => ErrorPathSegment::Identifier("diagnostic".into()),
    }
}

fn typed_projected_batch_path(segment: &SdkDiagnosticPathSegment) -> ErrorPathSegment {
    match segment {
        SdkDiagnosticPathSegment::Argument(value) => {
            ErrorPathSegment::Argument(value.as_str().to_owned())
        }
        other => typed_sdk_path(other),
    }
}

fn append_generated_path_segment(path: &mut Vec<ErrorPathSegment>, segment: &str) {
    let Some(first_index) = segment.find('[') else {
        path.push(ErrorPathSegment::Field(segment.to_owned()));
        return;
    };
    let mut parsed = Vec::new();
    if first_index > 0 {
        parsed.push(ErrorPathSegment::Field(segment[..first_index].to_owned()));
    }
    let mut remainder = &segment[first_index..];
    while remainder.starts_with('[') {
        let Some(end) = remainder.find(']') else {
            path.push(ErrorPathSegment::Field(segment.to_owned()));
            return;
        };
        let Ok(index) = remainder[1..end].parse::<u64>() else {
            path.push(ErrorPathSegment::Field(segment.to_owned()));
            return;
        };
        parsed.push(ErrorPathSegment::Index(index));
        remainder = &remainder[end + 1..];
    }
    if !remainder.is_empty() || parsed.is_empty() {
        path.push(ErrorPathSegment::Field(segment.to_owned()));
    } else {
        path.extend(parsed);
    }
}

fn flatten_sdk_detail(value: &SdkDiagnosticDetailValue) -> ErrorDetail {
    match value {
        SdkDiagnosticDetailValue::Boolean(value) => ErrorDetail::Boolean(*value),
        SdkDiagnosticDetailValue::Count(value) | SdkDiagnosticDetailValue::ByteCount(value) => {
            i64::try_from(*value)
                .map_or_else(|_| ErrorDetail::Text(value.to_string()), ErrorDetail::Long)
        }
        SdkDiagnosticDetailValue::Capability(value) => ErrorDetail::Text(value.as_str().to_owned()),
        SdkDiagnosticDetailValue::ValueType(value) => ErrorDetail::Text(value.as_str().to_owned()),
        SdkDiagnosticDetailValue::Type(value) => {
            ErrorDetail::Text(value.label().as_str().to_owned())
        }
        SdkDiagnosticDetailValue::Field(value) => {
            ErrorDetail::Text(value.attribute().label().as_str().to_owned())
        }
        SdkDiagnosticDetailValue::Role(value) => {
            ErrorDetail::Text(value.label().as_str().to_owned())
        }
        SdkDiagnosticDetailValue::Fingerprint(value) => ErrorDetail::Text(value.digest().to_hex()),
        SdkDiagnosticDetailValue::ProviderOperation(value) => {
            ErrorDetail::Text(value.as_str().to_owned())
        }
        SdkDiagnosticDetailValue::CommitOutcome(value) => {
            ErrorDetail::Text(value.as_str().to_owned())
        }
        SdkDiagnosticDetailValue::Signed(value) => ErrorDetail::Long(*value),
        SdkDiagnosticDetailValue::QueryCategory(value) => {
            ErrorDetail::QueryCategory(query_category(*value))
        }
        SdkDiagnosticDetailValue::QueryIdentity(value) => {
            ErrorDetail::QueryIdentity(value.as_str().to_owned())
        }
        SdkDiagnosticDetailValue::QueryIdentityList(values) => ErrorDetail::QueryIdentityList(
            values
                .iter()
                .map(|value| value.as_str().to_owned())
                .collect(),
        ),
        _ => ErrorDetail::Text("diagnostic".into()),
    }
}

fn sdk_query_category(error: &SdkExecutionDiagnostic) -> Option<SdkQueryDiagnosticCategory> {
    error.details().iter().find_map(|(name, value)| {
        (name.as_str() == "query_category").then(|| {
            let SdkDiagnosticDetailValue::QueryCategory(category) = value else {
                return None;
            };
            Some(*category)
        })?
    })
}

const fn query_category(value: SdkQueryDiagnosticCategory) -> QueryDiagnosticCategory {
    match value {
        SdkQueryDiagnosticCategory::InvalidPlan => QueryDiagnosticCategory::InvalidPlan,
        SdkQueryDiagnosticCategory::Cardinality => QueryDiagnosticCategory::Cardinality,
        SdkQueryDiagnosticCategory::UnsupportedCapability => {
            QueryDiagnosticCategory::UnsupportedCapability
        }
        SdkQueryDiagnosticCategory::StaleSchema => QueryDiagnosticCategory::StaleSchema,
        SdkQueryDiagnosticCategory::ResourceLimit => QueryDiagnosticCategory::ResourceLimit,
        SdkQueryDiagnosticCategory::Cancelled => QueryDiagnosticCategory::Cancelled,
        SdkQueryDiagnosticCategory::Provider => QueryDiagnosticCategory::Provider,
        SdkQueryDiagnosticCategory::ResultDecode => QueryDiagnosticCategory::ResultDecode,
        _ => QueryDiagnosticCategory::ResultDecode,
    }
}

const fn acceptance_path_kind(value: SdkQueryDiagnosticPathKind) -> QueryDiagnosticPathKind {
    match value {
        SdkQueryDiagnosticPathKind::Request => QueryDiagnosticPathKind::Request,
        SdkQueryDiagnosticPathKind::Plan => QueryDiagnosticPathKind::Plan,
        SdkQueryDiagnosticPathKind::Operation => QueryDiagnosticPathKind::Operation,
        SdkQueryDiagnosticPathKind::Predicate => QueryDiagnosticPathKind::Predicate,
        SdkQueryDiagnosticPathKind::Output => QueryDiagnosticPathKind::Output,
        SdkQueryDiagnosticPathKind::ProviderEvidence => QueryDiagnosticPathKind::ProviderEvidence,
        SdkQueryDiagnosticPathKind::Result => QueryDiagnosticPathKind::Result,
        _ => QueryDiagnosticPathKind::Result,
    }
}

/// Convenience Result type for the TypeBridge client.
pub type Result<T, E = Error> = std::result::Result<T, E>;

#[cfg(test)]
mod tests {
    use super::{Error, ErrorCategory};

    #[test]
    fn public_error_categories_and_remote_constructor_are_stable() {
        let categories = [
            (ErrorCategory::Connection, "connection"),
            (ErrorCategory::Schema, "schema"),
            (ErrorCategory::ModelValidation, "model_validation"),
            (ErrorCategory::Integrity, "integrity"),
            (ErrorCategory::QueryAuthoring, "query_authoring"),
            (ErrorCategory::QueryExecution, "query_execution"),
            (ErrorCategory::Transaction, "transaction"),
            (ErrorCategory::Remote, "remote"),
            (ErrorCategory::Capability, "capability"),
            (ErrorCategory::ResourceLimit, "resource_limit"),
            (ErrorCategory::NotFound, "not_found"),
            (ErrorCategory::Lifecycle, "lifecycle"),
            (ErrorCategory::Database, "database"),
            (ErrorCategory::Other, "other"),
        ];
        for (category, spelling) in categories {
            assert_eq!(category.as_str(), spelling);
            assert_eq!(category.to_string(), spelling);
        }

        let error = Error::remote("remote_transport", "connection reset", None);
        assert_eq!(error.category(), ErrorCategory::Remote);
        assert_eq!(error.code(), Some("remote_transport"));
        assert_eq!(error.path(), Some(&[][..]));
        assert_eq!(error.message(), "connection reset");
    }
}