eros-engine-core 0.9.1

Pure-domain types and rules for the eros-engine AI companion engine: persona, six-dimensional affinity, PDE decisions, and ghost-message logic with no I/O.
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
// SPDX-License-Identifier: AGPL-3.0-only
//! Persona Decision Engine — produces an ActionPlan per event.
//!
//! Strategy: deterministic rules first, LLM fallback only when rules cannot
//! decide. Ghost / energy mappings are all rule-based.

use crate::affinity::AffinityDeltas;
use crate::ghost::{self, GhostDecision, GhostSignals};
use crate::types::{ActionPlan, ActionType, DecisionInput, Event, ImageRef, ReplyStyle};

// Decision thresholds — tune here rather than at call sites.
const LONG_MSG_CHARS: usize = 30;
const SHORT_MSG_CHARS: usize = 3;
const STALE_HOURS: f64 = 24.0;

const INTRIGUE_LONG_BUMP: f64 = 0.02;
const PATIENCE_LONG_BUMP: f64 = 0.02;
const PATIENCE_SHORT_PENALTY: f64 = -0.02;
const PATIENCE_STALE_PENALTY: f64 = -0.05;
const TENSION_STALE_BUMP: f64 = 0.03;

const ENERGY_COST_REPLY: f64 = 0.05;
const ENERGY_COST_PROACTIVE: f64 = 0.10;
const ENERGY_COST_GHOST: f64 = 0.0;
const ENERGY_COST_APP_OPEN: f64 = 0.0;

const GHOST_DELTA_PATIENCE: f64 = -0.05;
const GHOST_DELTA_TENSION: f64 = 0.05;

/// Core decision function.
///
/// Phase 2: rules only. Phase 6 adds the LLM fallback path.
pub fn decide(input: &DecisionInput) -> ActionPlan {
    // 0. Tip on a user message — always reply, never ghost. Tone is driven by
    //    tip_personality (injected into the prompt downstream); the ReplyStyle
    //    here is only a baseline / fallback. Affinity deltas stay normal.
    if let Event::UserMessage {
        tips_amount_usd: Some(_),
        ..
    } = &input.event
    {
        let reply_style = match input.persona.genome.tip_personality.as_deref() {
            Some(_) => ReplyStyle::Neutral,
            None => ReplyStyle::Tsundere,
        };
        return ActionPlan {
            action_type: ActionType::ReplyText,
            reply_style,
            affinity_deltas: predict_reply_deltas(input),
            energy_cost: ENERGY_COST_REPLY,
            context_hints: vec![],
            reply_tone: None,
            image_prompt: None,
            image_ref: ImageRef::Face,
            aspect_ratio: None,
        };
    }

    // 1. Ghost judgement (via existing ghost module)
    let ghost_signals = GhostSignals {
        message_count: input.signals.message_count,
        hours_since_last_ghost: input.signals.hours_since_last_ghost,
    };
    if ghost::decide(&input.affinity, ghost_signals) == GhostDecision::Ghost {
        return ActionPlan {
            action_type: ActionType::Ghost,
            reply_style: ReplyStyle::Cold,
            affinity_deltas: ghost_affinity_deltas(),
            energy_cost: ENERGY_COST_GHOST,
            context_hints: vec![],
            reply_tone: None,
            image_prompt: None,
            image_ref: ImageRef::Face,
            aspect_ratio: None,
        };
    }

    // 2. Proactive trigger is passed through — Phase 6 defines full behaviour
    if matches!(input.event, Event::ProactiveTrigger) {
        return ActionPlan {
            action_type: ActionType::Proactive,
            reply_style: ReplyStyle::Neutral,
            affinity_deltas: AffinityDeltas::default(),
            energy_cost: ENERGY_COST_PROACTIVE,
            context_hints: vec![],
            reply_tone: None,
            image_prompt: None,
            image_ref: ImageRef::Face,
            aspect_ratio: None,
        };
    }

    // 3. AppOpen: user just opened the app — route to Proactive path with no cost.
    // Handler / post-process decide whether to actually send anything.
    if matches!(input.event, Event::AppOpen) {
        return ActionPlan {
            action_type: ActionType::Proactive,
            reply_style: ReplyStyle::Neutral,
            affinity_deltas: AffinityDeltas::default(),
            energy_cost: ENERGY_COST_APP_OPEN,
            context_hints: vec![],
            reply_tone: None,
            image_prompt: None,
            image_ref: ImageRef::Face,
            aspect_ratio: None,
        };
    }

    // 4. Regular reply
    ActionPlan {
        action_type: ActionType::ReplyText,
        reply_style: ReplyStyle::Neutral,
        affinity_deltas: predict_reply_deltas(input),
        energy_cost: ENERGY_COST_REPLY,
        context_hints: vec![],
        reply_tone: None,
        image_prompt: None,
        image_ref: ImageRef::Face,
        aspect_ratio: None,
    }
}

