1use crate::domains::{Domain, DomainGenerator};
9use crate::Result;
10use rand::rngs::StdRng;
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use std::collections::HashMap;
14use std::hash::{Hash, Hasher};
15use std::sync::{Arc, RwLock};
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct PersonaProfile {
20 pub id: String,
22 pub domain: Domain,
24 pub traits: HashMap<String, String>,
26 pub seed: u64,
28 #[serde(default, skip_serializing_if = "Option::is_none")]
30 pub backstory: Option<String>,
31 #[serde(default)]
35 pub relationships: HashMap<String, Vec<String>>,
36 #[serde(default)]
38 pub metadata: HashMap<String, Value>,
39 #[serde(skip_serializing_if = "Option::is_none")]
41 pub lifecycle: Option<crate::persona_lifecycle::PersonaLifecycle>,
42}
43
44impl PersonaProfile {
45 pub fn new(id: String, domain: Domain) -> Self {
50 let seed = Self::derive_seed(&id, domain);
51 Self {
52 id,
53 domain,
54 traits: HashMap::new(),
55 seed,
56 backstory: None,
57 relationships: HashMap::new(),
58 metadata: HashMap::new(),
59 lifecycle: None,
60 }
61 }
62
63 pub fn with_traits(id: String, domain: Domain, traits: HashMap<String, String>) -> Self {
65 let mut persona = Self::new(id, domain);
66 persona.traits = traits;
67 persona
68 }
69
70 pub fn set_lifecycle(&mut self, lifecycle: crate::persona_lifecycle::PersonaLifecycle) {
72 self.lifecycle = Some(lifecycle);
73 }
74
75 pub fn get_lifecycle(&self) -> Option<&crate::persona_lifecycle::PersonaLifecycle> {
77 self.lifecycle.as_ref()
78 }
79
80 pub fn get_lifecycle_mut(&mut self) -> Option<&mut crate::persona_lifecycle::PersonaLifecycle> {
82 self.lifecycle.as_mut()
83 }
84
85 pub fn update_lifecycle_state(&mut self, current_time: chrono::DateTime<chrono::Utc>) {
89 if let Some(ref mut lifecycle) = self.lifecycle {
90 if let Some((new_state, _rule)) = lifecycle.transition_if_elapsed(current_time) {
91 lifecycle.transition_to(new_state, current_time);
92
93 let effects = lifecycle.apply_lifecycle_effects();
95 for (key, value) in effects {
96 self.set_trait(key, value);
97 }
98 }
99 }
100 }
101
102 fn derive_seed(id: &str, domain: Domain) -> u64 {
107 use std::collections::hash_map::DefaultHasher;
108 let mut hasher = DefaultHasher::new();
109 id.hash(&mut hasher);
110 domain.as_str().hash(&mut hasher);
111 hasher.finish()
112 }
113
114 pub fn set_trait(&mut self, name: String, value: String) {
116 self.traits.insert(name, value);
117 }
118
119 pub fn get_trait(&self, name: &str) -> Option<&String> {
121 self.traits.get(name)
122 }
123
124 pub fn set_metadata(&mut self, key: String, value: Value) {
126 self.metadata.insert(key, value);
127 }
128
129 pub fn get_metadata(&self, key: &str) -> Option<&Value> {
131 self.metadata.get(key)
132 }
133
134 pub fn set_backstory(&mut self, backstory: String) {
139 self.backstory = Some(backstory);
140 }
141
142 pub fn get_backstory(&self) -> Option<&String> {
144 self.backstory.as_ref()
145 }
146
147 pub fn has_backstory(&self) -> bool {
149 self.backstory.is_some()
150 }
151
152 pub fn add_relationship(&mut self, relationship_type: String, related_persona_id: String) {
158 self.relationships
159 .entry(relationship_type)
160 .or_default()
161 .push(related_persona_id);
162 }
163
164 pub fn get_relationships(&self, relationship_type: &str) -> Option<&Vec<String>> {
168 self.relationships.get(relationship_type)
169 }
170
171 pub fn get_related_personas(&self, relationship_type: &str) -> Vec<String> {
175 self.relationships.get(relationship_type).cloned().unwrap_or_default()
176 }
177
178 pub fn get_relationship_types(&self) -> Vec<String> {
180 self.relationships.keys().cloned().collect()
181 }
182
183 pub fn remove_relationship(
188 &mut self,
189 relationship_type: &str,
190 related_persona_id: &str,
191 ) -> bool {
192 if let Some(related_ids) = self.relationships.get_mut(relationship_type) {
193 if let Some(pos) = related_ids.iter().position(|id| id == related_persona_id) {
194 related_ids.remove(pos);
195 if related_ids.is_empty() {
197 self.relationships.remove(relationship_type);
198 }
199 return true;
200 }
201 }
202 false
203 }
204}
205
206#[derive(Debug, Clone)]
211pub struct PersonaRegistry {
212 personas: Arc<RwLock<HashMap<String, PersonaProfile>>>,
214 default_traits: HashMap<String, String>,
216 graph: Arc<crate::persona_graph::PersonaGraph>,
218}
219
220impl PersonaRegistry {
221 pub fn new() -> Self {
223 Self {
224 personas: Arc::new(RwLock::new(HashMap::new())),
225 default_traits: HashMap::new(),
226 graph: Arc::new(crate::persona_graph::PersonaGraph::new()),
227 }
228 }
229
230 pub fn with_default_traits(default_traits: HashMap<String, String>) -> Self {
232 Self {
233 personas: Arc::new(RwLock::new(HashMap::new())),
234 default_traits,
235 graph: Arc::new(crate::persona_graph::PersonaGraph::new()),
236 }
237 }
238
239 pub fn graph(&self) -> Arc<crate::persona_graph::PersonaGraph> {
241 Arc::clone(&self.graph)
242 }
243
244 pub fn get_or_create_persona(&self, id: String, domain: Domain) -> PersonaProfile {
249 let personas = self.personas.read().unwrap();
250
251 if let Some(persona) = personas.get(&id) {
253 return persona.clone();
254 }
255 drop(personas);
256
257 let mut persona = PersonaProfile::new(id.clone(), domain);
259 for (key, value) in &self.default_traits {
260 persona.set_trait(key.clone(), value.clone());
261 }
262
263 let mut personas = self.personas.write().unwrap();
265 personas.insert(id.clone(), persona.clone());
266
267 let entity_type = persona.domain.as_str().to_string();
269 let graph_node = crate::persona_graph::PersonaNode::new(id.clone(), entity_type);
270 self.graph.add_node(graph_node);
271
272 persona
273 }
274
275 pub fn get_persona(&self, id: &str) -> Option<PersonaProfile> {
277 let personas = self.personas.read().unwrap();
278 personas.get(id).cloned()
279 }
280
281 pub fn update_persona(&self, id: &str, traits: HashMap<String, String>) -> Result<()> {
283 let mut personas = self.personas.write().unwrap();
284 if let Some(persona) = personas.get_mut(id) {
285 for (key, value) in traits {
286 persona.set_trait(key, value);
287 }
288 Ok(())
289 } else {
290 Err(crate::Error::generic(format!("Persona with ID '{}' not found", id)))
291 }
292 }
293
294 pub fn update_persona_backstory(&self, id: &str, backstory: String) -> Result<()> {
298 let mut personas = self.personas.write().unwrap();
299 if let Some(persona) = personas.get_mut(id) {
300 persona.set_backstory(backstory);
301 Ok(())
302 } else {
303 Err(crate::Error::generic(format!("Persona with ID '{}' not found", id)))
304 }
305 }
306
307 pub fn update_persona_full(
312 &self,
313 id: &str,
314 traits: Option<HashMap<String, String>>,
315 backstory: Option<String>,
316 relationships: Option<HashMap<String, Vec<String>>>,
317 ) -> Result<()> {
318 let mut personas = self.personas.write().unwrap();
319 if let Some(persona) = personas.get_mut(id) {
320 if let Some(traits) = traits {
321 for (key, value) in traits {
322 persona.set_trait(key, value);
323 }
324 }
325 if let Some(backstory) = backstory {
326 persona.set_backstory(backstory);
327 }
328 if let Some(relationships) = relationships {
329 for (rel_type, related_ids) in relationships {
330 for related_id in related_ids {
331 persona.add_relationship(rel_type.clone(), related_id);
332 }
333 }
334 }
335 Ok(())
336 } else {
337 Err(crate::Error::generic(format!("Persona with ID '{}' not found", id)))
338 }
339 }
340
341 pub fn remove_persona(&self, id: &str) -> bool {
343 let mut personas = self.personas.write().unwrap();
344 personas.remove(id).is_some()
345 }
346
347 pub fn list_persona_ids(&self) -> Vec<String> {
349 let personas = self.personas.read().unwrap();
350 personas.keys().cloned().collect()
351 }
352
353 pub fn clear(&self) {
355 let mut personas = self.personas.write().unwrap();
356 personas.clear();
357 }
358
359 pub fn count(&self) -> usize {
361 let personas = self.personas.read().unwrap();
362 personas.len()
363 }
364
365 pub fn get_related_personas(
369 &self,
370 persona_id: &str,
371 relationship_type: &str,
372 ) -> Result<Vec<PersonaProfile>> {
373 let personas = self.personas.read().unwrap();
374 if let Some(persona) = personas.get(persona_id) {
375 let related_ids = persona.get_related_personas(relationship_type);
376 let mut related_personas = Vec::new();
377 for related_id in related_ids {
378 if let Some(related_persona) = personas.get(&related_id) {
379 related_personas.push(related_persona.clone());
380 }
381 }
382 Ok(related_personas)
383 } else {
384 Err(crate::Error::generic(format!("Persona with ID '{}' not found", persona_id)))
385 }
386 }
387
388 pub fn find_personas_with_relationship_to(
392 &self,
393 target_persona_id: &str,
394 relationship_type: &str,
395 ) -> Vec<PersonaProfile> {
396 let personas = self.personas.read().unwrap();
397 let mut result = Vec::new();
398
399 for persona in personas.values() {
400 if let Some(related_ids) = persona.get_relationships(relationship_type) {
401 if related_ids.contains(&target_persona_id.to_string()) {
402 result.push(persona.clone());
403 }
404 }
405 }
406
407 result
408 }
409
410 pub fn add_relationship(
414 &self,
415 from_persona_id: &str,
416 relationship_type: String,
417 to_persona_id: String,
418 ) -> Result<()> {
419 let mut personas = self.personas.write().unwrap();
420 if let Some(persona) = personas.get_mut(from_persona_id) {
421 persona.add_relationship(relationship_type.clone(), to_persona_id.clone());
422
423 self.graph
425 .add_edge(from_persona_id.to_string(), to_persona_id, relationship_type);
426
427 Ok(())
428 } else {
429 Err(crate::Error::generic(format!(
430 "Persona with ID '{}' not found",
431 from_persona_id
432 )))
433 }
434 }
435
436 pub fn coherent_persona_switch<F>(
450 &self,
451 root_persona_id: &str,
452 relationship_types: Option<&[String]>,
453 update_callback: Option<F>,
454 ) -> Result<Vec<String>>
455 where
456 F: Fn(&str, &mut PersonaProfile),
457 {
458 let related_ids = self.graph.find_related_bfs(root_persona_id, relationship_types, None);
460
461 let mut updated_ids = vec![root_persona_id.to_string()];
463 updated_ids.extend(related_ids);
464
465 let mut personas = self.personas.write().unwrap();
467 for persona_id in &updated_ids {
468 if let Some(persona) = personas.get_mut(persona_id) {
469 if let Some(ref callback) = update_callback {
471 callback(persona_id, persona);
472 }
473 }
474 }
475
476 Ok(updated_ids)
477 }
478}
479
480impl Default for PersonaRegistry {
481 fn default() -> Self {
482 Self::new()
483 }
484}
485
486#[derive(Debug)]
491pub struct PersonaGenerator {
492 domain_generator: DomainGenerator,
494}
495
496impl PersonaGenerator {
497 pub fn new(domain: Domain) -> Self {
499 Self {
500 domain_generator: DomainGenerator::new(domain),
501 }
502 }
503
504 pub fn generate_for_persona(
509 &self,
510 persona: &PersonaProfile,
511 field_type: &str,
512 ) -> Result<Value> {
513 self.generate_for_persona_with_reality(persona, field_type, 0.0, None, None)
515 }
516
517 pub fn generate_for_persona_with_reality(
531 &self,
532 persona: &PersonaProfile,
533 field_type: &str,
534 reality_ratio: f64,
535 recorded_data: Option<&Value>,
536 real_data: Option<&Value>,
537 ) -> Result<Value> {
538 use rand::rngs::StdRng;
540 use rand::SeedableRng;
541 let mut rng = StdRng::seed_from_u64(persona.seed);
542
543 let mut synthetic_value = self.domain_generator.generate(field_type)?;
545
546 synthetic_value =
548 self.apply_persona_traits(persona, field_type, synthetic_value, &mut rng)?;
549
550 let reality_ratio = reality_ratio.clamp(0.0, 1.0);
552
553 if reality_ratio < 0.3 {
554 Ok(synthetic_value)
556 } else if reality_ratio < 0.7 {
557 if let Some(recorded) = recorded_data {
559 self.blend_values(&synthetic_value, recorded, reality_ratio)
560 } else {
561 Ok(synthetic_value)
563 }
564 } else {
565 if let Some(real) = real_data {
567 self.blend_values(&synthetic_value, real, reality_ratio)
568 } else if let Some(recorded) = recorded_data {
569 self.blend_values(&synthetic_value, recorded, reality_ratio)
571 } else {
572 Ok(synthetic_value)
574 }
575 }
576 }
577
578 fn blend_values(&self, synthetic: &Value, other: &Value, ratio: f64) -> Result<Value> {
582 match (synthetic, other) {
583 (Value::Number(syn_num), Value::Number(other_num)) => {
585 if let (Some(syn_f64), Some(other_f64)) = (syn_num.as_f64(), other_num.as_f64()) {
586 let adjusted_ratio = if ratio < 0.7 {
589 (ratio - 0.3) / 0.4
591 } else {
592 (ratio - 0.7) / 0.3
594 };
595 let blended = syn_f64 * (1.0 - adjusted_ratio) + other_f64 * adjusted_ratio;
596 Ok(Value::Number(
597 serde_json::Number::from_f64(blended).unwrap_or(syn_num.clone()),
598 ))
599 } else {
600 Ok(synthetic.clone())
601 }
602 }
603 (Value::String(_), Value::String(other_str)) => {
605 let adjusted_ratio = if ratio < 0.7 {
606 (ratio - 0.3) / 0.4
607 } else {
608 (ratio - 0.7) / 0.3
609 };
610 if adjusted_ratio >= 0.5 {
611 Ok(Value::String(other_str.clone()))
612 } else {
613 Ok(synthetic.clone())
614 }
615 }
616 (Value::Bool(_), Value::Bool(other_bool)) => {
618 let adjusted_ratio = if ratio < 0.7 {
619 (ratio - 0.3) / 0.4
620 } else {
621 (ratio - 0.7) / 0.3
622 };
623 if adjusted_ratio >= 0.5 {
624 Ok(Value::Bool(*other_bool))
625 } else {
626 Ok(synthetic.clone())
627 }
628 }
629 _ => {
631 let adjusted_ratio = if ratio < 0.7 {
632 (ratio - 0.3) / 0.4
633 } else {
634 (ratio - 0.7) / 0.3
635 };
636 if adjusted_ratio >= 0.5 {
637 Ok(other.clone())
638 } else {
639 Ok(synthetic.clone())
640 }
641 }
642 }
643 }
644
645 pub fn generate_traits_from_backstory(
650 &self,
651 persona: &PersonaProfile,
652 ) -> Result<HashMap<String, String>> {
653 let mut inferred_traits = HashMap::new();
654
655 let backstory = match persona.get_backstory() {
657 Some(bs) => bs,
658 None => return Ok(inferred_traits),
659 };
660
661 let backstory_lower = backstory.to_lowercase();
662
663 match persona.domain {
665 Domain::Finance => {
666 if backstory_lower.contains("high-spending")
668 || backstory_lower.contains("high spending")
669 || backstory_lower.contains("big spender")
670 {
671 inferred_traits.insert("spending_level".to_string(), "high".to_string());
672 } else if backstory_lower.contains("conservative")
673 || backstory_lower.contains("low spending")
674 || backstory_lower.contains("frugal")
675 {
676 inferred_traits
677 .insert("spending_level".to_string(), "conservative".to_string());
678 } else if backstory_lower.contains("moderate") {
679 inferred_traits.insert("spending_level".to_string(), "moderate".to_string());
680 }
681
682 if backstory_lower.contains("premium") {
684 inferred_traits.insert("account_type".to_string(), "premium".to_string());
685 } else if backstory_lower.contains("business") {
686 inferred_traits.insert("account_type".to_string(), "business".to_string());
687 } else if backstory_lower.contains("savings") {
688 inferred_traits.insert("account_type".to_string(), "savings".to_string());
689 } else if backstory_lower.contains("checking") {
690 inferred_traits.insert("account_type".to_string(), "checking".to_string());
691 }
692
693 let currencies = ["usd", "eur", "gbp", "jpy", "cny"];
695 for currency in ¤cies {
696 if backstory_lower.contains(currency) {
697 inferred_traits
698 .insert("preferred_currency".to_string(), currency.to_uppercase());
699 break;
700 }
701 }
702
703 if backstory_lower.contains("long-term") || backstory_lower.contains("long term") {
705 inferred_traits.insert("account_age".to_string(), "long_term".to_string());
706 } else if backstory_lower.contains("established") {
707 inferred_traits.insert("account_age".to_string(), "established".to_string());
708 } else if backstory_lower.contains("new") {
709 inferred_traits.insert("account_age".to_string(), "new".to_string());
710 }
711 }
712 Domain::Ecommerce => {
713 if backstory_lower.contains("vip") {
715 inferred_traits.insert("customer_segment".to_string(), "VIP".to_string());
716 } else if backstory_lower.contains("new") {
717 inferred_traits.insert("customer_segment".to_string(), "new".to_string());
718 } else {
719 inferred_traits.insert("customer_segment".to_string(), "regular".to_string());
720 }
721
722 if backstory_lower.contains("frequent") {
724 inferred_traits
725 .insert("purchase_frequency".to_string(), "frequent".to_string());
726 } else if backstory_lower.contains("occasional") {
727 inferred_traits
728 .insert("purchase_frequency".to_string(), "occasional".to_string());
729 } else if backstory_lower.contains("regular") {
730 inferred_traits.insert("purchase_frequency".to_string(), "regular".to_string());
731 }
732
733 let categories = ["electronics", "clothing", "books", "home", "sports"];
735 for category in &categories {
736 if backstory_lower.contains(category) {
737 inferred_traits
738 .insert("preferred_category".to_string(), category.to_string());
739 break;
740 }
741 }
742
743 if backstory_lower.contains("express") || backstory_lower.contains("overnight") {
745 inferred_traits.insert("preferred_shipping".to_string(), "express".to_string());
746 } else if backstory_lower.contains("standard") {
747 inferred_traits
748 .insert("preferred_shipping".to_string(), "standard".to_string());
749 }
750 }
751 Domain::Healthcare => {
752 if backstory_lower.contains("private") {
754 inferred_traits.insert("insurance_type".to_string(), "private".to_string());
755 } else if backstory_lower.contains("medicare") {
756 inferred_traits.insert("insurance_type".to_string(), "medicare".to_string());
757 } else if backstory_lower.contains("medicaid") {
758 inferred_traits.insert("insurance_type".to_string(), "medicaid".to_string());
759 } else if backstory_lower.contains("uninsured") {
760 inferred_traits.insert("insurance_type".to_string(), "uninsured".to_string());
761 }
762
763 let blood_types = ["a+", "a-", "b+", "b-", "ab+", "ab-", "o+", "o-"];
765 for blood_type in &blood_types {
766 if backstory_lower.contains(blood_type) {
767 inferred_traits.insert("blood_type".to_string(), blood_type.to_uppercase());
768 break;
769 }
770 }
771
772 if backstory_lower.contains("pediatric") || backstory_lower.contains("child") {
774 inferred_traits.insert("age_group".to_string(), "pediatric".to_string());
775 } else if backstory_lower.contains("senior") || backstory_lower.contains("elderly")
776 {
777 inferred_traits.insert("age_group".to_string(), "senior".to_string());
778 } else {
779 inferred_traits.insert("age_group".to_string(), "adult".to_string());
780 }
781
782 if backstory_lower.contains("frequent") {
784 inferred_traits.insert("visit_frequency".to_string(), "frequent".to_string());
785 } else if backstory_lower.contains("regular") {
786 inferred_traits.insert("visit_frequency".to_string(), "regular".to_string());
787 } else if backstory_lower.contains("occasional") {
788 inferred_traits.insert("visit_frequency".to_string(), "occasional".to_string());
789 } else if backstory_lower.contains("rare") {
790 inferred_traits.insert("visit_frequency".to_string(), "rare".to_string());
791 }
792
793 if backstory_lower.contains("multiple") || backstory_lower.contains("several") {
795 inferred_traits
796 .insert("chronic_conditions".to_string(), "multiple".to_string());
797 } else if backstory_lower.contains("single") || backstory_lower.contains("one") {
798 inferred_traits.insert("chronic_conditions".to_string(), "single".to_string());
799 } else if backstory_lower.contains("none")
800 || backstory_lower.contains("no conditions")
801 {
802 inferred_traits.insert("chronic_conditions".to_string(), "none".to_string());
803 }
804 }
805 _ => {
806 }
808 }
809
810 Ok(inferred_traits)
811 }
812
813 fn apply_persona_traits(
820 &self,
821 persona: &PersonaProfile,
822 field_type: &str,
823 value: Value,
824 _rng: &mut StdRng,
825 ) -> Result<Value> {
826 let mut effective_persona = persona.clone();
828 if persona.has_backstory() && persona.traits.is_empty() {
829 if let Ok(inferred_traits) = self.generate_traits_from_backstory(persona) {
830 for (key, val) in inferred_traits {
831 effective_persona.set_trait(key, val);
832 }
833 }
834 }
835
836 match effective_persona.domain {
837 Domain::Finance => self.apply_finance_traits(&effective_persona, field_type, value),
838 Domain::Ecommerce => self.apply_ecommerce_traits(&effective_persona, field_type, value),
839 Domain::Healthcare => {
840 self.apply_healthcare_traits(&effective_persona, field_type, value)
841 }
842 _ => Ok(value), }
844 }
845
846 fn apply_finance_traits(
848 &self,
849 persona: &PersonaProfile,
850 field_type: &str,
851 value: Value,
852 ) -> Result<Value> {
853 match field_type {
854 "amount" | "balance" | "transaction_amount" => {
855 if let Some(spending_level) = persona.get_trait("spending_level") {
857 let multiplier = match spending_level.as_str() {
858 "high" => 2.0,
859 "moderate" => 1.0,
860 "conservative" | "low" => 0.5,
861 _ => 1.0,
862 };
863
864 if let Some(num) = value.as_f64() {
865 return Ok(Value::Number(
866 serde_json::Number::from_f64(num * multiplier)
867 .unwrap_or_else(|| serde_json::Number::from(0)),
868 ));
869 }
870 }
871 Ok(value)
872 }
873 "currency" => {
874 if let Some(currency) = persona.get_trait("preferred_currency") {
876 return Ok(Value::String(currency.clone()));
877 }
878 Ok(value)
879 }
880 "account_type" => {
881 if let Some(account_type) = persona.get_trait("account_type") {
883 return Ok(Value::String(account_type.clone()));
884 }
885 Ok(value)
886 }
887 _ => Ok(value),
888 }
889 }
890
891 fn apply_ecommerce_traits(
893 &self,
894 persona: &PersonaProfile,
895 field_type: &str,
896 value: Value,
897 ) -> Result<Value> {
898 match field_type {
899 "price" | "order_total" => {
900 if let Some(segment) = persona.get_trait("customer_segment") {
902 let multiplier = match segment.as_str() {
903 "VIP" => 1.5,
904 "regular" => 1.0,
905 "new" => 0.7,
906 _ => 1.0,
907 };
908
909 if let Some(num) = value.as_f64() {
910 return Ok(Value::Number(
911 serde_json::Number::from_f64(num * multiplier)
912 .unwrap_or_else(|| serde_json::Number::from(0)),
913 ));
914 }
915 }
916 Ok(value)
917 }
918 "shipping_method" => {
919 if let Some(shipping) = persona.get_trait("preferred_shipping") {
921 return Ok(Value::String(shipping.clone()));
922 }
923 Ok(value)
924 }
925 _ => Ok(value),
926 }
927 }
928
929 fn apply_healthcare_traits(
931 &self,
932 persona: &PersonaProfile,
933 field_type: &str,
934 value: Value,
935 ) -> Result<Value> {
936 match field_type {
937 "insurance_type" => {
938 if let Some(insurance) = persona.get_trait("insurance_type") {
940 return Ok(Value::String(insurance.clone()));
941 }
942 Ok(value)
943 }
944 "blood_type" => {
945 if let Some(blood_type) = persona.get_trait("blood_type") {
947 return Ok(Value::String(blood_type.clone()));
948 }
949 Ok(value)
950 }
951 _ => Ok(value),
952 }
953 }
954}
955
956#[cfg(test)]
957mod tests {
958 use super::*;
959
960 #[test]
961 fn test_persona_profile_new() {
962 let persona = PersonaProfile::new("user123".to_string(), Domain::Finance);
963 assert_eq!(persona.id, "user123");
964 assert_eq!(persona.domain, Domain::Finance);
965 assert!(persona.traits.is_empty());
966 assert!(persona.seed > 0);
967 }
968
969 #[test]
970 fn test_persona_profile_deterministic_seed() {
971 let persona1 = PersonaProfile::new("user123".to_string(), Domain::Finance);
972 let persona2 = PersonaProfile::new("user123".to_string(), Domain::Finance);
973
974 assert_eq!(persona1.seed, persona2.seed);
976 }
977
978 #[test]
979 fn test_persona_profile_different_seeds() {
980 let persona1 = PersonaProfile::new("user123".to_string(), Domain::Finance);
981 let persona2 = PersonaProfile::new("user456".to_string(), Domain::Finance);
982
983 assert_ne!(persona1.seed, persona2.seed);
985 }
986
987 #[test]
988 fn test_persona_profile_traits() {
989 let mut persona = PersonaProfile::new("user123".to_string(), Domain::Finance);
990 persona.set_trait("spending_level".to_string(), "high".to_string());
991
992 assert_eq!(persona.get_trait("spending_level"), Some(&"high".to_string()));
993 assert_eq!(persona.get_trait("nonexistent"), None);
994 }
995
996 #[test]
997 fn test_persona_registry_get_or_create() {
998 let registry = PersonaRegistry::new();
999
1000 let persona1 = registry.get_or_create_persona("user123".to_string(), Domain::Finance);
1001 let persona2 = registry.get_or_create_persona("user123".to_string(), Domain::Finance);
1002
1003 assert_eq!(persona1.id, persona2.id);
1005 assert_eq!(persona1.seed, persona2.seed);
1006 }
1007
1008 #[test]
1009 fn test_persona_registry_default_traits() {
1010 let mut default_traits = HashMap::new();
1011 default_traits.insert("spending_level".to_string(), "high".to_string());
1012
1013 let registry = PersonaRegistry::with_default_traits(default_traits);
1014 let persona = registry.get_or_create_persona("user123".to_string(), Domain::Finance);
1015
1016 assert_eq!(persona.get_trait("spending_level"), Some(&"high".to_string()));
1017 }
1018
1019 #[test]
1020 fn test_persona_registry_update() {
1021 let registry = PersonaRegistry::new();
1022 registry.get_or_create_persona("user123".to_string(), Domain::Finance);
1023
1024 let mut traits = HashMap::new();
1025 traits.insert("spending_level".to_string(), "low".to_string());
1026
1027 registry.update_persona("user123", traits).unwrap();
1028
1029 let persona = registry.get_persona("user123").unwrap();
1030 assert_eq!(persona.get_trait("spending_level"), Some(&"low".to_string()));
1031 }
1032
1033 #[test]
1034 fn test_persona_generator_finance_traits() {
1035 let generator = PersonaGenerator::new(Domain::Finance);
1036 let mut persona = PersonaProfile::new("user123".to_string(), Domain::Finance);
1037 persona.set_trait("spending_level".to_string(), "high".to_string());
1038
1039 let value = generator.generate_for_persona(&persona, "amount").unwrap();
1041 assert!(value.is_string() || value.is_number());
1042 }
1043
1044 #[test]
1045 fn test_persona_generator_consistency() {
1046 let generator = PersonaGenerator::new(Domain::Finance);
1047 let persona = PersonaProfile::new("user123".to_string(), Domain::Finance);
1048
1049 let value1 = generator.generate_for_persona(&persona, "amount").unwrap();
1051 let value2 = generator.generate_for_persona(&persona, "amount").unwrap();
1052
1053 assert!(value1.is_string() || value1.is_number());
1056 assert!(value2.is_string() || value2.is_number());
1057 }
1058
1059 #[test]
1060 fn test_persona_backstory() {
1061 let mut persona = PersonaProfile::new("user123".to_string(), Domain::Finance);
1062 assert!(!persona.has_backstory());
1063 assert_eq!(persona.get_backstory(), None);
1064
1065 persona
1066 .set_backstory("High-spending finance professional with premium account".to_string());
1067 assert!(persona.has_backstory());
1068 assert!(persona.get_backstory().is_some());
1069 assert!(persona.get_backstory().unwrap().contains("High-spending"));
1070 }
1071
1072 #[test]
1073 fn test_persona_relationships() {
1074 let mut persona = PersonaProfile::new("user123".to_string(), Domain::Finance);
1075
1076 persona.add_relationship("owns_devices".to_string(), "device1".to_string());
1078 persona.add_relationship("owns_devices".to_string(), "device2".to_string());
1079 persona.add_relationship("belongs_to_org".to_string(), "org1".to_string());
1080
1081 let devices = persona.get_related_personas("owns_devices");
1083 assert_eq!(devices.len(), 2);
1084 assert!(devices.contains(&"device1".to_string()));
1085 assert!(devices.contains(&"device2".to_string()));
1086
1087 let orgs = persona.get_related_personas("belongs_to_org");
1088 assert_eq!(orgs.len(), 1);
1089 assert_eq!(orgs[0], "org1");
1090
1091 let types = persona.get_relationship_types();
1093 assert_eq!(types.len(), 2);
1094 assert!(types.contains(&"owns_devices".to_string()));
1095 assert!(types.contains(&"belongs_to_org".to_string()));
1096
1097 assert!(persona.remove_relationship("owns_devices", "device1"));
1099 let devices_after = persona.get_related_personas("owns_devices");
1100 assert_eq!(devices_after.len(), 1);
1101 assert_eq!(devices_after[0], "device2");
1102 }
1103
1104 #[test]
1105 fn test_persona_registry_relationships() {
1106 let registry = PersonaRegistry::new();
1107
1108 let _user = registry.get_or_create_persona("user123".to_string(), Domain::Finance);
1110 let _device = registry.get_or_create_persona("device1".to_string(), Domain::Iot);
1111 let _org = registry.get_or_create_persona("org1".to_string(), Domain::General);
1112
1113 registry
1115 .add_relationship("user123", "owns_devices".to_string(), "device1".to_string())
1116 .unwrap();
1117 registry
1118 .add_relationship("user123", "belongs_to_org".to_string(), "org1".to_string())
1119 .unwrap();
1120
1121 let related_devices = registry.get_related_personas("user123", "owns_devices").unwrap();
1123 assert_eq!(related_devices.len(), 1);
1124 assert_eq!(related_devices[0].id, "device1");
1125
1126 let owners = registry.find_personas_with_relationship_to("device1", "owns_devices");
1128 assert_eq!(owners.len(), 1);
1129 assert_eq!(owners[0].id, "user123");
1130 }
1131}