smos-domain 0.2.1

SMOS domain layer — entities, value objects, pure domain logic. NO IO dependencies.
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
//! `Fact` aggregate root — canonical stored memory.
//!
//! The fact is the central aggregate of SMOS. All mutations go through methods
//! that enforce the aggregate's five invariants; there are no public setters
//! for individual fields. Status transitions are gated so a finalised fact
//! cannot be silently resurrected.

use crate::config::{ConfidenceConfig, MergeConfig};
use crate::enums::{FactStatus, FactType, NliLabel};
use crate::error::DomainError;
use crate::value_objects::{
    Confidence, Cosine, Embedding, FactContent, FactId, Heat, MemoryKey, NliResult, SessionId,
    SourceSessions, Timestamp,
};
use serde::{Deserialize, Serialize};

/// Canonical English statement about the world, sourced from one or more
/// sessions, classified by NLI, and retrievable by similarity.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Fact {
    id: FactId,
    memory_key: MemoryKey,
    content: FactContent,
    fact_type: FactType,
    confidence: Confidence,
    status: FactStatus,
    valid_from: Timestamp,
    valid_until: Option<Timestamp>,
    extracted_at: Timestamp,
    source_sessions: SourceSessions,
    conflicts_with: Vec<FactId>,
    heat_base: Heat,
    last_access_at: Timestamp,
    embedding: Option<Embedding>,
}

/// One pool member that survived the cosine merge threshold.
///
/// Deliberately not `PartialEq`: comparing full `Fact` clones is brittle (it
/// drags in `f32` via `Confidence`/`Heat`). Tests compare fields directly.
#[derive(Debug, Clone)]
pub struct MergeCandidate {
    /// Cloned existing fact (a pool member).
    pub fact: Fact,
    pub cosine_similarity: Cosine,
}

/// Named-argument bundle for [`Fact::rehydrate`]: the full persisted
/// state of a `Fact`, one field per positional parameter of [`Fact::rehydrate`].
///
/// Persistence adapters assemble this on read and hand it to
/// [`Fact::rehydrate`]; the record-struct shape makes call sites
/// order-independent and self-documenting, eliminating the 14-argument
/// positional data-clump. Field types and order mirror `Fact` itself so the
/// round-trip `save(f); get(id) == f` holds exactly.
#[derive(Debug, Clone)]
pub struct FactRecord {
    pub id: FactId,
    pub memory_key: MemoryKey,
    pub content: FactContent,
    pub fact_type: FactType,
    pub confidence: Confidence,
    pub status: FactStatus,
    pub valid_from: Timestamp,
    pub valid_until: Option<Timestamp>,
    pub extracted_at: Timestamp,
    pub source_sessions: SourceSessions,
    pub conflicts_with: Vec<FactId>,
    pub heat_base: Heat,
    pub last_access_at: Timestamp,
    pub embedding: Option<Embedding>,
}

/// Named-argument bundle for [`Fact::new_pending`]: the six inputs a
/// freshly-extracted pending fact needs.
///
/// `content` borrows (lifetime `'a`) so a caller holding a `&str` from the
/// extraction pipeline can construct the request without an intermediate
/// allocation. The borrowing request is consumed synchronously by
/// [`Fact::new_pending`], which returns an owned [`Fact`].
#[derive(Debug)]
pub struct NewPendingRequest<'a> {
    pub content: &'a str,
    pub memory_key: MemoryKey,
    pub session: SessionId,
    pub embedding: Embedding,
    pub extracted_at: Timestamp,
    pub base_confidence: f32,
}

impl Fact {
    /// Construct a fresh pending fact right after extraction.
    ///
    /// Defaults match the POC: status `Pending`, confidence `base_confidence`,
    /// heat `1.0`, fact_type `Entity`, no conflicts, no `valid_until`.
    /// Confidence and status are recomputed by [`Fact::reclassify`] once NLI
    /// is available. The caller passes the configured
    /// [`ConfidenceConfig::base`] (via [`NewPendingRequest::base_confidence`])
    /// so the domain stays free of the "default 0.5" hard-coding that bit the
    /// POC (a config tweak to `confidence.base` was silently ignored at
    /// extraction time).
    pub fn new_pending(req: NewPendingRequest<'_>) -> Result<Self, DomainError> {
        Ok(Self {
            id: FactId::from_content(req.content),
            memory_key: req.memory_key,
            content: FactContent::new(req.content.to_string())?,
            fact_type: FactType::Entity,
            confidence: Confidence::new(req.base_confidence)?,
            status: FactStatus::Pending,
            valid_from: req.extracted_at,
            valid_until: None,
            extracted_at: req.extracted_at,
            source_sessions: SourceSessions::from_one(req.session),
            conflicts_with: Vec::new(),
            heat_base: Heat::new(1.0)?,
            last_access_at: req.extracted_at,
            embedding: Some(req.embedding),
        })
    }

