type-bridge 2.2.1

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
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
//! Schema package markers and type-branded installation handshake.

use core::marker::PhantomData;
use std::sync::Arc;

use type_bridge_contract::projection::{ProjectionConfig, RuntimeProjection};
use type_bridge_contract::schema::encode_declared_schema;
use type_bridge_contract::sdk_diagnostic::{
    SdkExecutionDiagnostic, SdkProjectionEvidenceSlotPresence,
};
use type_bridge_schema::{
    MAX_SCHEMA_AUTHORITY_BYTES, VerifiedSchemaAuthority, decode_schema_authority,
    schema_authority_capability_vocabulary,
};
use type_bridge_schema_codegen::RustEmitter;

use crate::__codegen::{
    CompleteModel, EncodedCreate, GroupedQueryValue, HydratedRow, HydrationCapability,
    IntoEncodedCreate, IntoEncodedReference, IntoEncodedScalar, IntoEncodedStruct,
    IntoHydratedSnapshot, MaterializeCreate, MaterializeModel, MaterializeReference,
    MaterializeStruct, Model, StructValue, ValidationError, ValidationPath,
};
use crate::CanonicalCodecOptions;
use crate::canonical_codec::{
    CapturedCanonicalCodecControl, input_error as canonical_input_error,
    output_error as canonical_output_error,
};
use crate::error::{Error, ModelValidationPhase, Result};

#[doc(hidden)]
pub mod sealed {
    pub trait Sealed {}
}

/// A type-level marker representing a generated schema package.
pub trait Schema: sealed::Sealed + Send + Sync + 'static {}

/// Default marker representing an unbound database handle.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Unbound;

impl sealed::Sealed for Unbound {}
impl Schema for Unbound {}

fn canonical_contract_error(error: type_bridge_contract::diagnostic::Diagnostic) -> Error {
    let code = error.code().as_str().to_owned();
    Error::model_validation(
        ModelValidationPhase::Input,
        code,
        Vec::new(),
        "canonical projected-record contract rejected the value",
        Some(Box::new(error)),
    )
}

fn canonical_codec_error(error: type_bridge_orm::ProjectedCodecError) -> Error {
    if matches!(
        &error,
        type_bridge_orm::ProjectedCodecError::Contract(diagnostic)
            if diagnostic.code().as_str() == "projected_codec_declared_schema_mismatch"
    ) {
        return Error::from_sdk_execution(
            SdkExecutionDiagnostic::projected_record_schema_mismatch(),
            ModelValidationPhase::Input,
        );
    }
    Error::model_validation(
        ModelValidationPhase::Input,
        "canonical_projected_codec_failure",
        Vec::new(),
        "installed projection rejected canonical record materialization",
        Some(Box::new(error)),
    )
}

/// Opaque installed projection used by generated successor runtimes.
#[doc(hidden)]
pub struct GeneratedProjectionValidator {
    installed: Arc<type_bridge_orm::InstalledRuntimeProjection>,
}

impl GeneratedProjectionValidator {
    /// Validate one generated create encoding through the common projected model authority.
    pub fn validate_create(&self, encoded: &EncodedCreate) -> Result<(), ValidationError> {
        crate::projected_codec::validate_encoded_create(encoded, &self.installed)
            .map_err(generated_validation_error)
    }

    /// Validate one generated hydration row through the common projected model authority.
    pub fn validate_hydration(&self, row: &HydratedRow) -> Result<(), ValidationError> {
        crate::projected_codec::validate_hydrated_row(row, &self.installed)
            .map_err(generated_validation_error)
    }
}

fn generated_validation_error(error: Error) -> ValidationError {
    let code = error
        .code()
        .expect("generated projected validation always returns a classified model error")
        .to_owned();
    let path = error
        .path()
        .map(generated_validation_path)
        .unwrap_or_default();
    ValidationError::new(path, code)
}

fn generated_validation_path(segments: &[String]) -> String {
    let mut path = String::new();
    for segment in segments {
        if segment.starts_with('[') {
            path.push_str(segment);
        } else {
            if !path.is_empty() {
                path.push('.');
            }
            path.push_str(segment);
        }
    }
    path
}

/// A generated schema package marker carrying fingerprint evidence branded by `S: Schema`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SchemaPackage<S: Schema> {
    semantic_fingerprint_json: &'static str,
    projection_fingerprint_json: &'static str,
    runtime_projection_json: &'static str,
    declared_schema_json: Option<&'static str>,
    schema_authority_json: Option<&'static str>,
    managed_scope_id: Option<&'static str>,
    semantic_profile_id: Option<&'static str>,
    marker: PhantomData<fn() -> S>,
}

impl<S: Schema> SchemaPackage<S> {
    /// Encode one exact generated attribute value as canonical projected-record bytes.
    pub fn encode_attribute<T>(&self, value: T) -> Result<Vec<u8>>
    where
        T: Model<Schema = S> + IntoEncodedScalar,
    {
        self.encode_attribute_controlled(value, &CanonicalCodecOptions::default())
    }

    /// Encode one generated attribute under cancellation, deadline, and tighten-only limits.
    pub fn encode_attribute_controlled<T>(
        &self,
        value: T,
        options: &CanonicalCodecOptions,
    ) -> Result<Vec<u8>>
    where
        T: Model<Schema = S> + IntoEncodedScalar,
    {
        let control = CapturedCanonicalCodecControl::capture(options, false)?;
        control.check()?;
        let installed = self.verify_and_install()?;
        let projected = crate::projected_codec::project_attribute_inferred(&value, &installed)?;
        let record = type_bridge_orm::record_from_attribute(&installed, &projected)
            .map_err(canonical_codec_error)?;
        control.check_decoded_weight(record.decoded_weight())?;
        control.check()?;
        let bytes = record
            .encode_with_limits(control.output_limits())
            .map_err(canonical_output_error)?;
        control.check()?;
        Ok(bytes)
    }

    /// Decode canonical projected-record bytes as one exact generated attribute value.
    pub fn decode_attribute<T>(&self, bytes: &[u8]) -> Result<T>
    where
        T: Model<Schema = S> + GroupedQueryValue,
    {
        self.decode_attribute_controlled(bytes, &CanonicalCodecOptions::default())
    }

    /// Decode one exact generated attribute under cancellation, deadline, and limits.
    pub fn decode_attribute_controlled<T>(
        &self,
        bytes: &[u8],
        options: &CanonicalCodecOptions,
    ) -> Result<T>
    where
        T: Model<Schema = S> + GroupedQueryValue,
    {
        let control = CapturedCanonicalCodecControl::capture(options, false)?;
        control.check()?;
        let installed = self.verify_and_install()?;
        let record = type_bridge_contract::projected_record::ProjectedRecord::decode_with_limits(
            bytes,
            control.input_limits(),
        )
        .map_err(canonical_input_error)?;
        control.check_decoded_weight(record.decoded_weight())?;
        control.check()?;
        let value = type_bridge_orm::materialize_record(&installed, &record)
            .map_err(canonical_codec_error)?;
        let type_bridge_orm::ProjectedCodecValue::Attribute(value) = value else {
            return Err(Error::model_validation(
                ModelValidationPhase::Input,
                "canonical_record_kind_mismatch",
                Vec::new(),
                "canonical record is not a generated attribute value",
                None,
            ));
        };
        let expected = type_bridge_contract::codec::from_canonical_json::<
            type_bridge_contract::id::TypeId,
        >(T::TYPE_ID_JSON.as_bytes())
        .map_err(canonical_contract_error)?;
        if value.attribute_type() != &expected {
            return Err(Error::model_validation(
                ModelValidationPhase::Input,
                "canonical_attribute_type_mismatch",
                Vec::new(),
                "canonical attribute record does not match the requested generated type",
                None,
            ));
        }
        let scalar = crate::projected_codec::projected_to_decoded_attribute(&value)?;
        let decoded = T::from_group_scalar(scalar).map_err(|error| {
            Error::model_validation(
                ModelValidationPhase::Input,
                "canonical_attribute_materialization_failed",
                Vec::new(),
                "canonical attribute could not materialize as the requested generated type",
                Some(Box::new(error)),
            )
        })?;
        control.check()?;
        Ok(decoded)
    }

