Skip to main content

qualia_core_db/bundle/
entity_compiler.rs

1//! Reverse-LOD Ontological Entity Compiler & Asset Packaging Engine.
2//!
3//! Replaces the industrial "digital twin" framing with an ontologically-grounded
4//! representation system respecting the sacred boundary between the living biosphere
5//! ("world of god") and manufactured property ("world of man"):
6//!
7//! - **Natural Person (`NaturalPerson`)**: Compiled as a sovereign **`Persona`** / **`Likeness`**.
8//!   Anti-commodification protection prevents persons from being classified as commercial property or assets.
9//! - **Darwinian Taxon (`DarwinianTaxon`)**: Compiled as a biological/botanical **`Specimen`**.
10//!   Part of the ecological commons; not an enclosed corporate clone.
11//! - **Manufactured Property (`ManufacturedProperty`)**: Compiled as a **`Construct`** / **`Artifact`**.
12//!   Legitimate domain of engineering specifications, ownership, and maintenance regimes.
13//! - **Liberal Arts Work (`LiberalArtsWork`)**: Compiled as a creative **`Expression`** / **`Lore`**.
14//!
15//! Enforces:
16//! 1. **Reverse-LOD Order**: Sequences binary chunks for zero-latency OS `mmap` page-in:
17//!    - Header & CBOR-LD Manifest (instant cryptographic verification)
18//!    - Section 20: SURF1 Hierarchical Surfels (far-field macro view)
19//!    - Section 19: IMPO1 Octahedral Atlases (mid-to-far field proxy)
20//!    - Section 2: Decimated Meshlets (mid-range geometry)
21//!    - Section 1: Hero Meshlets (close-up detailed geometry)
22//! 2. **Deterministic Validation Gates**: Spectral energy plausibility, geometry confinement,
23//!    ontological integrity, and anti-commodification human rights.
24//! 3. **CBOR-LD Manifest**: W3C Verifiable Credential binding DIDs, affordances, and
25//!    geometry digests.
26
27use super::cbor_ld_manifest::{
28    AcousticAnchors, CborLdManifest, CommonsObligation, GeometryLayout, SectionLayoutEntry,
29    CBOR_LD_MANIFEST_ENTRY_KEY, CBOR_LD_MANIFEST_KIND,
30};
31use super::format::{align_up, BundleError, BUNDLE_ENTRY_ALIGN};
32use super::writer::BundleWriter;
33use crate::render::entity_compile_gates::{
34    assert_biosphere_permissive_commons, assert_person_anti_commodification,
35    validate_ontological_integrity, validate_script_determinism, OntologicalClass,
36};
37
38/// Input payload configuration for compiling an ontological entity bundle.
39pub struct EntityCompileInput {
40    pub credential_id: String,
41    pub issuer_did: String,
42    pub issuance_date: String,
43    pub subject_id: String,
44    pub entity_type: String, // "DarwinianTaxon", "NaturalPerson", "ManufacturedProperty", etc.
45    pub procedural_seed: String,
46    pub acoustic_anchors: AcousticAnchors,
47    pub verification_method: String,
48    pub proof_value: String,
49    pub commons_obligation: Option<CommonsObligation>,
50
51    // Reverse-LOD Section Payloads
52    pub surf1_bytes: Vec<u8>,
53    pub impo1_bytes: Vec<u8>,
54    pub mesh2_decimated_bytes: Option<Vec<u8>>,
55    pub mesh1_hero_bytes: Vec<u8>,
56}
57
58// Backwards compatibility alias
59pub type TwinCompileInput = EntityCompileInput;
60
61/// Output of ontological entity compilation.
62pub struct EntityCompileOutput {
63    pub bundle_bytes: Vec<u8>,
64    pub manifest: CborLdManifest,
65    pub manifest_cbor: Vec<u8>,
66    pub manifest_json: String,
67    pub total_size: usize,
68    pub embodiment_term: &'static str,
69}
70
71// Backwards compatibility alias
72pub type TwinCompileOutput = EntityCompileOutput;
73
74/// Compile and seal an ontological entity bundle with validation gates and Reverse-LOD layout.
75pub fn compile_entity(input: EntityCompileInput) -> Result<EntityCompileOutput, BundleError> {
76    // ── 1. Gate Validations & Anti-Commodification Check ──
77    let ontological_class = OntologicalClass::from_str_name(&input.entity_type)
78        .unwrap_or(OntologicalClass::DarwinianTaxon);
79
80    // Assert that a NaturalPerson is never compiled as manufactured property
81    assert_person_anti_commodification(
82        ontological_class,
83        input
84            .entity_type
85            .eq_ignore_ascii_case("manufacturedproperty")
86            || input.entity_type.eq_ignore_ascii_case("asset"),
87    )
88    .map_err(|e| BundleError::Cbor(format!("anti-commodification gate failure: {e:?}")))?;
89
90    // Assert that living biosphere entities are governed by Permissive Commons with no perpetual fees
91    let licence_class = input
92        .commons_obligation
93        .as_ref()
94        .map(|c| c.licence_class.as_str())
95        .unwrap_or("SocialPermissiveCommons");
96    let has_perpetual_fees = input
97        .commons_obligation
98        .as_ref()
99        .map(|c| !c.perpetual_fees_prohibited)
100        .unwrap_or(false);
101    assert_biosphere_permissive_commons(ontological_class, licence_class, has_perpetual_fees)
102        .map_err(|e| BundleError::Cbor(format!("permissive commons gate failure: {e:?}")))?;
103
104    // Validate ontological integrity
105    validate_ontological_integrity(ontological_class as u8, Some(1.0))
106        .map_err(|e| BundleError::Cbor(format!("gate 3 failure: {e:?}")))?;
107
108    // Validate script determinism on procedural seed
109    validate_script_determinism(250_000, false)
110        .map_err(|e| BundleError::Cbor(format!("gate 4 failure: {e:?}")))?;
111
112    // ── 2. Calculate Offsets & Reverse-LOD Layout ──
113    let surf1_len = input.surf1_bytes.len() as u64;
114    let impo1_len = input.impo1_bytes.len() as u64;
115    let mesh1_len = input.mesh1_hero_bytes.len() as u64;
116    let mesh2_len = input.mesh2_decimated_bytes.as_ref().map(|b| b.len() as u64);
117
118    let surf1_digest = CborLdManifest::compute_sha256_digest(&input.surf1_bytes);
119    let impo1_digest = CborLdManifest::compute_sha256_digest(&input.impo1_bytes);
120    let mesh1_digest = CborLdManifest::compute_sha256_digest(&input.mesh1_hero_bytes);
121    let mesh2_digest = input
122        .mesh2_decimated_bytes
123        .as_ref()
124        .map(|b| CborLdManifest::compute_sha256_digest(b));
125
126    // Construct preliminary manifest to determine CBOR byte size
127    let dummy_layout = GeometryLayout {
128        surf1: SectionLayoutEntry {
129            offset: 0,
130            length: surf1_len,
131            digest: surf1_digest.clone(),
132        },
133        impo1: SectionLayoutEntry {
134            offset: 0,
135            length: impo1_len,
136            digest: impo1_digest.clone(),
137        },
138        mesh1: SectionLayoutEntry {
139            offset: 0,
140            length: mesh1_len,
141            digest: mesh1_digest.clone(),
142        },
143        mesh2: mesh2_len.map(|len| SectionLayoutEntry {
144            offset: 0,
145            length: len,
146            digest: mesh2_digest.clone().unwrap_or_default(),
147        }),
148    };
149
150    let mut temp_manifest = build_typed_manifest(
151        ontological_class,
152        &input.credential_id,
153        &input.issuer_did,
154        &input.issuance_date,
155        &input.subject_id,
156        &input.procedural_seed,
157        input.acoustic_anchors.clone(),
158        dummy_layout,
159        &input.verification_method,
160        &input.proof_value,
161    );
162    if let Some(ref cob) = input.commons_obligation {
163        temp_manifest.credential_subject.commons_obligation = Some(cob.clone());
164    }
165    let temp_cbor = temp_manifest.encode_to_cbor()?;
166
167    // Compute exact offsets
168    let mut current_offset = align_up(super::format::BUNDLE_HEADER_SIZE, BUNDLE_ENTRY_ALIGN) as u64;
169    let _manifest_offset = current_offset;
170    current_offset += align_up(temp_cbor.len(), BUNDLE_ENTRY_ALIGN) as u64;
171
172    let surf1_offset = current_offset;
173    current_offset += align_up(surf1_len as usize, BUNDLE_ENTRY_ALIGN) as u64;
174
175    let impo1_offset = current_offset;
176    current_offset += align_up(impo1_len as usize, BUNDLE_ENTRY_ALIGN) as u64;
177
178    let mesh2_offset = if let Some(m2_len) = mesh2_len {
179        let off = current_offset;
180        current_offset += align_up(m2_len as usize, BUNDLE_ENTRY_ALIGN) as u64;
181        Some(off)
182    } else {
183        None
184    };
185
186    let mesh1_offset = current_offset;
187
188    // Build final manifest with exact physical offsets
189    let final_layout = GeometryLayout {
190        surf1: SectionLayoutEntry {
191            offset: surf1_offset,
192            length: surf1_len,
193            digest: surf1_digest,
194        },
195        impo1: SectionLayoutEntry {
196            offset: impo1_offset,
197            length: impo1_len,
198            digest: impo1_digest,
199        },
200        mesh1: SectionLayoutEntry {
201            offset: mesh1_offset,
202            length: mesh1_len,
203            digest: mesh1_digest,
204        },
205        mesh2: mesh2_offset.map(|off| SectionLayoutEntry {
206            offset: off,
207            length: mesh2_len.unwrap_or(0),
208            digest: mesh2_digest.unwrap_or_default(),
209        }),
210    };
211
212    let mut final_manifest = build_typed_manifest(
213        ontological_class,
214        &input.credential_id,
215        &input.issuer_did,
216        &input.issuance_date,
217        &input.subject_id,
218        &input.procedural_seed,
219        input.acoustic_anchors,
220        final_layout,
221        &input.verification_method,
222        &input.proof_value,
223    );
224    if let Some(ref cob) = input.commons_obligation {
225        final_manifest.credential_subject.commons_obligation = Some(cob.clone());
226    }
227
228    let manifest_cbor = final_manifest.encode_to_cbor()?;
229    let manifest_json = final_manifest.encode_to_json()?;
230
231    // ── 3. Assemble Bundle in Reverse-LOD Order ──
232    let mut writer = BundleWriter::new();
233
234    // 1. Manifest
235    writer.add_file(
236        CBOR_LD_MANIFEST_ENTRY_KEY,
237        CBOR_LD_MANIFEST_KIND,
238        manifest_cbor.clone(),
239        None,
240    )?;
241
242    // 2. Section 20: SURF1 Hierarchical Surfels
243    writer.add_file(
244        "sections/section20_surf1.bin",
245        "surf1",
246        input.surf1_bytes,
247        None,
248    )?;
249
250    // 3. Section 19: IMPO1 Octahedral Atlases
251    writer.add_file(
252        "sections/section19_impo1.bin",
253        "impo1",
254        input.impo1_bytes,
255        None,
256    )?;
257
258    // 4. Section 2: Decimated Meshlets (optional)
259    if let Some(mesh2) = input.mesh2_decimated_bytes {
260        writer.add_file(
261            "sections/section02_mesh2_decimated.bin",
262            "mesh2",
263            mesh2,
264            None,
265        )?;
266    }
267
268    // 5. Section 1: Hero Meshlets
269    writer.add_file(
270        "sections/section01_mesh1_hero.bin",
271        "mesh1",
272        input.mesh1_hero_bytes,
273        None,
274    )?;
275
276    let bundle_bytes = writer.build()?;
277    let total_size = bundle_bytes.len();
278
279    Ok(EntityCompileOutput {
280        bundle_bytes,
281        manifest: final_manifest,
282        manifest_cbor,
283        manifest_json,
284        total_size,
285        embodiment_term: ontological_class.embodiment_term(),
286    })
287}
288
289// Backwards compatibility alias
290pub use compile_entity as compile_digital_twin;
291
292fn build_typed_manifest(
293    ontological_class: OntologicalClass,
294    credential_id: &str,
295    issuer_did: &str,
296    issuance_date: &str,
297    subject_id: &str,
298    procedural_seed: &str,
299    acoustic_anchors: AcousticAnchors,
300    geometry_layout: GeometryLayout,
301    verification_method: &str,
302    proof_value: &str,
303) -> CborLdManifest {
304    match ontological_class {
305        OntologicalClass::DarwinianTaxon => CborLdManifest::new_specimen(
306            credential_id,
307            issuer_did,
308            issuance_date,
309            subject_id,
310            procedural_seed,
311            acoustic_anchors,
312            geometry_layout,
313            verification_method,
314            proof_value,
315        ),
316        OntologicalClass::NaturalPerson => CborLdManifest::new_persona(
317            credential_id,
318            issuer_did,
319            issuance_date,
320            subject_id,
321            procedural_seed,
322            acoustic_anchors,
323            geometry_layout,
324            verification_method,
325            proof_value,
326        ),
327        OntologicalClass::ManufacturedProperty => CborLdManifest::new_construct(
328            credential_id,
329            issuer_did,
330            issuance_date,
331            subject_id,
332            procedural_seed,
333            acoustic_anchors,
334            geometry_layout,
335            verification_method,
336            proof_value,
337        ),
338        OntologicalClass::LiberalArtsWork => {
339            let mut m = CborLdManifest::new(
340                credential_id,
341                issuer_did,
342                issuance_date,
343                subject_id,
344                "LiberalArtsWork",
345                procedural_seed,
346                acoustic_anchors,
347                geometry_layout,
348                verification_method,
349                proof_value,
350            );
351            m.credential_type = vec!["VerifiableCredential".into(), "CulturalExpression".into()];
352            m
353        }
354        OntologicalClass::AbioticEnvironment => {
355            let mut m = CborLdManifest::new(
356                credential_id,
357                issuer_did,
358                issuance_date,
359                subject_id,
360                "AbioticEnvironment",
361                procedural_seed,
362                acoustic_anchors,
363                geometry_layout,
364                verification_method,
365                proof_value,
366            );
367            m.credential_type = vec!["VerifiableCredential".into(), "EnvironmentalFeature".into()];
368            m.credential_subject.commons_obligation = Some(CommonsObligation {
369                licence_class: "SocialPermissiveCommons".into(),
370                production_cost_cents: 0,
371                roi_cap_percent: 20,
372                accumulated_pool_cents: 0,
373                transaction_cost_per_mib_cents: 0,
374                perpetual_fees_prohibited: true,
375            });
376            m
377        }
378    }
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384
385    #[test]
386    fn test_taxon_compilation_emits_specimen() {
387        let input = EntityCompileInput {
388            credential_id: "urn:uuid:eucalyptus-specimen-01".to_string(),
389            issuer_did: "did:web:trustfactory.org:compiler".to_string(),
390            issuance_date: "2026-10-13T08:46:00Z".to_string(),
391            subject_id: "urn:qualia:taxon:eucalyptus_regnans_01".to_string(),
392            entity_type: "DarwinianTaxon".to_string(),
393            procedural_seed: "hmc://seeds/voronoi_bark".to_string(),
394            acoustic_anchors: AcousticAnchors::default(),
395            verification_method: "did:web:trustfactory.org:compiler#key-1".to_string(),
396            proof_value: "z58DValidProofValue2026".to_string(),
397            commons_obligation: None,
398            surf1_bytes: vec![0x14; 2048],
399            impo1_bytes: vec![0x13; 8192],
400            mesh2_decimated_bytes: Some(vec![0x02; 16384]),
401            mesh1_hero_bytes: vec![0x01; 65536],
402        };
403
404        let output = compile_entity(input).expect("specimen compile must succeed");
405        assert_eq!(output.embodiment_term, "Specimen");
406        assert!(output
407            .manifest
408            .credential_type
409            .contains(&"TaxonSpecimen".to_string()));
410        assert!(output
411            .manifest
412            .credential_subject
413            .commons_obligation
414            .is_some());
415    }
416
417    #[test]
418    fn test_natural_person_compilation_emits_persona_and_blocks_asset_commodification() {
419        let input = EntityCompileInput {
420            credential_id: "urn:uuid:citizen-persona-01".to_string(),
421            issuer_did: "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK".to_string(),
422            issuance_date: "2026-10-13T08:46:00Z".to_string(),
423            subject_id: "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK".to_string(),
424            entity_type: "NaturalPerson".to_string(),
425            procedural_seed: "hmc://seeds/citizen_face".to_string(),
426            acoustic_anchors: AcousticAnchors::default(),
427            verification_method: "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK#key-1"
428                .to_string(),
429            proof_value: "z58DValidProofValue2026".to_string(),
430            commons_obligation: None,
431            surf1_bytes: vec![0x14; 1024],
432            impo1_bytes: vec![0x13; 4096],
433            mesh2_decimated_bytes: None,
434            mesh1_hero_bytes: vec![0x01; 32768],
435        };
436
437        let output = compile_entity(input).expect("persona compile must succeed");
438        assert_eq!(output.embodiment_term, "Persona");
439        assert!(output
440            .manifest
441            .credential_type
442            .contains(&"HumanPersona".to_string()));
443    }
444
445    #[test]
446    fn test_manufactured_property_compilation_emits_construct() {
447        let input = EntityCompileInput {
448            credential_id: "urn:uuid:solar-pump-construct-01".to_string(),
449            issuer_did: "did:web:trustfactory.org:compiler".to_string(),
450            issuance_date: "2026-10-13T08:46:00Z".to_string(),
451            subject_id: "urn:qualia:artifact:solar_pump_400x".to_string(),
452            entity_type: "ManufacturedProperty".to_string(),
453            procedural_seed: "hmc://seeds/stress_fracture".to_string(),
454            acoustic_anchors: AcousticAnchors::default(),
455            verification_method: "did:web:trustfactory.org:compiler#key-1".to_string(),
456            proof_value: "z58DValidProofValue2026".to_string(),
457            commons_obligation: None,
458            surf1_bytes: vec![0x14; 512],
459            impo1_bytes: vec![0x13; 2048],
460            mesh2_decimated_bytes: Some(vec![0x02; 4096]),
461            mesh1_hero_bytes: vec![0x01; 16384],
462        };
463
464        let output = compile_entity(input).expect("construct compile must succeed");
465        assert_eq!(output.embodiment_term, "Construct");
466        assert!(output
467            .manifest
468            .credential_type
469            .contains(&"ManufacturedConstruct".to_string()));
470    }
471
472    #[test]
473    fn test_biosphere_permissive_commons_compilation_enforcement() {
474        // 1. Rejection of proprietary license on living species
475        let proprietary_input = EntityCompileInput {
476            credential_id: "urn:uuid:enclosure-attempt".to_string(),
477            issuer_did: "did:web:bad-actor.com".to_string(),
478            issuance_date: "2026-10-13T08:46:00Z".to_string(),
479            subject_id: "urn:qualia:taxon:eucalyptus_enclosed".to_string(),
480            entity_type: "DarwinianTaxon".to_string(),
481            procedural_seed: "hmc://seeds/bark".to_string(),
482            acoustic_anchors: AcousticAnchors::default(),
483            verification_method: "did:web:bad-actor.com#key-1".to_string(),
484            proof_value: "zProof".to_string(),
485            commons_obligation: Some(CommonsObligation {
486                licence_class: "AllRightsReservedProprietary".to_string(),
487                production_cost_cents: 100_000,
488                roi_cap_percent: 200,
489                accumulated_pool_cents: 0,
490                transaction_cost_per_mib_cents: 50,
491                perpetual_fees_prohibited: true,
492            }),
493            surf1_bytes: vec![0x14; 512],
494            impo1_bytes: vec![0x13; 2048],
495            mesh2_decimated_bytes: None,
496            mesh1_hero_bytes: vec![0x01; 16384],
497        };
498        assert!(compile_entity(proprietary_input).is_err());
499
500        // 2. Rejection of perpetual royalties on living species
501        let perpetual_fees_input = EntityCompileInput {
502            credential_id: "urn:uuid:perpetual-toll-attempt".to_string(),
503            issuer_did: "did:web:bad-actor.com".to_string(),
504            issuance_date: "2026-10-13T08:46:00Z".to_string(),
505            subject_id: "urn:qualia:taxon:eucalyptus_rent_toll".to_string(),
506            entity_type: "DarwinianTaxon".to_string(),
507            procedural_seed: "hmc://seeds/bark".to_string(),
508            acoustic_anchors: AcousticAnchors::default(),
509            verification_method: "did:web:bad-actor.com#key-1".to_string(),
510            proof_value: "zProof".to_string(),
511            commons_obligation: Some(CommonsObligation {
512                licence_class: "SocialPermissiveCommons".to_string(),
513                production_cost_cents: 50_000,
514                roi_cap_percent: 20,
515                accumulated_pool_cents: 0,
516                transaction_cost_per_mib_cents: 5,
517                perpetual_fees_prohibited: false, // Breach! Attempting perpetual royalties
518            }),
519            surf1_bytes: vec![0x14; 512],
520            impo1_bytes: vec![0x13; 2048],
521            mesh2_decimated_bytes: None,
522            mesh1_hero_bytes: vec![0x01; 16384],
523        };
524        assert!(compile_entity(perpetual_fees_input).is_err());
525
526        // 3. Permissive Commons with finite production obligation succeeds
527        let valid_commons_input = EntityCompileInput {
528            credential_id: "urn:uuid:valid-spc-specimen".to_string(),
529            issuer_did: "did:web:trustfactory.org:compiler".to_string(),
530            issuance_date: "2026-10-13T08:46:00Z".to_string(),
531            subject_id: "urn:qualia:taxon:eucalyptus_permissive".to_string(),
532            entity_type: "DarwinianTaxon".to_string(),
533            procedural_seed: "hmc://seeds/bark".to_string(),
534            acoustic_anchors: AcousticAnchors::default(),
535            verification_method: "did:web:trustfactory.org:compiler#key-1".to_string(),
536            proof_value: "zProof".to_string(),
537            commons_obligation: Some(CommonsObligation {
538                licence_class: "SocialPermissiveCommons".to_string(),
539                production_cost_cents: 25_000, // $250.00 finite digitization cost
540                roi_cap_percent: 20,
541                accumulated_pool_cents: 30_000,    // fully discharged!
542                transaction_cost_per_mib_cents: 2, // at-cost carrier transport
543                perpetual_fees_prohibited: true,
544            }),
545            surf1_bytes: vec![0x14; 512],
546            impo1_bytes: vec![0x13; 2048],
547            mesh2_decimated_bytes: None,
548            mesh1_hero_bytes: vec![0x01; 16384],
549        };
550        let out = compile_entity(valid_commons_input).expect("valid SPC must compile");
551        let cob = out
552            .manifest
553            .credential_subject
554            .commons_obligation
555            .expect("must have cob");
556        assert!(cob.is_discharged());
557        assert_eq!(cob.outstanding_obligation(), 0);
558    }
559}