    /// Rehydrate a `Fact` from a persisted representation (storage → domain).
    ///
    /// This constructor is the **only** way to rebuild a fact with arbitrary
    /// field values; every other constructor derives some fields from inputs
    /// (e.g. [`Fact::new_pending`] derives `id` from content). Persistence
    /// adapters assemble a [`FactRecord`] on read and call this so the
    /// round-trip `save(f); get(id) == f` holds exactly, without recomputation
    /// that would silently mutate stored confidence/status/heat.
    ///
    /// All invariants are still enforced: confidence and heat must be in
    /// `[0.0, 1.0]`, `valid_until` (when `Some`) must be strictly after
    /// `valid_from`, and the id must equal `FactId::from_content(content)`.
    /// The constructor returns the matching `DomainError` if any invariant
    /// fails so the caller can surface data corruption rather than silently
    /// re-stamp it.
    pub fn rehydrate(rec: FactRecord) -> Result<Self, DomainError> {
        // Sanity check: the caller-supplied id must match the canonical
        // content-derived id. If it doesn't, the persisted row is corrupt
        // (someone wrote a row whose record id disagrees with its content).
        if rec.id != FactId::from_content(rec.content.as_str()) {
            return Err(DomainError::InvalidFactId(format!(
                "rehydrate id mismatch: record={} expected={}",
                rec.id,
                FactId::from_content(rec.content.as_str())
            )));
        }
        // `valid_until` invariant (mirrors `set_valid_until`).
        if let Some(until) = rec.valid_until
            && until <= rec.valid_from
        {
            return Err(DomainError::ValidUntilBeforeValidFrom {
                from: rec.valid_from,
                until,
            });
        }
        Ok(Self {
            id: rec.id,
            memory_key: rec.memory_key,
            content: rec.content,
            fact_type: rec.fact_type,
            confidence: rec.confidence,
            status: rec.status,
            valid_from: rec.valid_from,
            valid_until: rec.valid_until,
            extracted_at: rec.extracted_at,
            source_sessions: rec.source_sessions,
            conflicts_with: rec.conflicts_with,
            heat_base: rec.heat_base,
            last_access_at: rec.last_access_at,
            embedding: rec.embedding,
        })
    }

    /// Recompute confidence + status from NLI context and the active config.
    ///
    /// Atomic: either both fields update or neither does. Safe to call with
    /// `nli = None` to refresh the gate after a provenance change.
    pub fn reclassify(
        &mut self,
        nli: Option<&NliResult>,
        cfg: &ConfidenceConfig,
    ) -> Result<(), DomainError> {
        let new_conf = self.compute_confidence(nli, cfg);
        let new_status = new_conf.classify(cfg);
        self.set_status_and_confidence(new_status, new_conf, cfg)
    }

    /// Compute the confidence for this fact given optional NLI context.
    ///
    /// Formula (§5.4, §9):
    /// ```text
    /// score = base
    ///       + multi_source_bonus     if 2+ distinct sessions observed the fact
    ///       + no_contradiction_bonus if NLI ran and did not flag a contradiction
    /// ```
    ///
    /// The result is clamped to `[0, 1]` by `Confidence::new_unchecked`.
    ///
    /// NOTE: the contradiction check here is intentionally label-only (not the
    /// threshold-aware `NliResult::is_contradiction`). This faithfully mirrors
    /// the POC: the bonus rewards "any non-contradiction verdict observed",
    /// whereas the threshold-aware predicate drives the merge/drift decision.
    /// Mixing the two would couple two independently-tunable policies.
    pub fn compute_confidence(
        &self,
        nli: Option<&NliResult>,
        cfg: &ConfidenceConfig,
    ) -> Confidence {
        let mut score = cfg.base;

        if self.source_sessions.distinct_count() >= 2 {
            score += cfg.multi_source_bonus;
        }

        if let Some(nli) = nli
            && nli.available
            && nli.label != NliLabel::Contradiction
        {
            score += cfg.no_contradiction_bonus;
        }

        Confidence::new_unchecked(score)
    }

    /// Stateless heat decay (§7): `heat_base * exp(-decay_rate * hours)`.
    ///
    /// Delegates to the canonical [`Heat::decay`] formula. Past access is the
    /// normal case (positive hours); future timestamps (clock skew) clamp to
    /// zero so we never amplify heat above `heat_base`.
    pub fn heat_live(&self, now: Timestamp, decay_rate: f32) -> f32 {
        Heat::decay(self.heat_base, self.last_access_at, now, decay_rate)
    }