    /// Construct a type-branded schema package marker from verified JSON evidence (generated-code SPI).
    #[doc(hidden)]
    #[must_use]
    pub const fn new(
        semantic_fingerprint_json: &'static str,
        projection_fingerprint_json: &'static str,
        runtime_projection_json: &'static str,
    ) -> Self {
        Self {
            semantic_fingerprint_json,
            projection_fingerprint_json,
            runtime_projection_json,
            declared_schema_json: None,
            schema_authority_json: None,
            managed_scope_id: None,
            semantic_profile_id: None,
            marker: PhantomData,
        }
    }

    /// Construct a generated package carrying canonical remote query
    /// authority in addition to verified runtime projection evidence.
    #[doc(hidden)]
    #[must_use]
    pub const fn new_with_declared(
        semantic_fingerprint_json: &'static str,
        projection_fingerprint_json: &'static str,
        runtime_projection_json: &'static str,
        declared_schema_json: &'static str,
    ) -> Self {
        Self {
            semantic_fingerprint_json,
            projection_fingerprint_json,
            runtime_projection_json,
            declared_schema_json: Some(declared_schema_json),
            schema_authority_json: None,
            managed_scope_id: None,
            semantic_profile_id: None,
            marker: PhantomData,
        }
    }

    /// Construct a generated package carrying one exact compiled schema
    /// authority and its constructor-extracted query inputs.
    #[doc(hidden)]
    #[must_use]
    pub const fn new_with_authority(
        semantic_fingerprint_json: &'static str,
        projection_fingerprint_json: &'static str,
        runtime_projection_json: &'static str,
        schema_authority_json: &'static str,
        declared_schema_json: &'static str,
        managed_scope_id: &'static str,
        semantic_profile_id: &'static str,
    ) -> Self {
        Self {
            semantic_fingerprint_json,
            projection_fingerprint_json,
            runtime_projection_json,
            declared_schema_json: Some(declared_schema_json),
            schema_authority_json: Some(schema_authority_json),
            managed_scope_id: Some(managed_scope_id),
            semantic_profile_id: Some(semantic_profile_id),
            marker: PhantomData,
        }
    }

    /// Encode one exact generated create payload as canonical projected-record bytes.
    pub fn encode_create<T>(&self, value: T) -> Result<Vec<u8>>
    where
        T: IntoEncodedCreate,
    {
        self.encode_create_controlled(value, &CanonicalCodecOptions::default())
    }

    /// Encode one generated create under cancellation, deadline, and tighten-only limits.
    pub fn encode_create_controlled<T>(
        &self,
        value: T,
        options: &CanonicalCodecOptions,
    ) -> Result<Vec<u8>>
    where
        T: IntoEncodedCreate,
    {
        let control = CapturedCanonicalCodecControl::capture(options, false)?;
        control.check()?;
        let installed = self.verify_and_install()?;
        let projected = crate::projected_codec::project_create_inferred(value, &installed)?;
        let record = type_bridge_orm::record_from_create(&installed, &projected)
            .map_err(canonical_codec_error)?;
        control.check_decoded_weight(record.decoded_weight())?;
        control.check()?;
        let bytes = record
            .encode_with_limits(control.output_limits())
            .map_err(canonical_output_error)?;
        control.check()?;
        Ok(bytes)
    }

    /// Decode canonical projected-record bytes as one exact generated create type.
    pub fn decode_create<T>(&self, bytes: &[u8]) -> Result<T>
    where
        T: MaterializeCreate<Schema = S>,
    {
        self.decode_create_controlled(bytes, &CanonicalCodecOptions::default())
    }

    /// Decode one exact generated create under cancellation, deadline, and limits.
    pub fn decode_create_controlled<T>(
        &self,
        bytes: &[u8],
        options: &CanonicalCodecOptions,
    ) -> Result<T>
    where
        T: MaterializeCreate<Schema = S>,
    {
        let control = CapturedCanonicalCodecControl::capture(options, false)?;
        control.check()?;
        let installed = self.verify_and_install()?;
        let record = type_bridge_contract::projected_record::ProjectedRecord::decode_with_limits(
            bytes,
            control.input_limits(),
        )
        .map_err(canonical_input_error)?;
        control.check_decoded_weight(record.decoded_weight())?;
        control.check()?;
        let value = type_bridge_orm::materialize_record(&installed, &record)
            .map_err(canonical_codec_error)?;
        let type_bridge_orm::ProjectedCodecValue::Create(value) = value else {
            return Err(Error::model_validation(
                ModelValidationPhase::Input,
                "canonical_record_kind_mismatch",
                Vec::new(),
                "canonical record is not a generated create payload",
                None,
            ));
        };
        let decoded = crate::projected_codec::projected_to_decoded_create(&value, &installed)?;
        let decoded =
            T::materialize_create(&decoded, &ValidationPath::root()).map_err(|error| {
                Error::model_validation(
                    ModelValidationPhase::Input,
                    "canonical_create_materialization_failed",
                    Vec::new(),
                    "canonical create could not materialize as the requested generated type",
                    Some(Box::new(error)),
                )
            })?;
        control.check()?;
        Ok(decoded)
    }

    /// Encode one exact generated detached reference as canonical projected-record bytes.
    pub fn encode_reference<T>(&self, value: T) -> Result<Vec<u8>>
    where
        T: IntoEncodedReference,
    {
        self.encode_reference_controlled(value, &CanonicalCodecOptions::default())
    }

    /// Encode one generated reference under cancellation, deadline, and tighten-only limits.
    pub fn encode_reference_controlled<T>(
        &self,
        value: T,
        options: &CanonicalCodecOptions,
    ) -> Result<Vec<u8>>
    where
        T: IntoEncodedReference,
    {
        let control = CapturedCanonicalCodecControl::capture(options, false)?;
        control.check()?;
        let installed = self.verify_and_install()?;
        let projected = crate::projected_codec::project_reference_inferred(value, &installed)?;
        let record = type_bridge_orm::record_from_reference(&installed, &projected)
            .map_err(canonical_codec_error)?;
        control.check_decoded_weight(record.decoded_weight())?;
        control.check()?;
        let bytes = record
            .encode_with_limits(control.output_limits())
            .map_err(canonical_output_error)?;
        control.check()?;
        Ok(bytes)
    }

    /// Decode canonical projected-record bytes as one exact generated detached reference.
    pub fn decode_reference<T>(&self, bytes: &[u8]) -> Result<T>
    where
        T: MaterializeReference<Schema = S>,
    {
        self.decode_reference_controlled(bytes, &CanonicalCodecOptions::default())
    }

    /// Decode one exact generated reference under cancellation, deadline, and limits.
    pub fn decode_reference_controlled<T>(
        &self,
        bytes: &[u8],
        options: &CanonicalCodecOptions,
    ) -> Result<T>
    where
        T: MaterializeReference<Schema = S>,
    {
        let control = CapturedCanonicalCodecControl::capture(options, false)?;
        control.check()?;
        let installed = self.verify_and_install()?;
        let record = type_bridge_contract::projected_record::ProjectedRecord::decode_with_limits(
            bytes,
            control.input_limits(),
        )
        .map_err(canonical_input_error)?;
        control.check_decoded_weight(record.decoded_weight())?;
        control.check()?;
        let value = type_bridge_orm::materialize_record(&installed, &record)
            .map_err(canonical_codec_error)?;
        let type_bridge_orm::ProjectedCodecValue::Reference(value) = value else {
            return Err(Error::model_validation(
                ModelValidationPhase::Input,
                "canonical_record_kind_mismatch",
                Vec::new(),
                "canonical record is not a generated reference",
                None,
            ));
        };
        let decoded = crate::projected_codec::projected_to_hydrated_player(&value, &installed)?;
        let decoded =
            T::materialize_reference(&decoded, &ValidationPath::root()).map_err(|error| {
                Error::model_validation(
                    ModelValidationPhase::Input,
                    "canonical_reference_materialization_failed",
                    Vec::new(),
                    "canonical reference could not materialize as the requested generated type",
                    Some(Box::new(error)),
                )
            })?;
        control.check()?;
        Ok(decoded)
    }

