type-bridge-workspace 2.2.2

Validated programmatic workspace configuration 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
use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;
use std::fmt;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use type_bridge_contract::capability::CapabilitySet;
use type_bridge_contract::codec::{
    CodecVersion, FormatVersion, from_canonical_json_with_limits, to_canonical_json_with_limits,
};
use type_bridge_contract::diagnostic::Diagnostic;
use type_bridge_contract::fingerprint::{
    CanonicalizationVersion, Fingerprint, FingerprintDomain, SemanticProfileId,
};
use type_bridge_contract::limits::{
    CodecLimits, MAX_CANONICAL_COLLECTION_LEN, MAX_CANONICAL_DEPTH, MAX_CANONICAL_STRING_BYTES,
};
use type_bridge_contract::managed_scope::{ManagedScopeBinding, SemanticProfileBinding};
use type_bridge_contract::projection::{
    BindingTarget, CodeResourceDigest, ProjectionConfig, ProjectionHandler, RuntimeProjection,
};
use type_bridge_contract::projection_wire::decode_runtime_projection_verified;
use type_bridge_contract::schema::{
    CollectionMode, DeclaredSchema, ManagedSchemaState, SchemaDiagnostics, decode_declared_schema,
    encode_declared_schema,
};
use type_bridge_schema::{
    DeltaError, ManagedDeltaContext, ResolvedSchema, managed_schema_state, project,
    resolve_schema_with_capabilities,
};

use crate::{ExtensionRequirement, TypeBridgeWorkspace, WorkspaceConfigError};

/// The first closed compiled-schema bundle format.
pub const TYPEBRIDGE_SCHEMA_BUNDLE_V1: &str = "typebridge.schema-bundle/v1";
/// Fingerprint domain for the exact bundle content envelope.
pub const SCHEMA_BUNDLE_FINGERPRINT_DOMAIN: &str = "typebridge.schema.bundle";
/// Canonicalization identity for the first bundle content envelope.
pub const SCHEMA_BUNDLE_FINGERPRINT_CANONICALIZATION: &str = "typebridge.schema-bundle/v1";
/// Maximum canonical compiled bundle size: 16 MiB.
pub const MAX_SCHEMA_BUNDLE_BYTES: usize = 16 * 1024 * 1024;

const SCHEMA_BUNDLE_LIMITS: CodecLimits = CodecLimits {
    max_bytes: MAX_SCHEMA_BUNDLE_BYTES,
    max_depth: MAX_CANONICAL_DEPTH,
    max_collection_len: MAX_CANONICAL_COLLECTION_LEN,
    max_string_bytes: MAX_CANONICAL_STRING_BYTES,
};

/// Stable high-level failure classification for bundle construction and verification.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SchemaBundleErrorCode {
    /// A nested contract codec or constructor rejected input.
    Contract,
    /// Schema resolution or projection reported source-neutral schema diagnostics.
    Schema,
    /// A bundle, codec, or schema-IR version is unsupported.
    UnsupportedVersion,
    /// Bundle policy differs from the explicit verification context.
    ContextMismatch,
    /// A digest, fingerprint, state, or independently derived value is stale.
    IntegrityMismatch,
    /// A projection target is missing, duplicated, or out of canonical order.
    ProjectionTargetMismatch,
    /// A required extension is not available in the verification context.
    ExtensionUnavailable,
    /// Projection bytes or their detached evidence failed independent verification.
    ProjectionMismatch,
    /// Projection handler or resource evidence does not support the resolved schema features.
    UnsupportedProjectionEvidence,
}

/// A fail-closed bundle failure retaining nested contract or schema diagnostics.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SchemaBundleError {
    code: SchemaBundleErrorCode,
    message: &'static str,
    config: Option<Box<WorkspaceConfigError>>,
    contract: Option<Box<Diagnostic>>,
    schema: Option<Box<SchemaDiagnostics>>,
}

impl SchemaBundleError {
    fn new(code: SchemaBundleErrorCode, message: &'static str) -> Self {
        Self {
            code,
            message,
            config: None,
            contract: None,
            schema: None,
        }
    }

    fn projection(error: Diagnostic) -> Self {
        Self {
            code: SchemaBundleErrorCode::ProjectionMismatch,
            message: "runtime projection verification failed",
            config: None,
            contract: Some(Box::new(error)),
            schema: None,
        }
    }

    /// Return the stable high-level failure code.
    #[must_use]
    pub const fn code(&self) -> SchemaBundleErrorCode {
        self.code
    }

    /// Return a nested contract diagnostic, when one caused the failure.
    #[must_use]
    pub fn contract(&self) -> Option<&Diagnostic> {
        self.contract.as_deref()
    }

