eros-engine-core 1.2.0

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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
// SPDX-License-Identifier: AGPL-3.0-only
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Affinity {
    pub id: Uuid,
    pub session_id: Uuid,
    pub user_id: Uuid,
    pub instance_id: Uuid,
    pub warmth: f64,   // -1.0 ..= 1.0
    pub trust: f64,    //  0.0 ..= 1.0
    pub intrigue: f64, //  0.0 ..= 1.0
    pub intimacy: f64, //  0.0 ..= 1.0
    pub patience: f64, //  0.0 ..= 1.0
    pub tension: f64,  //  0.0 ..= 1.0
    pub ghost_streak: i32,
    pub last_ghost_at: Option<DateTime<Utc>>,
    pub total_ghosts: i32,
    pub relationship_label: Option<RelationshipLabel>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RelationshipLabel {
    Stranger,
    Romantic,
    Friend,
    Frenemy,
    SlowBurn,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AffinityDeltas {
    pub warmth: f64,
    pub trust: f64,
    pub intrigue: f64,
    pub intimacy: f64,
    pub patience: f64,
    pub tension: f64,
}

impl Affinity {
    /// Apply committed deltas directly, clamping each axis to its range.
    /// Damping lives in `grade_turn`'s tier decay, so a committed delta means
    /// exactly what it says.
    pub fn apply_deltas(&mut self, d: &AffinityDeltas) {
        self.warmth = clamp(self.warmth + d.warmth, -1.0, 1.0);
        self.trust = clamp(self.trust + d.trust, 0.0, 1.0);
        self.intrigue = clamp(self.intrigue + d.intrigue, 0.0, 1.0);
        self.intimacy = clamp(self.intimacy + d.intimacy, 0.0, 1.0);
        self.patience = clamp(self.patience + d.patience, 0.0, 1.0);
        self.tension = clamp(self.tension + d.tension, 0.0, 1.0);
        self.updated_at = Utc::now();
    }

    pub fn apply_time_decay(&mut self) {
        let days = (Utc::now() - self.updated_at).num_minutes() as f64 / (60.0 * 24.0);
        if days <= 0.0 {
            return;
        }
        self.intrigue = clamp(self.intrigue - 0.01 * days, 0.0, 1.0);
        self.patience = clamp(self.patience + 0.005 * days, 0.0, 1.0);
        self.tension = clamp(self.tension - 0.005 * days, 0.0, 1.0);
    }

    /// Legacy 5-name relationship label (back-compat), derived purely from the
    /// two line scores — replaces the old multi-axis `infer_label` heuristic.
    /// New consumers should read `bond_label`/`chemistry_label`. `frenemy` is
    /// retired from emission (kept in the enum for parse compat).
    pub fn legacy_relationship_label(&self) -> RelationshipLabel {
        let bond = self.bond_score();
        let chem = self.chemistry_score();
        if tier_index(bond) == 1 && tier_index(chem) == 1 {
            return RelationshipLabel::Stranger;
        }
        if chem > bond {
            if tier_index(chem) >= 3 {
                RelationshipLabel::Romantic
            } else {
                RelationshipLabel::SlowBurn
            }
        } else {
            RelationshipLabel::Friend
        }
    }
}

fn clamp(v: f64, lo: f64, hi: f64) -> f64 {
    if v < lo {
        lo
    } else if v > hi {
        hi
    } else {
        v
    }
}

// ─── Bond / Chemistry lines (read-layer folds of the 6 axes) ────────
//
// Two composites folded from the unchanged 6-axis base. `warmth` is shared into
// both and FLOORED at 0 (a neutral/cold session contributes nothing, so a fresh
// session sits near 0). `patience` is rule-owned and excluded.
//
// Mirrored by the `bond`/`chemistry` GENERATED columns in store migration 0029
// (warmth floored via GREATEST(warmth,0)). Keep the formula in sync.

/// Tier upper bounds on a line's 0..1 score. Widening by design: easy early, a
/// grind near the top. Tier 1 = [0, T1), 2 = [T1, T2), 3 = [T2, T3),
/// 4 = [T3, T4), 5 = [T4, 1]. Tunable.
const TIER1_HI: f64 = 0.15;
const TIER2_HI: f64 = 0.35;
const TIER3_HI: f64 = 0.62;
const TIER4_HI: f64 = 0.9;

/// Floor of the top intimacy rung, on `max(bond_score, chemistry_score)`. Sits
/// *inside* tier 4 rather than on the tier-5 edge, deliberately loose: the rung
/// ladder exists to stop a stranger talking their way into a nude, not to make
/// intimacy expensive, and gating the top rung at the apex (`TIER4_HI`) is a
/// wall rather than a gate. The bottom rung still folds `TIER1_HI`, so only this
/// cut is independent — keep it in `(TIER3_HI, TIER4_HI)` so the rungs stay
/// coarser than the tier ladder they sit on. Tunable.
const INTIMACY_RUNG3_LO: f64 = 0.76;

const _: () = assert!(
    TIER3_HI < INTIMACY_RUNG3_LO && INTIMACY_RUNG3_LO < TIER4_HI,
    "the top intimacy rung must open inside tier 4, not at the apex"
);

/// Patience band cut-points: low = [0, LO), mid = [LO, HI), high = [HI, 1].
/// Separate from the tier ladder above on purpose — `patience` is rule-owned
/// and never folded into either composite, so it carries its own cuts. These
/// mirror the three bands the PDE judge prompt already prescribes; the engine
/// owns them so the judge classifies against a stated band instead of
/// comparing floats itself. Tunable.
const PATIENCE_LO: f64 = 0.35;
const PATIENCE_HI: f64 = 0.65;

/// 1..=5 tier index for a 0..1 line score.
fn tier_index(score: f64) -> u8 {
    if score < TIER1_HI {
        1
    } else if score < TIER2_HI {
        2
    } else if score < TIER3_HI {
        3
    } else if score < TIER4_HI {
        4
    } else {
        5
    }
}

/// Friendship-line tier (pure function of `bond_score`). Serialised snake_case
/// key is the frontend's lookup; Chinese display lives in the frontend.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum BondLabel {
    Acquaintance,
    Friend,
    CloseFriend,
    Confidant,
    Soulmate,
}

impl BondLabel {
    pub fn as_key(self) -> &'static str {
        match self {
            BondLabel::Acquaintance => "acquaintance",
            BondLabel::Friend => "friend",
            BondLabel::CloseFriend => "close_friend",
            BondLabel::Confidant => "confidant",
            BondLabel::Soulmate => "soulmate",
        }
    }
}