    /// Encode one exact generated hydrated model as a provider-free canonical snapshot.
    pub fn encode_snapshot<T>(&self, value: T) -> Result<Vec<u8>>
    where
        T: IntoHydratedSnapshot + Model<Schema = S>,
    {
        self.encode_snapshot_controlled(value, &CanonicalCodecOptions::default())
    }

    /// Encode one generated snapshot under cancellation, deadline, and tighten-only limits.
    pub fn encode_snapshot_controlled<T>(
        &self,
        value: T,
        options: &CanonicalCodecOptions,
    ) -> Result<Vec<u8>>
    where
        T: IntoHydratedSnapshot + Model<Schema = S>,
    {
        let control = CapturedCanonicalCodecControl::capture(options, false)?;
        control.check()?;
        let installed = self.verify_and_install()?;
        let projected = crate::projected_codec::project_snapshot_inferred(value, &installed)?;
        let record = type_bridge_orm::record_from_snapshot(&installed, &projected)
            .map_err(canonical_codec_error)?;
        control.check_decoded_weight(record.decoded_weight())?;
        control.check()?;
        let bytes = record
            .encode_with_limits(control.output_limits())
            .map_err(canonical_output_error)?;
        control.check()?;
        Ok(bytes)
    }

    /// Decode canonical snapshot bytes as one exact detached generated model.
    pub fn decode_snapshot<T>(&self, bytes: &[u8]) -> Result<T>
    where
        T: CompleteModel<Schema = S> + MaterializeModel,
    {
        self.decode_snapshot_controlled(bytes, &CanonicalCodecOptions::default())
    }

    /// Decode one exact detached snapshot under cancellation, deadline, and limits.
    pub fn decode_snapshot_controlled<T>(
        &self,
        bytes: &[u8],
        options: &CanonicalCodecOptions,
    ) -> Result<T>
    where
        T: CompleteModel<Schema = S> + MaterializeModel,
    {
        let control = CapturedCanonicalCodecControl::capture(options, false)?;
        control.check()?;
        let installed = self.verify_and_install()?;
        let record = type_bridge_contract::projected_record::ProjectedRecord::decode_with_limits(
            bytes,
            control.input_limits(),
        )
        .map_err(canonical_input_error)?;
        control.check_decoded_weight(record.decoded_weight())?;
        control.check()?;
        let value = type_bridge_orm::materialize_record(&installed, &record)
            .map_err(canonical_codec_error)?;
        let type_bridge_orm::ProjectedCodecValue::Snapshot(value) = value else {
            return Err(Error::model_validation(
                ModelValidationPhase::Hydration,
                "canonical_record_kind_mismatch",
                Vec::new(),
                "canonical record is not a generated hydrated snapshot",
                None,
            ));
        };
        let mut row = crate::projected_codec::projected_to_hydrated_row(&value, &installed)?;
        row.mark_detached_snapshot();
        let decoded = T::materialize(&row, &HydrationCapability::new()).map_err(|error| {
            crate::entity_codec::map_validation_error(error, ModelValidationPhase::Hydration)
        })?;
        control.check()?;
        Ok(decoded)
    }

    /// Perform offline fingerprint, authority, and exact emitter-evidence verification
    /// without connecting to a live server.
    pub fn verify(&self) -> Result<()> {
        let _ = self.verify_and_install_with_authority()?;
        Ok(())
    }

    /// Verify this generated package and open an already schema-bound direct
    /// database through the canonical connection policy.
    ///
    /// Server compatibility is discovered authoritatively; callers cannot
    /// supply or override the server version used for admission.
    #[cfg(feature = "typedb")]
    pub async fn connect(
        self,
        policy: type_bridge_orm::DirectConnectionPolicy,
    ) -> Result<crate::session::Database<S>> {
        self.connect_with_cancellation(policy, type_bridge_orm::AnswerCancellation::default())
            .await
    }

    /// Verify this generated package and open an already schema-bound direct
    /// database with one wakeable connection-cancellation owner.
    #[cfg(feature = "typedb")]
    pub async fn connect_with_cancellation(
        self,
        policy: type_bridge_orm::DirectConnectionPolicy,
        cancellation: type_bridge_orm::AnswerCancellation,
    ) -> Result<crate::session::Database<S>> {
        let (installed, authority) = self.verify_and_install_with_authority()?;
        let match_registry = crate::session::build_match_registry(&installed)?;
        let inner =
            type_bridge_orm::Database::connect_direct(installed.as_ref(), &policy, cancellation)
                .await
                .map_err(Error::from_direct_connection)?;
        Ok(crate::session::Database::from_bound_parts(
            inner,
            installed,
            match_registry,
            authority.map(|authority| authority.managed_scope().id().clone()),
        ))
    }

    /// Install the package's exact projection for generated successor-runtime validation.
    /// Package verification remains projection-evidence admission; generated-token package
    /// fencing is provided by the nominal generated Rust types.
    #[doc(hidden)]
    pub fn generated_projection_validator(
        &self,
    ) -> std::result::Result<GeneratedProjectionValidator, ValidationError> {
        self.verify_and_install()
            .map(|installed| GeneratedProjectionValidator { installed })
            .map_err(|_| {
                ValidationError::new("projection_evidence", "projection_evidence_mismatch")
            })
    }

    /// Encode one exact generated struct as canonical projected-record bytes.
    pub fn encode_struct<T>(&self, value: T) -> Result<Vec<u8>>
    where
        T: IntoEncodedStruct + StructValue<Schema = S>,
    {
        self.encode_struct_controlled(value, &CanonicalCodecOptions::default())
    }

    /// Encode one generated struct under cancellation, deadline, and tighten-only limits.
    pub fn encode_struct_controlled<T>(
        &self,
        value: T,
        options: &CanonicalCodecOptions,
    ) -> Result<Vec<u8>>
    where
        T: IntoEncodedStruct + StructValue<Schema = S>,
    {
        let control = CapturedCanonicalCodecControl::capture(options, false)?;
        control.check()?;
        let installed = self.verify_and_install()?;
        let projected = crate::projected_codec::project_struct_inferred(value, &installed)?;
        let record = type_bridge_orm::record_from_struct(&installed, &projected)
            .map_err(canonical_codec_error)?;
        control.check_decoded_weight(record.decoded_weight())?;
        control.check()?;
        let bytes = record
            .encode_with_limits(control.output_limits())
            .map_err(canonical_output_error)?;
        control.check()?;
        Ok(bytes)
    }

    /// Decode canonical projected-record bytes as one exact generated struct.
    pub fn decode_struct<T>(&self, bytes: &[u8]) -> Result<T>
    where
        T: MaterializeStruct + StructValue<Schema = S>,
    {
        self.decode_struct_controlled(bytes, &CanonicalCodecOptions::default())
    }

    /// Decode one exact generated struct under cancellation, deadline, and limits.
    pub fn decode_struct_controlled<T>(
        &self,
        bytes: &[u8],
        options: &CanonicalCodecOptions,
    ) -> Result<T>
    where
        T: MaterializeStruct + StructValue<Schema = S>,
    {
        let control = CapturedCanonicalCodecControl::capture(options, false)?;
        control.check()?;
        let installed = self.verify_and_install()?;
        let record = type_bridge_contract::projected_record::ProjectedRecord::decode_with_limits(
            bytes,
            control.input_limits(),
        )
        .map_err(canonical_input_error)?;
        control.check_decoded_weight(record.decoded_weight())?;
        control.check()?;
        let value = type_bridge_orm::materialize_record(&installed, &record)
            .map_err(canonical_codec_error)?;
        let type_bridge_orm::ProjectedCodecValue::Struct(value) = value else {
            return Err(Error::model_validation(
                ModelValidationPhase::Input,
                "canonical_record_kind_mismatch",
                Vec::new(),
                "canonical record is not a generated struct",
                None,
            ));
        };
        let decoded = crate::projected_codec::projected_to_decoded_struct(&value, &installed)?;
        let decoded =
            T::materialize_struct(&decoded, &ValidationPath::root()).map_err(|error| {
                Error::model_validation(
                    ModelValidationPhase::Input,
                    "canonical_struct_materialization_failed",
                    Vec::new(),
                    "canonical struct could not materialize as the requested generated type",
                    Some(Box::new(error)),
                )
            })?;
        control.check()?;
        Ok(decoded)
    }

