type-bridge-schema 2.2.3

Canonical schema resolution and projection engine 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
use std::collections::{BTreeMap, BTreeSet};

use type_bridge_contract::capability::{CapabilityId, CapabilitySet};
use type_bridge_contract::codec::to_canonical_json;
use type_bridge_contract::diagnostic::DiagnosticCategory;
use type_bridge_contract::fingerprint::{
    CanonicalizationVersion, Fingerprint, FingerprintDomain, SemanticProfileId,
};
use type_bridge_contract::id::{AttributeId, FunctionId, RoleId, StructId, TypeId, TypeKind};
use type_bridge_contract::schema::{
    AnnotationKindId, AnnotationSubjectId, CollectionMode, DeclaredIdentityFingerprint,
    DeclaredSchema, FunctionFact, InterfaceKind, OwnsFact, OwnsFactId, PlaysFact, PlaysFactId,
    RelatesFact, SchemaAnnotationValue, SchemaDiagnostics, SchemaFact, SchemaFactId,
    SemanticProfile, SemanticSchemaFingerprint, StructFact, StructField, SubFactId, ValueFactId,
};
use type_bridge_contract::value::{Cardinality, ValueTypeTag};

use crate::semantic::{semantic_schema_fingerprint, validate_collection_profile};

/// Direct-fact identity plus the inheritance path used to derive an effective entry.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ResolutionOrigin {
    declared: SchemaFactId,
    inheritance_path: Vec<TypeId>,
}

impl ResolutionOrigin {
    fn direct(declared: SchemaFactId) -> Self {
        Self {
            declared,
            inheritance_path: Vec::new(),
        }
    }

    fn inherited(&self, via: TypeId) -> Self {
        let mut origin = self.clone();
        origin.inheritance_path.push(via);
        origin
    }

    /// Return the direct fact from which this entry was derived.
    #[must_use]
    pub const fn declared(&self) -> &SchemaFactId {
        &self.declared
    }

    /// Return the ordered inheritance path; empty means direct.
    #[must_use]
    pub fn inheritance_path(&self) -> &[TypeId] {
        &self.inheritance_path
    }

    /// Report whether the effective entry is direct on its resolved type.
    #[must_use]
    pub fn is_direct(&self) -> bool {
        self.inheritance_path.is_empty()
    }
}

/// Effective ownership, including resolved constraints and direct origin.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EffectiveOwns {
    id: OwnsFactId,
    origin: ResolutionOrigin,
    collection_mode: CollectionMode,
    annotations: BTreeMap<AnnotationKindId, SchemaAnnotationValue>,
    cardinality: Cardinality,
    key: bool,
    unique: bool,
}

impl EffectiveOwns {
    /// Return the effective ownership identity for the resolved owner.
    #[must_use]
    pub const fn id(&self) -> &OwnsFactId {
        &self.id
    }

    /// Return its direct declaration origin.
    #[must_use]
    pub const fn origin(&self) -> &ResolutionOrigin {
        &self.origin
    }

    /// Return the effective collection semantics.
    #[must_use]
    pub const fn collection_mode(&self) -> CollectionMode {
        self.collection_mode
    }

    /// Report whether members must be distinct within the ordered collection.
    #[must_use]
    pub fn is_distinct(&self) -> bool {
        self.annotations.contains_key(&AnnotationKindId::Distinct)
    }

    /// Return all direct or inherited annotations keyed by independent kind.
    #[must_use]
    pub const fn annotations(&self) -> &BTreeMap<AnnotationKindId, SchemaAnnotationValue> {
        &self.annotations
    }

    /// Return explicit or profile-materialized cardinality.
    #[must_use]
    pub const fn cardinality(&self) -> Cardinality {
        self.cardinality
    }

    /// Report key semantics.
    #[must_use]
    pub const fn is_key(&self) -> bool {
        self.key
    }

    /// Report uniqueness semantics independent of key.
    #[must_use]
    pub const fn is_unique(&self) -> bool {
        self.unique
    }
}

/// Effective role-playing interface and its independent annotations.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EffectivePlays {
    id: PlaysFactId,
    origin: ResolutionOrigin,
    annotations: BTreeMap<AnnotationKindId, SchemaAnnotationValue>,
    cardinality: Cardinality,
}

impl EffectivePlays {
    /// Return the effective playing identity.
    #[must_use]
    pub const fn id(&self) -> &PlaysFactId {
        &self.id
    }

    /// Return its direct declaration origin.
    #[must_use]
    pub const fn origin(&self) -> &ResolutionOrigin {
        &self.origin
    }

    /// Return independent annotations for this exact player-role fact.
    #[must_use]
    pub const fn annotations(&self) -> &BTreeMap<AnnotationKindId, SchemaAnnotationValue> {
        &self.annotations
    }

    /// Return explicit or profile-materialized cardinality.
    #[must_use]
    pub const fn cardinality(&self) -> Cardinality {
        self.cardinality
    }
}

/// Derived relation-role identity that can represent an inherited role interface.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct EffectiveRelatesId {
    relation: TypeId,
    role: RoleId,
}

impl EffectiveRelatesId {
    fn new(relation: TypeId, role: RoleId) -> Self {
        Self { relation, role }
    }

    /// Return the relation on which the role is effective.
    #[must_use]
    pub const fn relation(&self) -> &TypeId {
        &self.relation
    }