    /// Return a nested workspace-constructor diagnostic, when one caused the failure.
    #[must_use]
    pub fn config(&self) -> Option<&WorkspaceConfigError> {
        self.config.as_deref()
    }

    /// Return nested schema diagnostics, when resolution or projection caused the failure.
    #[must_use]
    pub fn schema(&self) -> Option<&SchemaDiagnostics> {
        self.schema.as_deref()
    }
}

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

impl Error for SchemaBundleError {}

impl From<Diagnostic> for SchemaBundleError {
    fn from(value: Diagnostic) -> Self {
        Self {
            code: SchemaBundleErrorCode::Contract,
            message: "a compiled bundle contract is invalid",
            config: None,
            contract: Some(Box::new(value)),
            schema: None,
        }
    }
}

impl From<SchemaDiagnostics> for SchemaBundleError {
    fn from(value: SchemaDiagnostics) -> Self {
        Self {
            code: SchemaBundleErrorCode::Schema,
            message: "compiled schema reconstruction failed",
            config: None,
            contract: None,
            schema: Some(Box::new(value)),
        }
    }
}

impl From<WorkspaceConfigError> for SchemaBundleError {
    fn from(value: WorkspaceConfigError) -> Self {
        Self {
            code: SchemaBundleErrorCode::Contract,
            message: "a compiled bundle workspace contract is invalid",
            config: Some(Box::new(value)),
            contract: None,
            schema: None,
        }
    }
}

impl From<DeltaError> for SchemaBundleError {
    fn from(value: DeltaError) -> Self {
        match value {
            DeltaError::Contract(error) => error.into(),
            DeltaError::Schema(error) => error.into(),
        }
    }
}

/// Exact target policy plus handler and resource evidence for one compiled projection.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BundleProjectionContext {
    config: ProjectionConfig,
    handlers: Vec<ProjectionHandler>,
    code_resources: Vec<CodeResourceDigest>,
}

impl BundleProjectionContext {
    /// Validate one target's legacy unordered projection context.
    ///
    /// This compatibility constructor retains the pre-resource bundle shape. Use
    /// [`Self::new_with_evidence`] for a complete emitter evidence ledger.
    pub fn new(
        config: ProjectionConfig,
        handlers: Vec<ProjectionHandler>,
    ) -> Result<Self, SchemaBundleError> {
        let context = Self::new_with_evidence(config, handlers, Vec::new())?;
        if context.uses_successor_handler() {
            return Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ContextMismatch,
                "legacy projection context requires the exact legacy target handler",
            ));
        }
        Ok(context)
    }

    /// Validate one target's exact handler and fixed-resource evidence ledger.
    pub fn new_with_evidence(
        config: ProjectionConfig,
        mut handlers: Vec<ProjectionHandler>,
        mut code_resources: Vec<CodeResourceDigest>,
    ) -> Result<Self, SchemaBundleError> {
        handlers.sort_by(|left, right| {
            left.id()
                .cmp(right.id())
                .then(left.version().cmp(&right.version()))
        });
        if handlers.windows(2).any(|pair| pair[0].id() == pair[1].id()) {
            return Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ContextMismatch,
                "projection context contains duplicate handler identities",
            ));
        }
        code_resources.sort_by(|left, right| left.id().cmp(right.id()));
        if code_resources
            .windows(2)
            .any(|pair| pair[0].id() == pair[1].id())
        {
            return Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ContextMismatch,
                "projection context contains duplicate code-resource identities",
            ));
        }

        let legacy = required_projection_handler(config.target(), false)?;
        let successor = required_projection_handler(config.target(), true)?;
        let uses_successor = handlers.first() == Some(&successor);
        if handlers.len() != 1
            || handlers
                .first()
                .is_none_or(|handler| handler != &legacy && handler != &successor)
        {
            return Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ContextMismatch,
                "projection context handler evidence differs from the exact shipped target sets",
            ));
        }
        if uses_successor && code_resources.is_empty() {
            return Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ContextMismatch,
                "ordered successor projection context requires exact code-resource evidence",
            ));
        }
        if !uses_successor && !code_resources.is_empty() {
            return Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ContextMismatch,
                "legacy projection context must retain the empty resource-evidence ledger",
            ));
        }
        if !code_resources.is_empty()
            && !resource_ids_match_target(config.target(), &code_resources)?
        {
            return Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ContextMismatch,
                "projection context code-resource identities differ from the exact shipped target set",
            ));
        }

        Ok(Self {
            config,
            handlers,
            code_resources,
        })
    }

    /// Return the exact target configuration.
    #[must_use]
    pub const fn config(&self) -> &ProjectionConfig {
        &self.config
    }

    /// Return the target selected by the projection configuration.
    #[must_use]
    pub const fn target(&self) -> BindingTarget {
        self.config.target()
    }

    /// Return canonical handler evidence.
    #[must_use]
    pub fn handlers(&self) -> &[ProjectionHandler] {
        &self.handlers
    }

    /// Return canonical fixed-resource evidence.
    #[must_use]
    pub fn code_resources(&self) -> &[CodeResourceDigest] {
        &self.code_resources
    }

    fn uses_successor_handler(&self) -> bool {
        self.handlers.first()
            == required_projection_handler(self.target(), true)
                .ok()
                .as_ref()
    }
}

