1use crate::domains::{Domain, DomainGenerator};
9use mockforge_core::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_insert_with(Vec::new)
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(mockforge_core::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(mockforge_core::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(mockforge_core::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(mockforge_core::Error::generic(format!(
385 "Persona with ID '{}' not found",
386 persona_id
387 )))
388 }
389 }
390
391 pub fn find_personas_with_relationship_to(
395 &self,
396 target_persona_id: &str,
397 relationship_type: &str,
398 ) -> Vec<PersonaProfile> {
399 let personas = self.personas.read().unwrap();
400 let mut result = Vec::new();
401
402 for persona in personas.values() {
403 if let Some(related_ids) = persona.get_relationships(relationship_type) {
404 if related_ids.contains(&target_persona_id.to_string()) {
405 result.push(persona.clone());
406 }
407 }
408 }
409
410 result
411 }
412
413 pub fn add_relationship(
417 &self,
418 from_persona_id: &str,
419 relationship_type: String,
420 to_persona_id: String,
421 ) -> Result<()> {
422 let mut personas = self.personas.write().unwrap();
423 if let Some(persona) = personas.get_mut(from_persona_id) {
424 persona.add_relationship(relationship_type.clone(), to_persona_id.clone());
425
426 self.graph
428 .add_edge(from_persona_id.to_string(), to_persona_id, relationship_type);
429
430 Ok(())
431 } else {
432 Err(mockforge_core::Error::generic(format!(
433 "Persona with ID '{}' not found",
434 from_persona_id
435 )))
436 }
437 }
438
439 pub fn coherent_persona_switch<F>(
453 &self,
454 root_persona_id: &str,
455 relationship_types: Option<&[String]>,
456 update_callback: Option<F>,
457 ) -> Result<Vec<String>>
458 where
459 F: Fn(&str, &mut PersonaProfile),
460 {
461 let related_ids = self.graph.find_related_bfs(root_persona_id, relationship_types, None);
463
464 let mut updated_ids = vec![root_persona_id.to_string()];
466 updated_ids.extend(related_ids);
467
468 let mut personas = self.personas.write().unwrap();
470 for persona_id in &updated_ids {
471 if let Some(persona) = personas.get_mut(persona_id) {
472 if let Some(ref callback) = update_callback {
474 callback(persona_id, persona);
475 }
476 }
477 }
478
479 Ok(updated_ids)
480 }
481}
482
483impl Default for PersonaRegistry {
484 fn default() -> Self {
485 Self::new()
486 }
487}
488
489#[derive(Debug)]
494pub struct PersonaGenerator {
495 domain_generator: DomainGenerator,
497}
498
499impl PersonaGenerator {
500 pub fn new(domain: Domain) -> Self {
502 Self {
503 domain_generator: DomainGenerator::new(domain),
504 }
505 }
506
507 pub fn generate_for_persona(
512 &self,
513 persona: &PersonaProfile,
514 field_type: &str,
515 ) -> Result<Value> {
516 self.generate_for_persona_with_reality(persona, field_type, 0.0, None, None)
518 }
519
520 pub fn generate_for_persona_with_reality(
534 &self,
535 persona: &PersonaProfile,
536 field_type: &str,
537 reality_ratio: f64,
538 recorded_data: Option<&Value>,
539 real_data: Option<&Value>,
540 ) -> Result<Value> {
541 use rand::rngs::StdRng;
543 use rand::SeedableRng;
544 let mut rng = StdRng::seed_from_u64(persona.seed);
545
546 let mut synthetic_value = self.domain_generator.generate(field_type)?;
548
549 synthetic_value =
551 self.apply_persona_traits(persona, field_type, synthetic_value, &mut rng)?;
552
553 let reality_ratio = reality_ratio.clamp(0.0, 1.0);
555
556 if reality_ratio < 0.3 {
557 Ok(synthetic_value)
559 } else if reality_ratio < 0.7 {
560 if let Some(recorded) = recorded_data {
562 self.blend_values(&synthetic_value, recorded, reality_ratio)
563 } else {
564 Ok(synthetic_value)
566 }
567 } else {
568 if let Some(real) = real_data {
570 self.blend_values(&synthetic_value, real, reality_ratio)
571 } else if let Some(recorded) = recorded_data {
572 self.blend_values(&synthetic_value, recorded, reality_ratio)
574 } else {
575 Ok(synthetic_value)
577 }
578 }
579 }
580
581 fn blend_values(&self, synthetic: &Value, other: &Value, ratio: f64) -> Result<Value> {
585 match (synthetic, other) {
586 (Value::Number(syn_num), Value::Number(other_num)) => {
588 if let (Some(syn_f64), Some(other_f64)) = (syn_num.as_f64(), other_num.as_f64()) {
589 let adjusted_ratio = if ratio < 0.7 {
592 (ratio - 0.3) / 0.4
594 } else {
595 (ratio - 0.7) / 0.3
597 };
598 let blended = syn_f64 * (1.0 - adjusted_ratio) + other_f64 * adjusted_ratio;
599 Ok(Value::Number(
600 serde_json::Number::from_f64(blended).unwrap_or(syn_num.clone()),
601 ))
602 } else {
603 Ok(synthetic.clone())
604 }
605 }
606 (Value::String(_), Value::String(other_str)) => {
608 let adjusted_ratio = if ratio < 0.7 {
609 (ratio - 0.3) / 0.4
610 } else {
611 (ratio - 0.7) / 0.3
612 };
613 if adjusted_ratio >= 0.5 {
614 Ok(Value::String(other_str.clone()))
615 } else {
616 Ok(synthetic.clone())
617 }
618 }
619 (Value::Bool(_), Value::Bool(other_bool)) => {
621 let adjusted_ratio = if ratio < 0.7 {
622 (ratio - 0.3) / 0.4
623 } else {
624 (ratio - 0.7) / 0.3
625 };
626 if adjusted_ratio >= 0.5 {
627 Ok(Value::Bool(*other_bool))
628 } else {
629 Ok(synthetic.clone())
630 }
631 }
632 _ => {
634 let adjusted_ratio = if ratio < 0.7 {
635 (ratio - 0.3) / 0.4
636 } else {
637 (ratio - 0.7) / 0.3
638 };
639 if adjusted_ratio >= 0.5 {
640 Ok(other.clone())
641 } else {
642 Ok(synthetic.clone())
643 }
644 }
645 }
646 }
647
648 pub fn generate_traits_from_backstory(
653 &self,
654 persona: &PersonaProfile,
655 ) -> Result<HashMap<String, String>> {
656 let mut inferred_traits = HashMap::new();
657
658 let backstory = match persona.get_backstory() {
660 Some(bs) => bs,
661 None => return Ok(inferred_traits),
662 };
663
664 let backstory_lower = backstory.to_lowercase();
665
666 match persona.domain {
668 Domain::Finance => {
669 if backstory_lower.contains("high-spending")
671 || backstory_lower.contains("high spending")
672 || backstory_lower.contains("big spender")
673 {
674 inferred_traits.insert("spending_level".to_string(), "high".to_string());
675 } else if backstory_lower.contains("conservative")
676 || backstory_lower.contains("low spending")
677 || backstory_lower.contains("frugal")
678 {
679 inferred_traits
680 .insert("spending_level".to_string(), "conservative".to_string());
681 } else if backstory_lower.contains("moderate") {
682 inferred_traits.insert("spending_level".to_string(), "moderate".to_string());
683 }
684
685 if backstory_lower.contains("premium") {
687 inferred_traits.insert("account_type".to_string(), "premium".to_string());
688 } else if backstory_lower.contains("business") {
689 inferred_traits.insert("account_type".to_string(), "business".to_string());
690 } else if backstory_lower.contains("savings") {
691 inferred_traits.insert("account_type".to_string(), "savings".to_string());
692 } else if backstory_lower.contains("checking") {
693 inferred_traits.insert("account_type".to_string(), "checking".to_string());
694 }
695
696 let currencies = ["usd", "eur", "gbp", "jpy", "cny"];
698 for currency in ¤cies {
699 if backstory_lower.contains(currency) {
700 inferred_traits
701 .insert("preferred_currency".to_string(), currency.to_uppercase());
702 break;
703 }
704 }
705
706 if backstory_lower.contains("long-term") || backstory_lower.contains("long term") {
708 inferred_traits.insert("account_age".to_string(), "long_term".to_string());
709 } else if backstory_lower.contains("established") {
710 inferred_traits.insert("account_age".to_string(), "established".to_string());
711 } else if backstory_lower.contains("new") {
712 inferred_traits.insert("account_age".to_string(), "new".to_string());
713 }
714 }
715 Domain::Ecommerce => {
716 if backstory_lower.contains("vip") {
718 inferred_traits.insert("customer_segment".to_string(), "VIP".to_string());
719 } else if backstory_lower.contains("new") {
720 inferred_traits.insert("customer_segment".to_string(), "new".to_string());
721 } else {
722 inferred_traits.insert("customer_segment".to_string(), "regular".to_string());
723 }
724
725 if backstory_lower.contains("frequent") {
727 inferred_traits
728 .insert("purchase_frequency".to_string(), "frequent".to_string());
729 } else if backstory_lower.contains("occasional") {
730 inferred_traits
731 .insert("purchase_frequency".to_string(), "occasional".to_string());
732 } else if backstory_lower.contains("regular") {
733 inferred_traits.insert("purchase_frequency".to_string(), "regular".to_string());
734 }
735
736 let categories = ["electronics", "clothing", "books", "home", "sports"];
738 for category in &categories {
739 if backstory_lower.contains(category) {
740 inferred_traits
741 .insert("preferred_category".to_string(), category.to_string());
742 break;
743 }
744 }
745
746 if backstory_lower.contains("express") || backstory_lower.contains("overnight") {
748 inferred_traits.insert("preferred_shipping".to_string(), "express".to_string());
749 } else if backstory_lower.contains("standard") {
750 inferred_traits
751 .insert("preferred_shipping".to_string(), "standard".to_string());
752 }
753 }
754 Domain::Healthcare => {
755 if backstory_lower.contains("private") {
757 inferred_traits.insert("insurance_type".to_string(), "private".to_string());
758 } else if backstory_lower.contains("medicare") {
759 inferred_traits.insert("insurance_type".to_string(), "medicare".to_string());
760 } else if backstory_lower.contains("medicaid") {
761 inferred_traits.insert("insurance_type".to_string(), "medicaid".to_string());
762 } else if backstory_lower.contains("uninsured") {
763 inferred_traits.insert("insurance_type".to_string(), "uninsured".to_string());
764 }
765
766 let blood_types = ["a+", "a-", "b+", "b-", "ab+", "ab-", "o+", "o-"];
768 for blood_type in &blood_types {
769 if backstory_lower.contains(blood_type) {
770 inferred_traits.insert("blood_type".to_string(), blood_type.to_uppercase());
771 break;
772 }
773 }
774
775 if backstory_lower.contains("pediatric") || backstory_lower.contains("child") {
777 inferred_traits.insert("age_group".to_string(), "pediatric".to_string());
778 } else if backstory_lower.contains("senior") || backstory_lower.contains("elderly")
779 {
780 inferred_traits.insert("age_group".to_string(), "senior".to_string());
781 } else {
782 inferred_traits.insert("age_group".to_string(), "adult".to_string());
783 }
784
785 if backstory_lower.contains("frequent") {
787 inferred_traits.insert("visit_frequency".to_string(), "frequent".to_string());
788 } else if backstory_lower.contains("regular") {
789 inferred_traits.insert("visit_frequency".to_string(), "regular".to_string());
790 } else if backstory_lower.contains("occasional") {
791 inferred_traits.insert("visit_frequency".to_string(), "occasional".to_string());
792 } else if backstory_lower.contains("rare") {
793 inferred_traits.insert("visit_frequency".to_string(), "rare".to_string());
794 }
795
796 if backstory_lower.contains("multiple") || backstory_lower.contains("several") {
798 inferred_traits
799 .insert("chronic_conditions".to_string(), "multiple".to_string());
800 } else if backstory_lower.contains("single") || backstory_lower.contains("one") {
801 inferred_traits.insert("chronic_conditions".to_string(), "single".to_string());
802 } else if backstory_lower.contains("none")
803 || backstory_lower.contains("no conditions")
804 {
805 inferred_traits.insert("chronic_conditions".to_string(), "none".to_string());
806 }
807 }
808 _ => {
809 }
811 }
812
813 Ok(inferred_traits)
814 }
815
816 fn apply_persona_traits(
823 &self,
824 persona: &PersonaProfile,
825 field_type: &str,
826 value: Value,
827 _rng: &mut StdRng,
828 ) -> Result<Value> {
829 let mut effective_persona = persona.clone();
831 if persona.has_backstory() && persona.traits.is_empty() {
832 if let Ok(inferred_traits) = self.generate_traits_from_backstory(persona) {
833 for (key, val) in inferred_traits {
834 effective_persona.set_trait(key, val);
835 }
836 }
837 }
838
839 match effective_persona.domain {
840 Domain::Finance => self.apply_finance_traits(&effective_persona, field_type, value),
841 Domain::Ecommerce => self.apply_ecommerce_traits(&effective_persona, field_type, value),
842 Domain::Healthcare => {
843 self.apply_healthcare_traits(&effective_persona, field_type, value)
844 }
845 _ => Ok(value), }
847 }
848
849 fn apply_finance_traits(
851 &self,
852 persona: &PersonaProfile,
853 field_type: &str,
854 value: Value,
855 ) -> Result<Value> {
856 match field_type {
857 "amount" | "balance" | "transaction_amount" => {
858 if let Some(spending_level) = persona.get_trait("spending_level") {
860 let multiplier = match spending_level.as_str() {
861 "high" => 2.0,
862 "moderate" => 1.0,
863 "conservative" | "low" => 0.5,
864 _ => 1.0,
865 };
866
867 if let Some(num) = value.as_f64() {
868 return Ok(Value::Number(
869 serde_json::Number::from_f64(num * multiplier)
870 .unwrap_or_else(|| serde_json::Number::from(0)),
871 ));
872 }
873 }
874 Ok(value)
875 }
876 "currency" => {
877 if let Some(currency) = persona.get_trait("preferred_currency") {
879 return Ok(Value::String(currency.clone()));
880 }
881 Ok(value)
882 }
883 "account_type" => {
884 if let Some(account_type) = persona.get_trait("account_type") {
886 return Ok(Value::String(account_type.clone()));
887 }
888 Ok(value)
889 }
890 _ => Ok(value),
891 }
892 }
893
894 fn apply_ecommerce_traits(
896 &self,
897 persona: &PersonaProfile,
898 field_type: &str,
899 value: Value,
900 ) -> Result<Value> {
901 match field_type {
902 "price" | "order_total" => {
903 if let Some(segment) = persona.get_trait("customer_segment") {
905 let multiplier = match segment.as_str() {
906 "VIP" => 1.5,
907 "regular" => 1.0,
908 "new" => 0.7,
909 _ => 1.0,
910 };
911
912 if let Some(num) = value.as_f64() {
913 return Ok(Value::Number(
914 serde_json::Number::from_f64(num * multiplier)
915 .unwrap_or_else(|| serde_json::Number::from(0)),
916 ));
917 }
918 }
919 Ok(value)
920 }
921 "shipping_method" => {
922 if let Some(shipping) = persona.get_trait("preferred_shipping") {
924 return Ok(Value::String(shipping.clone()));
925 }
926 Ok(value)
927 }
928 _ => Ok(value),
929 }
930 }
931
932 fn apply_healthcare_traits(
934 &self,
935 persona: &PersonaProfile,
936 field_type: &str,
937 value: Value,
938 ) -> Result<Value> {
939 match field_type {
940 "insurance_type" => {
941 if let Some(insurance) = persona.get_trait("insurance_type") {
943 return Ok(Value::String(insurance.clone()));
944 }
945 Ok(value)
946 }
947 "blood_type" => {
948 if let Some(blood_type) = persona.get_trait("blood_type") {
950 return Ok(Value::String(blood_type.clone()));
951 }
952 Ok(value)
953 }
954 _ => Ok(value),
955 }
956 }
957}
958
959#[cfg(test)]
960mod tests {
961 use super::*;
962
963 #[test]
964 fn test_persona_profile_new() {
965 let persona = PersonaProfile::new("user123".to_string(), Domain::Finance);
966 assert_eq!(persona.id, "user123");
967 assert_eq!(persona.domain, Domain::Finance);
968 assert!(persona.traits.is_empty());
969 assert!(persona.seed > 0);
970 }
971
972 #[test]
973 fn test_persona_profile_deterministic_seed() {
974 let persona1 = PersonaProfile::new("user123".to_string(), Domain::Finance);
975 let persona2 = PersonaProfile::new("user123".to_string(), Domain::Finance);
976
977 assert_eq!(persona1.seed, persona2.seed);
979 }
980
981 #[test]
982 fn test_persona_profile_different_seeds() {
983 let persona1 = PersonaProfile::new("user123".to_string(), Domain::Finance);
984 let persona2 = PersonaProfile::new("user456".to_string(), Domain::Finance);
985
986 assert_ne!(persona1.seed, persona2.seed);
988 }
989
990 #[test]
991 fn test_persona_profile_traits() {
992 let mut persona = PersonaProfile::new("user123".to_string(), Domain::Finance);
993 persona.set_trait("spending_level".to_string(), "high".to_string());
994
995 assert_eq!(persona.get_trait("spending_level"), Some(&"high".to_string()));
996 assert_eq!(persona.get_trait("nonexistent"), None);
997 }
998
999 #[test]
1000 fn test_persona_registry_get_or_create() {
1001 let registry = PersonaRegistry::new();
1002
1003 let persona1 = registry.get_or_create_persona("user123".to_string(), Domain::Finance);
1004 let persona2 = registry.get_or_create_persona("user123".to_string(), Domain::Finance);
1005
1006 assert_eq!(persona1.id, persona2.id);
1008 assert_eq!(persona1.seed, persona2.seed);
1009 }
1010
1011 #[test]
1012 fn test_persona_registry_default_traits() {
1013 let mut default_traits = HashMap::new();
1014 default_traits.insert("spending_level".to_string(), "high".to_string());
1015
1016 let registry = PersonaRegistry::with_default_traits(default_traits);
1017 let persona = registry.get_or_create_persona("user123".to_string(), Domain::Finance);
1018
1019 assert_eq!(persona.get_trait("spending_level"), Some(&"high".to_string()));
1020 }
1021
1022 #[test]
1023 fn test_persona_registry_update() {
1024 let registry = PersonaRegistry::new();
1025 registry.get_or_create_persona("user123".to_string(), Domain::Finance);
1026
1027 let mut traits = HashMap::new();
1028 traits.insert("spending_level".to_string(), "low".to_string());
1029
1030 registry.update_persona("user123", traits).unwrap();
1031
1032 let persona = registry.get_persona("user123").unwrap();
1033 assert_eq!(persona.get_trait("spending_level"), Some(&"low".to_string()));
1034 }
1035
1036 #[test]
1037 fn test_persona_generator_finance_traits() {
1038 let generator = PersonaGenerator::new(Domain::Finance);
1039 let mut persona = PersonaProfile::new("user123".to_string(), Domain::Finance);
1040 persona.set_trait("spending_level".to_string(), "high".to_string());
1041
1042 let value = generator.generate_for_persona(&persona, "amount").unwrap();
1044 assert!(value.is_string() || value.is_number());
1045 }
1046
1047 #[test]
1048 fn test_persona_generator_consistency() {
1049 let generator = PersonaGenerator::new(Domain::Finance);
1050 let persona = PersonaProfile::new("user123".to_string(), Domain::Finance);
1051
1052 let value1 = generator.generate_for_persona(&persona, "amount").unwrap();
1054 let value2 = generator.generate_for_persona(&persona, "amount").unwrap();
1055
1056 assert!(value1.is_string() || value1.is_number());
1059 assert!(value2.is_string() || value2.is_number());
1060 }
1061
1062 #[test]
1063 fn test_persona_backstory() {
1064 let mut persona = PersonaProfile::new("user123".to_string(), Domain::Finance);
1065 assert!(!persona.has_backstory());
1066 assert_eq!(persona.get_backstory(), None);
1067
1068 persona
1069 .set_backstory("High-spending finance professional with premium account".to_string());
1070 assert!(persona.has_backstory());
1071 assert!(persona.get_backstory().is_some());
1072 assert!(persona.get_backstory().unwrap().contains("High-spending"));
1073 }
1074
1075 #[test]
1076 fn test_persona_relationships() {
1077 let mut persona = PersonaProfile::new("user123".to_string(), Domain::Finance);
1078
1079 persona.add_relationship("owns_devices".to_string(), "device1".to_string());
1081 persona.add_relationship("owns_devices".to_string(), "device2".to_string());
1082 persona.add_relationship("belongs_to_org".to_string(), "org1".to_string());
1083
1084 let devices = persona.get_related_personas("owns_devices");
1086 assert_eq!(devices.len(), 2);
1087 assert!(devices.contains(&"device1".to_string()));
1088 assert!(devices.contains(&"device2".to_string()));
1089
1090 let orgs = persona.get_related_personas("belongs_to_org");
1091 assert_eq!(orgs.len(), 1);
1092 assert_eq!(orgs[0], "org1");
1093
1094 let types = persona.get_relationship_types();
1096 assert_eq!(types.len(), 2);
1097 assert!(types.contains(&"owns_devices".to_string()));
1098 assert!(types.contains(&"belongs_to_org".to_string()));
1099
1100 assert!(persona.remove_relationship("owns_devices", "device1"));
1102 let devices_after = persona.get_related_personas("owns_devices");
1103 assert_eq!(devices_after.len(), 1);
1104 assert_eq!(devices_after[0], "device2");
1105 }
1106
1107 #[test]
1108 fn test_persona_registry_relationships() {
1109 let registry = PersonaRegistry::new();
1110
1111 let _user = registry.get_or_create_persona("user123".to_string(), Domain::Finance);
1113 let _device = registry.get_or_create_persona("device1".to_string(), Domain::Iot);
1114 let _org = registry.get_or_create_persona("org1".to_string(), Domain::General);
1115
1116 registry
1118 .add_relationship("user123", "owns_devices".to_string(), "device1".to_string())
1119 .unwrap();
1120 registry
1121 .add_relationship("user123", "belongs_to_org".to_string(), "org1".to_string())
1122 .unwrap();
1123
1124 let related_devices = registry.get_related_personas("user123", "owns_devices").unwrap();
1126 assert_eq!(related_devices.len(), 1);
1127 assert_eq!(related_devices[0].id, "device1");
1128
1129 let owners = registry.find_personas_with_relationship_to("device1", "owns_devices");
1131 assert_eq!(owners.len(), 1);
1132 assert_eq!(owners[0].id, "user123");
1133 }
1134}