/// Romance-line tier (pure function of `chemistry_score`).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ChemistryLabel {
    Spark,
    Flirtation,
    Crush,
    Lover,
    Beloved,
}

impl ChemistryLabel {
    pub fn as_key(self) -> &'static str {
        match self {
            ChemistryLabel::Spark => "spark",
            ChemistryLabel::Flirtation => "flirtation",
            ChemistryLabel::Crush => "crush",
            ChemistryLabel::Lover => "lover",
            ChemistryLabel::Beloved => "beloved",
        }
    }
}

/// Patience band for the PDE judge. Three bands, not five: the judge prompt
/// prescribes one interaction register per band (how curt the tone runs,
/// whether irritation shows), and the engine states which band applies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PatienceBand {
    Low,
    Mid,
    High,
}

/// One line's tier transition this turn, as serialised keys.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LabelTransition {
    pub from: String,
    pub to: String,
}

/// Per-turn tier transition across the two lines. Serde skips `None` fields, so
/// a JSON object only carries the line(s) that actually moved.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TurnLabelChanges {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bond: Option<LabelTransition>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chemistry: Option<LabelTransition>,
}

impl TurnLabelChanges {
    pub fn is_empty(&self) -> bool {
        self.bond.is_none() && self.chemistry.is_none()
    }
}

/// Tier transition over a delta-only span (before = post-decay/pre-delta,
/// after = post-delta). `None` when neither line crossed a tier.
pub fn diff_labels(before: &Affinity, after: &Affinity) -> Option<TurnLabelChanges> {
    let bond = (before.bond_label() != after.bond_label()).then(|| LabelTransition {
        from: before.bond_label().as_key().to_string(),
        to: after.bond_label().as_key().to_string(),
    });
    let chemistry =
        (before.chemistry_label() != after.chemistry_label()).then(|| LabelTransition {
            from: before.chemistry_label().as_key().to_string(),
            to: after.chemistry_label().as_key().to_string(),
        });
    let changes = TurnLabelChanges { bond, chemistry };
    (!changes.is_empty()).then_some(changes)
}

impl Affinity {
    /// 0..1 friendship composite. warmth floored at 0; mirrors the `bond`
    /// generated column in migration 0029.
    pub fn bond_score(&self) -> f64 {
        let warm_pos = self.warmth.max(0.0);
        clamp((warm_pos + self.trust + self.intrigue) / 3.0, 0.0, 1.0)
    }

    /// 0..1 romance composite. warmth floored at 0; mirrors the `chemistry`
    /// generated column in migration 0029.
    pub fn chemistry_score(&self) -> f64 {
        let warm_pos = self.warmth.max(0.0);
        clamp((warm_pos + self.intimacy + self.tension) / 3.0, 0.0, 1.0)
    }

    /// Friendship-line tier label.
    pub fn bond_label(&self) -> BondLabel {
        match tier_index(self.bond_score()) {
            1 => BondLabel::Acquaintance,
            2 => BondLabel::Friend,
            3 => BondLabel::CloseFriend,
            4 => BondLabel::Confidant,
            _ => BondLabel::Soulmate,
        }
    }

    /// Romance-line tier label.
    pub fn chemistry_label(&self) -> ChemistryLabel {
        match tier_index(self.chemistry_score()) {
            1 => ChemistryLabel::Spark,
            2 => ChemistryLabel::Flirtation,
            3 => ChemistryLabel::Crush,
            4 => ChemistryLabel::Lover,
            _ => ChemistryLabel::Beloved,
        }
    }

    /// Coarse 1..=3 intimacy rung for the PDE image gate, taken over whichever
    /// line is further along. Rung 1 = both lines still tier 1; rung 3 = at or
    /// above `INTIMACY_RUNG3_LO`; rung 2 = everything between. `max` rather than
    /// a sum so a purely romantic track and a purely companionable one can each
    /// unlock on their own.
    ///
    /// The bottom cut folds `TIER1_HI` and so cannot drift away from the
    /// `Acquaintance` / `Spark` labels the rest of the system shows. The top cut
    /// is deliberately its own constant, set below the tier-5 apex — see
    /// `INTIMACY_RUNG3_LO`.
    pub fn intimacy_rung(&self) -> u8 {
        let s = self.bond_score().max(self.chemistry_score());
        if tier_index(s) == 1 {
            1
        } else if s < INTIMACY_RUNG3_LO {
            2
        } else {
            3
        }
    }

