1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
29#[serde(rename_all = "snake_case")]
30#[repr(u8)]
31pub enum OntologicalOrigin {
32 #[default]
34 DarwinianTaxon = 0,
35 ManufacturedProperty = 1,
37 AbioticEnvironment = 2,
39 LiberalArtsWork = 3,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
45#[serde(rename_all = "snake_case")]
46#[repr(u8)]
47pub enum LifecycleStage {
48 SeedOrSpore = 0,
50 Juvenile = 1,
52 #[default]
54 Adult = 2,
55 Senescent = 3,
57 Deceased = 4,
59 Manufactured = 5,
61 Operational = 6,
63 Degraded = 7,
65 Decommissioned = 8,
67}
68
69impl LifecycleStage {
70 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
90#[serde(rename_all = "snake_case")]
91#[repr(u8)]
92pub enum AffordanceCategory {
93 #[default]
95 Biological = 0,
96 Physical = 1,
98 Social = 2,
100 Maintenance = 3,
102 Sensing = 4,
104 Governance = 5,
106}
107
108impl AffordanceCategory {
109 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
126pub struct ActionPrecondition {
127 pub min_energy_permill: u16,
129 pub max_damage_permill: u16,
131 pub min_hydration_permill: u16,
133 pub max_wear_permill: u16,
135 pub required_capability_hash: u64,
137 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
156pub struct ActionEffect {
157 pub energy_delta: i16,
159 pub damage_delta: i16,
161 pub hydration_delta: i16,
163 pub wear_delta: i16,
165 pub emitted_topic_hash: u64,
167 pub animation_clip_id: u32,
169}
170
171#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173pub struct ActionAffordance {
174 pub action_id: u64,
176 pub name: String,
178 pub description: String,
180 pub category: AffordanceCategory,
182 pub preconditions: ActionPrecondition,
184 pub effects: ActionEffect,
186 pub input_schema_json: String,
188}
189
190impl ActionAffordance {
191 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
214pub struct EntityOntology {
215 pub entity_id: EntityId,
217 pub origin: OntologicalOrigin,
219 pub taxon_or_system_iri: String,
221 pub stage: LifecycleStage,
223 pub energy_permill: u16,
225 pub damage_permill: u16,
227 pub hydration_permill: u16,
229 pub wear_permill: u16,
231 pub affordances: Vec<ActionAffordance>,
233}
234
235pub type PersonalOntology = EntityOntology;
237
238impl EntityOntology {
239 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 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 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 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 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 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 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 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 let metadata = (0x01u64 << 61) | ((intent.lamport_clock as u64) & 0xFFFF_FFFF);
362 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
435pub struct ActionIntent {
436 pub caller_did_hash: u64,
438 pub target_entity_hash: u64,
440 pub action_id: u64,
442 pub parameters_hash: u64,
444 pub lamport_clock: u32,
446}
447
448#[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#[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 let fail = onto.evaluate_intent(&intent, ObserverStatus::Public);
570 assert!(matches!(fail, Err(IntentError::PermissionDenied { .. })));
571
572 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 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 let tools_json = onto.export_ai_tools_json();
587 assert!(tools_json.contains("\"name\": \"prune\""));
588 assert!(tools_json.contains("\"type\": \"function\""));
589
590 let mut buffer = [NQuin::default(); 8];
592 let count = onto.to_nquins(&mut buffer).unwrap();
593 assert_eq!(count, 2);
594 }
595}