    /// Return the role identity, whose declaring relation may be an ancestor.
    #[must_use]
    pub const fn role(&self) -> &RoleId {
        &self.role
    }
}

/// Effective related role, including specialization replacement history.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EffectiveRelates {
    id: EffectiveRelatesId,
    origin: ResolutionOrigin,
    collection_mode: CollectionMode,
    annotations: BTreeMap<AnnotationKindId, SchemaAnnotationValue>,
    cardinality: Cardinality,
    replaced_roles: BTreeSet<RoleId>,
    is_abstract: bool,
}

impl EffectiveRelates {
    /// Return the effective related-role identity.
    #[must_use]
    pub const fn id(&self) -> &EffectiveRelatesId {
        &self.id
    }

    /// Return its direct declaration origin.
    #[must_use]
    pub const fn origin(&self) -> &ResolutionOrigin {
        &self.origin
    }

    /// Return the effective collection semantics.
    #[must_use]
    pub const fn collection_mode(&self) -> CollectionMode {
        self.collection_mode
    }

    /// Report whether players must be distinct within the ordered collection.
    #[must_use]
    pub fn is_distinct(&self) -> bool {
        self.annotations.contains_key(&AnnotationKindId::Distinct)
    }

    /// Return independent annotations on the exact relates fact.
    #[must_use]
    pub const fn annotations(&self) -> &BTreeMap<AnnotationKindId, SchemaAnnotationValue> {
        &self.annotations
    }

    /// Return explicit or profile-materialized cardinality.
    #[must_use]
    pub const fn cardinality(&self) -> Cardinality {
        self.cardinality
    }

    /// Return every inherited role interface replaced by specialization.
    #[must_use]
    pub const fn replaced_roles(&self) -> &BTreeSet<RoleId> {
        &self.replaced_roles
    }

    /// Report whether this role cannot be instantiated directly.
    #[must_use]
    pub const fn is_abstract(&self) -> bool {
        self.is_abstract
    }

    /// Report whether players may fill this role at the effective relation scope.
    ///
    /// TypeDB forbids players only at the relation that directly declares an
    /// abstract role. A concrete child relation may use the same role when it is
    /// inherited without specialization, while the role remains schema-abstract.
    #[must_use]
    pub fn accepts_players_at_effective_scope(&self) -> bool {
        !self.is_abstract || !self.origin.is_direct()
    }
}

/// Effective direct or inherited attribute value domain.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EffectiveValueType {
    value_type: ValueTypeTag,
    origin: ResolutionOrigin,
    annotations: BTreeMap<AnnotationKindId, SchemaAnnotationValue>,
}

impl EffectiveValueType {
    /// Return the effective value domain.
    #[must_use]
    pub const fn value_type(&self) -> ValueTypeTag {
        self.value_type
    }

    /// Return its direct value-fact origin.
    #[must_use]
    pub const fn origin(&self) -> &ResolutionOrigin {
        &self.origin
    }

    /// Return effective value-domain constraints.
    #[must_use]
    pub const fn annotations(&self) -> &BTreeMap<AnnotationKindId, SchemaAnnotationValue> {
        &self.annotations
    }
}

/// One direct subtype edge, including its exact declaration origin and annotations.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EffectiveSub {
    id: SubFactId,
    origin: ResolutionOrigin,
    annotations: BTreeMap<AnnotationKindId, SchemaAnnotationValue>,
}

impl EffectiveSub {
    /// Return the exact direct subtype-edge identity.
    #[must_use]
    pub const fn id(&self) -> &SubFactId {
        &self.id
    }

    /// Return the direct declaration origin.
    #[must_use]
    pub const fn origin(&self) -> &ResolutionOrigin {
        &self.origin
    }

    /// Return annotations attached to this exact subtype edge.
    #[must_use]
    pub const fn annotations(&self) -> &BTreeMap<AnnotationKindId, SchemaAnnotationValue> {
        &self.annotations
    }
}

/// Fully resolved type semantics, rebuilt only from direct facts.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ResolvedType {
    id: TypeId,
    supertypes: Vec<TypeId>,
    subtypes: BTreeSet<TypeId>,
    direct_sub: Option<EffectiveSub>,
    annotations: BTreeMap<AnnotationKindId, SchemaAnnotationValue>,
    value_type: Option<EffectiveValueType>,
    owns: BTreeMap<AttributeId, EffectiveOwns>,
    plays: BTreeMap<RoleId, EffectivePlays>,
    relates: BTreeMap<RoleId, EffectiveRelates>,
    key_attributes: BTreeSet<AttributeId>,
    unique_attributes: BTreeSet<AttributeId>,
    owned_attribute_order: Vec<AttributeId>,
    is_abstract: bool,
    constructible: bool,
}

impl ResolvedType {
    /// Return the stable type identity.
    #[must_use]
    pub const fn id(&self) -> &TypeId {
        &self.id
    }

    /// Return transitive supertypes from nearest to furthest.
    #[must_use]
    pub fn supertypes(&self) -> &[TypeId] {
        &self.supertypes
    }

    /// Return all transitive subtypes.
    #[must_use]
    pub const fn subtypes(&self) -> &BTreeSet<TypeId> {
        &self.subtypes
    }

    /// Return the exact direct subtype edge, if this type declares a parent.
    #[must_use]
    pub const fn direct_sub(&self) -> Option<&EffectiveSub> {
        self.direct_sub.as_ref()
    }

