bhava 2.0.0

Emotion and personality engine — trait spectrums, mood vectors, archetypes, behavioral mapping
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! Emotional intelligence (EQ) — the Mayer-Salovey four-branch model.
//!
//! Quantifies an entity's emotional competence across four branches
//! (Mayer & Salovey 1997):
//!
//! 1. **Perception** — accuracy in identifying emotions in self, others,
//!    and stimuli. High perception → better at reading micro-expressions,
//!    detecting contagion, and recognizing compound emotions.
//! 2. **Facilitation** — using emotions to enhance cognitive processes.
//!    High facilitation → mood-congruent creativity boosts, better
//!    emotional memory recall, and flow-state sensitivity.
//! 3. **Understanding** — comprehending emotional vocabulary, blends,
//!    transitions, and causes. High understanding → richer appraisal,
//!    better prediction of emotional consequences.
//! 4. **Management** — regulating emotions in self and others.
//!    High management → more effective regulation strategies,
//!    better contagion control, faster stress recovery.
//!
//! EQ scores range from 0.0 (minimal competence) to 1.0 (exceptional).
//! A baseline can be derived from personality traits, then refined by
//! observed behavior over time.

use serde::{Deserialize, Serialize};

use crate::types::{Normalized01, ThresholdClassifier};

/// Emotional intelligence profile — four-branch scores.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EqProfile {
    /// Accuracy in identifying emotions (0.0–1.0).
    pub perception: Normalized01,
    /// Using emotions to enhance thinking (0.0–1.0).
    pub facilitation: Normalized01,
    /// Comprehending emotional language and transitions (0.0–1.0).
    pub understanding: Normalized01,
    /// Regulating emotions in self and others (0.0–1.0).
    pub management: Normalized01,
}

impl Default for EqProfile {
    fn default() -> Self {
        Self {
            perception: Normalized01::HALF,
            facilitation: Normalized01::HALF,
            understanding: Normalized01::HALF,
            management: Normalized01::HALF,
        }
    }
}

impl EqProfile {
    /// Create with default mid-range scores.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create with explicit scores (clamped to 0.0–1.0).
    #[must_use]
    pub fn with_scores(
        perception: f32,
        facilitation: f32,
        understanding: f32,
        management: f32,
    ) -> Self {
        Self {
            perception: Normalized01::new(perception),
            facilitation: Normalized01::new(facilitation),
            understanding: Normalized01::new(understanding),
            management: Normalized01::new(management),
        }
    }

    /// Overall EQ score — weighted average of all branches.
    ///
    /// Weights follow the hierarchical model where higher branches
    /// (understanding, management) are weighted more heavily as they
    /// depend on the lower ones.
    #[must_use]
    #[inline]
    pub fn overall(&self) -> f32 {
        // Weights: perception 0.15, facilitation 0.20, understanding 0.30, management 0.35
        self.perception.get() * 0.15
            + self.facilitation.get() * 0.20
            + self.understanding.get() * 0.30
            + self.management.get() * 0.35
    }

    /// Get score for a specific branch.
    #[must_use]
    #[inline]
    pub fn get(&self, branch: EqBranch) -> f32 {
        match branch {
            EqBranch::Perception => self.perception.get(),
            EqBranch::Facilitation => self.facilitation.get(),
            EqBranch::Understanding => self.understanding.get(),
            EqBranch::Management => self.management.get(),
        }
    }

    /// Set score for a specific branch (clamped to 0.0–1.0).
    #[inline]
    pub fn set(&mut self, branch: EqBranch, value: f32) {
        let v = Normalized01::new(value);
        match branch {
            EqBranch::Perception => self.perception = v,
            EqBranch::Facilitation => self.facilitation = v,
            EqBranch::Understanding => self.understanding = v,
            EqBranch::Management => self.management = v,
        }
    }

    /// Classify the overall EQ level.
    #[must_use]
    pub fn level(&self) -> EqLevel {
        const CLASSIFIER: ThresholdClassifier<EqLevel> = ThresholdClassifier::new(
            &[
                (0.8, EqLevel::Exceptional),
                (0.6, EqLevel::High),
                (0.4, EqLevel::Average),
                (0.2, EqLevel::Low),
            ],
            EqLevel::Minimal,
        );
        CLASSIFIER.classify(self.overall())
    }

    /// Micro-expression detection bonus from perception.
    ///
    /// Higher perception → better at noticing micro-expressions.
    /// Returns a multiplier: 0.5 (low perception) to 1.5 (high perception).
    #[must_use]
    pub fn perception_bonus(&self) -> f32 {
        0.5 + self.perception.get()
    }