/// Build the `ActionPlan` for an LLM-chosen action, reusing the rule heuristic
/// and energy constants internally. Per action:
///   ReplyText / ReplyImage / ReplyTextImage → Neutral, predict_reply_deltas,
///                                              ENERGY_COST_REPLY, context_hints = hints,
///                                              reply_tone kept (ReplyImage drops it)
///   Ghost                                   → Cold, ghost_affinity_deltas,
///                                              ENERGY_COST_GHOST, hints discarded, tone discarded
///   ProductQa                               → Neutral, all-zero deltas, zero energy,
///                                              hints/tone dropped (out-of-character aside)
///   Proactive                               → unreachable! (comes only from decide)
pub fn plan_for(
    input: &DecisionInput,
    action: ActionType,
    hints: Vec<String>,
    reply_tone: Option<String>,
    image_prompt: Option<String>,
    image_ref: ImageRef,
    aspect_ratio: Option<String>,
) -> ActionPlan {
    match action {
        ActionType::ReplyText | ActionType::ReplyImage | ActionType::ReplyTextImage => ActionPlan {
            action_type: action,
            reply_style: ReplyStyle::Neutral,
            affinity_deltas: predict_reply_deltas(input),
            energy_cost: ENERGY_COST_REPLY,
            context_hints: hints,
            // Delivery directive only makes sense where there is text to
            // deliver; a bare image turn drops it.
            reply_tone: if matches!(action, ActionType::ReplyImage) {
                None
            } else {
                reply_tone
            },
            image_prompt,
            image_ref,
            aspect_ratio,
        },
        ActionType::Ghost => ActionPlan {
            action_type: ActionType::Ghost,
            reply_style: ReplyStyle::Cold,
            affinity_deltas: ghost_affinity_deltas(),
            energy_cost: ENERGY_COST_GHOST,
            context_hints: vec![],
            reply_tone: None,
            image_prompt: None,
            image_ref: ImageRef::Face,
            aspect_ratio: None,
        },
        ActionType::ProductQa => ActionPlan {
            action_type: ActionType::ProductQa,
            reply_style: ReplyStyle::Neutral,
            // Out-of-character aside: no relationship movement, no energy,
            // no persona-prompt inputs (hints/tone are dropped — there is no
            // companion prompt to fold them into).
            affinity_deltas: AffinityDeltas::default(),
            energy_cost: 0.0,
            context_hints: vec![],
            reply_tone: None,
            image_prompt: None,
            image_ref: ImageRef::Face,
            aspect_ratio: None,
        },
        ActionType::Proactive => {
            unreachable!("plan_for is never called with Proactive; it comes only from pde::decide")
        }
    }
}

/// Predict affinity delta sign based on user message length / signals.
/// Conservative: small positive/negative heuristics only. Full evaluation
/// remains deterministic so no LLM JSON parsing is needed here.
fn predict_reply_deltas(input: &DecisionInput) -> AffinityDeltas {
    let mut d = AffinityDeltas::default();

    if let Event::UserMessage { content, .. } = &input.event {
        let chars = content.chars().count();
        // Long, thoughtful user message — small intrigue/patience bump
        if chars >= LONG_MSG_CHARS {
            d.intrigue += INTRIGUE_LONG_BUMP;
            d.patience += PATIENCE_LONG_BUMP;
        }
        // Very short/one-word — patience penalty
        if chars <= SHORT_MSG_CHARS {
            d.patience += PATIENCE_SHORT_PENALTY;
        }
    }

    // Time gap large — patience penalty + tension bump
    if input.signals.hours_since_last_message > STALE_HOURS {
        d.patience += PATIENCE_STALE_PENALTY;
        d.tension += TENSION_STALE_BUMP;
    }

    d
}