    /// Patience band. Reads the raw axis, not a composite — `patience` is
    /// rule-owned and stays outside both folds.
    pub fn patience_band(&self) -> PatienceBand {
        if self.patience < PATIENCE_LO {
            PatienceBand::Low
        } else if self.patience < PATIENCE_HI {
            PatienceBand::Mid
        } else {
            PatienceBand::High
        }
    }
}

// ─── Affinity 3.0 write-side pipeline (grades → raw → decay → penalty → gate) ───
//
// The judge reports per-axis *grades* (0..=4 magnitude + direction, folded to a
// signed integer at parse time); the engine owns every number. A grade converts
// to a raw delta, positive raw is damped by the line's tier, line-exclusive
// axes pay a cross-line penalty while the counterpart line is high, and the
// resulting real delta passes a threshold accumulator before it commits.
// Design spec: docs/superpowers/specs/2026-08-13-affinity-30-grade-pipeline-design.md

/// Tuning knobs for the 3.0 pipeline, env-driven server-side. Defaults
/// set the single-turn envelope: grade ±4 lands +0.20 / −0.30 per axis.
#[derive(Debug, Clone, PartialEq)]
pub struct AffinityTuning {
    /// Raw score per grade step (`AFFINITY_GRADE_UNIT`).
    pub grade_unit: f64,
    /// Extra multiplier on negative raw scores (`AFFINITY_NEG_FACTOR`) —
    /// keeps 2.0's "slow up, fast down" asymmetry.
    pub neg_factor: f64,
    /// Positive-delta damping per tier 1..=5 (`AFFINITY_TIER_DECAY`).
    pub tier_decay: [f64; 5],
    /// Cross-line penalty ceiling κ (`AFFINITY_CROSS_PENALTY`).
    pub cross_penalty: f64,
    /// Counterpart line score where the penalty starts (`AFFINITY_CROSS_PENALTY_START`).
    pub cross_penalty_start: f64,
    /// Commit threshold θ (`AFFINITY_DELTA_THRESHOLD`); 0 commits every turn.
    pub delta_threshold: f64,
    /// Multiplier on the judge's positive raw component for demo sessions
    /// (`AFFINITY_DEMO_BOOST`); rule nudges are unaffected.
    pub demo_boost: f64,
}

impl Default for AffinityTuning {
    fn default() -> Self {
        Self {
            grade_unit: 0.05,
            neg_factor: 1.5,
            tier_decay: [1.0, 0.70, 0.45, 0.25, 0.10],
            cross_penalty: 0.05,
            cross_penalty_start: 0.35,
            delta_threshold: 0.0,
            demo_boost: 1.4,
        }
    }
}

/// Signed judge grades, one per evaluated axis, −4..=4 (out-of-range input is
/// clamped). 0 = nothing happened, the overwhelmingly common verdict.
/// `patience` is absent by construction: it stays on its absolute channel.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AxisGrades {
    pub warmth: i8,
    pub trust: i8,
    pub intrigue: i8,
    pub intimacy: i8,
    pub tension: i8,
}

/// Per-axis balance the threshold gate is still holding back. Persisted as
/// JSONB on the affinity row; absent column reads as all-zero.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct PendingDeltas {
    #[serde(default)]
    pub warmth: f64,
    #[serde(default)]
    pub trust: f64,
    #[serde(default)]
    pub intrigue: f64,
    #[serde(default)]
    pub intimacy: f64,
    #[serde(default)]
    pub tension: f64,
}

impl PendingDeltas {
    pub fn is_zero(&self) -> bool {
        self.warmth == 0.0
            && self.trust == 0.0
            && self.intrigue == 0.0
            && self.intimacy == 0.0
            && self.tension == 0.0
    }
}

/// One turn through the 3.0 pipeline.
/// `raw` = grade conversion (boost applied) + rule deltas, pre-decay — what the
/// event row records as `deltas`. `committed` = what actually applies to the
/// axes this turn (zero while the gate holds). `pending` = the gate's new
/// balance. `patience` is a rule axis: its rule delta passes through both
/// `raw` and `committed` untouched (no decay, penalty or gating), so the
/// judge-failure fallback still lands 1:1.
#[derive(Debug, Clone, Default)]
pub struct GradeTurnOutcome {
    pub raw: AffinityDeltas,
    pub committed: AffinityDeltas,
    pub pending: PendingDeltas,
}

