Skip to main content

qualia_core_db/q42/asset_envelope/
envelope.rs

1//! Versioned Q42 governed-asset envelope (AST-01).
2
3use super::error::AssetEnvelopeError;
4use super::licence::LicencePolicy;
5
6/// Envelope schema version encoded on the wire.
7pub const ASSET_ENVELOPE_VERSION: u16 = 1;
8/// Soft ceiling for a single serialized envelope (cold metadata, not payload).
9pub const MAX_ENVELOPE_BYTES: usize = 256 * 1024;
10/// 42 MiB Sentinel pass budget referenced by every chunk plan.
11pub const SENTINEL_PASS_BUDGET_BYTES: u64 = 42 * 1024 * 1024;
12/// Maximum derived-from parents retained on one envelope.
13pub const MAX_DERIVED_FROM: usize = 16;
14/// Maximum rejection reason strings retained.
15pub const MAX_REJECTION_REASONS: usize = 32;
16/// Maximum identifier namespaces retained.
17pub const MAX_NAMESPACES: usize = 16;
18
19/// Sensitivity class for the asset graph (mirrors Quin sensitivity tiers used for medical).
20#[repr(u8)]
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum AssetSensitivity {
23    Public = 0,
24    Restricted = 1,
25    Medical = 3,
26    Fiduciary = 4,
27}
28
29impl AssetSensitivity {
30    /// Builds `AssetSensitivity` from `u8`.
31    pub fn from_u8(value: u8) -> Result<Self, AssetEnvelopeError> {
32        match value {
33            0 => Ok(Self::Public),
34            1 => Ok(Self::Restricted),
35            3 => Ok(Self::Medical),
36            4 => Ok(Self::Fiduciary),
37            _ => Err(AssetEnvelopeError::InvalidSensitivity),
38        }
39    }
40}
41
42/// Commons-routing lane hint for derived Quins.
43#[repr(u8)]
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum AssetRoutingLane {
46    Passthrough = 0,
47    Commons = 1,
48    Bilateral = 2,
49    Spatial = 3,
50}
51
52impl AssetRoutingLane {
53    /// Builds `AssetRoutingLane` from `u8`.
54    pub fn from_u8(value: u8) -> Result<Self, AssetEnvelopeError> {
55        match value {
56            0 => Ok(Self::Passthrough),
57            1 => Ok(Self::Commons),
58            2 => Ok(Self::Bilateral),
59            3 => Ok(Self::Spatial),
60            _ => Err(AssetEnvelopeError::InvalidRoutingLane),
61        }
62    }
63}
64
65/// One bounded ingestion chunk under the 42 MiB Sentinel pass budget.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct ChunkSpec {
68    pub index: u32,
69    pub byte_budget: u64,
70    pub record_budget: u64,
71}
72
73/// Counts retained from a release import.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
75pub struct RecordCounts {
76    pub source: u64,
77    pub accepted: u64,
78    pub quarantined: u64,
79}
80
81/// Upstream release identity for an immutable raw artifact.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct UpstreamRelease {
84    pub source_name: String,
85    pub release_id: String,
86    pub source_url: String,
87    pub retrieved_unix: u64,
88    pub byte_length: u64,
89    pub sha256: [u8; 32],
90}
91
92/// Parser / mapping toolchain versions that produced derived assets.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct ToolchainVersions {
95    pub parser_version: String,
96    pub mapping_version: String,
97}
98
99/// Versioned core schema for a governed Q42 dataset asset.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct Q42AssetEnvelope {
102    pub asset_id: String,
103    pub upstream: UpstreamRelease,
104    pub licence: LicencePolicy,
105    pub toolchain: ToolchainVersions,
106    pub raw_format: String,
107    pub media_type: String,
108    pub counts: RecordCounts,
109    pub rejection_reasons: Vec<String>,
110    pub identifier_namespaces: Vec<String>,
111    pub cross_reference_policy: String,
112    pub evidence_grade: String,
113    pub citation: String,
114    pub curation_status: String,
115    pub sensitivity: AssetSensitivity,
116    pub routing_lane: AssetRoutingLane,
117    pub derived_from: Vec<String>,
118    pub shacl_profile: String,
119    pub validation_report: String,
120    pub chunk_plan: Vec<ChunkSpec>,
121}
122
123impl Q42AssetEnvelope {
124    /// Fail closed on unknown licence, empty identity, inconsistent counts, or oversize chunks.
125    pub fn validate(&self) -> Result<(), AssetEnvelopeError> {
126        if self.asset_id.trim().is_empty() {
127            return Err(AssetEnvelopeError::MissingAssetId);
128        }
129        if self.upstream.source_name.trim().is_empty() || self.upstream.release_id.trim().is_empty()
130        {
131            return Err(AssetEnvelopeError::MissingUpstreamRelease);
132        }
133        if self.licence.class == super::licence::LicenceClass::Unknown {
134            return Err(AssetEnvelopeError::UnknownLicence);
135        }
136        if self.counts.accepted.saturating_add(self.counts.quarantined) > self.counts.source {
137            return Err(AssetEnvelopeError::CountInconsistency);
138        }
139        if self.chunk_plan.is_empty() {
140            return Err(AssetEnvelopeError::EmptyChunkPlan);
141        }
142        for chunk in &self.chunk_plan {
143            if chunk.byte_budget == 0 || chunk.byte_budget > SENTINEL_PASS_BUDGET_BYTES {
144                return Err(AssetEnvelopeError::ChunkBudgetExceeded);
145            }
146        }
147        if self.derived_from.len() > MAX_DERIVED_FROM
148            || self.rejection_reasons.len() > MAX_REJECTION_REASONS
149            || self.identifier_namespaces.len() > MAX_NAMESPACES
150        {
151            return Err(AssetEnvelopeError::Oversize);
152        }
153        Ok(())
154    }
155
156    /// Build a derived envelope that inherits the union of licence obligations.
157    pub fn derive_with(
158        &self,
159        asset_id: impl Into<String>,
160        other_licence: &LicencePolicy,
161        toolchain: ToolchainVersions,
162        chunk_plan: Vec<ChunkSpec>,
163    ) -> Result<Self, AssetEnvelopeError> {
164        let mut derived = self.clone();
165        derived.asset_id = asset_id.into();
166        derived.licence = self.licence.union_obligations(other_licence);
167        derived.toolchain = toolchain;
168        derived.chunk_plan = chunk_plan;
169        derived.derived_from = {
170            let mut parents = vec![self.asset_id.clone()];
171            parents.extend(self.derived_from.iter().cloned());
172            parents.truncate(MAX_DERIVED_FROM);
173            parents
174        };
175        derived.validate()?;
176        Ok(derived)
177    }
178
179    /// Verify a payload digest against the upstream SHA-256 recorded on the envelope.
180    pub fn verify_payload_digest(&self, digest: &[u8; 32]) -> Result<(), AssetEnvelopeError> {
181        if digest == &self.upstream.sha256 {
182            Ok(())
183        } else {
184            Err(AssetEnvelopeError::DigestMismatch)
185        }
186    }
187}
188
189/// Compute SHA-256 into a caller-owned buffer (ABI-facing digest path).
190pub fn sha256_into(bytes: &[u8], out: &mut [u8; 32]) {
191    use sha2::{Digest, Sha256};
192    let digest = Sha256::digest(bytes);
193    out.copy_from_slice(&digest);
194}
195
196/// Allocate-free convenience for cold tests and tooling.
197pub fn sha256_of(bytes: &[u8]) -> [u8; 32] {
198    let mut out = [0u8; 32];
199    sha256_into(bytes, &mut out);
200    out
201}