fn ghost_affinity_deltas() -> AffinityDeltas {
    AffinityDeltas {
        patience: GHOST_DELTA_PATIENCE,
        tension: GHOST_DELTA_TENSION,
        ..Default::default()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::affinity::Affinity;
    use crate::persona::{CompanionPersona, PersonaGenome, PersonaInstance};
    use crate::types::ConversationSignals;
    use chrono::Utc;
    use uuid::Uuid;

    fn base_persona() -> CompanionPersona {
        let iid = Uuid::new_v4();
        let gid = Uuid::new_v4();
        let oid = Uuid::new_v4();
        CompanionPersona {
            instance_id: iid,
            genome: PersonaGenome {
                id: gid,
                name: "Mia".into(),
                system_prompt: "You are Mia.".into(),
                tip_personality: Some("normal".into()),
                art_metadata: serde_json::json!({}),
            },
            instance: PersonaInstance {
                id: iid,
                genome_id: gid,
                owner_uid: oid,
                status: "active".into(),
            },
        }
    }

    fn base_affinity() -> Affinity {
        let now = Utc::now();
        Affinity {
            id: Uuid::new_v4(),
            session_id: Uuid::new_v4(),
            user_id: Uuid::new_v4(),
            instance_id: Uuid::new_v4(),
            warmth: 0.4,
            trust: 0.3,
            intrigue: 0.5,
            intimacy: 0.2,
            patience: 0.5,
            tension: 0.1,
            ghost_streak: 0,
            last_ghost_at: None,
            total_ghosts: 0,
            relationship_label: None,
            created_at: now,
            updated_at: now,
        }
    }

    fn base_signals() -> ConversationSignals {
        ConversationSignals {
            message_count: 20,
            hours_since_last_message: 1.0,
            ghost_streak: 0,
            hours_since_last_ghost: Some(10.0),
        }
    }

    fn user_msg(content: &str) -> Event {
        Event::UserMessage {
            content: content.into(),
            message_id: Uuid::new_v4(),
            prompt_traits: Vec::new(),
            audit: None,
            tier: None,
            memory_scope: Default::default(),
            affinity_scope: Default::default(),
            tips_amount_usd: None,
            history_anchor: Default::default(),
        }
    }

    fn tip_msg(amount: f64) -> Event {
        Event::UserMessage {
            content: String::new(),
            message_id: Uuid::new_v4(),
            prompt_traits: Vec::new(),
            audit: None,
            tier: None,
            memory_scope: Default::default(),
            affinity_scope: Default::default(),
            tips_amount_usd: Some(amount),
            history_anchor: Default::default(),
        }
    }

    fn persona_with_tip(tip: Option<&str>) -> CompanionPersona {
        let mut p = base_persona();
        p.genome.tip_personality = tip.map(String::from);
        p
    }

    #[test]
    fn test_tip_forces_reply_even_when_ghost_signals_present() {
        // Same affinity that drives test_ghost_threshold_triggers_ghost_action.
        let mut affinity = base_affinity();
        affinity.intrigue = 0.05;
        affinity.patience = 0.05;
        affinity.tension = 0.5;
        let input = DecisionInput {
            event: tip_msg(20.0),
            affinity,
            persona: persona_with_tip(None),
            signals: base_signals(),
        };
        let plan = decide(&input);
        assert_eq!(
            plan.action_type,
            ActionType::ReplyText,
            "a tip must never be ghosted"
        );
    }

    #[test]
    fn test_tip_reply_style_neutral_when_personality_present() {
        let input = DecisionInput {
            event: tip_msg(20.0),
            affinity: base_affinity(),
            persona: persona_with_tip(Some("傲娇")),
            signals: base_signals(),
        };
        let plan = decide(&input);
        assert_eq!(plan.action_type, ActionType::ReplyText);
        assert_eq!(plan.reply_style, ReplyStyle::Neutral);
    }

    #[test]
    fn test_tip_reply_style_tsundere_when_personality_absent() {
        let input = DecisionInput {
            event: tip_msg(20.0),
            affinity: base_affinity(),
            persona: persona_with_tip(None),
            signals: base_signals(),
        };
        let plan = decide(&input);
        assert_eq!(plan.action_type, ActionType::ReplyText);
        assert_eq!(plan.reply_style, ReplyStyle::Tsundere);
    }

    #[test]
    fn test_ghost_threshold_triggers_ghost_action() {
        let mut affinity = base_affinity();
        affinity.intrigue = 0.05;
        affinity.patience = 0.05;
        affinity.tension = 0.5;

        let input = DecisionInput {
            event: user_msg("."),
            affinity,
            persona: base_persona(),
            signals: base_signals(),
        };
        let plan = decide(&input);
        assert_eq!(plan.action_type, ActionType::Ghost);
    }

    #[test]
    fn test_new_relationship_never_ghosts() {
        let mut affinity = base_affinity();
        affinity.intrigue = 0.05;
        affinity.patience = 0.05;
        affinity.tension = 0.5;

        let mut signals = base_signals();
        signals.message_count = 3; // within protection window

        let input = DecisionInput {
            event: user_msg("hello"),
            affinity,
            persona: base_persona(),
            signals,
        };
        let plan = decide(&input);
        assert_eq!(plan.action_type, ActionType::ReplyText);
    }

    #[test]
    fn test_long_message_predicts_positive_intrigue() {
        let input = DecisionInput {
            event: user_msg(&"deep content".repeat(10)),
            affinity: base_affinity(),
            persona: base_persona(),
            signals: base_signals(),
        };
        let plan = decide(&input);
        assert!(plan.affinity_deltas.intrigue > 0.0);
    }

    #[test]
    fn test_long_absence_penalises_patience() {
        let mut signals = base_signals();
        signals.hours_since_last_message = 48.0;

        let input = DecisionInput {
            event: user_msg("hey"),
            affinity: base_affinity(),
            persona: base_persona(),
            signals,
        };
        let plan = decide(&input);
        assert!(plan.affinity_deltas.patience < 0.0);
    }

    #[test]
    fn test_app_open_does_not_reply_and_has_zero_cost() {
        let input = DecisionInput {
            event: Event::AppOpen,
            affinity: base_affinity(),
            persona: base_persona(),
            signals: base_signals(),
        };
        let plan = decide(&input);
        assert_eq!(plan.action_type, ActionType::Proactive);
        assert_eq!(plan.energy_cost, 0.0);
    }

    #[test]
    fn test_short_msg_and_stale_both_apply_to_patience() {
        let mut signals = base_signals();
        signals.hours_since_last_message = 48.0;
        let input = DecisionInput {
            event: user_msg("k"),
            affinity: base_affinity(),
            persona: base_persona(),
            signals,
        };
        let plan = decide(&input);
        // short penalty (-0.02) + stale penalty (-0.05) = -0.07
        assert!((plan.affinity_deltas.patience - (-0.07)).abs() < 1e-9);
    }

    fn test_decision_input() -> DecisionInput {
        DecisionInput {
            event: user_msg("hello"),
            affinity: base_affinity(),
            persona: base_persona(),
            signals: base_signals(),
        }
    }

    #[test]
    fn plan_for_reply_text_is_neutral_with_hints() {
        let input = test_decision_input();
        let plan = plan_for(
            &input,
            ActionType::ReplyText,
            vec!["有点开心".into()],
            None,
            None,
            ImageRef::Face,
            None,
        );
        assert_eq!(plan.action_type, ActionType::ReplyText);
        assert_eq!(plan.reply_style, ReplyStyle::Neutral);
        assert_eq!(plan.context_hints, vec!["有点开心".to_string()]);
        assert_eq!(plan.energy_cost, ENERGY_COST_REPLY);
    }

    #[test]
    fn plan_for_ghost_is_cold_and_drops_hints() {
        let input = test_decision_input();
        let plan = plan_for(
            &input,
            ActionType::Ghost,
            vec!["想躲".into()],
            None,
            None,
            ImageRef::Face,
            None,
        );
        assert_eq!(plan.action_type, ActionType::Ghost);
        assert_eq!(plan.reply_style, ReplyStyle::Cold);
        assert!(plan.context_hints.is_empty());
        assert_eq!(plan.energy_cost, ENERGY_COST_GHOST);
    }

    #[test]
    fn plan_for_threads_image_prompt() {
        let input = test_decision_input();
        let plan = plan_for(
            &input,
            ActionType::ReplyTextImage,
            vec![],
            None,
            Some("a selfie in a cafe".to_string()),
            ImageRef::Face,
            None,
        );
        assert_eq!(plan.action_type, ActionType::ReplyTextImage);
        assert_eq!(plan.image_prompt.as_deref(), Some("a selfie in a cafe"));

        let ghost = plan_for(
            &input,
            ActionType::Ghost,
            vec![],
            None,
            Some("ignored".into()),
            ImageRef::Face,
            None,
        );
        assert_eq!(ghost.image_prompt, None, "ghost carries no image prompt");
    }

    #[test]
    fn plan_for_threads_image_ref_and_aspect() {
        let input = test_decision_input(); // reuse the helper the sibling plan_for tests use
        let plan = plan_for(
            &input,
            ActionType::ReplyImage,
            vec![],
            None,
            Some("a subject".into()),
            ImageRef::Previous,
            Some("9:16".into()),
        );
        assert_eq!(plan.image_ref, ImageRef::Previous);
        assert_eq!(plan.aspect_ratio.as_deref(), Some("9:16"));

        // ghost discards image fields → defaults
        let ghost = plan_for(
            &input,
            ActionType::Ghost,
            vec![],
            None,
            Some("ignored".into()),
            ImageRef::Previous,
            Some("9:16".into()),
        );
        assert_eq!(ghost.image_ref, ImageRef::Face);
        assert_eq!(ghost.aspect_ratio, None);
    }

    #[test]
    fn plan_for_keeps_tone_for_text_bearing_drops_for_image_and_ghost() {
        let input = test_decision_input(); // the existing fixture at pde.rs:431
        let tone = Some("语气敷衍一点".to_string());

        let text = plan_for(
            &input,
            ActionType::ReplyText,
            vec![],
            tone.clone(),
            None,
            ImageRef::Face,
            None,
        );
        assert_eq!(text.reply_tone.as_deref(), Some("语气敷衍一点"));

        let text_image = plan_for(
            &input,
            ActionType::ReplyTextImage,
            vec![],
            tone.clone(),
            Some("selfie".into()),
            ImageRef::Face,
            None,
        );
        assert_eq!(text_image.reply_tone.as_deref(), Some("语气敷衍一点"));

        let image_only = plan_for(
            &input,
            ActionType::ReplyImage,
            vec![],
            tone.clone(),
            Some("selfie".into()),
            ImageRef::Face,
            None,
        );
        assert_eq!(
            image_only.reply_tone, None,
            "reply_image has no text to tone"
        );

        let ghost = plan_for(
            &input,
            ActionType::Ghost,
            vec![],
            tone,
            None,
            ImageRef::Face,
            None,
        );
        assert_eq!(
            ghost.reply_tone, None,
            "ghost discards tone like it discards hints"
        );

        // Rule engine never tones.
        assert_eq!(decide(&input).reply_tone, None);
    }

    #[test]
    fn plan_for_product_qa_is_inert_out_of_character_plan() {
        let input = test_decision_input(); // the module's existing DecisionInput helper
        let plan = plan_for(
            &input,
            ActionType::ProductQa,
            vec!["ignored".into()],
            Some("ignored".into()),
            None,
            ImageRef::Face,
            None,
        );
        assert_eq!(plan.action_type, ActionType::ProductQa);
        assert_eq!(plan.reply_style, ReplyStyle::Neutral);
        // zero deltas — a product answer moves no relationship axis
        assert_eq!(plan.affinity_deltas.warmth, 0.0);
        assert_eq!(plan.affinity_deltas.trust, 0.0);
        assert_eq!(plan.affinity_deltas.intrigue, 0.0);
        assert_eq!(plan.affinity_deltas.intimacy, 0.0);
        assert_eq!(plan.affinity_deltas.patience, 0.0);
        assert_eq!(plan.affinity_deltas.tension, 0.0);
        assert_eq!(plan.energy_cost, 0.0);
        assert!(plan.context_hints.is_empty()); // hints/tone dropped — no persona prompt
        assert!(plan.reply_tone.is_none());
        assert!(!ActionType::ProductQa.is_text_reply());
    }
}