    /// Compose already canonical package records into one deterministic ordered archive.
    pub fn encode_archive<I, B>(&self, records: I) -> Result<Vec<u8>>
    where
        I: IntoIterator<Item = B>,
        B: AsRef<[u8]>,
    {
        self.encode_archive_controlled(records, &CanonicalCodecOptions::default())
    }

    /// Compose canonical records under cancellation, deadline, and tighten-only limits.
    pub fn encode_archive_controlled<I, B>(
        &self,
        records: I,
        options: &CanonicalCodecOptions,
    ) -> Result<Vec<u8>>
    where
        I: IntoIterator<Item = B>,
        B: AsRef<[u8]>,
    {
        let control = CapturedCanonicalCodecControl::capture(options, true)?;
        control.check()?;
        let installed = self.verify_and_install()?;
        let mut verified = Vec::new();
        for bytes in records {
            control.check_record_count(verified.len().saturating_add(1))?;
            control.check()?;
            let record =
                type_bridge_contract::projected_record::ProjectedRecord::decode_with_limits(
                    bytes.as_ref(),
                    control.input_limits(),
                )
                .map_err(canonical_input_error)?;
            let _ = type_bridge_orm::materialize_record(&installed, &record)
                .map_err(canonical_codec_error)?;
            verified.push(record);
        }
        let archive = type_bridge_contract::projected_record::ProjectedArchive::try_new(verified)
            .map_err(canonical_contract_error)?;
        control.check_decoded_weight(archive.decoded_weight())?;
        control.check()?;
        let bytes = archive
            .encode_with_limits(control.output_limits())
            .map_err(canonical_output_error)?;
        control.check()?;
        Ok(bytes)
    }

    /// Strictly decode one complete package archive into canonical individual records.
    pub fn decode_archive(&self, bytes: &[u8]) -> Result<Vec<Vec<u8>>> {
        self.decode_archive_controlled(bytes, &CanonicalCodecOptions::default())
    }

    /// Decode one complete archive under cancellation, deadline, and tighten-only limits.
    pub fn decode_archive_controlled(
        &self,
        bytes: &[u8],
        options: &CanonicalCodecOptions,
    ) -> Result<Vec<Vec<u8>>> {
        let control = CapturedCanonicalCodecControl::capture(options, true)?;
        control.check()?;
        let installed = self.verify_and_install()?;
        let archive = type_bridge_contract::projected_record::ProjectedArchive::decode_with_limits(
            bytes,
            control.input_limits(),
        )
        .map_err(canonical_input_error)?;
        control.check_record_count(archive.records().len())?;
        control.check_decoded_weight(archive.decoded_weight())?;
        let mut records = Vec::with_capacity(archive.records().len());
        let mut output_bytes = 0_usize;
        for record in archive.records() {
            control.check()?;
            let _ = type_bridge_orm::materialize_record(&installed, record)
                .map_err(canonical_codec_error)?;
            let encoded = record
                .encode_with_limits(control.output_limits())
                .map_err(canonical_output_error)?;
            output_bytes = output_bytes.saturating_add(encoded.len());
            control.check_output_bytes(output_bytes)?;
            records.push(encoded);
        }
        control.check()?;
        Ok(records)
    }

    /// Return the semantic schema fingerprint JSON string (generated-code SPI).
    #[doc(hidden)]
    #[must_use]
    pub const fn semantic_fingerprint_json(&self) -> &'static str {
        self.semantic_fingerprint_json
    }

    /// Return the binding target projection fingerprint JSON string (generated-code SPI).
    #[doc(hidden)]
    #[must_use]
    pub const fn projection_fingerprint_json(&self) -> &'static str {
        self.projection_fingerprint_json
    }

    /// Return the canonical runtime projection JSON string (generated-code SPI).
    #[doc(hidden)]
    #[must_use]
    pub const fn runtime_projection_json(&self) -> &'static str {
        self.runtime_projection_json
    }

    pub(crate) const fn declared_schema_json(&self) -> Option<&'static str> {
        self.declared_schema_json
    }

    /// Verify all package evidence and derive provider descriptors without provider I/O
    /// (crate-internal).
    pub(crate) fn verify_and_install(
        &self,
    ) -> Result<Arc<type_bridge_orm::InstalledRuntimeProjection>> {
        self.verify_and_install_with_authority()
            .map(|(projection, _authority)| projection)
    }

    pub(crate) fn verify_and_install_with_authority(
        &self,
    ) -> Result<(
        Arc<type_bridge_orm::InstalledRuntimeProjection>,
        Option<VerifiedSchemaAuthority>,
    )> {
        let authority_backed = self.schema_authority_json.is_some();
        // The detached semantic-fingerprint string is canonical evidence slot
        // zero. Empty bytes are the generated Rust install boundary's only
        // representable absence; every nonempty shape remains merely present
        // until the binding-neutral rejection classifier sees the failure.
        let semantic_fingerprint_presence = if self.semantic_fingerprint_json.is_empty() {
            SdkProjectionEvidenceSlotPresence::Absent
        } else {
            SdkProjectionEvidenceSlotPresence::Present
        };
        let authority = self.verify_embedded_authority().map_err(|error| {
            classify_admission_error(authority_backed, semantic_fingerprint_presence, error)
        })?;
        let mut projection = type_bridge_orm::InstalledRuntimeProjection::from_verified_rust_json(
            self.runtime_projection_json.as_bytes(),
            self.semantic_fingerprint_json.as_bytes(),
            self.projection_fingerprint_json.as_bytes(),
        )
        .map_err(|err| {
            classify_admission_error(
                authority_backed,
                semantic_fingerprint_presence,
                Error::SchemaVerification {
                    message: err.to_string(),
                    source: Some(Box::new(err)),
                },
            )
        })?;
        if let Some(authority) = authority.as_ref() {
            projection = projection.with_declared_schema_identity(
                authority
                    .resolved_schema()
                    .declared_identity_fingerprint()
                    .clone(),
            );
        }
        let successor =
            authority_backed || projection_uses_ordered_collections(projection.projection());
        if authority.as_ref().is_some_and(|authority| {
            authority.resolved_schema().semantic_fingerprint()
                != projection.projection().semantic_fingerprint()
        }) {
            return Err(classify_admission_error(
                successor,
                semantic_fingerprint_presence,
                authority_error(
                    "generated schema authority does not match the installed runtime projection",
                ),
            ));
        }
        verify_rust_projection_evidence(&projection, authority.as_ref()).map_err(|error| {
            classify_admission_error(successor, semantic_fingerprint_presence, error)
        })?;
        Ok((Arc::new(projection), authority))
    }

    fn verify_embedded_authority(&self) -> Result<Option<VerifiedSchemaAuthority>> {
        let parts = (
            self.schema_authority_json,
            self.declared_schema_json,
            self.managed_scope_id,
            self.semantic_profile_id,
        );
        let (Some(envelope), Some(declared), Some(scope), Some(profile)) = parts else {
            if parts.0.is_none() && parts.2.is_none() && parts.3.is_none() {
                return Ok(None);
            }
            return Err(authority_error(
                "generated schema package contains incomplete compiled authority evidence",
            ));
        };
        if envelope.len() > MAX_SCHEMA_AUTHORITY_BYTES {
            return Err(authority_error(
                "generated schema authority exceeds the canonical byte ceiling",
            ));
        }
        let authority = decode_schema_authority(
            envelope.as_bytes(),
            &schema_authority_capability_vocabulary(),
        )
        .map_err(|error| Error::SchemaVerification {
            message: format!(
                "generated schema package contains invalid compiled authority ({:?})",
                error.code()
            ),
            source: Some(Box::new(error)),
        })?;
        let reconstructed_declared =
            encode_declared_schema(authority.declared_schema()).map_err(|error| {
                Error::SchemaVerification {
                    message: "generated schema authority declaration cannot be reconstructed"
                        .into(),
                    source: Some(Box::new(error)),
                }
            })?;
        if reconstructed_declared != declared.as_bytes()
            || authority.managed_scope().id().as_str() != scope
            || authority.semantic_profile().id().as_str() != profile
        {
            return Err(authority_error(
                "generated schema authority disagrees with its extracted query evidence",
            ));
        }
        Ok(Some(authority))
    }
}