    /// Return effective type annotations.
    #[must_use]
    pub const fn annotations(&self) -> &BTreeMap<AnnotationKindId, SchemaAnnotationValue> {
        &self.annotations
    }

    /// Return the effective attribute value domain, if this is an attribute.
    #[must_use]
    pub const fn value_type(&self) -> Option<&EffectiveValueType> {
        self.value_type.as_ref()
    }

    /// Return effective ownerships keyed by attribute identity.
    #[must_use]
    pub const fn owns(&self) -> &BTreeMap<AttributeId, EffectiveOwns> {
        &self.owns
    }

    /// Return effective role-playing interfaces keyed by role identity.
    #[must_use]
    pub const fn plays(&self) -> &BTreeMap<RoleId, EffectivePlays> {
        &self.plays
    }

    /// Return effective related roles for relation types.
    #[must_use]
    pub const fn relates(&self) -> &BTreeMap<RoleId, EffectiveRelates> {
        &self.relates
    }

    /// Return effective key attributes.
    #[must_use]
    pub const fn key_attributes(&self) -> &BTreeSet<AttributeId> {
        &self.key_attributes
    }

    /// Return effective unique attributes not implied solely by key.
    #[must_use]
    pub const fn unique_attributes(&self) -> &BTreeSet<AttributeId> {
        &self.unique_attributes
    }

    /// Return deterministic ownership order metadata.
    #[must_use]
    pub fn owned_attribute_order(&self) -> &[AttributeId] {
        &self.owned_attribute_order
    }

    /// Report direct abstractness.
    #[must_use]
    pub const fn is_abstract(&self) -> bool {
        self.is_abstract
    }

    /// Report whether instances can be constructed under effective role constraints.
    #[must_use]
    pub const fn is_constructible(&self) -> bool {
        self.constructible
    }
}

/// Resolved role descriptor and accepted concrete player types.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ResolvedRole {
    id: RoleId,
    accepted_players: BTreeSet<TypeId>,
    replacing_roles: BTreeSet<RoleId>,
    is_abstract: bool,
}

impl ResolvedRole {
    /// Return the declared role identity.
    #[must_use]
    pub const fn id(&self) -> &RoleId {
        &self.id
    }

    /// Return concrete entity or relation types accepted as players.
    #[must_use]
    pub const fn accepted_players(&self) -> &BTreeSet<TypeId> {
        &self.accepted_players
    }

    /// Return ancestor role interfaces this role replaces.
    #[must_use]
    pub const fn replacing_roles(&self) -> &BTreeSet<RoleId> {
        &self.replacing_roles
    }

    /// Report declared role abstractness.
    #[must_use]
    pub const fn is_abstract(&self) -> bool {
        self.is_abstract
    }
}

/// Opaque resolved function retained without speculative body typing.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ResolvedFunction {
    declaration: FunctionFact,
    annotations: BTreeMap<AnnotationKindId, SchemaAnnotationValue>,
}

impl ResolvedFunction {
    /// Return the stable function identity.
    #[must_use]
    pub const fn id(&self) -> &FunctionId {
        self.declaration.id()
    }

    /// Return the validated direct declaration without rewriting its body.
    #[must_use]
    pub const fn declaration(&self) -> &FunctionFact {
        &self.declaration
    }

    /// Return function documentation and metadata.
    #[must_use]
    pub const fn annotations(&self) -> &BTreeMap<AnnotationKindId, SchemaAnnotationValue> {
        &self.annotations
    }
}

/// A validated struct in resolved schema output.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ResolvedStruct {
    id: StructId,
    fields: Vec<StructField>,
}

impl ResolvedStruct {
    /// Return the stable struct identity.
    #[must_use]
    pub const fn id(&self) -> &StructId {
        &self.id
    }

    /// Return fields in their semantic declaration order.
    #[must_use]
    pub fn fields(&self) -> &[StructField] {
        &self.fields
    }
}

/// Stable content-addressed query descriptor identity.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct DescriptorId(String);

impl DescriptorId {
    /// Return the lowercase content-addressed descriptor string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Stable direct-fact descriptor lookup.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DescriptorIndex {
    descriptors: BTreeMap<DescriptorId, SchemaFactId>,
}

impl DescriptorIndex {
    /// Return the fact associated with a descriptor.
    #[must_use]
    pub fn get(&self, descriptor: &DescriptorId) -> Option<&SchemaFactId> {
        self.descriptors.get(descriptor)
    }

    /// Iterate descriptors in stable content order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = (&DescriptorId, &SchemaFactId)> {
        self.descriptors.iter()
    }
}

/// Projection dependency edges and deterministic strongly connected components.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct SchemaDependencyGraph {
    edges: BTreeMap<TypeId, BTreeSet<TypeId>>,
    strongly_connected_components: Vec<BTreeSet<TypeId>>,
}

impl SchemaDependencyGraph {
    /// Return outgoing projection dependencies for one type.
    #[must_use]
    pub fn dependencies(&self, id: &TypeId) -> Option<&BTreeSet<TypeId>> {
        self.edges.get(id)
    }

    /// Return deterministic projection-dependency SCCs.
    #[must_use]
    pub fn strongly_connected_components(&self) -> &[BTreeSet<TypeId>] {
        &self.strongly_connected_components
    }
}