fn required_projection_handler(
    target: BindingTarget,
    ordered: bool,
) -> Result<ProjectionHandler, SchemaBundleError> {
    match (target, ordered) {
        (BindingTarget::Python, false) => Ok(ProjectionHandler::python_v1()),
        (BindingTarget::Python, true) => Ok(ProjectionHandler::python_v2()),
        (BindingTarget::TypeScript, false) => Ok(ProjectionHandler::typescript_v1()),
        (BindingTarget::TypeScript, true) => Ok(ProjectionHandler::typescript_v2()),
        (BindingTarget::Rust, false) => Ok(ProjectionHandler::rust_v1()),
        (BindingTarget::Rust, true) => Ok(ProjectionHandler::rust_v2()),
        (BindingTarget::C, false) => Ok(ProjectionHandler::c_v2()),
        (BindingTarget::C, true) => Ok(ProjectionHandler::c_v3()),
        _ => Err(SchemaBundleError::new(
            SchemaBundleErrorCode::ProjectionTargetMismatch,
            "projection context contains an unsupported binding target",
        )),
    }
}

fn resource_ids_match_target(
    target: BindingTarget,
    resources: &[CodeResourceDigest],
) -> Result<bool, SchemaBundleError> {
    let required: &[&str] = match target {
        BindingTarget::Python => &[
            "typebridge.generator.python.py-typed",
            "typebridge.generator.python.query-source",
            "typebridge.generator.python.query-stub",
            "typebridge.generator.python.runtime-source",
            "typebridge.generator.python.runtime-stub",
        ],
        BindingTarget::TypeScript => &[
            "typebridge.generator.typescript.package-json",
            "typebridge.generator.typescript.runtime-source",
            "typebridge.generator.typescript.tsconfig-json",
        ],
        BindingTarget::Rust => &[
            "typebridge.generator.rust.cargo-toml",
            "typebridge.generator.rust.runtime-source",
        ],
        BindingTarget::C => &[
            "typebridge.generator.c.cmake-package-config-template",
            "typebridge.generator.c.cmake-template",
            "typebridge.generator.c.pkg-config-template",
        ],
        _ => {
            return Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ProjectionTargetMismatch,
                "projection context contains an unsupported binding target",
            ));
        }
    };
    Ok(resources.len() == required.len()
        && resources
            .iter()
            .zip(required)
            .all(|(actual, expected)| actual.id().as_str() == *expected))
}

/// Explicit capability, extension, scope, profile, and projection trust context.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BundleVerificationContext {
    available_capabilities: CapabilitySet,
    available_extensions: BTreeSet<ExtensionRequirement>,
    managed_scope: ManagedScopeBinding,
    projections: BTreeMap<BindingTarget, BundleProjectionContext>,
    semantic_profile: SemanticProfileId,
}

impl BundleVerificationContext {
    /// Construct a closed verification context without consulting sources or providers.
    pub fn new(
        semantic_profile: SemanticProfileId,
        managed_scope: ManagedScopeBinding,
        available_capabilities: CapabilitySet,
        available_extensions: impl IntoIterator<Item = ExtensionRequirement>,
        projections: impl IntoIterator<Item = BundleProjectionContext>,
    ) -> Result<Self, SchemaBundleError> {
        SemanticProfileBinding::resolve(semantic_profile.clone())?;
        let mut extension_set = BTreeSet::new();
        for extension in available_extensions {
            if !extension_set.insert(extension) {
                return Err(SchemaBundleError::new(
                    SchemaBundleErrorCode::ContextMismatch,
                    "verification context contains a duplicate extension requirement",
                ));
            }
        }
        let mut projection_map = BTreeMap::new();
        for projection in projections {
            if projection_map
                .insert(projection.target(), projection)
                .is_some()
            {
                return Err(SchemaBundleError::new(
                    SchemaBundleErrorCode::ProjectionTargetMismatch,
                    "verification context contains a duplicate projection target",
                ));
            }
        }
        Ok(Self {
            available_capabilities,
            available_extensions: extension_set,
            managed_scope,
            projections: projection_map,
            semantic_profile,
        })
    }