fn verify_rust_projection_evidence(
    installed: &type_bridge_orm::InstalledRuntimeProjection,
    authority: Option<&VerifiedSchemaAuthority>,
) -> Result<()> {
    let projection = installed.projection();
    let emitter = RustEmitter::new();
    if projection.config().rust_naming_policy() != ProjectionConfig::rust().rust_naming_policy()
        || projection.config().rust_create_policy() != ProjectionConfig::rust().rust_create_policy()
    {
        return Err(authority_error(
            "generated Rust schema package does not match the exact shipped projection configuration",
        ));
    }
    if let Some(authority) = authority {
        return type_bridge_schema_codegen::verify_projection_evidence(authority, projection)
            .map_err(|error| Error::SchemaVerification {
                message: "generated Rust schema package does not match compiled schema authority and exact shipped emitter evidence"
                    .into(),
                source: Some(Box::new(error)),
            });
    }

    if projection_uses_ordered_collections(projection) {
        return Err(authority_error(
            "ordered Rust schema packages require compiled schema authority",
        ));
    }
    let resources = emitter
        .code_resources()
        .map_err(|error| Error::SchemaVerification {
            message: "legacy Rust schema package resource evidence cannot be reconstructed".into(),
            source: Some(Box::new(error)),
        })?;
    if projection.generator_handlers() != emitter.generator_handlers()
        || projection.code_resources() != resources
    {
        return Err(authority_error(
            "legacy Rust schema package does not match the exact shipped handler and resource evidence",
        ));
    }

    Ok(())
}

fn projection_uses_ordered_collections(projection: &RuntimeProjection) -> bool {
    projection.models().values().any(|model| {
        model
            .query_tokens()
            .fields()
            .values()
            .any(|field| !field.multiplicity().collection_mode().is_unordered())
            || model
                .query_tokens()
                .roles()
                .values()
                .any(|role| !role.multiplicity().collection_mode().is_unordered())
    })
}

fn authority_error(message: &'static str) -> Error {
    Error::SchemaVerification {
        message: message.into(),
        source: None,
    }
}

fn projection_evidence_error(presence: SdkProjectionEvidenceSlotPresence) -> Error {
    Error::projection_evidence_rejection(presence)
}