    /// Scan `pool` for merge candidates against this fact (§5.3 candidate
    /// selection).
    ///
    /// Filters:
    /// - Same `memory_key` as `self` (cross-namespace matches never merge).
    /// - Skip the pool member whose id matches `self.id` (would be a self-match).
    /// - Cosine similarity at/above `cfg.cosine_threshold`.
    ///
    /// Results are sorted by cosine similarity descending so the closest
    /// candidate is processed first.
    pub fn find_merge_candidates(&self, pool: &[Fact], cfg: &MergeConfig) -> Vec<MergeCandidate> {
        let Some(self_emb) = self.embedding.as_ref() else {
            return Vec::new();
        };
        let self_key = &self.memory_key;
        let self_id = &self.id;

        let mut candidates: Vec<MergeCandidate> = pool
            .iter()
            .filter(|f| &f.memory_key == self_key)
            .filter(|f| &f.id != self_id)
            .filter_map(|f| {
                let emb = f.embedding()?;
                let sim = self_emb.cosine(emb);
                if sim.value() >= cfg.cosine_threshold {
                    Some(MergeCandidate {
                        fact: f.clone(),
                        cosine_similarity: sim,
                    })
                } else {
                    None
                }
            })
            .collect();

        candidates.sort_by(|a, b| {
            b.cosine_similarity
                .value()
                .partial_cmp(&a.cosine_similarity.value())
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        candidates
    }

    /// Mark this fact and `other` as conflicting, on both sides, idempotently.
    ///
    /// Convenience wrapper around [`Fact::flag_conflict`] so session-end code
    /// cannot accidentally flag only one direction (§5.2: both facts must carry
    /// the conflict link).
    pub fn flag_conflict_bidirectional(&mut self, other: &mut Fact) -> Result<(), DomainError> {
        let self_id = self.id.clone();
        let other_id = other.id.clone();
        self.flag_conflict(other_id)?;
        other.flag_conflict(self_id)?;
        Ok(())
    }

    /// Cross-session confirmation (parity with POC `_confirm_existing_fact`).
    ///
    /// Adds the session to provenance if it is new, then recomputes confidence
    /// and re-applies the validation gate — the multi-source bonus (≥2 sessions)
    /// can lift a single-session `Pending` fact above the accept threshold, at
    /// which point the status is promoted to `Accepted`. Returns `true` iff the
    /// provenance grew.
    pub fn confirm_cross_session(
        &mut self,
        session: &SessionId,
        cfg: &ConfidenceConfig,
    ) -> Result<bool, DomainError> {
        let grew = self.source_sessions.add_unique(session.clone());
        if grew {
            self.reclassify(None, cfg)?;
        }
        Ok(grew)
    }

    /// Union provenance and conflict flags from `other`.
    ///
    /// Used by the merge path; the caller is responsible for reclassifying
    /// afterwards. Self-references and duplicates are skipped.
    pub fn merge_into(&mut self, other: &Fact) -> Result<(), DomainError> {
        self.source_sessions.union(&other.source_sessions);
        for cid in &other.conflicts_with {
            if *cid != self.id && !self.conflicts_with.contains(cid) {
                self.conflicts_with.push(cid.clone());
            }
        }
        Ok(())
    }

    /// Mark this fact as conflicting with `other_id` (one side of a bidirectional
    /// flag; caller flags the other side). Rejects self-conflicts.
    pub fn flag_conflict(&mut self, other_id: FactId) -> Result<(), DomainError> {
        if other_id == self.id {
            return Err(DomainError::SelfConflict(self.id.clone()));
        }
        if !self.conflicts_with.contains(&other_id) {
            self.conflicts_with.push(other_id);
        }
        Ok(())
    }

    /// Rewarm the fact after a retrieval hit (§7 boost).
    pub fn boost_heat(&mut self, now: Timestamp) {
        self.heat_base = Heat::MAX;
        self.last_access_at = now;
    }

    /// Set the validity tombstone (`valid_until`).
    ///
    /// Returns [`DomainError::ValidUntilBeforeValidFrom`] if `until` is at or
    /// before `valid_from`. `None` clears a previously-set tombstone (fact
    /// becomes current again).
    pub fn set_valid_until(&mut self, until: Option<Timestamp>) -> Result<(), DomainError> {
        if let Some(ts) = until
            && ts <= self.valid_from
        {
            return Err(DomainError::ValidUntilBeforeValidFrom {
                from: self.valid_from,
                until: ts,
            });
        }
        self.valid_until = until;
        Ok(())
    }

    /// Set status and confidence together, enforcing all transition invariants.
    ///
    /// Rules:
    /// 1. Outgoing transitions from a terminal state (`Accepted`/`Rejected`)
    ///    are illegal — only self-refresh is allowed.
    /// 2. Accepted implies `confidence >= cfg.accept_threshold`.
    pub fn set_status_and_confidence(
        &mut self,
        status: FactStatus,
        conf: Confidence,
        cfg: &ConfidenceConfig,
    ) -> Result<(), DomainError> {
        if self.status.is_terminal() && status != self.status {
            return Err(DomainError::IllegalStatusTransition {
                from: self.status,
                to: status,
            });
        }
        if status == FactStatus::Accepted && conf.value() < cfg.accept_threshold {
            return Err(DomainError::ConfidenceBelowAcceptThreshold {
                threshold: cfg.accept_threshold,
                actual: conf.value(),
            });
        }
        self.status = status;
        self.confidence = conf;
        Ok(())
    }

    // Read-only accessors. No public setters: every mutation goes through a
    // method that enforces an invariant.

    pub fn id(&self) -> &FactId {
        &self.id
    }

    pub fn memory_key(&self) -> &MemoryKey {
        &self.memory_key
    }

    pub fn content(&self) -> &str {
        self.content.as_str()
    }

    pub fn fact_type(&self) -> FactType {
        self.fact_type
    }

    pub fn confidence(&self) -> Confidence {
        self.confidence
    }

    pub fn status(&self) -> FactStatus {
        self.status
    }

    pub fn valid_from(&self) -> Timestamp {
        self.valid_from
    }

    pub fn valid_until(&self) -> Option<Timestamp> {
        self.valid_until
    }

    pub fn extracted_at(&self) -> Timestamp {
        self.extracted_at
    }

    pub fn source_sessions(&self) -> &SourceSessions {
        &self.source_sessions
    }

    pub fn conflicts_with(&self) -> &[FactId] {
        &self.conflicts_with
    }

    pub fn heat_base(&self) -> Heat {
        self.heat_base
    }

    pub fn last_access_at(&self) -> Timestamp {
        self.last_access_at
    }

    pub fn embedding(&self) -> Option<&Embedding> {
        self.embedding.as_ref()
    }

    /// Builder-style constructor combinator: replace the embedding.
    ///
    /// Exposed because the persistence adapter rebuilds a `Fact` from markdown
    /// frontmatter and may need to attach (or detach) the in-memory embedding
    /// after the fact. This is the *only* way to mutate the embedding after
    /// construction — all other fields stay invariant.
    pub fn with_embedding(mut self, embedding: Option<Embedding>) -> Self {
        self.embedding = embedding;
        self
    }
}

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

    fn sid(suffix: u8) -> SessionId {
        let hex = format!("sess_{:012x}", suffix as u64);
        SessionId::from_raw(&hex).unwrap()
    }

    fn emb(dim: usize) -> Embedding {
        Embedding::new((0..dim).map(|i| i as f32 + 1.0).collect()).unwrap()
    }

    fn pending_fact(content: &str, session: SessionId) -> Fact {
        Fact::new_pending(NewPendingRequest {
            content,
            memory_key: MemoryKey::from_raw("origa").unwrap(),
            session,
            embedding: emb(8),
            extracted_at: Timestamp::from_unix_secs(1_700_000_000).unwrap(),
            base_confidence: ConfidenceConfig::default().base,
        })
        .unwrap()
    }

    fn default_cfg() -> ConfidenceConfig {
        ConfidenceConfig::default()
    }

    #[test]
    fn new_pending_initialises_all_fields() {
        let session = sid(1);
        let fact = pending_fact("Rust is fast", session.clone());

        assert_eq!(fact.content(), "Rust is fast");
        assert_eq!(fact.memory_key().as_str(), "origa");
        assert_eq!(fact.fact_type(), FactType::Entity);
        assert_eq!(fact.confidence().value(), 0.5);
        assert_eq!(fact.status(), FactStatus::Pending);
        assert!(fact.valid_until().is_none());
        assert_eq!(fact.source_sessions().distinct_count(), 1);
        assert!(fact.conflicts_with().is_empty());
        assert_eq!(fact.heat_base().value(), 1.0);
        assert!(fact.embedding().is_some());
        assert_eq!(fact.id(), &FactId::from_content("Rust is fast"));
    }

    #[test]
    fn new_pending_rejects_empty_content() {
        let err = Fact::new_pending(NewPendingRequest {
            content: "  ",
            memory_key: MemoryKey::shared(),
            session: sid(1),
            embedding: emb(4),
            extracted_at: Timestamp::from_unix_secs(0).unwrap(),
            base_confidence: ConfidenceConfig::default().base,
        })
        .unwrap_err();
        assert!(matches!(err, DomainError::EmptyFactContent));
    }

    #[test]
    fn set_status_pending_to_accepted_when_confidence_is_high_enough() {
        let mut fact = pending_fact("a", sid(1));
        fact.set_status_and_confidence(
            FactStatus::Accepted,
            Confidence::new(0.7).unwrap(),
            &default_cfg(),
        )
        .unwrap();
        assert_eq!(fact.status(), FactStatus::Accepted);
    }

    #[test]
    fn set_status_pending_to_accepted_rejects_low_confidence() {
        let mut fact = pending_fact("a", sid(1));
        let err = fact
            .set_status_and_confidence(
                FactStatus::Accepted,
                Confidence::new(0.5).unwrap(),
                &default_cfg(),
            )
            .unwrap_err();
        assert!(matches!(
            err,
            DomainError::ConfidenceBelowAcceptThreshold {
                threshold: 0.7,
                actual: 0.5
            }
        ));
    }

    #[test]
    fn set_status_pending_to_rejected_is_allowed() {
        let mut fact = pending_fact("a", sid(1));
        fact.set_status_and_confidence(
            FactStatus::Rejected,
            Confidence::new(0.0).unwrap(),
            &default_cfg(),
        )
        .unwrap();
        assert_eq!(fact.status(), FactStatus::Rejected);
    }

    #[test]
    fn set_status_accepted_to_accepted_is_allowed_for_refresh() {
        let mut fact = pending_fact("a", sid(1));
        fact.set_status_and_confidence(
            FactStatus::Accepted,
            Confidence::new(0.9).unwrap(),
            &default_cfg(),
        )
        .unwrap();
        fact.set_status_and_confidence(
            FactStatus::Accepted,
            Confidence::new(0.95).unwrap(),
            &default_cfg(),
        )
        .unwrap();
        assert_eq!(fact.confidence().value(), 0.95);
    }

    #[test]
    fn set_status_accepted_to_pending_is_illegal() {
        let mut fact = pending_fact("a", sid(1));
        fact.set_status_and_confidence(
            FactStatus::Accepted,
            Confidence::new(0.9).unwrap(),
            &default_cfg(),
        )
        .unwrap();
        let err = fact
            .set_status_and_confidence(
                FactStatus::Pending,
                Confidence::new(0.5).unwrap(),
                &default_cfg(),
            )
            .unwrap_err();
        assert!(matches!(
            err,
            DomainError::IllegalStatusTransition {
                from: FactStatus::Accepted,
                to: FactStatus::Pending
            }
        ));
    }

    #[test]
    fn set_status_accepted_to_rejected_is_illegal() {
        let mut fact = pending_fact("a", sid(1));
        fact.set_status_and_confidence(
            FactStatus::Accepted,
            Confidence::new(0.9).unwrap(),
            &default_cfg(),
        )
        .unwrap();
        assert!(
            fact.set_status_and_confidence(
                FactStatus::Rejected,
                Confidence::new(0.0).unwrap(),
                &default_cfg(),
            )
            .is_err()
        );
    }

    #[test]
    fn set_status_rejected_to_anything_is_illegal() {
        let mut fact = pending_fact("a", sid(1));
        fact.set_status_and_confidence(
            FactStatus::Rejected,
            Confidence::new(0.0).unwrap(),
            &default_cfg(),
        )
        .unwrap();
        for target in [FactStatus::Pending, FactStatus::Accepted] {
            assert!(
                fact.set_status_and_confidence(
                    target,
                    Confidence::new(0.5).unwrap(),
                    &default_cfg()
                )
                .is_err()
            );
        }
    }

    #[test]
    fn reclassify_applies_confidence_and_status_atomically() {
        let mut fact = pending_fact("a", sid(1));
        // No NLI, single source: base 0.5 → Pending.
        fact.reclassify(None, &default_cfg()).unwrap();
        assert_eq!(fact.confidence().value(), 0.5);
        assert_eq!(fact.status(), FactStatus::Pending);
    }

    #[test]
    fn confirm_cross_session_adds_session_first_time() {
        let mut fact = pending_fact("a", sid(1));
        let grew = fact.confirm_cross_session(&sid(2), &default_cfg()).unwrap();
        assert!(grew);
        assert_eq!(fact.source_sessions().distinct_count(), 2);
    }

    #[test]
    fn confirm_cross_session_returns_false_on_repeat() {
        let mut fact = pending_fact("a", sid(1));
        fact.confirm_cross_session(&sid(2), &default_cfg()).unwrap();
        let grew = fact.confirm_cross_session(&sid(2), &default_cfg()).unwrap();
        assert!(!grew);
    }

    #[test]
    fn confirm_cross_session_lifts_confidence_to_accept_threshold() {
        let mut fact = pending_fact("a", sid(1));
        fact.confirm_cross_session(&sid(2), &default_cfg()).unwrap();
        // 0.5 base + 0.2 multi_source = 0.7 → Accepted.
        assert!((fact.confidence().value() - 0.7).abs() < 1e-6);
        assert_eq!(fact.status(), FactStatus::Accepted);
    }

    #[test]
    fn merge_into_unions_source_sessions() {
        let mut left = pending_fact("a", sid(1));
        let mut right = pending_fact("a", sid(2));
        right
            .confirm_cross_session(&sid(3), &default_cfg())
            .unwrap();
        left.merge_into(&right).unwrap();
        assert_eq!(left.source_sessions().distinct_count(), 3);
    }

    #[test]
    fn merge_into_unions_conflicts_without_self_reference() {
        let mut left = pending_fact("a", sid(1));
        let other_id = FactId::from_content("other");
        left.flag_conflict(other_id.clone()).unwrap();
        let right = pending_fact("a", sid(2));
        left.merge_into(&right).unwrap();
        assert!(left.conflicts_with().contains(&other_id));
    }

    #[test]
    fn merge_into_dedups_conflict_flags() {
        let mut left = pending_fact("a", sid(1));
        let other_id = FactId::from_content("other");
        left.flag_conflict(other_id.clone()).unwrap();
        let mut right = pending_fact("a", sid(2));
        right.flag_conflict(other_id.clone()).unwrap();
        left.merge_into(&right).unwrap();
        let count = left
            .conflicts_with()
            .iter()
            .filter(|id| **id == other_id)
            .count();
        assert_eq!(count, 1);
    }

    #[test]
    fn flag_conflict_rejects_self_conflict() {
        let mut fact = pending_fact("a", sid(1));
        let err = fact.flag_conflict(fact.id().clone()).unwrap_err();
        assert!(matches!(err, DomainError::SelfConflict(_)));
    }

    #[test]
    fn flag_conflict_is_idempotent() {
        let mut fact = pending_fact("a", sid(1));
        let other = FactId::from_content("other");
        fact.flag_conflict(other.clone()).unwrap();
        fact.flag_conflict(other.clone()).unwrap();
        assert_eq!(
            fact.conflicts_with()
                .iter()
                .filter(|id| **id == other)
                .count(),
            1
        );
    }

    #[test]
    fn boost_heat_sets_max_heat_and_refreshes_access_time() {
        let mut fact = pending_fact("a", sid(1));
        let now = Timestamp::from_unix_secs(1_800_000_000).unwrap();
        fact.boost_heat(now);
        assert_eq!(fact.heat_base().value(), 1.0);
        assert_eq!(fact.last_access_at().as_unix_secs(), 1_800_000_000);
    }

    #[test]
    fn set_valid_until_accepts_timestamp_strictly_after_valid_from() {
        let mut fact = pending_fact("a", sid(1));
        let original_valid_from = fact.valid_from();
        let later = Timestamp::from_unix_secs(original_valid_from.as_unix_secs() + 3600).unwrap();
        fact.set_valid_until(Some(later)).unwrap();
        assert_eq!(fact.valid_until(), Some(later));
    }

    #[test]
    fn set_valid_until_rejects_timestamp_at_or_before_valid_from() {
        let mut fact = pending_fact("a", sid(1));
        let original_valid_from = fact.valid_from();
        let equal = original_valid_from;
        let earlier = Timestamp::from_unix_secs(original_valid_from.as_unix_secs() - 10).unwrap();
        assert!(fact.set_valid_until(Some(equal)).is_err());
        assert!(fact.set_valid_until(Some(earlier)).is_err());
    }

    #[test]
    fn set_valid_until_none_clears_tombstone() {
        let mut fact = pending_fact("a", sid(1));
        let original = fact.valid_from();
        let later = Timestamp::from_unix_secs(original.as_unix_secs() + 3600).unwrap();
        fact.set_valid_until(Some(later)).unwrap();
        fact.set_valid_until(None).unwrap();
        assert!(fact.valid_until().is_none());
    }

    #[test]
    fn with_embedding_overrides_embedding() {
        let fact = pending_fact("a", sid(1));
        let replaced = fact.with_embedding(None);
        assert!(replaced.embedding().is_none());
    }

    #[test]
    fn serde_roundtrip_preserves_fact_fields() {
        let fact = pending_fact("Rust fact", sid(1));
        let json = serde_json::to_string(&fact).unwrap();
        let back: Fact = serde_json::from_str(&json).unwrap();
        assert_eq!(back.content(), "Rust fact");
        assert_eq!(back.status(), FactStatus::Pending);
        assert_eq!(back.confidence().value(), 0.5);
    }

    #[test]
    fn rehydrate_roundtrips_every_field_verbatim() {
        // Persistence adapters call `rehydrate` on read; this test pins the
        // round-trip contract: every persisted field must survive unchanged.
        let mut fact = pending_fact("Rust fact", sid(1));
        fact.set_status_and_confidence(
            FactStatus::Accepted,
            Confidence::new(0.92).unwrap(),
            &default_cfg(),
        )
        .unwrap();
        fact.flag_conflict(FactId::from_content("other")).unwrap();
        fact.set_valid_until(Some(
            Timestamp::from_unix_secs(fact.valid_from().as_unix_secs() + 3600).unwrap(),
        ))
        .unwrap();

        let rehydrated = Fact::rehydrate(FactRecord {
            id: fact.id().clone(),
            memory_key: fact.memory_key().clone(),
            content: FactContent::new(fact.content().to_string()).unwrap(),
            fact_type: fact.fact_type(),
            confidence: fact.confidence(),
            status: fact.status(),
            valid_from: fact.valid_from(),
            valid_until: fact.valid_until(),
            extracted_at: fact.extracted_at(),
            source_sessions: fact.source_sessions().clone(),
            conflicts_with: fact.conflicts_with().to_vec(),
            heat_base: fact.heat_base(),
            last_access_at: fact.last_access_at(),
            embedding: fact.embedding().cloned(),
        })
        .unwrap();

        assert_eq!(rehydrated.id(), fact.id());
        assert_eq!(rehydrated.content(), fact.content());
        assert_eq!(rehydrated.fact_type(), fact.fact_type());
        assert_eq!(rehydrated.confidence().value(), fact.confidence().value());
        assert_eq!(rehydrated.status(), fact.status());
        assert_eq!(rehydrated.valid_from(), fact.valid_from());
        assert_eq!(rehydrated.valid_until(), fact.valid_until());
        assert_eq!(rehydrated.extracted_at(), fact.extracted_at());
        assert_eq!(
            rehydrated.source_sessions().distinct_count(),
            fact.source_sessions().distinct_count()
        );
        assert_eq!(rehydrated.conflicts_with(), fact.conflicts_with());
        assert_eq!(rehydrated.heat_base().value(), fact.heat_base().value());
        assert_eq!(rehydrated.last_access_at(), fact.last_access_at());
    }

    #[test]
    fn rehydrate_rejects_id_that_disagrees_with_content() {
        let fact = pending_fact("Rust fact", sid(1));
        let wrong_id = FactId::from_content("different content");
        let err = Fact::rehydrate(FactRecord {
            id: wrong_id.clone(),
            memory_key: fact.memory_key().clone(),
            content: FactContent::new(fact.content().to_string()).unwrap(),
            fact_type: fact.fact_type(),
            confidence: fact.confidence(),
            status: fact.status(),
            valid_from: fact.valid_from(),
            valid_until: None,
            extracted_at: fact.extracted_at(),
            source_sessions: fact.source_sessions().clone(),
            conflicts_with: Vec::new(),
            heat_base: fact.heat_base(),
            last_access_at: fact.last_access_at(),
            embedding: None,
        })
        .unwrap_err();
        assert!(matches!(err, DomainError::InvalidFactId(_)));
    }

    #[test]
    fn rehydrate_rejects_valid_until_at_or_before_valid_from() {
        let fact = pending_fact("Rust fact", sid(1));
        let at_valid_from = fact.valid_from();
        let err = Fact::rehydrate(FactRecord {
            id: fact.id().clone(),
            memory_key: fact.memory_key().clone(),
            content: FactContent::new(fact.content().to_string()).unwrap(),
            fact_type: fact.fact_type(),
            confidence: fact.confidence(),
            status: fact.status(),
            valid_from: fact.valid_from(),
            valid_until: Some(at_valid_from),
            extracted_at: fact.extracted_at(),
            source_sessions: fact.source_sessions().clone(),
            conflicts_with: Vec::new(),
            heat_base: fact.heat_base(),
            last_access_at: fact.last_access_at(),
            embedding: None,
        })
        .unwrap_err();
        assert!(matches!(err, DomainError::ValidUntilBeforeValidFrom { .. }));
    }

    // -----------------------------------------------------------------
    // compute_confidence — multi-source + NLI bonus formula
    // -----------------------------------------------------------------

    fn nli_result(label: NliLabel, available: bool) -> NliResult {
        use crate::value_objects::NliScores;
        NliResult {
            label,
            scores: NliScores {
                entailment: if label == NliLabel::Entailment {
                    1.0
                } else {
                    0.0
                },
                neutral: if label == NliLabel::Neutral { 1.0 } else { 0.0 },
                contradiction: if label == NliLabel::Contradiction {
                    1.0
                } else {
                    0.0
                },
            },
            available,
        }
    }

    #[test]
    fn compute_confidence_base_only_for_single_source_no_nli() {
        let fact = pending_fact("a", sid(1));
        let c = fact.compute_confidence(None, &default_cfg());
        assert!((c.value() - 0.5).abs() < 1e-6);
    }

    #[test]
    fn compute_confidence_multi_source_bonus_applies_with_two_sessions() {
        let mut fact = pending_fact("a", sid(1));
        fact.confirm_cross_session(&sid(2), &default_cfg()).unwrap();
        let c = fact.compute_confidence(None, &default_cfg());
        assert!((c.value() - 0.7).abs() < 1e-6);
    }

    #[test]
    fn compute_confidence_no_contradiction_bonus_for_entailment() {
        let fact = pending_fact("a", sid(1));
        let c = fact.compute_confidence(
            Some(&nli_result(NliLabel::Entailment, true)),
            &default_cfg(),
        );
        assert!((c.value() - 0.6).abs() < 1e-6);
    }

    #[test]
    fn compute_confidence_no_contradiction_bonus_skipped_for_contradiction() {
        let fact = pending_fact("a", sid(1));
        let c = fact.compute_confidence(
            Some(&nli_result(NliLabel::Contradiction, true)),
            &default_cfg(),
        );
        assert!((c.value() - 0.5).abs() < 1e-6);
    }

    #[test]
    fn compute_confidence_no_contradiction_bonus_skipped_when_unavailable() {
        let fact = pending_fact("a", sid(1));
        let c = fact.compute_confidence(
            Some(&nli_result(NliLabel::Entailment, false)),
            &default_cfg(),
        );
        assert!((c.value() - 0.5).abs() < 1e-6);
    }

    #[test]
    fn compute_confidence_both_bonuses_stack_and_clamp_at_one() {
        let mut fact = pending_fact("a", sid(1));
        fact.confirm_cross_session(&sid(2), &default_cfg()).unwrap();
        fact.confirm_cross_session(&sid(3), &default_cfg()).unwrap();
        let c = fact.compute_confidence(
            Some(&nli_result(NliLabel::Entailment, true)),
            &default_cfg(),
        );
        assert!((c.value() - 0.8).abs() < 1e-6);
    }

    // -----------------------------------------------------------------
    // heat_live — exponential decay
    // -----------------------------------------------------------------

    #[test]
    fn heat_live_fresh_fact_has_full_heat() {
        let fact = pending_fact("a", sid(1));
        let now = fact.last_access_at();
        assert!((fact.heat_live(now, 0.03) - 1.0).abs() < 1e-6);
    }

    #[test]
    fn heat_live_decays_after_24_hours_at_known_rate() {
        // exp(-0.03 * 24) ≈ 0.4868
        let fact = pending_fact("a", sid(1));
        let base = fact.last_access_at();
        let one_day_later = Timestamp::from_unix_secs(base.as_unix_secs() + 24 * 3600).unwrap();
        let h = fact.heat_live(one_day_later, 0.03);
        assert!((h - 0.4868).abs() < 1e-3, "got {h}");
    }

    #[test]
    fn heat_live_future_access_clamps_to_zero_decay() {
        let fact = pending_fact("a", sid(1));
        let base = fact.last_access_at();
        let earlier = Timestamp::from_unix_secs(base.as_unix_secs() - 3600).unwrap();
        assert!((fact.heat_live(earlier, 0.03) - 1.0).abs() < 1e-6);
    }

    // -----------------------------------------------------------------
    // find_merge_candidates — cosine similarity scan
    // -----------------------------------------------------------------

    fn fact_with_key_embedding(content: &str, key: &str, embedding: Vec<f32>) -> Fact {
        Fact::new_pending(NewPendingRequest {
            content,
            memory_key: MemoryKey::from_raw(key).unwrap(),
            session: sid(1),
            embedding: Embedding::new(embedding).unwrap(),
            extracted_at: Timestamp::from_unix_secs(0).unwrap(),
            base_confidence: ConfidenceConfig::default().base,
        })
        .unwrap()
    }

    #[test]
    fn find_merge_candidates_empty_pool_returns_empty() {
        let pending = fact_with_key_embedding("p", "origa", vec![1.0, 0.0]);
        assert!(
            pending
                .find_merge_candidates(&[], &MergeConfig::default())
                .is_empty()
        );
    }

    #[test]
    fn find_merge_candidates_filters_below_threshold() {
        let pending = fact_with_key_embedding("p", "origa", vec![1.0, 0.0]);
        // Orthogonal → cosine 0.0 < 0.85.
        let pool = vec![fact_with_key_embedding("x", "origa", vec![0.0, 1.0])];
        assert!(
            pending
                .find_merge_candidates(&pool, &MergeConfig::default())
                .is_empty()
        );
    }

    #[test]
    fn find_merge_candidates_keeps_above_threshold_sorted_desc() {
        let pending = fact_with_key_embedding("p", "origa", vec![1.0, 0.0]);
        let pool = vec![
            fact_with_key_embedding("ortho", "origa", vec![0.0, 1.0]),
            fact_with_key_embedding("mid", "origa", vec![1.0, 1.0]),
            fact_with_key_embedding("perfect", "origa", vec![1.0, 0.0]),
        ];
        let out = pending.find_merge_candidates(&pool, &MergeConfig::default());
        // Only "perfect" passes the default 0.85 threshold.
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].fact.content(), "perfect");
        assert!((out[0].cosine_similarity.value() - 1.0).abs() < 1e-5);
    }

    #[test]
    fn find_merge_candidates_excludes_self_id() {
        let pending = fact_with_key_embedding("same", "origa", vec![1.0, 0.0]);
        // Same content → same id → excluded as a self-match.
        let pool = vec![fact_with_key_embedding("same", "origa", vec![1.0, 0.0])];
        assert!(
            pending
                .find_merge_candidates(&pool, &MergeConfig::default())
                .is_empty()
        );
    }

    #[test]
    fn find_merge_candidates_excludes_different_memory_key() {
        let pending = fact_with_key_embedding("p", "origa", vec![1.0, 0.0]);
        let pool = vec![fact_with_key_embedding("x", "other", vec![1.0, 0.0])];
        assert!(
            pending
                .find_merge_candidates(&pool, &MergeConfig::default())
                .is_empty()
        );
    }

    #[test]
    fn find_merge_candidates_skips_pool_member_without_embedding() {
        let pending = fact_with_key_embedding("p", "origa", vec![1.0, 0.0]);
        let pool_member =
            fact_with_key_embedding("x", "origa", vec![1.0, 0.0]).with_embedding(None);
        let pool = vec![pool_member];
        assert!(
            pending
                .find_merge_candidates(&pool, &MergeConfig::default())
                .is_empty()
        );
    }

    // -----------------------------------------------------------------
    // flag_conflict_bidirectional — symmetric conflict flag
    // -----------------------------------------------------------------

    #[test]
    fn flag_conflict_bidirectional_sets_both_sides() {
        let mut a = pending_fact("alpha", sid(1));
        let mut b = pending_fact("beta", sid(2));
        a.flag_conflict_bidirectional(&mut b).unwrap();
        assert!(a.conflicts_with().contains(b.id()));
        assert!(b.conflicts_with().contains(a.id()));
    }

    #[test]
    fn flag_conflict_bidirectional_is_idempotent() {
        let mut a = pending_fact("alpha", sid(1));
        let mut b = pending_fact("beta", sid(2));
        a.flag_conflict_bidirectional(&mut b).unwrap();
        a.flag_conflict_bidirectional(&mut b).unwrap();
        assert_eq!(a.conflicts_with().len(), 1);
        assert_eq!(b.conflicts_with().len(), 1);
    }
}