/// Immutable pure resolution result.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ResolvedSchema {
    declared_identity: DeclaredIdentityFingerprint,
    semantic_fingerprint: SemanticSchemaFingerprint,
    types: BTreeMap<TypeId, ResolvedType>,
    roles: BTreeMap<RoleId, ResolvedRole>,
    functions: BTreeMap<FunctionId, ResolvedFunction>,
    structs: BTreeMap<StructId, ResolvedStruct>,
    descriptor_index: DescriptorIndex,
    dependency_graph: SchemaDependencyGraph,
}

impl ResolvedSchema {
    /// Return the unchanged direct-declaration identity.
    #[must_use]
    pub const fn declared_identity_fingerprint(&self) -> &DeclaredIdentityFingerprint {
        &self.declared_identity
    }

    /// Return canonical direct semantics under the selected profile.
    #[must_use]
    pub const fn semantic_fingerprint(&self) -> &SemanticSchemaFingerprint {
        &self.semantic_fingerprint
    }

    /// Return resolved types by stable identity.
    #[must_use]
    pub const fn types(&self) -> &BTreeMap<TypeId, ResolvedType> {
        &self.types
    }

    /// Return resolved roles by declaring-role identity.
    #[must_use]
    pub const fn roles(&self) -> &BTreeMap<RoleId, ResolvedRole> {
        &self.roles
    }

    /// Return opaque resolved functions.
    #[must_use]
    pub const fn functions(&self) -> &BTreeMap<FunctionId, ResolvedFunction> {
        &self.functions
    }

    /// Return resolved structs in stable identity order.
    #[must_use]
    pub const fn structs(&self) -> &BTreeMap<StructId, ResolvedStruct> {
        &self.structs
    }

    /// Return stable direct-fact descriptors.
    #[must_use]
    pub const fn descriptor_index(&self) -> &DescriptorIndex {
        &self.descriptor_index
    }

    /// Return projection dependency SCCs.
    #[must_use]
    pub const fn dependency_graph(&self) -> &SchemaDependencyGraph {
        &self.dependency_graph
    }
}

#[derive(Default)]
struct DirectIndex {
    types: BTreeSet<TypeId>,
    parents: BTreeMap<TypeId, Vec<SubFactId>>,
    values: BTreeMap<AttributeId, (ValueTypeTag, ValueFactId)>,
    owns: BTreeMap<TypeId, Vec<OwnsFact>>,
    relates: BTreeMap<TypeId, Vec<RelatesFact>>,
    plays: BTreeMap<TypeId, Vec<PlaysFact>>,
    annotations: BTreeMap<AnnotationSubjectId, BTreeMap<AnnotationKindId, SchemaAnnotationValue>>,
    functions: BTreeMap<FunctionId, FunctionFact>,
    structs: BTreeMap<StructId, StructFact>,
}

/// Schema-feature capabilities implemented by the built-in compatibility resolver.
pub const BUILTIN_SCHEMA_CAPABILITY_IDS: &[&str] =
    &["schema.annotations", "schema.doc-meta", "schema.roles"];

fn builtin_schema_capabilities() -> CapabilitySet {
    BUILTIN_SCHEMA_CAPABILITY_IDS
        .iter()
        .map(|capability| {
            CapabilityId::new(*capability).expect("built-in schema capability IDs are canonical")
        })
        .collect()
}

/// Resolve direct schema facts under the built-in semantic-profile compatibility surface.
pub fn resolve(
    declared: &DeclaredSchema,
    profile_id: &SemanticProfileId,
) -> Result<ResolvedSchema, SchemaDiagnostics> {
    resolve_schema_with_capabilities(declared, profile_id, &builtin_schema_capabilities())
}