fn classify_admission_error(
    successor: bool,
    semantic_fingerprint_presence: SdkProjectionEvidenceSlotPresence,
    error: Error,
) -> Error {
    if successor {
        projection_evidence_error(semantic_fingerprint_presence)
    } else {
        error
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::Value;
    use type_bridge_contract::codec::to_canonical_json;
    use type_bridge_contract::fingerprint::{
        CanonicalizationVersion, Fingerprint, FingerprintDomain, SemanticProfileId,
    };
    use type_bridge_contract::managed_scope::ManagedScopeId;
    use type_bridge_contract::projection::{BindingTarget, ProjectionConfig};
    use type_bridge_contract::schema::{DocumentId, encode_declared_schema};
    use type_bridge_contract::sdk_diagnostic::{
        SdkDiagnosticCategory, SdkDiagnosticDetailValue, SdkDiagnosticPathSegment,
        SdkExecutionDiagnostic,
    };
    use type_bridge_schema::{
        ManagedDeltaContext, SCHEMA_AUTHORITY_FINGERPRINT_CANONICALIZATION,
        SCHEMA_AUTHORITY_FINGERPRINT_DOMAIN, SchemaDocumentSet, build_schema_authority,
        encode_schema_authority, normalize_documents, project, resolve,
    };
    use type_bridge_schema_codegen::{PythonEmitter, RustEmitter};
    use type_bridge_schema_migration::{
        MigrationHistoryGraph, VerifiedMigrationHistoryBundle,
        encode_verified_migration_history_bundle,
    };

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    struct TestSchema;
    impl sealed::Sealed for TestSchema {}
    impl Schema for TestSchema {}

    fn leak(bytes: Vec<u8>) -> &'static str {
        Box::leak(String::from_utf8(bytes).unwrap().into_boxed_str())
    }

    fn generated_package(source: &str, scope: &str) -> SchemaPackage<TestSchema> {
        package_with_evidence(source, scope, None, None)
    }

    fn package_with_evidence(
        source: &str,
        scope: &str,
        handlers: Option<Vec<type_bridge_contract::projection::ProjectionHandler>>,
        resources: Option<Vec<type_bridge_contract::projection::CodeResourceDigest>>,
    ) -> SchemaPackage<TestSchema> {
        let documents =
            SchemaDocumentSet::parse([(DocumentId::new("authority-test.yaml").unwrap(), source)])
                .unwrap();
        let declared = normalize_documents(&documents).unwrap();
        let profile = SemanticProfileId::new("typedb-3.12.1/v1").unwrap();
        let resolved = resolve(&declared, &profile).unwrap();
        let authority = build_schema_authority(
            &declared,
            declared.required_capabilities(),
            &ManagedDeltaContext::new(
                ManagedScopeId::new(scope).unwrap(),
                profile,
                schema_authority_capability_vocabulary(),
            ),
        )
        .unwrap();
        let emitter = RustEmitter::new();
        let handlers = handlers.unwrap_or_else(|| emitter.generator_handlers_for(&resolved));
        let resources = resources.unwrap_or_else(|| emitter.code_resources_for(&resolved).unwrap());
        let projection = project(
            &resolved,
            BindingTarget::Rust,
            &ProjectionConfig::rust(),
            &handlers,
            &resources,
        )
        .unwrap();
        SchemaPackage::new_with_authority(
            leak(to_canonical_json(projection.semantic_fingerprint()).unwrap()),
            leak(to_canonical_json(projection.projection_fingerprint()).unwrap()),
            leak(to_canonical_json(&projection).unwrap()),
            leak(encode_schema_authority(&authority)),
            leak(encode_declared_schema(&declared).unwrap()),
            Box::leak(scope.to_owned().into_boxed_str()),
            "typedb-3.12.1/v1",
        )
    }

    fn without_authority(package: SchemaPackage<TestSchema>) -> SchemaPackage<TestSchema> {
        SchemaPackage::new(
            package.semantic_fingerprint_json,
            package.projection_fingerprint_json,
            package.runtime_projection_json,
        )
    }

    fn with_runtime_projection(
        package: SchemaPackage<TestSchema>,
        runtime_projection_json: &'static str,
    ) -> SchemaPackage<TestSchema> {
        SchemaPackage::new_with_authority(
            package.semantic_fingerprint_json,
            package.projection_fingerprint_json,
            runtime_projection_json,
            package.schema_authority_json.unwrap(),
            package.declared_schema_json.unwrap(),
            package.managed_scope_id.unwrap(),
            package.semantic_profile_id.unwrap(),
        )
    }

    fn with_envelope(
        package: SchemaPackage<TestSchema>,
        envelope: &'static str,
    ) -> SchemaPackage<TestSchema> {
        SchemaPackage::new_with_authority(
            package.semantic_fingerprint_json,
            package.projection_fingerprint_json,
            package.runtime_projection_json,
            envelope,
            package.declared_schema_json.unwrap(),
            package.managed_scope_id.unwrap(),
            package.semantic_profile_id.unwrap(),
        )
    }

    fn with_semantic_fingerprint(
        package: SchemaPackage<TestSchema>,
        semantic_fingerprint_json: &'static str,
    ) -> SchemaPackage<TestSchema> {
        SchemaPackage::new_with_authority(
            semantic_fingerprint_json,
            package.projection_fingerprint_json,
            package.runtime_projection_json,
            package.schema_authority_json.unwrap(),
            package.declared_schema_json.unwrap(),
            package.managed_scope_id.unwrap(),
            package.semantic_profile_id.unwrap(),
        )
    }

    fn canonical(value: &Value) -> &'static str {
        leak(to_canonical_json(value).unwrap())
    }

    #[test]
    fn authority_backed_package_opens_and_fences_generated_migration_catalogs_offline() {
        let package = generated_package(
            "format: typebridge.schema/v2\nentities:\n  person: {}\n",
            "rust-migration-catalog",
        );
        let graph = MigrationHistoryGraph::from_verified(std::iter::empty::<
            type_bridge_schema_migration::VerifiedSchemaMigrationManifest,
        >())
        .unwrap();
        let bundle = VerifiedMigrationHistoryBundle::from_graph(&graph).unwrap();
        let bytes = encode_verified_migration_history_bundle(&bundle).unwrap();
        let catalog = package
            .open_migration_catalog(&bytes)
            .expect("verified generated bundle opens without provider I/O");
        assert!(catalog.is_empty());
        assert_eq!(catalog.fingerprint(), bundle.fingerprint());
        let preview = catalog
            .preview_apply(Vec::new(), None)
            .expect("empty generated catalog previews without provider I/O");
        assert!(preview.is_apply());
        assert!(preview.is_empty());
        assert!(!preview.execution_authorized());
        let approvals = preview
            .approval_builder()
            .finish()
            .expect("empty exact approval set freezes");
        assert!(approvals.is_empty());
        let executable = preview
            .authorize(&approvals)
            .expect("fresh plan is authorized from the exact preview owner");
        assert!(executable.execution_authorized());
        let foreign_preview = catalog.preview_apply(Vec::new(), None).unwrap();
        let mismatch = foreign_preview
            .authorize(&approvals)
            .expect_err("approval owner mismatch rejects");
        assert!(
            mismatch
                .message()
                .contains("migration_approval_plan_mismatch")
        );

        let mut tampered: Value = serde_json::from_slice(&bytes).unwrap();
        tampered["format"] = Value::String("foreign.history/v1".to_owned());
        let tampered = to_canonical_json(&tampered).unwrap();
        let error = package
            .open_migration_catalog(&tampered)
            .expect_err("foreign bundle rejects before provider I/O");
        assert!(matches!(error, Error::SchemaVerification { .. }));
    }

    fn resign(value: &mut Value) {
        let content = to_canonical_json(&value["content"]).unwrap();
        let fingerprint = Fingerprint::compute(
            FingerprintDomain::new(SCHEMA_AUTHORITY_FINGERPRINT_DOMAIN).unwrap(),
            CanonicalizationVersion::new(SCHEMA_AUTHORITY_FINGERPRINT_CANONICALIZATION).unwrap(),
            None,
            &content,
        );
        value["authority_fingerprint"] = serde_json::to_value(fingerprint).unwrap();
    }

    fn assert_projection_evidence_mismatch(error: &Error) {
        assert_eq!(error.category(), crate::ErrorCategory::Integrity);
        assert_eq!(error.model_validation_phase(), None);
        assert_eq!(error.code(), Some("projection_evidence_mismatch"));
        assert_eq!(
            error.path().expect("evidence mismatch has a stable path"),
            ["projection_evidence"],
        );
        assert_eq!(
            error.message(),
            "Generated projection evidence does not match the verified schema package",
        );
        assert!(matches!(
            error
                .diagnostic_path()
                .expect("evidence mismatch retains its typed path"),
            [crate::ErrorPathSegment::Argument(name)] if name == "projection_evidence"
        ));
        assert!(
            error
                .details()
                .expect("evidence mismatch retains typed details")
                .is_empty()
        );

        let diagnostic = std::error::Error::source(error)
            .and_then(|source| source.downcast_ref::<SdkExecutionDiagnostic>())
            .expect("the public Rust error retains the common SDK diagnostic");
        assert_eq!(diagnostic.category(), SdkDiagnosticCategory::Integrity);
        assert!(matches!(
            diagnostic.path(),
            [SdkDiagnosticPathSegment::Argument(name)]
                if name.as_str() == "projection_evidence"
        ));
        assert!(diagnostic.details().is_empty());
    }

    fn assert_missing_semantic_fingerprint(error: &Error) {
        assert_eq!(error.category(), crate::ErrorCategory::Integrity);
        assert_eq!(error.model_validation_phase(), None);
        assert_eq!(error.code(), Some("projection_evidence_mismatch"));
        assert_eq!(
            error.path().expect("missing evidence has a stable path"),
            ["projection_evidence", "[0]", "semantic_schema_fingerprint",],
        );
        assert!(matches!(
            error
                .diagnostic_path()
                .expect("missing evidence retains its typed path"),
            [
                crate::ErrorPathSegment::Argument(argument),
                crate::ErrorPathSegment::Index(0),
                crate::ErrorPathSegment::ContractIdentity(identity),
            ] if argument == "projection_evidence"
                && identity == "semantic_schema_fingerprint"
        ));
        assert_eq!(
            error
                .details()
                .expect("missing evidence retains typed details"),
            &std::collections::BTreeMap::from([
                (
                    "actual_occurrence_count".to_owned(),
                    crate::ErrorDetail::Long(0),
                ),
                (
                    "expected_occurrence_count".to_owned(),
                    crate::ErrorDetail::Long(1),
                ),
                (
                    "foreign_package".to_owned(),
                    crate::ErrorDetail::Boolean(false),
                ),
            ]),
        );

        let diagnostic = std::error::Error::source(error)
            .and_then(|source| source.downcast_ref::<SdkExecutionDiagnostic>())
            .expect("the Rust error retains the exact common SDK diagnostic");
        assert!(matches!(
            diagnostic.path(),
            [
                SdkDiagnosticPathSegment::Argument(argument),
                SdkDiagnosticPathSegment::Index(0),
                SdkDiagnosticPathSegment::ContractIdentity(identity),
            ] if argument.as_str() == "projection_evidence"
                && identity.as_str() == "semantic_schema_fingerprint"
        ));
        assert_eq!(
            diagnostic
                .details()
                .iter()
                .map(|(name, value)| (name.as_str(), value))
                .collect::<Vec<_>>(),
            vec![
                (
                    "actual_occurrence_count",
                    &SdkDiagnosticDetailValue::Count(0),
                ),
                (
                    "expected_occurrence_count",
                    &SdkDiagnosticDetailValue::Count(1),
                ),
                ("foreign_package", &SdkDiagnosticDetailValue::Boolean(false),),
            ],
        );
    }

    #[test]
    fn compiled_authority_is_fully_verified_and_bound_to_projection() {
        let package = generated_package(
            "format: typebridge.schema/v2\nentities:\n  person: {}\n",
            "rust-authority-test",
        );
        let (projection, authority) = package.verify_and_install_with_authority().unwrap();
        let authority = authority.expect("generated package has compiled authority");
        assert_eq!(
            projection.projection().semantic_fingerprint(),
            authority.resolved_schema().semantic_fingerprint(),
        );

        let foreign = generated_package(
            "format: typebridge.schema/v2\nentities:\n  organization: {}\n",
            "rust-authority-test",
        );
        let mismatched: SchemaPackage<TestSchema> = SchemaPackage::new_with_authority(
            package.semantic_fingerprint_json,
            package.projection_fingerprint_json,
            package.runtime_projection_json,
            foreign.schema_authority_json.unwrap(),
            foreign.declared_schema_json.unwrap(),
            foreign.managed_scope_id.unwrap(),
            foreign.semantic_profile_id.unwrap(),
        );
        let error = mismatched
            .verify()
            .expect_err("foreign semantic authority must not bind to the projection");
        assert_projection_evidence_mismatch(&error);
    }

    #[test]
    fn ordered_package_requires_exact_successor_handler_and_compiled_authority() {
        const ORDERED: &str = "format: typebridge.schema/v2\nattributes:\n  tag: { value: string }\nentities:\n  person:\n    owns:\n      tag:\n        card: 1\n        ordered: true\n        distinct: true\n";

        let valid = generated_package(ORDERED, "rust-ordered-evidence");
        let installed = valid.verify_and_install().unwrap();
        assert_eq!(
            installed.projection().generator_handlers(),
            [type_bridge_contract::projection::ProjectionHandler::rust_v2()],
        );
        let resource_ids = installed
            .projection()
            .code_resources()
            .iter()
            .map(|resource| resource.id().as_str())
            .collect::<Vec<_>>();
        assert_eq!(
            resource_ids,
            [
                "typebridge.generator.rust.cargo-toml",
                "typebridge.generator.rust.runtime-source",
            ],
        );
        assert_ne!(
            installed.projection().code_resources(),
            RustEmitter::new().code_resources().unwrap(),
            "the ordered package must carry the successor runtime-resource digest",
        );

        let legacy = package_with_evidence(
            ORDERED,
            "rust-ordered-evidence",
            Some(vec![
                type_bridge_contract::projection::ProjectionHandler::rust_v1(),
            ]),
            Some(RustEmitter::new().code_resources().unwrap()),
        );
        let error = legacy
            .verify()
            .expect_err("an ordered package cannot claim the legacy Rust ledger");
        assert_projection_evidence_mismatch(&error);

        let authorityless = without_authority(valid);
        let error = authorityless
            .verify()
            .expect_err("ordered packages require reconstructable schema authority");
        assert_projection_evidence_mismatch(&error);

        let diagnostic = authorityless
            .generated_projection_validator()
            .err()
            .expect("ordered successor validation must reject the detached package");
        assert_eq!(diagnostic.code(), "projection_evidence_mismatch");
        assert_eq!(diagnostic.field(), "projection_evidence");
    }

    #[test]
    fn package_rejects_missing_forged_and_foreign_resource_evidence() {
        const UNORDERED: &str = "format: typebridge.schema/v2\nentities:\n  person: {}\n";
        const ORDERED: &str = "format: typebridge.schema/v2\nattributes:\n  tag: { value: string }\nentities:\n  person:\n    owns:\n      tag:\n        card: 1\n        ordered: true\n";

        let missing = package_with_evidence(
            ORDERED,
            "rust-resource-evidence",
            Some(vec![
                type_bridge_contract::projection::ProjectionHandler::rust_v2(),
            ]),
            Some(Vec::new()),
        );
        let error = missing
            .verify()
            .expect_err("ordered resource evidence is mandatory");
        assert_projection_evidence_mismatch(&error);

        let emitter = RustEmitter::new();
        let documents =
            SchemaDocumentSet::parse([(DocumentId::new("forged-resource.yaml").unwrap(), ORDERED)])
                .unwrap();
        let declared = normalize_documents(&documents).unwrap();
        let profile = SemanticProfileId::new("typedb-3.12.1/v1").unwrap();
        let resolved = resolve(&declared, &profile).unwrap();
        let mut forged_resources = emitter.code_resources_for(&resolved).unwrap();
        let first_id = forged_resources[0].id().as_str().to_owned();
        forged_resources[0] = type_bridge_contract::projection::CodeResourceDigest::from_bytes(
            first_id,
            b"forged Rust emitter resource",
        )
        .unwrap();
        let forged = package_with_evidence(
            ORDERED,
            "rust-resource-evidence",
            Some(emitter.generator_handlers_for(&resolved)),
            Some(forged_resources),
        );
        let error = forged
            .verify()
            .expect_err("self-consistent forged resource evidence must reject");
        assert_projection_evidence_mismatch(&error);

        let foreign_resources = type_bridge_schema_codegen::PythonEmitter::new()
            .code_resources_for(&resolved)
            .unwrap();
        let foreign = package_with_evidence(
            ORDERED,
            "rust-resource-evidence",
            Some(emitter.generator_handlers_for(&resolved)),
            Some(foreign_resources),
        );
        let error = foreign
            .verify()
            .expect_err("foreign binding resource evidence must reject");
        assert_projection_evidence_mismatch(&error);

        let valid_legacy = generated_package(UNORDERED, "rust-resource-evidence");
        let installed_legacy = valid_legacy.verify_and_install().unwrap();
        assert_eq!(
            installed_legacy.projection().generator_handlers(),
            [type_bridge_contract::projection::ProjectionHandler::rust_v1()],
        );
        assert_eq!(
            installed_legacy.projection().code_resources(),
            RustEmitter::new().code_resources().unwrap(),
        );
        assert!(without_authority(valid_legacy).verify().is_ok());
    }

    #[test]
    fn successor_admission_classifies_only_absent_detached_semantic_fingerprint() {
        let package = generated_package(
            "format: typebridge.schema/v2\nattributes:\n  tag: { value: string }\nentities:\n  person:\n    owns:\n      tag:\n        card: 1\n        ordered: true\n",
            "rust-missing-semantic-evidence",
        );
        let malformed = with_semantic_fingerprint(package, "{")
            .verify()
            .expect_err("nonempty malformed semantic evidence must reject");
        assert_projection_evidence_mismatch(&malformed);

        let error = with_semantic_fingerprint(package, "")
            .verify()
            .expect_err("an absent detached semantic fingerprint must reject");
        assert_missing_semantic_fingerprint(&error);
    }

    #[test]
    fn package_rejects_stale_and_reordered_evidence() {
        const UNORDERED: &str = "format: typebridge.schema/v2\nentities:\n  person: {}\n";
        const ORDERED: &str = "format: typebridge.schema/v2\nattributes:\n  tag: { value: string }\nentities:\n  person:\n    owns:\n      tag:\n        card: 1\n        ordered: true\n";

        let emitter = RustEmitter::new();
        let ordered_documents =
            SchemaDocumentSet::parse([(DocumentId::new("stale-resource.yaml").unwrap(), ORDERED)])
                .unwrap();
        let ordered_declared = normalize_documents(&ordered_documents).unwrap();
        let profile = SemanticProfileId::new("typedb-3.12.1/v1").unwrap();
        let ordered_resolved = resolve(&ordered_declared, &profile).unwrap();
        let stale_successor = package_with_evidence(
            UNORDERED,
            "rust-stale-evidence",
            Some(emitter.generator_handlers_for(&ordered_resolved)),
            Some(emitter.code_resources_for(&ordered_resolved).unwrap()),
        );
        let error = stale_successor
            .verify()
            .expect_err("an unordered package cannot claim successor evidence");
        assert_projection_evidence_mismatch(&error);

        let ordered = generated_package(ORDERED, "rust-reordered-evidence");
        let mut runtime: Value = serde_json::from_str(ordered.runtime_projection_json).unwrap();
        runtime["code_resources"]
            .as_array_mut()
            .expect("runtime projection has a resource ledger")
            .swap(0, 1);
        let reordered = with_runtime_projection(ordered, canonical(&runtime));
        let error = reordered
            .verify()
            .expect_err("resource ledger wire order is canonical and cannot be changed");
        assert_projection_evidence_mismatch(&error);
    }

    #[test]
    fn authority_backed_admission_normalizes_malformed_extra_and_duplicate_evidence() {
        const ORDERED: &str = "format: typebridge.schema/v2\nattributes:\n  tag: { value: string }\nentities:\n  person:\n    owns:\n      tag:\n        card: 1\n        ordered: true\n";
        let package = generated_package(ORDERED, "rust-malformed-evidence");

        let malformed = with_envelope(package, "{")
            .verify()
            .expect_err("malformed authority evidence must reject");
        assert_projection_evidence_mismatch(&malformed);

        let runtime: Value = serde_json::from_str(package.runtime_projection_json).unwrap();
        let resource = runtime["code_resources"]
            .as_array()
            .and_then(|resources| resources.first())
            .cloned()
            .expect("successor projection carries resource evidence");

        let mut duplicate_runtime = runtime.clone();
        duplicate_runtime["code_resources"]
            .as_array_mut()
            .unwrap()
            .push(resource.clone());
        let duplicate = with_runtime_projection(package, canonical(&duplicate_runtime))
            .verify()
            .expect_err("duplicate resource evidence must reject");
        assert_projection_evidence_mismatch(&duplicate);

        let mut extra_resource = resource;
        extra_resource["id"] = Value::String("typebridge.generator.rust.zzz-extra".into());
        let mut extra_runtime = runtime;
        extra_runtime["code_resources"]
            .as_array_mut()
            .unwrap()
            .push(extra_resource);
        let extra = with_runtime_projection(package, canonical(&extra_runtime))
            .verify()
            .expect_err("extra resource evidence must reject");
        assert_projection_evidence_mismatch(&extra);
    }

    #[test]
    fn compiled_authority_rejects_missing_and_stale_outer_fingerprints() {
        let package = generated_package(
            "format: typebridge.schema/v2\nentities:\n  person: {}\n",
            "rust-authority-test",
        );
        let original: Value = serde_json::from_str(package.schema_authority_json.unwrap()).unwrap();

        let mut missing = original.clone();
        missing
            .as_object_mut()
            .unwrap()
            .remove("authority_fingerprint");
        let error = with_envelope(package, canonical(&missing))
            .verify()
            .expect_err("missing authority fingerprint must reject");
        assert_projection_evidence_mismatch(&error);

        let mut stale = original;
        stale["authority_fingerprint"]["digest"] = "0".repeat(64).into();
        let error = with_envelope(package, canonical(&stale))
            .verify()
            .expect_err("stale authority fingerprint must reject");
        assert_projection_evidence_mismatch(&error);
    }

    #[test]
    fn compiled_authority_reconstructs_managed_state_and_rejects_unsupported_claims() {
        let package = generated_package(
            "format: typebridge.schema/v2\nentities:\n  person: {}\n",
            "rust-authority-test",
        );
        let original: Value = serde_json::from_str(package.schema_authority_json.unwrap()).unwrap();

        let mut managed = original.clone();
        managed["content"]["managed_state"]["declared_identity"]["digest"] = "0".repeat(64).into();
        resign(&mut managed);
        let error = with_envelope(package, canonical(&managed))
            .verify()
            .expect_err("detached managed-state evidence must reject");
        assert_projection_evidence_mismatch(&error);

        let mut capabilities = original.clone();
        capabilities["content"]["required_capabilities"] =
            Value::Array(vec![Value::String("unsupported.runtime".into())]);
        resign(&mut capabilities);
        let error = with_envelope(package, canonical(&capabilities))
            .verify()
            .expect_err("unsupported artifact capability must fail closed");
        assert_projection_evidence_mismatch(&error);

        let mut version = original;
        version["content"]["authority_version"] =
            Value::String("typebridge.schema-authority/v2".into());
        resign(&mut version);
        let error = with_envelope(package, canonical(&version))
            .verify()
            .expect_err("unsupported artifact version must fail closed");
        assert_projection_evidence_mismatch(&error);
    }

    #[test]
    fn compiled_authority_rejects_oversize_and_detached_evidence() {
        let package = generated_package(
            "format: typebridge.schema/v2\nentities:\n  person: {}\n",
            "rust-authority-test",
        );
        let oversized = Box::leak(" ".repeat(MAX_SCHEMA_AUTHORITY_BYTES + 1).into_boxed_str());
        let error = with_envelope(package, oversized)
            .verify()
            .expect_err("oversize authority must fail before parsing");
        assert_projection_evidence_mismatch(&error);

        let detached: SchemaPackage<TestSchema> = SchemaPackage::new_with_authority(
            package.semantic_fingerprint_json,
            package.projection_fingerprint_json,
            package.runtime_projection_json,
            package.schema_authority_json.unwrap(),
            package.declared_schema_json.unwrap(),
            "other-scope",
            package.semantic_profile_id.unwrap(),
        );
        let error = detached
            .verify()
            .expect_err("detached scope must not override compiled authority");
        assert_projection_evidence_mismatch(&error);
    }

    #[test]
    fn schema_package_fingerprint_verification() {
        let documents = SchemaDocumentSet::parse([(
            DocumentId::new("test.yaml").unwrap(),
            "format: typebridge.schema/v2\nentities:\n  person: {}\n",
        )])
        .unwrap();
        let declared = normalize_documents(&documents).unwrap();
        let profile = SemanticProfileId::new("typedb-3.12.1/v1").unwrap();
        let resolved = resolve(&declared, &profile).unwrap();
        let emitter = RustEmitter::new();
        let resources = emitter.code_resources().unwrap();
        let projection = project(
            &resolved,
            BindingTarget::Rust,
            &ProjectionConfig::rust(),
            &emitter.generator_handlers(),
            &resources,
        )
        .unwrap();

        let semantic_json =
            String::from_utf8(to_canonical_json(projection.semantic_fingerprint()).unwrap())
                .unwrap();
        let projection_json =
            String::from_utf8(to_canonical_json(projection.projection_fingerprint()).unwrap())
                .unwrap();
        let runtime_json = String::from_utf8(to_canonical_json(&projection).unwrap()).unwrap();

        let semantic_ref: &'static str = Box::leak(semantic_json.into_boxed_str());
        let projection_ref: &'static str = Box::leak(projection_json.into_boxed_str());
        let runtime_ref: &'static str = Box::leak(runtime_json.into_boxed_str());

        let valid_package: SchemaPackage<TestSchema> =
            SchemaPackage::new(semantic_ref, projection_ref, runtime_ref);
        assert!(valid_package.verify().is_ok());

        let tampered_package: SchemaPackage<TestSchema> =
            SchemaPackage::new(semantic_ref, r#""rust/v1-tampered""#, runtime_ref);
        match tampered_package.verify() {
            Err(err) => {
                use std::error::Error as _;
                assert_eq!(err.category(), crate::ErrorCategory::Schema);
                assert_eq!(err.code(), None);
                assert_eq!(err.path(), None);
                assert!(err.source().is_some());
            }
            Ok(_) => panic!("tampered schema package must fail verification"),
        }
    }

    #[test]
    fn rejects_non_rust_target_projection() {
        let documents = SchemaDocumentSet::parse([(
            DocumentId::new("test.yaml").unwrap(),
            "format: typebridge.schema/v2\nentities:\n  person: {}\n",
        )])
        .unwrap();
        let declared = normalize_documents(&documents).unwrap();
        let profile = SemanticProfileId::new("typedb-3.12.1/v1").unwrap();
        let resolved = resolve(&declared, &profile).unwrap();
        let py_emitter = PythonEmitter::new();
        let py_resources = py_emitter.code_resources().unwrap();
        let py_projection = project(
            &resolved,
            BindingTarget::Python,
            &ProjectionConfig::python(),
            &py_emitter.generator_handlers(),
            &py_resources,
        )
        .unwrap();

        let semantic_json =
            String::from_utf8(to_canonical_json(py_projection.semantic_fingerprint()).unwrap())
                .unwrap();
        let projection_json =
            String::from_utf8(to_canonical_json(py_projection.projection_fingerprint()).unwrap())
                .unwrap();
        let runtime_json = String::from_utf8(to_canonical_json(&py_projection).unwrap()).unwrap();

        let semantic_ref: &'static str = Box::leak(semantic_json.into_boxed_str());
        let projection_ref: &'static str = Box::leak(projection_json.into_boxed_str());
        let runtime_ref: &'static str = Box::leak(runtime_json.into_boxed_str());

        let py_package: SchemaPackage<TestSchema> =
            SchemaPackage::new(semantic_ref, projection_ref, runtime_ref);
        let err = py_package.verify().unwrap_err();
        assert_eq!(err.category(), crate::ErrorCategory::Schema);
        assert_eq!(err.code(), None);
        assert_eq!(err.path(), None);
        assert!(err.to_string().contains("target mismatch") || err.to_string().contains("Rust"));
    }
}