    /// Return capabilities available to schema resolution and bundle consumption.
    #[must_use]
    pub const fn available_capabilities(&self) -> &CapabilitySet {
        &self.available_capabilities
    }

    /// Return extensions available to bundle consumption.
    #[must_use]
    pub const fn available_extensions(&self) -> &BTreeSet<ExtensionRequirement> {
        &self.available_extensions
    }

    /// Return the expected durable managed scope and frozen profile binding.
    #[must_use]
    pub const fn managed_scope(&self) -> &ManagedScopeBinding {
        &self.managed_scope
    }

    /// Return the expected semantic profile identity.
    #[must_use]
    pub const fn semantic_profile(&self) -> &SemanticProfileId {
        &self.semantic_profile
    }

    /// Look up exact projection verification policy by shipped target.
    #[must_use]
    pub fn projection(&self, target: BindingTarget) -> Option<&BundleProjectionContext> {
        self.projections.get(&target)
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
enum BindingTargetWire {
    Python,
    #[serde(rename = "typescript")]
    TypeScript,
    Rust,
    C,
}

impl BindingTargetWire {
    const fn rebuild(self) -> BindingTarget {
        match self {
            Self::Python => BindingTarget::Python,
            Self::TypeScript => BindingTarget::TypeScript,
            Self::Rust => BindingTarget::Rust,
            Self::C => BindingTarget::C,
        }
    }
}

impl TryFrom<BindingTarget> for BindingTargetWire {
    type Error = SchemaBundleError;

    fn try_from(value: BindingTarget) -> Result<Self, Self::Error> {
        match value {
            BindingTarget::Python => Ok(Self::Python),
            BindingTarget::TypeScript => Ok(Self::TypeScript),
            BindingTarget::Rust => Ok(Self::Rust),
            BindingTarget::C => Ok(Self::C),
            _ => Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ProjectionTargetMismatch,
                "bundle encoder does not support this binding target",
            )),
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(deny_unknown_fields)]
struct ExtensionRequirementWire {
    handler_id: String,
    version: String,
}

impl ExtensionRequirementWire {
    fn from_requirement(value: &ExtensionRequirement) -> Self {
        Self {
            handler_id: value.handler_id().to_owned(),
            version: value.version().to_owned(),
        }
    }

    fn rebuild(self) -> Result<ExtensionRequirement, SchemaBundleError> {
        ExtensionRequirement::new(self.handler_id, self.version).map_err(SchemaBundleError::from)
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct ProjectionEntryWire {
    binding_fingerprint: Value,
    canonical_projection: Value,
    config: Value,
    handler_evidence: Vec<Value>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    resource_evidence: Vec<Value>,
    target: BindingTargetWire,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct SchemaBundleContentWire {
    bundle_version: String,
    codec_version: u16,
    declared_schema: Value,
    expected_declared_identity: Value,
    expected_managed_declared_identity: Value,
    expected_managed_semantic_schema: Value,
    expected_semantic_schema: Value,
    managed_scope: Value,
    managed_state: Value,
    projections: Vec<ProjectionEntryWire>,
    required_capabilities: CapabilitySet,
    required_extensions: Vec<ExtensionRequirementWire>,
    schema_ir_version: u16,
    semantic_profile: Value,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct SchemaBundleWire {
    bundle_fingerprint: Value,
    content: SchemaBundleContentWire,
}

/// Opaque constructor-verified compiled schema bundle.
#[derive(Debug)]
pub struct VerifiedSchemaBundle {
    bundle_fingerprint: Fingerprint,
    canonical_bytes: Vec<u8>,
    declared: DeclaredSchema,
    managed_scope: ManagedScopeBinding,
    managed_state: ManagedSchemaState,
    projections: BTreeMap<BindingTarget, RuntimeProjection>,
    required_capabilities: CapabilitySet,
    required_extensions: BTreeSet<ExtensionRequirement>,
    resolved: ResolvedSchema,
    semantic_profile: SemanticProfileBinding,
}

impl VerifiedSchemaBundle {
    /// Return the exact bundle-content fingerprint.
    #[must_use]
    pub const fn bundle_fingerprint(&self) -> &Fingerprint {
        &self.bundle_fingerprint
    }

    /// Return constructor-validated direct schema facts with compiled provenance.
    #[must_use]
    pub const fn declared_schema(&self) -> &DeclaredSchema {
        &self.declared
    }

    /// Return independently resolved effective schema semantics.
    #[must_use]
    pub const fn resolved_schema(&self) -> &ResolvedSchema {
        &self.resolved
    }

    /// Return the frozen semantic-profile identity and content fingerprint.
    #[must_use]
    pub const fn semantic_profile(&self) -> &SemanticProfileBinding {
        &self.semantic_profile
    }

    /// Return the durable managed scope and frozen scope-profile binding.
    #[must_use]
    pub const fn managed_scope(&self) -> &ManagedScopeBinding {
        &self.managed_scope
    }

    /// Return the independently recomputed managed schema state.
    #[must_use]
    pub const fn managed_state(&self) -> &ManagedSchemaState {
        &self.managed_state
    }

    /// Return exact compiled capability requirements.
    #[must_use]
    pub const fn required_capabilities(&self) -> &CapabilitySet {
        &self.required_capabilities
    }

    /// Return exact compiled extension requirements.
    #[must_use]
    pub const fn required_extensions(&self) -> &BTreeSet<ExtensionRequirement> {
        &self.required_extensions
    }

    /// Look up one independently verified runtime projection.
    #[must_use]
    pub fn projection(&self, target: BindingTarget) -> Option<&RuntimeProjection> {
        self.projections.get(&target)
    }

    /// Iterate verified projections in stable target order.
    pub fn projections(
        &self,
    ) -> impl ExactSizeIterator<Item = (BindingTarget, &RuntimeProjection)> {
        self.projections
            .iter()
            .map(|(target, value)| (*target, value))
    }
}

/// Source-free runtime installed only from a verified compiled bundle.
#[derive(Debug)]
pub struct TypeBridgeRuntime {
    bundle: VerifiedSchemaBundle,
}

impl TypeBridgeRuntime {
    /// Decode and independently verify canonical bundle bytes without source access.
    pub fn from_bundle_bytes(
        bytes: &[u8],
        context: &BundleVerificationContext,
    ) -> Result<Self, SchemaBundleError> {
        Ok(Self {
            bundle: decode_verified_schema_bundle(bytes, context)?,
        })
    }

    /// Return the verified bundle fingerprint.
    #[must_use]
    pub const fn bundle_fingerprint(&self) -> &Fingerprint {
        self.bundle.bundle_fingerprint()
    }

    /// Return constructor-validated compiled declarations.
    #[must_use]
    pub const fn declared_schema(&self) -> &DeclaredSchema {
        self.bundle.declared_schema()
    }

    /// Return independently resolved compiled semantics.
    #[must_use]
    pub const fn resolved_schema(&self) -> &ResolvedSchema {
        self.bundle.resolved_schema()
    }

    /// Return the verified semantic-profile binding.
    #[must_use]
    pub const fn semantic_profile(&self) -> &SemanticProfileBinding {
        self.bundle.semantic_profile()
    }

    /// Return the verified durable managed-scope binding.
    #[must_use]
    pub const fn managed_scope(&self) -> &ManagedScopeBinding {
        self.bundle.managed_scope()
    }

    /// Return the recomputed managed state.
    #[must_use]
    pub const fn managed_state(&self) -> &ManagedSchemaState {
        self.bundle.managed_state()
    }

    /// Return exact runtime capability requirements.
    #[must_use]
    pub const fn required_capabilities(&self) -> &CapabilitySet {
        self.bundle.required_capabilities()
    }

    /// Return exact runtime extension requirements.
    #[must_use]
    pub const fn required_extensions(&self) -> &BTreeSet<ExtensionRequirement> {
        self.bundle.required_extensions()
    }

    /// Look up one verified target projection.
    #[must_use]
    pub fn projection(&self, target: BindingTarget) -> Option<&RuntimeProjection> {
        self.bundle.projection(target)
    }
}

/// Build and immediately reverify one source-free bundle from a source workspace.
pub fn build_verified_schema_bundle(
    workspace: &TypeBridgeWorkspace,
    context: &BundleVerificationContext,
) -> Result<VerifiedSchemaBundle, SchemaBundleError> {
    verify_workspace_context(workspace, context)?;
    let content = content_from_workspace(workspace, context)?;
    let bundle_fingerprint = compute_bundle_fingerprint(&content)?;
    let wire = SchemaBundleWire {
        bundle_fingerprint: canonical_value(&bundle_fingerprint)?,
        content,
    };
    let bytes = to_canonical_json_with_limits(&wire, SCHEMA_BUNDLE_LIMITS)?;
    decode_verified_schema_bundle(&bytes, context)
}

/// Return exact canonical bytes retained by an already verified bundle.
#[must_use]
pub fn encode_verified_schema_bundle(bundle: &VerifiedSchemaBundle) -> Vec<u8> {
    bundle.canonical_bytes.clone()
}

/// Decode, reconstruct, and independently verify one canonical compiled bundle.
pub fn decode_verified_schema_bundle(
    bytes: &[u8],
    context: &BundleVerificationContext,
) -> Result<VerifiedSchemaBundle, SchemaBundleError> {
    let wire: SchemaBundleWire = from_canonical_json_with_limits(bytes, SCHEMA_BUNDLE_LIMITS)?;
    let bundle_fingerprint = compute_bundle_fingerprint(&wire.content)?;
    if wire.bundle_fingerprint != canonical_value(&bundle_fingerprint)? {
        return Err(SchemaBundleError::new(
            SchemaBundleErrorCode::IntegrityMismatch,
            "bundle content fingerprint is stale",
        ));
    }
    let content = wire.content;
    if content.bundle_version != TYPEBRIDGE_SCHEMA_BUNDLE_V1
        || content.codec_version != CodecVersion::V1.get()
        || content.schema_ir_version != FormatVersion::V1.get()
    {
        return Err(SchemaBundleError::new(
            SchemaBundleErrorCode::UnsupportedVersion,
            "bundle, codec, or schema-IR version is unsupported",
        ));
    }

    let semantic_profile = SemanticProfileBinding::resolve(context.semantic_profile.clone())?;
    require_exact_value(
        &content.semantic_profile,
        &semantic_profile,
        "semantic profile binding differs from verification context",
    )?;
    require_exact_value(
        &content.managed_scope,
        &context.managed_scope,
        "managed scope binding differs from verification context",
    )?;
    content
        .required_capabilities
        .ensure_supported_by(&context.available_capabilities)?;
    let required_extensions = rebuild_extensions(&content.required_extensions)?;
    if !required_extensions.is_subset(&context.available_extensions) {
        return Err(SchemaBundleError::new(
            SchemaBundleErrorCode::ExtensionUnavailable,
            "bundle requires an extension absent from verification context",
        ));
    }

    let declared_bytes =
        to_canonical_json_with_limits(&content.declared_schema, SCHEMA_BUNDLE_LIMITS)?;
    let declared = decode_declared_schema(&declared_bytes)?;
    declared
        .required_capabilities()
        .ensure_supported_by(&content.required_capabilities)?;
    require_exact_value(
        &content.expected_declared_identity,
        declared.declared_identity_fingerprint(),
        "declared schema identity fingerprint is stale",
    )?;
    let resolved = resolve_schema_with_capabilities(
        &declared,
        context.semantic_profile(),
        context.available_capabilities(),
    )?;
    require_exact_value(
        &content.expected_semantic_schema,
        resolved.semantic_fingerprint(),
        "global semantic schema fingerprint is stale",
    )?;

    let managed_context = ManagedDeltaContext::new(
        context.managed_scope.id().clone(),
        context.semantic_profile.clone(),
        context.available_capabilities.clone(),
    );
    let managed_state = managed_schema_state(&declared, &managed_context)?;
    require_exact_value(
        &content.managed_state,
        &managed_state,
        "managed schema state is stale",
    )?;
    require_exact_value(
        &content.expected_managed_declared_identity,
        managed_state.managed_declared_identity(),
        "managed declared-identity fingerprint is stale",
    )?;
    require_exact_value(
        &content.expected_managed_semantic_schema,
        managed_state.managed_semantic_schema(),
        "managed semantic-schema fingerprint is stale",
    )?;

    let projections = verify_projections(&content.projections, &resolved, context)?;
    Ok(VerifiedSchemaBundle {
        bundle_fingerprint,
        canonical_bytes: bytes.to_vec(),
        declared,
        managed_scope: context.managed_scope.clone(),
        managed_state,
        projections,
        required_capabilities: content.required_capabilities,
        required_extensions,
        resolved,
        semantic_profile,
    })
}

fn verify_workspace_context(
    workspace: &TypeBridgeWorkspace,
    context: &BundleVerificationContext,
) -> Result<(), SchemaBundleError> {
    if workspace.config().semantic_profile() != context.semantic_profile()
        || workspace.config().managed_scope() != context.managed_scope()
    {
        return Err(SchemaBundleError::new(
            SchemaBundleErrorCode::ContextMismatch,
            "workspace profile or managed scope differs from bundle context",
        ));
    }
    workspace
        .required_capabilities()
        .ensure_supported_by(context.available_capabilities())?;
    if !workspace
        .config()
        .extensions()
        .is_subset(context.available_extensions())
    {
        return Err(SchemaBundleError::new(
            SchemaBundleErrorCode::ExtensionUnavailable,
            "workspace requires an extension absent from bundle context",
        ));
    }
    let output_targets = workspace
        .config()
        .outputs()
        .keys()
        .copied()
        .collect::<BTreeSet<_>>();
    let context_targets = context.projections.keys().copied().collect::<BTreeSet<_>>();
    if output_targets != context_targets {
        return Err(SchemaBundleError::new(
            SchemaBundleErrorCode::ProjectionTargetMismatch,
            "configured output targets and bundle projection contexts differ",
        ));
    }
    if let Some(c_context) = context.projections.get(&BindingTarget::C) {
        let expected = crate::c_symbol_prefix_for_app_label(workspace.config().app_label());
        if c_context.config().c_symbol_prefix() != Some(&expected) {
            return Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ContextMismatch,
                "C projection symbol prefix differs from the workspace app-label policy",
            ));
        }
    }
    Ok(())
}

fn content_from_workspace(
    workspace: &TypeBridgeWorkspace,
    context: &BundleVerificationContext,
) -> Result<SchemaBundleContentWire, SchemaBundleError> {
    let declared_bytes = encode_declared_schema(workspace.declared_schema())?;
    let declared_schema = from_canonical_json_with_limits(&declared_bytes, SCHEMA_BUNDLE_LIMITS)?;
    let semantic_profile = SemanticProfileBinding::resolve(context.semantic_profile.clone())?;
    validate_projection_evidence_for_schema(workspace.resolved_schema(), context)?;
    let mut projections = Vec::with_capacity(context.projections.len());
    for (&target, projection_context) in &context.projections {
        let projection = project(
            workspace.resolved_schema(),
            target,
            projection_context.config(),
            projection_context.handlers(),
            projection_context.code_resources(),
        )?;
        projections.push(ProjectionEntryWire {
            binding_fingerprint: canonical_value(
                projection.projection_fingerprint().as_fingerprint(),
            )?,
            canonical_projection: canonical_value(&projection)?,
            config: canonical_value(projection_context.config())?,
            handler_evidence: canonical_values(projection_context.handlers())?,
            resource_evidence: canonical_values(projection_context.code_resources())?,
            target: BindingTargetWire::try_from(target)?,
        });
    }
    Ok(SchemaBundleContentWire {
        bundle_version: TYPEBRIDGE_SCHEMA_BUNDLE_V1.to_owned(),
        codec_version: CodecVersion::V1.get(),
        declared_schema,
        expected_declared_identity: canonical_value(
            workspace.declared_schema().declared_identity_fingerprint(),
        )?,
        expected_managed_declared_identity: canonical_value(
            workspace.managed_state().managed_declared_identity(),
        )?,
        expected_managed_semantic_schema: canonical_value(
            workspace.managed_state().managed_semantic_schema(),
        )?,
        expected_semantic_schema: canonical_value(
            workspace.resolved_schema().semantic_fingerprint(),
        )?,
        managed_scope: canonical_value(context.managed_scope())?,
        managed_state: canonical_value(workspace.managed_state())?,
        projections,
        required_capabilities: workspace.required_capabilities().clone(),
        required_extensions: workspace
            .config()
            .extensions()
            .iter()
            .map(ExtensionRequirementWire::from_requirement)
            .collect(),
        schema_ir_version: workspace.declared_schema().format().get(),
        semantic_profile: canonical_value(&semantic_profile)?,
    })
}

fn verify_projections(
    entries: &[ProjectionEntryWire],
    resolved: &ResolvedSchema,
    context: &BundleVerificationContext,
) -> Result<BTreeMap<BindingTarget, RuntimeProjection>, SchemaBundleError> {
    validate_projection_evidence_for_schema(resolved, context)?;
    let expected_semantic = to_canonical_json_with_limits(
        resolved.semantic_fingerprint().as_fingerprint(),
        SCHEMA_BUNDLE_LIMITS,
    )?;
    let mut projections = BTreeMap::new();
    let mut previous = None;
    for entry in entries {
        let target = entry.target.rebuild();
        if previous.is_some_and(|value| value >= target) {
            return Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ProjectionTargetMismatch,
                "bundle projection entries are duplicated or not canonically ordered",
            ));
        }
        previous = Some(target);
        let expected = context.projection(target).ok_or_else(|| {
            SchemaBundleError::new(
                SchemaBundleErrorCode::ProjectionTargetMismatch,
                "bundle contains a projection target absent from context",
            )
        })?;
        if entry.config != canonical_value(expected.config())?
            || entry.handler_evidence != canonical_values(expected.handlers())?
            || entry.resource_evidence != canonical_values(expected.code_resources())?
        {
            return Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ContextMismatch,
                "projection configuration, handler, or resource evidence differs from context",
            ));
        }
        let projection_bytes =
            to_canonical_json_with_limits(&entry.canonical_projection, SCHEMA_BUNDLE_LIMITS)?;
        let binding_bytes =
            to_canonical_json_with_limits(&entry.binding_fingerprint, SCHEMA_BUNDLE_LIMITS)?;
        let decoded = decode_runtime_projection_verified(
            &projection_bytes,
            &expected_semantic,
            &binding_bytes,
        )
        .map_err(SchemaBundleError::projection)?;
        if decoded.target() != target
            || decoded.config() != expected.config()
            || decoded.generator_handlers() != expected.handlers()
            || decoded.code_resources() != expected.code_resources()
            || entry.binding_fingerprint
                != canonical_value(decoded.projection_fingerprint().as_fingerprint())?
        {
            return Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ProjectionMismatch,
                "decoded projection evidence differs from the closed bundle contract",
            ));
        }
        let recomputed = project(
            resolved,
            target,
            expected.config(),
            expected.handlers(),
            expected.code_resources(),
        )?;
        let recomputed_bytes = to_canonical_json_with_limits(&recomputed, SCHEMA_BUNDLE_LIMITS)?;
        if projection_bytes != recomputed_bytes || decoded != recomputed {
            return Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ProjectionMismatch,
                "projection bytes differ from pure re-projection",
            ));
        }
        projections.insert(target, decoded);
    }
    if projections.keys().copied().collect::<BTreeSet<_>>()
        != context.projections.keys().copied().collect::<BTreeSet<_>>()
    {
        return Err(SchemaBundleError::new(
            SchemaBundleErrorCode::ProjectionTargetMismatch,
            "bundle omits a projection required by verification context",
        ));
    }
    Ok(projections)
}