/// Resolve direct schema facts using an explicitly available schema-feature set.
pub fn resolve_schema_with_capabilities(
    declared: &DeclaredSchema,
    profile_id: &SemanticProfileId,
    available_capabilities: &CapabilitySet,
) -> Result<ResolvedSchema, SchemaDiagnostics> {
    declared
        .required_capabilities()
        .ensure_supported_by(available_capabilities)
        .map_err(|diagnostic| {
            type_bridge_contract::schema::SchemaDiagnostics::one(
                type_bridge_contract::schema::SchemaDiagnostic::new(diagnostic, None),
            )
        })?;
    let profile = SemanticProfile::resolve(profile_id).map_err(|diagnostic| {
        type_bridge_contract::schema::SchemaDiagnostics::one(
            type_bridge_contract::schema::SchemaDiagnostic::new(diagnostic, None),
        )
    })?;
    validate_collection_profile(declared, profile_id)?;
    let index = DirectIndex::build(declared)?;
    let parents = validate_parents(declared, &index)?;
    validate_inheritance_cycles(declared, &index.types, &parents)?;

    let mut order = index.types.iter().cloned().collect::<Vec<_>>();
    order.sort_by_key(|id| (ancestor_chain(id, &parents).len(), id.clone()));
    let mut types = BTreeMap::<TypeId, ResolvedType>::new();

    for id in order {
        let parent = parents.get(&id);
        let inherited = parent.and_then(|parent| types.get(parent)).cloned();
        let mut resolved = inherited
            .as_ref()
            .map(|parent| inherit_type(parent, &id, &profile))
            .transpose()?
            .unwrap_or_else(|| empty_resolved_type(id.clone()));
        resolved.id = id.clone();
        resolved.supertypes = ancestor_chain(&id, &parents);
        if let Some(parent) = parent {
            let sub_id = SubFactId::new(id.clone(), parent.clone()).map_err(no_source)?;
            resolved.direct_sub = Some(EffectiveSub {
                id: sub_id.clone(),
                origin: ResolutionOrigin::direct(SchemaFactId::Sub(sub_id.clone())),
                annotations: annotations_for(&index, AnnotationSubjectId::Sub(sub_id)),
            });
        }

        let direct_annotations = annotations_for(&index, AnnotationSubjectId::Type(id.clone()));
        if let Some(independent) = inherited
            .as_ref()
            .and_then(|parent| parent.annotations.get(&AnnotationKindId::Independent))
        {
            resolved
                .annotations
                .insert(AnnotationKindId::Independent, independent.clone());
        }
        resolved.annotations.extend(direct_annotations);
        resolved.is_abstract = resolved
            .annotations
            .contains_key(&AnnotationKindId::Abstract);

        if id.kind() == TypeKind::Attribute {
            let attribute = AttributeId::new(id.label().as_str()).map_err(no_source)?;
            if let Some((value_type, value_id)) = index.values.get(&attribute) {
                resolved.value_type = Some(EffectiveValueType {
                    value_type: *value_type,
                    origin: ResolutionOrigin::direct(SchemaFactId::Value(value_id.clone())),
                    annotations: annotations_for(
                        &index,
                        AnnotationSubjectId::Value(value_id.clone()),
                    ),
                });
            }
        }

        for owns in index.owns.get(&id).into_iter().flatten() {
            let annotations = annotations_for(&index, AnnotationSubjectId::Owns(owns.id().clone()));
            if let Some(inherited) = resolved.owns.get(owns.id().attribute())
                && inherited.collection_mode != owns.collection_mode()
            {
                return Err(collection_mode_conflict(
                    declared,
                    &SchemaFactId::Owns(owns.id().clone()),
                    inherited.origin.declared(),
                    "inherited_owns_collection_mode_conflict",
                    "a direct ownership redeclaration must preserve the inherited collection mode",
                    "inherited ownership collection mode is declared here",
                ));
            }
            let effective = EffectiveOwns {
                id: owns.id().clone(),
                origin: ResolutionOrigin::direct(SchemaFactId::Owns(owns.id().clone())),
                collection_mode: owns.collection_mode(),
                cardinality: cardinality(&annotations, &profile, InterfaceKind::Owns),
                key: annotations.contains_key(&AnnotationKindId::Key),
                unique: annotations.contains_key(&AnnotationKindId::Unique)
                    || annotations.contains_key(&AnnotationKindId::Key),
                annotations,
            };
            resolved
                .owns
                .insert(owns.id().attribute().clone(), effective);
        }

        for plays in index.plays.get(&id).into_iter().flatten() {
            let annotations =
                annotations_for(&index, AnnotationSubjectId::Plays(plays.id().clone()));
            let effective = EffectivePlays {
                id: plays.id().clone(),
                origin: ResolutionOrigin::direct(SchemaFactId::Plays(plays.id().clone())),
                cardinality: cardinality(&annotations, &profile, InterfaceKind::Plays),
                annotations,
            };
            resolved.plays.insert(plays.id().role().clone(), effective);
        }

        for relates in index.relates.get(&id).into_iter().flatten() {
            let annotations =
                annotations_for(&index, AnnotationSubjectId::Relates(relates.id().clone()));
            let mut replaced_roles = BTreeSet::new();
            if let Some(specialized) = relates.specializes() {
                let replaced_role = resolved
                    .relates
                    .iter()
                    .find_map(|(role, effective)| {
                        (role == specialized || effective.replaced_roles.contains(specialized))
                            .then(|| role.clone())
                    })
                    .ok_or_else(|| {
                        source_error(
                            declared,
                            &SchemaFactId::Relates(relates.id().clone()),
                            "invalid_role_specialization",
                            "specialized role is not effective on the child relation",
                        )
                    })?;
                let replaced = resolved
                    .relates
                    .get(&replaced_role)
                    .expect("located effective role exists");
                if replaced.collection_mode != relates.collection_mode() {
                    return Err(collection_mode_conflict(
                        declared,
                        &SchemaFactId::Relates(relates.id().clone()),
                        replaced.origin.declared(),
                        "specialized_role_collection_mode_conflict",
                        "a specialized role must preserve the effective parent-role collection mode",
                        "effective parent-role collection mode is declared here",
                    ));
                }
                let replaced = resolved
                    .relates
                    .remove(&replaced_role)
                    .expect("located effective role exists");
                replaced_roles.extend(replaced.replaced_roles);
                replaced_roles.insert(specialized.clone());
            }
            let effective = EffectiveRelates {
                id: EffectiveRelatesId::new(id.clone(), relates.id().role().clone()),
                origin: ResolutionOrigin::direct(SchemaFactId::Relates(relates.id().clone())),
                collection_mode: relates.collection_mode(),
                cardinality: cardinality(&annotations, &profile, InterfaceKind::Relates),
                is_abstract: annotations.contains_key(&AnnotationKindId::Abstract),
                annotations,
                replaced_roles,
            };
            resolved
                .relates
                .insert(relates.id().role().clone(), effective);
        }

        resolved.key_attributes = resolved
            .owns
            .values()
            .filter(|owns| owns.key)
            .map(|owns| owns.id.attribute().clone())
            .collect();
        resolved.unique_attributes = resolved
            .owns
            .values()
            .filter(|owns| owns.unique)
            .map(|owns| owns.id.attribute().clone())
            .collect();
        resolved.owned_attribute_order = resolved.owns.keys().cloned().collect();
        resolved.constructible = !resolved.is_abstract
            && resolved
                .relates
                .values()
                .all(EffectiveRelates::accepts_players_at_effective_scope);
        types.insert(id, resolved);
    }

    populate_subtypes(&mut types, &parents);
    let roles = resolve_roles(&types, &index);
    let functions = index
        .functions
        .values()
        .map(|function| {
            (
                function.id().clone(),
                ResolvedFunction {
                    declaration: function.clone(),
                    annotations: annotations_for(
                        &index,
                        AnnotationSubjectId::Function(function.id().clone()),
                    ),
                },
            )
        })
        .collect();
    let structs = index
        .structs
        .values()
        .map(|fact| {
            (
                fact.id().clone(),
                ResolvedStruct {
                    id: fact.id().clone(),
                    fields: fact.fields().to_vec(),
                },
            )
        })
        .collect();
    let descriptor_index = descriptor_index(declared)?;
    let dependency_graph = dependency_graph(&types, &roles);
    let semantic_fingerprint = semantic_schema_fingerprint(declared, profile_id)?;

    Ok(ResolvedSchema {
        declared_identity: declared.declared_identity_fingerprint().clone(),
        semantic_fingerprint,
        types,
        roles,
        functions,
        structs,
        descriptor_index,
        dependency_graph,
    })
}