    /// Creativity/flow facilitation bonus.
    ///
    /// Higher facilitation → mood states boost cognitive tasks more.
    /// Returns a multiplier: 0.5 to 1.5.
    #[must_use]
    pub fn facilitation_bonus(&self) -> f32 {
        0.5 + self.facilitation.get()
    }

    /// Emotion regulation effectiveness bonus from management.
    ///
    /// Higher management → regulation strategies work better.
    /// Returns a multiplier: 0.5 to 1.5.
    #[must_use]
    pub fn management_bonus(&self) -> f32 {
        0.5 + self.management.get()
    }

    /// Stress recovery rate bonus from management.
    ///
    /// Higher management → faster stress recovery.
    /// Returns a multiplier: 0.8 to 1.5.
    #[must_use]
    pub fn stress_recovery_bonus(&self) -> f32 {
        0.8 + self.management.get() * 0.7
    }

    /// Contagion resistance from management.
    ///
    /// Higher management → less susceptible to emotional contagion.
    /// Returns a resistance factor: 0.0 (fully susceptible) to 0.5 (resistant).
    #[must_use]
    pub fn contagion_resistance(&self) -> f32 {
        self.management.get() * 0.5
    }

    /// Appraisal accuracy bonus from understanding.
    ///
    /// Higher understanding → more nuanced emotion generation from events.
    /// Returns a multiplier: 0.5 to 1.5.
    #[must_use]
    pub fn appraisal_bonus(&self) -> f32 {
        0.5 + self.understanding.get()
    }
}

/// The four branches of emotional intelligence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum EqBranch {
    /// Identifying emotions in self, others, and stimuli.
    Perception,
    /// Using emotions to enhance cognitive processes.
    Facilitation,
    /// Comprehending emotional language and transitions.
    Understanding,
    /// Regulating emotions in self and others.
    Management,
}

impl EqBranch {
    /// All branches in hierarchical order (lower → higher).
    pub const ALL: &'static [EqBranch] = &[
        Self::Perception,
        Self::Facilitation,
        Self::Understanding,
        Self::Management,
    ];
}

impl_display!(EqBranch {
    Perception => "perception",
    Facilitation => "facilitation",
    Understanding => "understanding",
    Management => "management",
});

/// Named EQ classification level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum EqLevel {
    /// Overall < 0.2.
    Minimal,
    /// Overall 0.2–0.4.
    Low,
    /// Overall 0.4–0.6.
    Average,
    /// Overall 0.6–0.8.
    High,
    /// Overall >= 0.8.
    Exceptional,
}

impl_display!(EqLevel {
    Minimal => "minimal",
    Low => "low",
    Average => "average",
    High => "high",
    Exceptional => "exceptional",
});

/// Derive a baseline EQ profile from personality traits.
///
/// Trait mappings (Mayer-Salovey → Big Five/bhava traits):
/// - **Perception** ← empathy + curiosity (attentiveness to emotional signals)
/// - **Facilitation** ← creativity + confidence (leveraging emotions for thinking)
/// - **Understanding** ← empathy + patience + pedagogy (emotional vocabulary depth)
/// - **Management** ← patience + confidence + formality (self-regulation capacity)
#[cfg(feature = "traits")]
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
#[must_use]
pub fn eq_from_personality(profile: &crate::traits::PersonalityProfile) -> EqProfile {
    use crate::traits::TraitKind;

    let empathy = profile.get_trait(TraitKind::Empathy).normalized();
    let curiosity = profile.get_trait(TraitKind::Curiosity).normalized();
    let creativity = profile.get_trait(TraitKind::Creativity).normalized();
    let confidence = profile.get_trait(TraitKind::Confidence).normalized();
    let patience = profile.get_trait(TraitKind::Patience).normalized();
    let pedagogy = profile.get_trait(TraitKind::Pedagogy).normalized();
    let formality = profile.get_trait(TraitKind::Formality).normalized();

    // Map trait averages from -1..1 to 0..1
    let to_score = |v: f32| ((v + 1.0) / 2.0).clamp(0.0, 1.0);

    EqProfile {
        perception: Normalized01::new(to_score((empathy + curiosity) / 2.0)),
        facilitation: Normalized01::new(to_score((creativity + confidence) / 2.0)),
        understanding: Normalized01::new(to_score((empathy + patience + pedagogy) / 3.0)),
        management: Normalized01::new(to_score((patience + confidence + formality) / 3.0)),
    }
}