/// Run one judge verdict through conversion, tier decay, cross-line penalty
/// and the threshold gate. Pure: reads the *pre-turn* affinity snapshot (all
/// axes use the same tier lookup, so ordering inside a turn cannot matter) and
/// returns what to apply; the caller owns clamping and persistence.
pub fn grade_turn(
    a: &Affinity,
    grades: &AxisGrades,
    rule: &AffinityDeltas,
    pending: &PendingDeltas,
    boost: f64,
    t: &AffinityTuning,
) -> GradeTurnOutcome {
    // Pre-turn snapshot: every axis reads the same tiers and counterparts.
    let bond = a.bond_score();
    let chem = a.chemistry_score();
    let bond_tier = tier_index(bond) as usize;
    let chem_tier = tier_index(chem) as usize;

    let decay = |tier: usize| t.tier_decay[tier - 1];
    let penalty = |counterpart: f64| {
        let start = t.cross_penalty_start;
        let ramp = ((counterpart - start).max(0.0) / (1.0 - start)).powi(2);
        t.cross_penalty * ramp
    };

    // grade → raw: positive grades earn unit × boost, negative grades cost
    // unit × neg_factor. Rule nudges join pre-decay.
    let raw = |g: i8, rule_d: f64| {
        let g = f64::from(g.clamp(-4, 4));
        let judge = if g >= 0.0 {
            g * t.grade_unit * boost
        } else {
            g * t.grade_unit * t.neg_factor
        };
        judge + rule_d
    };

    // ρ = D·max(r,0) + min(r,0) − P·1[judged]: positive part damped, negative
    // part full price, the penalty only charged when the judge touched the axis.
    let real = |r: f64, own_tier: usize, counterpart: Option<f64>, judged: bool| {
        let p = match counterpart {
            Some(y) if judged => penalty(y),
            _ => 0.0,
        };
        decay(own_tier) * r.max(0.0) + r.min(0.0) - p
    };

    // Threshold gate: signed accumulation, everything commits once |acc| ≥ θ.
    let gate = |rho: f64, pend: f64| {
        let acc = pend + rho;
        if acc.abs() >= t.delta_threshold {
            (acc, 0.0)
        } else {
            (0.0, acc)
        }
    };

    let axis = |g: i8, rule_d: f64, own_tier: usize, counterpart: Option<f64>, pend: f64| {
        let r = raw(g, rule_d);
        let rho = real(r, own_tier, counterpart, g != 0);
        let (committed, pend) = gate(rho, pend);
        (r, committed, pend)
    };

    let max_tier = bond_tier.max(chem_tier);
    let (w_raw, w_com, w_pend) = axis(grades.warmth, rule.warmth, max_tier, None, pending.warmth);
    let (t_raw, t_com, t_pend) = axis(
        grades.trust,
        rule.trust,
        bond_tier,
        Some(chem),
        pending.trust,
    );
    let (ig_raw, ig_com, ig_pend) = axis(
        grades.intrigue,
        rule.intrigue,
        bond_tier,
        Some(chem),
        pending.intrigue,
    );
    let (im_raw, im_com, im_pend) = axis(
        grades.intimacy,
        rule.intimacy,
        chem_tier,
        Some(bond),
        pending.intimacy,
    );
    let (tn_raw, tn_com, tn_pend) = axis(
        grades.tension,
        rule.tension,
        chem_tier,
        Some(bond),
        pending.tension,
    );

    GradeTurnOutcome {
        raw: AffinityDeltas {
            warmth: w_raw,
            trust: t_raw,
            intrigue: ig_raw,
            intimacy: im_raw,
            tension: tn_raw,
            patience: rule.patience,
        },
        committed: AffinityDeltas {
            warmth: w_com,
            trust: t_com,
            intrigue: ig_com,
            intimacy: im_com,
            tension: tn_com,
            patience: rule.patience,
        },
        pending: PendingDeltas {
            warmth: w_pend,
            trust: t_pend,
            intrigue: ig_pend,
            intimacy: im_pend,
            tension: tn_pend,
        },
    }
}

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

    fn fresh() -> 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.3,
            trust: 0.2,
            intrigue: 0.5,
            intimacy: 0.0,
            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,
        }
    }

    #[test]
    fn apply_deltas_clamps_to_valid_ranges() {
        let mut a = fresh();
        a.apply_deltas(&AffinityDeltas {
            warmth: 5.0, // would push past 1.0
            trust: -2.0, // would push below 0.0
            intrigue: 0.1,
            intimacy: 0.0,
            patience: 0.0,
            tension: 0.0,
        });
        assert_eq!(a.warmth, 1.0, "warmth clamps to 1.0 (max)");
        assert_eq!(a.trust, 0.0, "trust clamps to 0.0 (min)");
        assert!((a.intrigue - 0.6).abs() < 1e-9);
    }

    #[test]
    fn warmth_can_go_negative_others_cannot() {
        let mut a = fresh();
        a.apply_deltas(&AffinityDeltas {
            warmth: -2.0, // -1.0 floor
            trust: 0.0,
            intrigue: 0.0,
            intimacy: 0.0,
            patience: 0.0,
            tension: 0.0,
        });
        assert_eq!(a.warmth, -1.0);
    }

    #[test]
    fn apply_deltas_is_direct_no_smoothing() {
        // A committed delta from grade_turn applies verbatim: 0.3 + 0.15 = 0.45.
        let mut a = fresh(); // warmth 0.3
        a.apply_deltas(&AffinityDeltas {
            warmth: 0.15,
            ..Default::default()
        });
        assert!((a.warmth - 0.45).abs() < 1e-9);
    }

    #[test]
    fn time_decay_reduces_intrigue_recovers_patience_softens_tension() {
        let mut a = fresh();
        a.intrigue = 0.5;
        a.patience = 0.5;
        a.tension = 0.5;
        a.warmth = 0.7;
        a.trust = 0.6;
        a.intimacy = 0.4;
        a.updated_at = Utc::now() - chrono::Duration::days(10);

        a.apply_time_decay();

        // 10 days * -0.01/day = -0.1
        assert!((a.intrigue - 0.4).abs() < 1e-9);
        // 10 days * +0.005/day = +0.05
        assert!((a.patience - 0.55).abs() < 1e-9);
        // 10 days * -0.005/day = -0.05
        assert!((a.tension - 0.45).abs() < 1e-9);
        // unchanged
        assert_eq!(a.warmth, 0.7);
        assert_eq!(a.trust, 0.6);
        assert_eq!(a.intimacy, 0.4);
    }

    #[test]
    fn time_decay_clamps_at_floors_and_ceilings() {
        let mut a = fresh();
        a.intrigue = 0.05;
        a.patience = 0.95;
        a.tension = 0.02;
        a.updated_at = Utc::now() - chrono::Duration::days(100);

        a.apply_time_decay();

        assert_eq!(a.intrigue, 0.0);
        assert_eq!(a.patience, 1.0);
        assert_eq!(a.tension, 0.0);
    }

    #[test]
    fn bond_chemistry_scores_fold_axes_with_warmth_floored() {
        let mut a = fresh();
        a.warmth = 0.2;
        a.trust = 0.4;
        a.intrigue = 0.6;
        a.intimacy = 0.1;
        a.tension = 0.3;
        // bond = (0.2 + 0.4 + 0.6)/3 = 0.4
        assert!((a.bond_score() - 0.4).abs() < 1e-9);
        // chemistry = (0.2 + 0.1 + 0.3)/3 = 0.2
        assert!((a.chemistry_score() - 0.2).abs() < 1e-9);
        // negative warmth floors to 0 in the composite
        a.warmth = -1.0;
        a.trust = 0.0;
        a.intrigue = 0.0;
        assert!((a.bond_score()).abs() < 1e-9);
    }

    #[test]
    fn tier_index_boundaries() {
        assert_eq!(tier_index(0.0), 1);
        assert_eq!(tier_index(0.149), 1);
        assert_eq!(tier_index(0.15), 2);
        assert_eq!(tier_index(0.349), 2);
        assert_eq!(tier_index(0.35), 3);
        assert_eq!(tier_index(0.619), 3);
        assert_eq!(tier_index(0.62), 4);
        assert_eq!(tier_index(0.899), 4);
        assert_eq!(tier_index(0.9), 5);
        assert_eq!(tier_index(1.0), 5);
    }

    /// Rung 1 stays welded to the bottom tier labels, so it cannot drift away
    /// from what the rest of the system displays. The top rung has a floor of
    /// its own, deliberately inside tier 4 — a tier-4 relationship already
    /// clears it, well short of the apex. (That the two ladders cannot cross is
    /// a compile-time assertion beside the constant. Exact cut values are not
    /// reachable through the `/3` composites in f64, hence values either side
    /// rather than on them.)
    #[test]
    fn intimacy_rung_cuts_against_the_tier_ladder() {
        let mut a = fresh();

        // Both lines at the bottom label → rung 1.
        a.warmth = 0.1;
        a.trust = 0.0;
        a.intrigue = 0.0;
        a.intimacy = 0.0;
        a.tension = 0.0;
        assert_eq!(a.bond_label(), BondLabel::Acquaintance);
        assert_eq!(a.chemistry_label(), ChemistryLabel::Spark);
        assert_eq!(a.intimacy_rung(), 1);

        // Clear of tier 1, short of the top floor → rung 2.
        a.warmth = 0.7;
        a.trust = 0.7;
        a.intrigue = 0.7;
        assert_eq!(a.intimacy_rung(), 2);

        // Past the floor while still tier 4 → rung 3 without reaching the apex.
        a.warmth = 0.8;
        a.trust = 0.8;
        a.intrigue = 0.8;
        assert_eq!(a.bond_label(), BondLabel::Confidant);
        assert_eq!(a.intimacy_rung(), 3);
    }

    /// `max` over the two lines: either track alone can unlock.
    #[test]
    fn intimacy_rung_takes_the_further_line() {
        let mut a = fresh();
        // chemistry = (warmth + intimacy + tension)/3 = 0.95, bond = 0.1
        a.warmth = 0.95;
        a.trust = 0.0;
        a.intrigue = 0.3;
        a.intimacy = 0.95;
        a.tension = 0.95;
        assert!(a.bond_score() < a.chemistry_score());
        assert_eq!(a.intimacy_rung(), 3);
        // Mirror image: bond ahead, chemistry flat.
        a.trust = 0.95;
        a.intrigue = 0.95;
        a.intimacy = 0.0;
        a.tension = 0.0;
        assert!(a.chemistry_score() < a.bond_score());
        assert_eq!(a.intimacy_rung(), 3);
    }

    /// A brand-new session (migration-0029 seed) is rung 1, not an absent value.
    #[test]
    fn intimacy_rung_of_a_seeded_session_is_one() {
        let mut a = fresh();
        a.warmth = 0.1;
        a.trust = 0.0;
        a.intrigue = 0.0;
        a.intimacy = 0.0;
        a.tension = 0.0;
        assert!(a.bond_score().max(a.chemistry_score()) < TIER1_HI);
        assert_eq!(a.intimacy_rung(), 1);
    }

    #[test]
    fn patience_band_boundaries() {
        let mut a = fresh();
        let mut at = |p: f64| {
            a.patience = p;
            a.patience_band()
        };
        assert_eq!(at(0.0), PatienceBand::Low);
        assert_eq!(at(0.349), PatienceBand::Low);
        assert_eq!(at(0.35), PatienceBand::Mid); // low → mid, inclusive
        assert_eq!(at(0.649), PatienceBand::Mid);
        assert_eq!(at(0.65), PatienceBand::High); // mid → high, inclusive
        assert_eq!(at(1.0), PatienceBand::High);
    }

    /// The band reads the raw axis: moving the composites must not move it.
    #[test]
    fn patience_band_is_independent_of_the_composites() {
        let mut a = fresh();
        a.patience = 0.2;
        a.warmth = 1.0;
        a.trust = 1.0;
        a.intrigue = 1.0;
        a.intimacy = 1.0;
        a.tension = 1.0;
        assert_eq!(a.intimacy_rung(), 3);
        assert_eq!(a.patience_band(), PatienceBand::Low);
    }

    #[test]
    fn labels_map_from_scores() {
        let mut a = fresh();
        a.warmth = 0.0;
        a.trust = 0.0;
        a.intrigue = 0.0;
        assert_eq!(a.bond_label(), BondLabel::Acquaintance); // bond 0
        a.trust = 0.6;
        a.intrigue = 0.6; // bond = 0.4 → tier 3
        assert_eq!(a.bond_label(), BondLabel::CloseFriend);
        a.warmth = 0.0;
        a.intimacy = 0.0;
        a.tension = 0.0;
        assert_eq!(a.chemistry_label(), ChemistryLabel::Spark); // chem 0
        a.intimacy = 1.0;
        a.tension = 1.0; // chem = 0.667 → tier 4
        assert_eq!(a.chemistry_label(), ChemistryLabel::Lover);
        // tier 5 apex
        a.warmth = 1.0;
        a.trust = 1.0;
        a.intrigue = 1.0; // bond = 1.0 → tier 5
        assert_eq!(a.bond_label(), BondLabel::Soulmate);
        a.intimacy = 1.0;
        a.tension = 1.0; // chem = 1.0 → tier 5
        assert_eq!(a.chemistry_label(), ChemistryLabel::Beloved);
        assert_eq!(BondLabel::Soulmate.as_key(), "soulmate");
        assert_eq!(ChemistryLabel::Beloved.as_key(), "beloved");
    }

    #[test]
    fn legacy_label_stranger_when_both_tier1() {
        let mut a = fresh();
        a.warmth = 0.0;
        a.trust = 0.0;
        a.intrigue = 0.0;
        a.intimacy = 0.0;
        a.tension = 0.0;
        assert_eq!(a.legacy_relationship_label(), RelationshipLabel::Stranger);
    }

    #[test]
    fn legacy_label_friend_when_bond_leads() {
        let mut a = fresh();
        // bond = (0.3+0.6+0.6)/3 = 0.5 ; chem = (0.3+0+0)/3 = 0.1
        a.warmth = 0.3;
        a.trust = 0.6;
        a.intrigue = 0.6;
        a.intimacy = 0.0;
        a.tension = 0.0;
        assert_eq!(a.legacy_relationship_label(), RelationshipLabel::Friend);
    }

    #[test]
    fn legacy_label_romantic_when_chemistry_high() {
        let mut a = fresh();
        // chem = (0.3+0.9+0.9)/3 = 0.7 (tier4) ; bond = 0.1
        a.warmth = 0.3;
        a.intimacy = 0.9;
        a.tension = 0.9;
        a.trust = 0.0;
        a.intrigue = 0.0;
        assert_eq!(a.legacy_relationship_label(), RelationshipLabel::Romantic);
    }

    #[test]
    fn legacy_label_slow_burn_when_chemistry_leads_but_mid() {
        let mut a = fresh();
        // chem = (0.3+0.3+0.2)/3 ≈ 0.267 (tier2) ; bond = 0.1 (tier1)
        a.warmth = 0.3;
        a.intimacy = 0.3;
        a.tension = 0.2;
        a.trust = 0.0;
        a.intrigue = 0.0;
        assert_eq!(a.legacy_relationship_label(), RelationshipLabel::SlowBurn);
    }

    #[test]
    fn diff_labels_none_when_no_tier_change() {
        let a = fresh();
        let b = a.clone();
        assert!(diff_labels(&a, &b).is_none());
    }

    #[test]
    fn diff_labels_reports_single_line_change() {
        let mut before = fresh();
        before.warmth = 0.0;
        before.trust = 0.0;
        before.intrigue = 0.0;
        before.intimacy = 0.0;
        before.tension = 0.0; // bond + chem both tier 1
        let mut after = before.clone();
        after.trust = 0.9;
        after.intrigue = 0.9; // bond = 0.6 → tier 3 (close_friend)
        let d = diff_labels(&before, &after).unwrap();
        let bond = d.bond.unwrap();
        assert_eq!(bond.from, "acquaintance");
        assert_eq!(bond.to, "close_friend");
        assert!(d.chemistry.is_none());
    }

    // ─── affinity 3.0 pipeline ───

    fn zeroed() -> Affinity {
        let mut a = fresh();
        a.warmth = 0.0;
        a.trust = 0.0;
        a.intrigue = 0.0;
        a.intimacy = 0.0;
        a.tension = 0.0;
        a
    }

    fn turn(
        a: &Affinity,
        grades: AxisGrades,
        rule: AffinityDeltas,
        pending: PendingDeltas,
        boost: f64,
        t: &AffinityTuning,
    ) -> GradeTurnOutcome {
        grade_turn(a, &grades, &rule, &pending, boost, t)
    }

    /// P3 envelope continuity: with defaults, grade +4 lands +0.20 and grade −4
    /// lands −0.30 — the 2.0 effective caps, bit for bit. patience never moves.
    #[test]
    fn grade_envelope_matches_2_0_effective_caps() {
        let a = zeroed();
        let o = turn(
            &a,
            AxisGrades {
                warmth: 4,
                trust: -4,
                ..Default::default()
            },
            AffinityDeltas::default(),
            PendingDeltas::default(),
            1.0,
            &AffinityTuning::default(),
        );
        assert!((o.raw.warmth - 0.2).abs() < 1e-9);
        assert!((o.committed.warmth - 0.2).abs() < 1e-9);
        assert!((o.committed.trust - (-0.3)).abs() < 1e-9);
        assert_eq!(o.raw.patience, 0.0);
        assert_eq!(o.committed.patience, 0.0);
    }

    /// Positive raw is damped by the OWN line's tier; a counterpart line inside
    /// the grace zone charges no penalty, past it the quadratic ramp starts.
    #[test]
    fn positive_decays_by_own_tier_and_pays_counterpart_ramp() {
        let mut a = zeroed();
        a.trust = 0.75;
        a.intrigue = 0.75; // bond = 0.5 → tier 3; chemistry = 0 → tier 1
        let o = turn(
            &a,
            AxisGrades {
                trust: 2,
                intimacy: 2,
                ..Default::default()
            },
            AffinityDeltas::default(),
            PendingDeltas::default(),
            1.0,
            &AffinityTuning::default(),
        );
        // trust: own tier 3 → 0.45 × 0.10, counterpart chem 0 → no penalty
        assert!((o.committed.trust - 0.045).abs() < 1e-9);
        // intimacy: own tier 1 → ×1.0, counterpart bond 0.5 → κ·((0.15/0.65)²)
        let p = 0.05 * (0.15f64 / 0.65).powi(2);
        assert!((o.committed.intimacy - (0.10 - p)).abs() < 1e-9);
    }

    /// warmth feeds both lines, so its damping reads the FURTHER line's tier
    /// (same max rule as the intimacy rung) and it never pays the penalty.
    #[test]
    fn warmth_decays_by_max_tier_and_is_penalty_exempt() {
        let mut a = zeroed();
        a.warmth = 0.85;
        a.intimacy = 1.0;
        a.tension = 1.0; // chemistry = 0.95 → tier 5; bond ≈ 0.283 → tier 2
        let o = turn(
            &a,
            AxisGrades {
                warmth: 2,
                ..Default::default()
            },
            AffinityDeltas::default(),
            PendingDeltas::default(),
            1.0,
            &AffinityTuning::default(),
        );
        assert!((o.committed.warmth - 0.1 * 0.10).abs() < 1e-9);
    }

    /// A positive push on an exclusive axis can be penalised through zero when
    /// the counterpart line is maxed — the friend-zone wall.
    #[test]
    fn penalty_flips_small_positive_pushes_negative() {
        let mut a = zeroed();
        a.warmth = 1.0;
        a.intimacy = 1.0;
        a.tension = 1.0; // chemistry = 1.0; bond = 1/3 → tier 2
        let g1 = turn(
            &a,
            AxisGrades {
                trust: 1,
                ..Default::default()
            },
            AffinityDeltas::default(),
            PendingDeltas::default(),
            1.0,
            &AffinityTuning::default(),
        );
        // 0.7 × 0.05 − 0.05 = −0.015: honest effort, net loss
        assert!((g1.committed.trust - (-0.015)).abs() < 1e-9);
        let g2 = turn(
            &a,
            AxisGrades {
                trust: 2,
                ..Default::default()
            },
            AffinityDeltas::default(),
            PendingDeltas::default(),
            1.0,
            &AffinityTuning::default(),
        );
        // 0.7 × 0.10 − 0.05 = +0.02: a clearer moment still lands
        assert!((g2.committed.trust - 0.02).abs() < 1e-9);
    }

    /// Negative raw is never damped by tier, and the penalty stacks on top.
    #[test]
    fn negative_skips_decay_and_pays_extra() {
        let mut a = zeroed();
        a.warmth = 1.0;
        a.intimacy = 1.0;
        a.tension = 1.0; // chemistry = 1.0
        a.trust = 0.9;
        a.intrigue = 0.9; // bond ≈ 0.933 → tier 5 (own tier must not soften the loss)
        let o = turn(
            &a,
            AxisGrades {
                trust: -2,
                ..Default::default()
            },
            AffinityDeltas::default(),
            PendingDeltas::default(),
            1.0,
            &AffinityTuning::default(),
        );
        // −2 × 0.05 × 1.5 = −0.15, minus κ·φ(1.0) = 0.05 → −0.20
        assert!((o.committed.trust - (-0.20)).abs() < 1e-9);
    }

    /// P6: the pipeline charges events, not rent — an all-zero verdict moves
    /// nothing no matter how high the lines sit, and pending survives intact.
    #[test]
    fn zero_verdict_charges_nothing() {
        let mut a = zeroed();
        a.warmth = 1.0;
        a.trust = 1.0;
        a.intrigue = 1.0;
        a.intimacy = 1.0;
        a.tension = 1.0;
        let pending = PendingDeltas {
            trust: 0.02,
            ..Default::default()
        };
        let t = AffinityTuning {
            delta_threshold: 0.5,
            ..Default::default()
        };
        let o = turn(
            &a,
            AxisGrades::default(),
            AffinityDeltas::default(),
            pending,
            1.0,
            &t,
        );
        assert_eq!(o.committed.trust, 0.0);
        assert_eq!(o.committed.warmth, 0.0);
        assert!((o.pending.trust - 0.02).abs() < 1e-9);
    }

    /// Rule nudges ride the same decay but never trigger the penalty (only a
    /// judge-touched axis pays it).
    #[test]
    fn rule_only_delta_decays_but_pays_no_penalty() {
        let mut a = zeroed();
        a.warmth = 1.0;
        a.intimacy = 1.0;
        a.tension = 1.0; // chem 1.0; bond 1/3 → tier 2
        let o = turn(
            &a,
            AxisGrades::default(),
            AffinityDeltas {
                intrigue: 0.02,
                ..Default::default()
            },
            PendingDeltas::default(),
            1.0,
            &AffinityTuning::default(),
        );
        assert!((o.committed.intrigue - 0.7 * 0.02).abs() < 1e-9);
    }

    /// The decision-doc threshold example, verbatim: θ=0.5, real scores
    /// 0.1 / 0.2 / 0.3 per turn → committed deltas 0 / 0 / 0.6.
    #[test]
    fn threshold_accumulates_until_it_clears() {
        let a = zeroed(); // trust stays 0 (nothing commits), so tier stays 1 and D=1
        let t = AffinityTuning {
            delta_threshold: 0.5,
            ..Default::default()
        };
        let mut pending = PendingDeltas::default();
        let mut committed = Vec::new();
        for r in [0.1, 0.2, 0.3] {
            let o = turn(
                &a,
                AxisGrades::default(),
                AffinityDeltas {
                    trust: r,
                    ..Default::default()
                },
                pending,
                1.0,
                &t,
            );
            committed.push(o.committed.trust);
            pending = o.pending;
        }
        assert_eq!(committed[0], 0.0);
        assert_eq!(committed[1], 0.0);
        assert!((committed[2] - 0.6).abs() < 1e-9);
        assert!(pending.is_zero());
    }

    /// Signed accumulation: opposite-sign real scores cancel inside the gate,
    /// and a cancelled balance neither commits nor lingers.
    #[test]
    fn threshold_gate_cancels_opposite_signs() {
        let a = zeroed();
        let t = AffinityTuning {
            delta_threshold: 0.5,
            ..Default::default()
        };
        let o = turn(
            &a,
            AxisGrades::default(),
            AffinityDeltas {
                trust: -0.1,
                ..Default::default()
            },
            PendingDeltas {
                trust: 0.1,
                ..Default::default()
            },
            1.0,
            &t,
        );
        assert_eq!(o.committed.trust, 0.0);
        assert_eq!(o.pending.trust, 0.0, "+0.1 pending − 0.1 real cancels out");
    }

    /// Demo boost multiplies positive raw only; losses stay full price.
    #[test]
    fn demo_boost_is_positive_only() {
        let a = zeroed();
        let o = turn(
            &a,
            AxisGrades {
                warmth: 1,
                trust: -1,
                ..Default::default()
            },
            AffinityDeltas::default(),
            PendingDeltas::default(),
            1.4,
            &AffinityTuning::default(),
        );
        assert!((o.committed.warmth - 0.07).abs() < 1e-9);
        assert!((o.committed.trust - (-0.075)).abs() < 1e-9);
    }

    /// patience is a rule axis: its rule delta passes through the pipeline
    /// untouched — no decay, no penalty, no threshold gate — so the fallback
    /// path (judge eval failed, rule nudges only) still lands 1:1.
    #[test]
    fn rule_patience_passes_through_ungated() {
        let a = zeroed();
        let t = AffinityTuning {
            delta_threshold: 0.5, // must NOT buffer patience
            ..Default::default()
        };
        let o = turn(
            &a,
            AxisGrades::default(),
            AffinityDeltas {
                patience: -0.02,
                ..Default::default()
            },
            PendingDeltas::default(),
            1.0,
            &t,
        );
        assert!((o.committed.patience - (-0.02)).abs() < 1e-9);
        assert!((o.raw.patience - (-0.02)).abs() < 1e-9);
    }

    /// Out-of-range grades clamp instead of scaling: the judge cannot mint
    /// more than a ±4 verdict no matter what it emits.
    #[test]
    fn grades_clamp_to_plus_minus_four() {
        let a = zeroed();
        let o = turn(
            &a,
            AxisGrades {
                warmth: 9,
                trust: -9,
                ..Default::default()
            },
            AffinityDeltas::default(),
            PendingDeltas::default(),
            1.0,
            &AffinityTuning::default(),
        );
        assert!((o.committed.warmth - 0.2).abs() < 1e-9);
        assert!((o.committed.trust - (-0.3)).abs() < 1e-9);
    }

    #[test]
    fn diff_labels_reports_both_lines() {
        let mut before = fresh();
        before.warmth = 0.0;
        before.trust = 0.0;
        before.intrigue = 0.0;
        before.intimacy = 0.0;
        before.tension = 0.0;
        let mut after = before.clone();
        after.trust = 0.9;
        after.intrigue = 0.9; // bond → close_friend
        after.intimacy = 0.9;
        after.tension = 0.9; // chem = 0.6 → tier 3 (crush)
        let d = diff_labels(&before, &after).unwrap();
        assert_eq!(d.bond.unwrap().to, "close_friend");
        assert_eq!(d.chemistry.unwrap().to, "crush");
    }
}