impl DirectIndex {
    fn build(declared: &DeclaredSchema) -> Result<Self, SchemaDiagnostics> {
        let mut index = Self::default();
        for fact in declared.facts() {
            match fact {
                SchemaFact::Type(fact) => {
                    index.types.insert(fact.id().clone());
                }
                SchemaFact::Sub(fact) => index
                    .parents
                    .entry(fact.id().subtype().clone())
                    .or_default()
                    .push(fact.id().clone()),
                SchemaFact::Value(fact) => {
                    index.values.insert(
                        fact.id().attribute().clone(),
                        (fact.value_type(), fact.id().clone()),
                    );
                }
                SchemaFact::Owns(fact) => index
                    .owns
                    .entry(fact.id().owner().clone())
                    .or_default()
                    .push(fact.clone()),
                SchemaFact::Relates(fact) => index
                    .relates
                    .entry(fact.id().relation().clone())
                    .or_default()
                    .push(fact.clone()),
                SchemaFact::Plays(fact) => index
                    .plays
                    .entry(fact.id().player().clone())
                    .or_default()
                    .push(fact.clone()),
                SchemaFact::Annotation(fact) => {
                    index
                        .annotations
                        .entry(fact.id().subject().clone())
                        .or_default()
                        .insert(fact.id().kind().clone(), fact.value().clone());
                }
                SchemaFact::Function(fact) => {
                    index.functions.insert(fact.id().clone(), fact.clone());
                }
                SchemaFact::Struct(fact) => {
                    index.structs.insert(fact.id().clone(), fact.clone());
                }
            }
        }
        Ok(index)
    }
}

fn validate_parents(
    declared: &DeclaredSchema,
    index: &DirectIndex,
) -> Result<BTreeMap<TypeId, TypeId>, SchemaDiagnostics> {
    let mut parents = BTreeMap::new();
    for (subtype, facts) in &index.parents {
        if facts.len() > 1 {
            let first = SchemaFactId::Sub(facts[0].clone());
            let second = SchemaFactId::Sub(facts[1].clone());
            let primary = declared.source(&second).cloned();
            let related = declared.source(&first).cloned();
            if let (Some(primary), Some(related)) = (primary, related) {
                return Err(crate::yaml::diagnostic_with_related(
                    DiagnosticCategory::InvalidContract,
                    "multiple_type_parents",
                    "a schema type has more than one same-kind parent",
                    primary,
                    related,
                    "first parent declaration is here",
                ));
            }
            return Err(source_error(
                declared,
                &second,
                "multiple_type_parents",
                "a schema type has more than one same-kind parent",
            ));
        }
        let parent = facts[0].supertype().clone();
        if subtype.kind() != parent.kind() {
            return Err(source_error(
                declared,
                &SchemaFactId::Sub(facts[0].clone()),
                "invalid_type_parent_kind",
                "schema subtype and supertype must have the same kind",
            ));
        }
        parents.insert(subtype.clone(), parent);
    }
    Ok(parents)
}

fn validate_inheritance_cycles(
    declared: &DeclaredSchema,
    types: &BTreeSet<TypeId>,
    parents: &BTreeMap<TypeId, TypeId>,
) -> Result<(), SchemaDiagnostics> {
    for start in types {
        let mut current = start;
        let mut visited = BTreeSet::new();
        while let Some(parent) = parents.get(current) {
            if !visited.insert(current.clone()) {
                let fact = SubFactId::new(current.clone(), parent.clone()).map_err(no_source)?;
                return Err(source_error(
                    declared,
                    &SchemaFactId::Sub(fact),
                    "schema_inheritance_cycle",
                    "schema type inheritance contains a cycle",
                ));
            }
            current = parent;
        }
    }
    Ok(())
}

fn ancestor_chain(id: &TypeId, parents: &BTreeMap<TypeId, TypeId>) -> Vec<TypeId> {
    let mut ancestors = Vec::new();
    let mut current = id;
    while let Some(parent) = parents.get(current) {
        ancestors.push(parent.clone());
        current = parent;
    }
    ancestors
}