fn validate_projection_evidence_for_schema(
    resolved: &ResolvedSchema,
    context: &BundleVerificationContext,
) -> Result<(), SchemaBundleError> {
    let ordered = resolved.types().values().any(|resolved_type| {
        resolved_type
            .owns()
            .values()
            .any(|owns| owns.collection_mode() == CollectionMode::OrderedList)
            || resolved_type
                .relates()
                .values()
                .any(|relates| relates.collection_mode() == CollectionMode::OrderedList)
    });
    if context
        .projections
        .values()
        .any(|projection| projection.uses_successor_handler() != ordered)
    {
        return Err(SchemaBundleError::new(
            SchemaBundleErrorCode::UnsupportedProjectionEvidence,
            "projection evidence does not match the resolved schema collection mode",
        ));
    }
    Ok(())
}

fn rebuild_extensions(
    wires: &[ExtensionRequirementWire],
) -> Result<BTreeSet<ExtensionRequirement>, SchemaBundleError> {
    let mut extensions = BTreeSet::new();
    let mut previous = None;
    for wire in wires {
        let extension = wire.clone().rebuild()?;
        if previous.as_ref().is_some_and(|value| value >= &extension)
            || !extensions.insert(extension.clone())
        {
            return Err(SchemaBundleError::new(
                SchemaBundleErrorCode::ContextMismatch,
                "bundle extension requirements are duplicated or not canonically ordered",
            ));
        }
        previous = Some(extension);
    }
    Ok(extensions)
}