/// Compose an EQ summary for system prompt injection.
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
#[must_use]
pub fn compose_eq_prompt(eq: &EqProfile) -> String {
    use std::fmt::Write;
    let mut prompt = String::with_capacity(200);
    prompt.push_str("## Emotional Intelligence\n\n");
    let _ = writeln!(
        prompt,
        "- Overall EQ: {} ({:.0}%)",
        eq.level(),
        eq.overall() * 100.0
    );
    for &branch in EqBranch::ALL {
        let score = eq.get(branch);
        let label = match score {
            s if s >= 0.8 => "exceptional",
            s if s >= 0.6 => "strong",
            s if s >= 0.4 => "moderate",
            s if s >= 0.2 => "developing",
            _ => "limited",
        };
        let _ = writeln!(prompt, "- {branch}: {label}");
    }
    prompt
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default() {
        let eq = EqProfile::new();
        assert!((eq.perception.get() - 0.5).abs() < f32::EPSILON);
        assert!((eq.facilitation.get() - 0.5).abs() < f32::EPSILON);
        assert!((eq.understanding.get() - 0.5).abs() < f32::EPSILON);
        assert!((eq.management.get() - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn test_with_scores_clamps() {
        let eq = EqProfile::with_scores(1.5, -0.5, 0.7, 0.3);
        assert!((eq.perception.get() - 1.0).abs() < f32::EPSILON);
        assert!(eq.facilitation.get().abs() < f32::EPSILON);
        assert!((eq.understanding.get() - 0.7).abs() < f32::EPSILON);
    }

    #[test]
    fn test_overall_weighted() {
        let eq = EqProfile::with_scores(1.0, 1.0, 1.0, 1.0);
        // 0.15 + 0.20 + 0.30 + 0.35 = 1.0
        assert!((eq.overall() - 1.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_overall_zero() {
        let eq = EqProfile::with_scores(0.0, 0.0, 0.0, 0.0);
        assert!(eq.overall().abs() < f32::EPSILON);
    }

    #[test]
    fn test_overall_management_heavy() {
        // Management has highest weight (0.35)
        let high_mgmt = EqProfile::with_scores(0.0, 0.0, 0.0, 1.0);
        let high_perc = EqProfile::with_scores(1.0, 0.0, 0.0, 0.0);
        assert!(high_mgmt.overall() > high_perc.overall());
    }

    #[test]
    fn test_get_set() {
        let mut eq = EqProfile::new();
        eq.set(EqBranch::Perception, 0.9);
        assert!((eq.get(EqBranch::Perception) - 0.9).abs() < f32::EPSILON);
        eq.set(EqBranch::Management, 1.5); // clamped
        assert!((eq.get(EqBranch::Management) - 1.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_level_exceptional() {
        let eq = EqProfile::with_scores(1.0, 1.0, 1.0, 1.0);
        assert_eq!(eq.level(), EqLevel::Exceptional);
    }

    #[test]
    fn test_level_minimal() {
        let eq = EqProfile::with_scores(0.0, 0.0, 0.0, 0.0);
        assert_eq!(eq.level(), EqLevel::Minimal);
    }

    #[test]
    fn test_level_average() {
        let eq = EqProfile::new(); // all 0.5
        assert_eq!(eq.level(), EqLevel::Average);
    }

    #[test]
    fn test_perception_bonus_range() {
        let low = EqProfile::with_scores(0.0, 0.5, 0.5, 0.5);
        let high = EqProfile::with_scores(1.0, 0.5, 0.5, 0.5);
        assert!((low.perception_bonus() - 0.5).abs() < f32::EPSILON);
        assert!((high.perception_bonus() - 1.5).abs() < f32::EPSILON);
    }

    #[test]
    fn test_management_bonus_range() {
        let low = EqProfile::with_scores(0.5, 0.5, 0.5, 0.0);
        let high = EqProfile::with_scores(0.5, 0.5, 0.5, 1.0);
        assert!((low.management_bonus() - 0.5).abs() < f32::EPSILON);
        assert!((high.management_bonus() - 1.5).abs() < f32::EPSILON);
    }

    #[test]
    fn test_stress_recovery_bonus() {
        let eq = EqProfile::with_scores(0.5, 0.5, 0.5, 1.0);
        assert!((eq.stress_recovery_bonus() - 1.5).abs() < f32::EPSILON);
        let low = EqProfile::with_scores(0.5, 0.5, 0.5, 0.0);
        assert!((low.stress_recovery_bonus() - 0.8).abs() < f32::EPSILON);
    }

    #[test]
    fn test_contagion_resistance() {
        let eq = EqProfile::with_scores(0.5, 0.5, 0.5, 1.0);
        assert!((eq.contagion_resistance() - 0.5).abs() < f32::EPSILON);
        let low = EqProfile::with_scores(0.5, 0.5, 0.5, 0.0);
        assert!(low.contagion_resistance().abs() < f32::EPSILON);
    }

    #[test]
    fn test_branch_display() {
        assert_eq!(EqBranch::Perception.to_string(), "perception");
        assert_eq!(EqBranch::Management.to_string(), "management");
    }

    #[test]
    fn test_level_display() {
        assert_eq!(EqLevel::Exceptional.to_string(), "exceptional");
        assert_eq!(EqLevel::Minimal.to_string(), "minimal");
    }

    #[test]
    fn test_branch_all() {
        assert_eq!(EqBranch::ALL.len(), 4);
    }

    #[test]
    fn test_compose_prompt() {
        let eq = EqProfile::with_scores(0.9, 0.7, 0.8, 0.6);
        let prompt = compose_eq_prompt(&eq);
        assert!(prompt.contains("## Emotional Intelligence"));
        assert!(prompt.contains("perception"));
        assert!(prompt.contains("management"));
    }

    #[test]
    fn test_serde_profile() {
        let eq = EqProfile::with_scores(0.8, 0.6, 0.7, 0.9);
        let json = serde_json::to_string(&eq).unwrap();
        let eq2: EqProfile = serde_json::from_str(&json).unwrap();
        assert!((eq2.perception.get() - eq.perception.get()).abs() < f32::EPSILON);
        assert!((eq2.management.get() - eq.management.get()).abs() < f32::EPSILON);
    }

    #[test]
    fn test_serde_branch() {
        let b = EqBranch::Understanding;
        let json = serde_json::to_string(&b).unwrap();
        let b2: EqBranch = serde_json::from_str(&json).unwrap();
        assert_eq!(b2, b);
    }

    #[test]
    fn test_serde_level() {
        let l = EqLevel::High;
        let json = serde_json::to_string(&l).unwrap();
        let l2: EqLevel = serde_json::from_str(&json).unwrap();
        assert_eq!(l2, l);
    }

    #[cfg(feature = "traits")]
    #[test]
    fn test_eq_from_personality_empathetic() {
        let mut p = crate::traits::PersonalityProfile::new("empath");
        p.set_trait(
            crate::traits::TraitKind::Empathy,
            crate::traits::TraitLevel::Highest,
        );
        p.set_trait(
            crate::traits::TraitKind::Patience,
            crate::traits::TraitLevel::Highest,
        );
        p.set_trait(
            crate::traits::TraitKind::Curiosity,
            crate::traits::TraitLevel::High,
        );
        let eq = eq_from_personality(&p);
        assert!(
            eq.perception.get() > 0.6,
            "perception: {}",
            eq.perception.get()
        );
        assert!(
            eq.understanding.get() > 0.6,
            "understanding: {}",
            eq.understanding.get()
        );
    }

    #[cfg(feature = "traits")]
    #[test]
    fn test_eq_from_personality_stoic() {
        let mut p = crate::traits::PersonalityProfile::new("stoic");
        p.set_trait(
            crate::traits::TraitKind::Formality,
            crate::traits::TraitLevel::Highest,
        );
        p.set_trait(
            crate::traits::TraitKind::Confidence,
            crate::traits::TraitLevel::Highest,
        );
        p.set_trait(
            crate::traits::TraitKind::Empathy,
            crate::traits::TraitLevel::Lowest,
        );
        let eq = eq_from_personality(&p);
        // High management (formality + confidence), low perception (low empathy)
        assert!(
            eq.management.get() > eq.perception.get(),
            "mgmt={} perc={}",
            eq.management.get(),
            eq.perception.get()
        );
    }

    #[cfg(feature = "traits")]
    #[test]
    fn test_eq_from_personality_balanced() {
        let p = crate::traits::PersonalityProfile::new("balanced");
        let eq = eq_from_personality(&p);
        // All balanced traits → all scores near 0.5
        for &branch in EqBranch::ALL {
            let s = eq.get(branch);
            assert!((s - 0.5).abs() < 0.1, "{branch}: {s} (expected ~0.5)");
        }
    }
}