fn empty_resolved_type(id: TypeId) -> ResolvedType {
    ResolvedType {
        id,
        supertypes: Vec::new(),
        subtypes: BTreeSet::new(),
        direct_sub: None,
        annotations: BTreeMap::new(),
        value_type: None,
        owns: BTreeMap::new(),
        plays: BTreeMap::new(),
        relates: BTreeMap::new(),
        key_attributes: BTreeSet::new(),
        unique_attributes: BTreeSet::new(),
        owned_attribute_order: Vec::new(),
        is_abstract: false,
        constructible: true,
    }
}

fn inherit_type(
    parent: &ResolvedType,
    child: &TypeId,
    profile: &SemanticProfile,
) -> Result<ResolvedType, SchemaDiagnostics> {
    let mut resolved = empty_resolved_type(child.clone());
    resolved.annotations = parent
        .annotations
        .iter()
        .filter(|(kind, _)| **kind == AnnotationKindId::Independent)
        .map(|(kind, value)| (kind.clone(), value.clone()))
        .collect();
    resolved.value_type = parent.value_type.as_ref().map(|value| EffectiveValueType {
        value_type: value.value_type,
        origin: value.origin.inherited(parent.id.clone()),
        annotations: value.annotations.clone(),
    });
    for owns in parent.owns.values() {
        let id = OwnsFactId::new(child.clone(), owns.id.attribute().clone()).map_err(no_source)?;
        let mut inherited = owns.clone();
        inherited.id = id;
        inherited.origin = inherited.origin.inherited(parent.id.clone());
        inherited.cardinality = profile.effective_cardinality(
            InterfaceKind::Owns,
            inherited
                .annotations
                .get(&AnnotationKindId::Card)
                .and_then(cardinality_value),
            inherited.key,
        );
        resolved
            .owns
            .insert(inherited.id.attribute().clone(), inherited);
    }
    for plays in parent.plays.values() {
        let id = PlaysFactId::new(child.clone(), plays.id.role().clone()).map_err(no_source)?;
        let mut inherited = plays.clone();
        inherited.id = id;
        inherited.origin = inherited.origin.inherited(parent.id.clone());
        resolved
            .plays
            .insert(inherited.id.role().clone(), inherited);
    }
    for relates in parent.relates.values() {
        let mut inherited = relates.clone();
        inherited.id = EffectiveRelatesId::new(child.clone(), relates.id.role().clone());
        inherited.origin = inherited.origin.inherited(parent.id.clone());
        resolved
            .relates
            .insert(inherited.id.role().clone(), inherited);
    }
    Ok(resolved)
}

fn annotations_for(
    index: &DirectIndex,
    subject: AnnotationSubjectId,
) -> BTreeMap<AnnotationKindId, SchemaAnnotationValue> {
    index.annotations.get(&subject).cloned().unwrap_or_default()
}

fn cardinality(
    annotations: &BTreeMap<AnnotationKindId, SchemaAnnotationValue>,
    profile: &SemanticProfile,
    kind: InterfaceKind,
) -> Cardinality {
    profile.effective_cardinality(
        kind,
        annotations
            .get(&AnnotationKindId::Card)
            .and_then(cardinality_value),
        kind == InterfaceKind::Owns && annotations.contains_key(&AnnotationKindId::Key),
    )
}

fn cardinality_value(value: &SchemaAnnotationValue) -> Option<Cardinality> {
    match value {
        SchemaAnnotationValue::Cardinality(cardinality) => Some(*cardinality),
        _ => None,
    }
}

fn populate_subtypes(
    types: &mut BTreeMap<TypeId, ResolvedType>,
    parents: &BTreeMap<TypeId, TypeId>,
) {
    let ids = types.keys().cloned().collect::<Vec<_>>();
    for id in ids {
        for parent in ancestor_chain(&id, parents) {
            if let Some(parent) = types.get_mut(&parent) {
                parent.subtypes.insert(id.clone());
            }
        }
    }
}

fn resolve_roles(
    types: &BTreeMap<TypeId, ResolvedType>,
    index: &DirectIndex,
) -> BTreeMap<RoleId, ResolvedRole> {
    let mut roles = BTreeMap::new();
    for relates in index.relates.values().flatten() {
        let annotations =
            annotations_for(index, AnnotationSubjectId::Relates(relates.id().clone()));
        roles.insert(
            relates.id().role().clone(),
            ResolvedRole {
                id: relates.id().role().clone(),
                accepted_players: BTreeSet::new(),
                replacing_roles: BTreeSet::new(),
                is_abstract: annotations.contains_key(&AnnotationKindId::Abstract),
            },
        );
    }
    for resolved in types.values() {
        for relates in resolved.relates.values() {
            if let Some(role) = roles.get_mut(relates.id.role()) {
                role.replacing_roles.extend(relates.replaced_roles.clone());
            }
        }
    }
    for resolved in types.values().filter(|resolved| resolved.constructible) {
        for plays in resolved.plays.values() {
            if let Some(role) = roles.get_mut(plays.id.role()) {
                role.accepted_players.insert(resolved.id.clone());
            }
        }
    }
    roles
}