fn compute_bundle_fingerprint(
    content: &SchemaBundleContentWire,
) -> Result<Fingerprint, SchemaBundleError> {
    let bytes = to_canonical_json_with_limits(content, SCHEMA_BUNDLE_LIMITS)?;
    Ok(Fingerprint::compute(
        FingerprintDomain::new(SCHEMA_BUNDLE_FINGERPRINT_DOMAIN)?,
        CanonicalizationVersion::new(SCHEMA_BUNDLE_FINGERPRINT_CANONICALIZATION)?,
        None,
        &bytes,
    ))
}

fn require_exact_value<T: Serialize>(
    actual: &Value,
    expected: &T,
    message: &'static str,
) -> Result<(), SchemaBundleError> {
    if actual == &canonical_value(expected)? {
        Ok(())
    } else {
        Err(SchemaBundleError::new(
            SchemaBundleErrorCode::IntegrityMismatch,
            message,
        ))
    }
}

fn canonical_value<T: Serialize>(value: &T) -> Result<Value, SchemaBundleError> {
    let bytes = to_canonical_json_with_limits(value, SCHEMA_BUNDLE_LIMITS)?;
    Ok(from_canonical_json_with_limits(
        &bytes,
        SCHEMA_BUNDLE_LIMITS,
    )?)
}

fn canonical_values<T: Serialize>(values: &[T]) -> Result<Vec<Value>, SchemaBundleError> {
    values.iter().map(canonical_value).collect()
}