Skip to main content

qualia_core_db/entity_view/
entity_ontologies.rs

1//! Entity Behavioral & Affordance Ontologies for Digital Twins.
2//!
3//! Digital twin representations model entities across distinct ontological domains:
4//! - **Darwinian / Ecological**: Natural organisms, species, and ecological actors governed
5//!   by evolutionary biology and life history (not moral or legal sovereigns).
6//! - **Manufactured Property**: Engineered artifacts, vehicles, machinery, and constructed
7//!   infrastructure subject to property rights, operational ratings, and maintenance regimes.
8//! - **Abiotic Aggregates**: Geological, soil, hydrological, and atmospheric systems.
9//! - **Liberal Arts & Scientific Works**: The authored descriptive model itself (3D geometry,
10//!   semantic graphs, audio, textures) as an expressive creative and scientific work.
11//!
12//! This module declares an entity's intrinsic operational profile:
13//! - Discoverable affordances (`wot:ActionAffordance`, `schema:Action`)
14//! - Machine-readable preconditions (required state/inventory/energy/biomass/permissions)
15//! - State transition effects (energy delta, wear delta, damage delta, animation clips)
16//! - Dynamic AI tool manifest generation (standard JSON schema for LLMs and autonomous agents)
17//! - Deterministic, bounded intent evaluation emitting 48-byte `NQuin` action records within
18//!   the 42MB Sentinel.
19
20use serde::{Deserialize, Serialize};
21
22use crate::entity_view::entity_id::EntityId;
23use crate::entity_view::observer::ObserverStatus;
24use crate::q_hash;
25use crate::NQuin;
26
27/// Ontological origin and domain of the represented entity.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
29#[serde(rename_all = "snake_case")]
30#[repr(u8)]
31pub enum OntologicalOrigin {
32    /// Darwinian organism or evolutionary taxon (part of the natural world / biosphere).
33    #[default]
34    DarwinianTaxon = 0,
35    /// Manufactured physical property, engineering asset, or fabricated machine.
36    ManufacturedProperty = 1,
37    /// Abiotic physical/environmental feature (rock, water body, terrain aggregate).
38    AbioticEnvironment = 2,
39    /// Expressive, liberal arts, cultural heritage, or open scientific dataset work.
40    LiberalArtsWork = 3,
41}
42
43/// Biological or mechanical lifecycle stage of an entity.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
45#[serde(rename_all = "snake_case")]
46#[repr(u8)]
47pub enum LifecycleStage {
48    /// Botanical / fungal seed, spore, or dormant embryonic stage.
49    SeedOrSpore = 0,
50    /// Developing juvenile, nymph, larva, seedling, or sapling.
51    Juvenile = 1,
52    /// Morphologically mature, fully functional organism.
53    #[default]
54    Adult = 2,
55    /// Post-reproductive or aged organism exhibiting degradation.
56    Senescent = 3,
57    /// Organic remains undergoing decomposition.
58    Deceased = 4,
59    /// Assembled / fabricated mechanical or architectural asset before commissioning.
60    Manufactured = 5,
61    /// Commissioned, fully operational constructed entity.
62    Operational = 6,
63    /// Degraded operational state requiring maintenance or repair.
64    Degraded = 7,
65    /// Decommissioned, scrap, or inert salvage.
66    Decommissioned = 8,
67}
68
69impl LifecycleStage {
70    /// Decode a `u8` into a lifecycle stage; out-of-range values default to
71    /// `Adult`.
72    pub const fn from_u8(raw: u8) -> Self {
73        match raw {
74            0 => Self::SeedOrSpore,
75            1 => Self::Juvenile,
76            2 => Self::Adult,
77            3 => Self::Senescent,
78            4 => Self::Deceased,
79            5 => Self::Manufactured,
80            6 => Self::Operational,
81            7 => Self::Degraded,
82            8 => Self::Decommissioned,
83            _ => Self::Adult,
84        }
85    }
86}
87
88/// Category of an affordance for behavioral dispatch and UI classification.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
90#[serde(rename_all = "snake_case")]
91#[repr(u8)]
92pub enum AffordanceCategory {
93    /// Ingestion, resting, reproduction, phototropism, respiration.
94    #[default]
95    Biological = 0,
96    /// Locomotion, manipulation, collision response, physical carrying.
97    Physical = 1,
98    /// Communication, herding, vocalization, mutualism, grooming, trading.
99    Social = 2,
100    /// Lubrication, fueling, pruning, weeding, structural repair, parts replacement.
101    Maintenance = 3,
102    /// Non-invasive sensor probing, sampling, telemetry read, spectral scan.
103    Sensing = 4,
104    /// Deontic admission, quarantine, guardianship, lease or ownership transfer.
105    Governance = 5,
106}
107
108impl AffordanceCategory {
109    /// Decode a `u8` into an affordance category; out-of-range values
110    /// default to `Biological`.
111    pub const fn from_u8(raw: u8) -> Self {
112        match raw {
113            0 => Self::Biological,
114            1 => Self::Physical,
115            2 => Self::Social,
116            3 => Self::Maintenance,
117            4 => Self::Sensing,
118            5 => Self::Governance,
119            _ => Self::Biological,
120        }
121    }
122}
123
124/// Operational preconditions that must be satisfied before an affordance can be invoked.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
126pub struct ActionPrecondition {
127    /// Minimum energy/biomass level in parts-per-thousand (0..1000).
128    pub min_energy_permill: u16,
129    /// Maximum allowed physical damage before affordance is disabled (0..1000).
130    pub max_damage_permill: u16,
131    /// Minimum hydration level required (0..1000).
132    pub min_hydration_permill: u16,
133    /// Maximum wear level allowed (0..1000).
134    pub max_wear_permill: u16,
135    /// Optional hash of required tool or capability (0 = none).
136    pub required_capability_hash: u64,
137    /// Minimum observer status / role required to invoke (e.g. Principal or Steward).
138    pub min_observer_status: ObserverStatus,
139}
140
141impl Default for ActionPrecondition {
142    fn default() -> Self {
143        Self {
144            min_energy_permill: 0,
145            max_damage_permill: 1000,
146            min_hydration_permill: 0,
147            max_wear_permill: 1000,
148            required_capability_hash: 0,
149            min_observer_status: ObserverStatus::Public,
150        }
151    }
152}
153
154/// State transition effects emitted upon successful execution of an affordance.
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
156pub struct ActionEffect {
157    /// Energy change delta (-1000..+1000 permill).
158    pub energy_delta: i16,
159    /// Damage change delta (-1000..+1000 permill, negative means repaired).
160    pub damage_delta: i16,
161    /// Hydration change delta.
162    pub hydration_delta: i16,
163    /// Wear change delta (positive means accrued wear).
164    pub wear_delta: i16,
165    /// Hash of the event topic or produced resource emitted to the session journal.
166    pub emitted_topic_hash: u64,
167    /// Visual/skeletal animation clip ID to trigger (0 = none).
168    pub animation_clip_id: u32,
169}
170
171/// A discoverable affordance exposed by a digital twin entity.
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173pub struct ActionAffordance {
174    /// Stable 64-bit identifier (usually `q_hash(action_name)`).
175    pub action_id: u64,
176    /// Machine-readable identifier (e.g. `"feed"`, `"prune"`, `"start_pump"`, `"inspect"`).
177    pub name: String,
178    /// Human and LLM readable semantic documentation of what the action accomplishes.
179    pub description: String,
180    /// Categorical taxonomic grouping.
181    pub category: AffordanceCategory,
182    /// Preconditions guarding execution.
183    pub preconditions: ActionPrecondition,
184    /// Intended state effects upon execution.
185    pub effects: ActionEffect,
186    /// JSON Schema defining parameters for LLM tool calling (e.g. `{"type":"object",...}`).
187    pub input_schema_json: String,
188}
189
190impl ActionAffordance {
191    /// Create an affordance with default (permissive) preconditions/effects
192    /// and an empty object input schema; `action_id` is `q_hash(name)`.
193    pub fn new(
194        name: impl Into<String>,
195        description: impl Into<String>,
196        category: AffordanceCategory,
197    ) -> Self {
198        let name_str = name.into();
199        let action_id = q_hash(&name_str);
200        Self {
201            action_id,
202            name: name_str,
203            description: description.into(),
204            category,
205            preconditions: ActionPrecondition::default(),
206            effects: ActionEffect::default(),
207            input_schema_json: "{\"type\":\"object\",\"properties\":{}}".to_string(),
208        }
209    }
210}
211
212/// Entity behavioral and affordance ontology profile for an entity instance.
213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
214pub struct EntityOntology {
215    /// Entity ID of the referent digital twin.
216    pub entity_id: EntityId,
217    /// Ontological origin (Darwinian taxon, manufactured property, abiotic aggregate, liberal arts work).
218    pub origin: OntologicalOrigin,
219    /// IRI or ontological class (e.g. `qualia:EucalyptusRegnans`, `qualia:CentrifugalPump`).
220    pub taxon_or_system_iri: String,
221    /// Current developmental or functional lifecycle stage.
222    pub stage: LifecycleStage,
223    /// Current internal energy / biomass reserve (0..1000).
224    pub energy_permill: u16,
225    /// Current damage / degradation level (0..1000).
226    pub damage_permill: u16,
227    /// Current hydration or fluid reserve (0..1000).
228    pub hydration_permill: u16,
229    /// Current mechanical / biological wear level (0..1000).
230    pub wear_permill: u16,
231    /// List of discoverable affordances published by this entity.
232    pub affordances: Vec<ActionAffordance>,
233}
234
235/// Compatibility type alias.
236pub type PersonalOntology = EntityOntology;
237
238impl EntityOntology {
239    /// Create a healthy adult `DarwinianTaxon` profile (full energy and
240    /// hydration, no damage/wear, no affordances).
241    pub fn new(entity_id: EntityId, taxon_or_system_iri: impl Into<String>) -> Self {
242        Self {
243            entity_id,
244            origin: OntologicalOrigin::DarwinianTaxon,
245            taxon_or_system_iri: taxon_or_system_iri.into(),
246            stage: LifecycleStage::Adult,
247            energy_permill: 1000,
248            damage_permill: 0,
249            hydration_permill: 1000,
250            wear_permill: 0,
251            affordances: Vec::new(),
252        }
253    }
254
255    /// Add an affordance to the entity ontology.
256    pub fn add_affordance(&mut self, affordance: ActionAffordance) {
257        if let Some(pos) = self
258            .affordances
259            .iter()
260            .position(|a| a.action_id == affordance.action_id)
261        {
262            self.affordances[pos] = affordance;
263        } else {
264            self.affordances.push(affordance);
265        }
266    }
267
268    /// Generate a standard JSON tool manifest compatible with LLM function-calling APIs
269    /// (OpenAI, Anthropic, Gemini, local Ollama/vLLM) for AI agent triggering.
270    pub fn export_ai_tools_json(&self) -> String {
271        let mut out = String::from("[\n");
272        for (i, aff) in self.affordances.iter().enumerate() {
273            if i > 0 {
274                out.push_str(",\n");
275            }
276            out.push_str("  {\n");
277            out.push_str("    \"type\": \"function\",\n");
278            out.push_str("    \"function\": {\n");
279            out.push_str(&format!("      \"name\": \"{}\",\n", aff.name));
280            out.push_str(&format!(
281                "      \"description\": \"{}\",\n",
282                aff.description.replace('"', "\\\"")
283            ));
284            out.push_str(&format!(
285                "      \"parameters\": {}\n",
286                aff.input_schema_json
287            ));
288            out.push_str("    }\n");
289            out.push_str("  }");
290        }
291        out.push_str("\n]");
292        out
293    }
294
295    /// Evaluate an incoming action intent against this entity ontology.
296    /// Pure, zero-heap evaluation that validates preconditions, enforces permissions,
297    /// updates internal state registers, and generates an auditable 48-byte `NQuin`.
298    pub fn evaluate_intent(
299        &self,
300        intent: &ActionIntent,
301        caller_status: ObserverStatus,
302    ) -> Result<ActionEvaluationVerdict, IntentError> {
303        let aff = self
304            .affordances
305            .iter()
306            .find(|a| a.action_id == intent.action_id)
307            .ok_or(IntentError::AffordanceNotFound {
308                action_id: intent.action_id,
309            })?;
310
311        // 1. Permission check
312        if (caller_status as u8) > (aff.preconditions.min_observer_status as u8) {
313            return Err(IntentError::PermissionDenied {
314                required: aff.preconditions.min_observer_status,
315                provided: caller_status,
316            });
317        }
318
319        // 2. Preconditions check
320        if self.energy_permill < aff.preconditions.min_energy_permill {
321            return Err(IntentError::InsufficientEnergy {
322                have: self.energy_permill,
323                need: aff.preconditions.min_energy_permill,
324            });
325        }
326        if self.damage_permill > aff.preconditions.max_damage_permill {
327            return Err(IntentError::ExcessiveDamage {
328                have: self.damage_permill,
329                max_allowed: aff.preconditions.max_damage_permill,
330            });
331        }
332        if self.hydration_permill < aff.preconditions.min_hydration_permill {
333            return Err(IntentError::InsufficientHydration {
334                have: self.hydration_permill,
335                need: aff.preconditions.min_hydration_permill,
336            });
337        }
338        if self.wear_permill > aff.preconditions.max_wear_permill {
339            return Err(IntentError::ExcessiveWear {
340                have: self.wear_permill,
341                max_allowed: aff.preconditions.max_wear_permill,
342            });
343        }
344
345        // 3. Compute updated state registers
346        let new_energy = ((self.energy_permill as i32) + (aff.effects.energy_delta as i32))
347            .clamp(0, 1000) as u16;
348        let new_damage = ((self.damage_permill as i32) + (aff.effects.damage_delta as i32))
349            .clamp(0, 1000) as u16;
350        let new_hydration = ((self.hydration_permill as i32) + (aff.effects.hydration_delta as i32))
351            .clamp(0, 1000) as u16;
352        let new_wear =
353            ((self.wear_permill as i32) + (aff.effects.wear_delta as i32)).clamp(0, 1000) as u16;
354
355        // 4. Construct 48-byte Super-Quin representing the executed action event
356        let subject = self.entity_id.0;
357        let predicate = aff.action_id;
358        let object = intent.parameters_hash;
359        let context = intent.caller_did_hash;
360        // Metadata: PermissiveCommons lane (0x01) + Lamport clock in lower 32 bits
361        let metadata = (0x01u64 << 61) | ((intent.lamport_clock as u64) & 0xFFFF_FFFF);
362        // Universal Quin XOR fold parity
363        let parity = subject ^ predicate ^ object ^ context ^ metadata;
364
365        let record_quin = NQuin {
366            subject,
367            predicate,
368            object,
369            context,
370            metadata,
371            parity,
372        };
373
374        Ok(ActionEvaluationVerdict {
375            new_energy,
376            new_damage,
377            new_hydration,
378            new_wear,
379            animation_clip_id: aff.effects.animation_clip_id,
380            emitted_topic_hash: aff.effects.emitted_topic_hash,
381            record_quin,
382        })
383    }
384
385    /// Serialise the ontology's affordance structure into caller-supplied `NQuin` slices.
386    /// Returns the number of quins written. Zero-heap operation.
387    pub fn to_nquins(&self, out: &mut [NQuin]) -> Result<usize, IntentError> {
388        let needed = 1 + self.affordances.len();
389        if out.len() < needed {
390            return Err(IntentError::OutputBufferTooSmall {
391                needed,
392                have: out.len(),
393            });
394        }
395
396        let taxon_hash = q_hash(&self.taxon_or_system_iri);
397        let entity_sub = self.entity_id.0;
398
399        // Base quin: Entity is-a Taxon
400        let is_a_pred = q_hash("rdf:type");
401        let meta_clock = 1u64;
402        let p0 = entity_sub ^ is_a_pred ^ taxon_hash ^ 0 ^ meta_clock;
403        out[0] = NQuin {
404            subject: entity_sub,
405            predicate: is_a_pred,
406            object: taxon_hash,
407            context: (self.stage as u64) << 56,
408            metadata: meta_clock,
409            parity: p0,
410        };
411
412        let has_affordance_pred = q_hash("wot:hasActionAffordance");
413        for (i, aff) in self.affordances.iter().enumerate() {
414            let cat_byte = aff.category as u64;
415            let ctx = (cat_byte << 56) | (aff.preconditions.min_observer_status as u64);
416            let meta = ((aff.effects.animation_clip_id as u64) << 32)
417                | (aff.preconditions.min_energy_permill as u64);
418            let parity = entity_sub ^ has_affordance_pred ^ aff.action_id ^ ctx ^ meta;
419            out[1 + i] = NQuin {
420                subject: entity_sub,
421                predicate: has_affordance_pred,
422                object: aff.action_id,
423                context: ctx,
424                metadata: meta,
425                parity,
426            };
427        }
428
429        Ok(needed)
430    }
431}
432
433/// An action invocation intent submitted by an AI agent or player controller.
434#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
435pub struct ActionIntent {
436    /// DID hash of the acting agent or player.
437    pub caller_did_hash: u64,
438    /// Target entity DID hash.
439    pub target_entity_hash: u64,
440    /// Action affordance ID being invoked.
441    pub action_id: u64,
442    /// Hash of input parameter payload (or 0 for parameterless actions).
443    pub parameters_hash: u64,
444    /// Lamport clock tick of the caller's session.
445    pub lamport_clock: u32,
446}
447
448/// The result of a successfully validated and executed action intent.
449#[derive(Debug, Clone, Copy, PartialEq, Eq)]
450pub struct ActionEvaluationVerdict {
451    pub new_energy: u16,
452    pub new_damage: u16,
453    pub new_hydration: u16,
454    pub new_wear: u16,
455    pub animation_clip_id: u32,
456    pub emitted_topic_hash: u64,
457    pub record_quin: NQuin,
458}
459
460/// Errors returned when an action intent cannot be admitted or executed.
461#[derive(Debug, Clone, PartialEq, Eq)]
462pub enum IntentError {
463    AffordanceNotFound {
464        action_id: u64,
465    },
466    PermissionDenied {
467        required: ObserverStatus,
468        provided: ObserverStatus,
469    },
470    InsufficientEnergy {
471        have: u16,
472        need: u16,
473    },
474    ExcessiveDamage {
475        have: u16,
476        max_allowed: u16,
477    },
478    InsufficientHydration {
479        have: u16,
480        need: u16,
481    },
482    ExcessiveWear {
483        have: u16,
484        max_allowed: u16,
485    },
486    MissingCapability {
487        required_hash: u64,
488    },
489    OutputBufferTooSmall {
490        needed: usize,
491        have: usize,
492    },
493}
494
495impl std::fmt::Display for IntentError {
496    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
497        match self {
498            Self::AffordanceNotFound { action_id } => {
499                write!(f, "affordance {action_id:#018x} not found on entity")
500            }
501            Self::PermissionDenied { required, provided } => {
502                write!(
503                    f,
504                    "permission denied: required {required:?}, got {provided:?}"
505                )
506            }
507            Self::InsufficientEnergy { have, need } => {
508                write!(f, "insufficient energy: have {have}‰, need {need}‰")
509            }
510            Self::ExcessiveDamage { have, max_allowed } => {
511                write!(
512                    f,
513                    "excessive damage: have {have}‰, max allowed {max_allowed}‰"
514                )
515            }
516            Self::InsufficientHydration { have, need } => {
517                write!(f, "insufficient hydration: have {have}‰, need {need}‰")
518            }
519            Self::ExcessiveWear { have, max_allowed } => {
520                write!(
521                    f,
522                    "excessive wear: have {have}‰, max allowed {max_allowed}‰"
523                )
524            }
525            Self::MissingCapability { required_hash } => {
526                write!(f, "missing required capability {required_hash:#018x}")
527            }
528            Self::OutputBufferTooSmall { needed, have } => {
529                write!(f, "output buffer too small: need {needed}, have {have}")
530            }
531        }
532    }
533}
534
535impl std::error::Error for IntentError {}
536
537#[cfg(test)]
538mod tests {
539    use super::*;
540
541    #[test]
542    fn entity_ontology_evaluates_intent_and_emits_valid_quin() {
543        let entity_id = EntityId::from_u64(0x1234_5678);
544        let mut onto = EntityOntology::new(entity_id, "qualia:EucalyptusRegnans");
545        onto.energy_permill = 800;
546        onto.damage_permill = 50;
547
548        let mut prune = ActionAffordance::new(
549            "prune",
550            "Remove dead or hazardous foliage to stimulate growth",
551            AffordanceCategory::Maintenance,
552        );
553        prune.preconditions.min_observer_status = ObserverStatus::Steward;
554        prune.preconditions.min_energy_permill = 200;
555        prune.effects.energy_delta = -100;
556        prune.effects.damage_delta = -20;
557        prune.effects.animation_clip_id = 42;
558        onto.add_affordance(prune);
559
560        let intent = ActionIntent {
561            caller_did_hash: 0xABCD_EF01,
562            target_entity_hash: entity_id.0,
563            action_id: q_hash("prune"),
564            parameters_hash: 0,
565            lamport_clock: 10,
566        };
567
568        // Unauthorized caller (Public < Steward)
569        let fail = onto.evaluate_intent(&intent, ObserverStatus::Public);
570        assert!(matches!(fail, Err(IntentError::PermissionDenied { .. })));
571
572        // Authorized caller (Steward)
573        let verdict = onto
574            .evaluate_intent(&intent, ObserverStatus::Steward)
575            .unwrap();
576        assert_eq!(verdict.new_energy, 700);
577        assert_eq!(verdict.new_damage, 30);
578        assert_eq!(verdict.animation_clip_id, 42);
579
580        // Verify emitted NQuin parity
581        let q = &verdict.record_quin;
582        let expected_parity = q.subject ^ q.predicate ^ q.object ^ q.context ^ q.metadata;
583        assert_eq!(q.parity, expected_parity);
584
585        // AI tool export contains JSON function definition
586        let tools_json = onto.export_ai_tools_json();
587        assert!(tools_json.contains("\"name\": \"prune\""));
588        assert!(tools_json.contains("\"type\": \"function\""));
589
590        // NQuin export fits within bounded caller array
591        let mut buffer = [NQuin::default(); 8];
592        let count = onto.to_nquins(&mut buffer).unwrap();
593        assert_eq!(count, 2);
594    }
595}