fn descriptor_index(declared: &DeclaredSchema) -> Result<DescriptorIndex, SchemaDiagnostics> {
    let domain = FingerprintDomain::new("typebridge.schema.descriptor").map_err(no_source)?;
    let canonicalization =
        CanonicalizationVersion::new("typebridge.schema-fact-id-json/v1").map_err(no_source)?;
    let mut descriptors = BTreeMap::new();
    for fact in declared.facts() {
        let id = fact.id();
        let canonical = to_canonical_json(&id).map_err(no_source)?;
        let digest =
            Fingerprint::compute(domain.clone(), canonicalization.clone(), None, &canonical)
                .digest()
                .to_hex();
        descriptors.insert(DescriptorId(format!("schema:{digest}")), id);
    }
    Ok(DescriptorIndex { descriptors })
}

fn dependency_graph(
    types: &BTreeMap<TypeId, ResolvedType>,
    roles: &BTreeMap<RoleId, ResolvedRole>,
) -> SchemaDependencyGraph {
    let mut edges = types
        .keys()
        .cloned()
        .map(|id| (id, BTreeSet::new()))
        .collect::<BTreeMap<_, _>>();
    for resolved in types.values() {
        if let Some(parent) = resolved.supertypes.first() {
            edges
                .entry(resolved.id.clone())
                .or_default()
                .insert(parent.clone());
        }
        for attribute in resolved.owns.keys() {
            if let Ok(attribute) = TypeId::new(TypeKind::Attribute, attribute.label().as_str()) {
                edges
                    .entry(resolved.id.clone())
                    .or_default()
                    .insert(attribute);
            }
        }
        for role in resolved.plays.keys() {
            if let Ok(relation) =
                TypeId::new(TypeKind::Relation, role.declaring_relation().as_str())
            {
                edges
                    .entry(resolved.id.clone())
                    .or_default()
                    .insert(relation);
            }
        }
        for relates in resolved.relates.values() {
            if let Some(role) = roles.get(relates.id().role()) {
                edges
                    .entry(resolved.id.clone())
                    .or_default()
                    .extend(role.accepted_players().iter().cloned());
            }
        }
    }
    let strongly_connected_components = strongly_connected_components(&edges);
    SchemaDependencyGraph {
        edges,
        strongly_connected_components,
    }
}

fn strongly_connected_components(
    edges: &BTreeMap<TypeId, BTreeSet<TypeId>>,
) -> Vec<BTreeSet<TypeId>> {
    struct Tarjan<'a> {
        edges: &'a BTreeMap<TypeId, BTreeSet<TypeId>>,
        index: usize,
        indices: BTreeMap<TypeId, usize>,
        lowlinks: BTreeMap<TypeId, usize>,
        stack: Vec<TypeId>,
        on_stack: BTreeSet<TypeId>,
        components: Vec<BTreeSet<TypeId>>,
    }
    impl Tarjan<'_> {
        fn visit(&mut self, node: TypeId) {
            let index = self.index;
            self.index += 1;
            self.indices.insert(node.clone(), index);
            self.lowlinks.insert(node.clone(), index);
            self.stack.push(node.clone());
            self.on_stack.insert(node.clone());

            for dependency in self.edges.get(&node).into_iter().flatten() {
                if !self.indices.contains_key(dependency) {
                    self.visit(dependency.clone());
                    let low = self.lowlinks[&node].min(self.lowlinks[dependency]);
                    self.lowlinks.insert(node.clone(), low);
                } else if self.on_stack.contains(dependency) {
                    let low = self.lowlinks[&node].min(self.indices[dependency]);
                    self.lowlinks.insert(node.clone(), low);
                }
            }

            if self.lowlinks[&node] == self.indices[&node] {
                let mut component = BTreeSet::new();
                loop {
                    let member = self.stack.pop().expect("SCC root has a stack member");
                    self.on_stack.remove(&member);
                    component.insert(member.clone());
                    if member == node {
                        break;
                    }
                }
                self.components.push(component);
            }
        }
    }

    let mut tarjan = Tarjan {
        edges,
        index: 0,
        indices: BTreeMap::new(),
        lowlinks: BTreeMap::new(),
        stack: Vec::new(),
        on_stack: BTreeSet::new(),
        components: Vec::new(),
    };
    for node in edges.keys() {
        if !tarjan.indices.contains_key(node) {
            tarjan.visit(node.clone());
        }
    }
    tarjan
        .components
        .sort_by(|left, right| left.first().cmp(&right.first()));
    tarjan.components
}

fn source_error(
    declared: &DeclaredSchema,
    fact: &SchemaFactId,
    code: &'static str,
    message: &'static str,
) -> SchemaDiagnostics {
    crate::yaml::diagnostic(
        DiagnosticCategory::InvalidContract,
        code,
        message,
        declared.source(fact).cloned(),
    )
}

fn collection_mode_conflict(
    declared: &DeclaredSchema,
    direct: &SchemaFactId,
    inherited: &SchemaFactId,
    code: &'static str,
    message: &'static str,
    related_message: &'static str,
) -> SchemaDiagnostics {
    match (declared.source(direct), declared.source(inherited)) {
        (Some(primary), Some(related)) => crate::yaml::diagnostic_with_related(
            DiagnosticCategory::InvalidContract,
            code,
            message,
            primary.clone(),
            related.clone(),
            related_message,
        ),
        _ => source_error(declared, direct, code, message),
    }
}

fn no_source(diagnostic: type_bridge_contract::diagnostic::Diagnostic) -> SchemaDiagnostics {
    type_bridge_contract::schema::SchemaDiagnostics::one(
        type_bridge_contract::schema::SchemaDiagnostic::new(diagnostic, None),
    )
}