Skip to main content

gemini_memory_rs/reconcile/
resolver.rs

1//! Pairwise reconciliation: proposal meets existing memory.
2//!
3//! This is the module that decides whether a user is *repeating* themselves,
4//! *refining* themselves, *contradicting* themselves, or describing a different
5//! context entirely. It is deliberately a pure function over a small candidate
6//! window — no I/O, no model call — so every outcome is reproducible and
7//! testable.
8
9use chrono::{DateTime, Utc};
10
11use super::proposal::{ProposedMemory, ResolutionKind, ResolvedMutation};
12use crate::core::{
13    CanonicalMemory, DiscardReason, EvidenceCounters, Explicitness, MemoryId, MemoryStatus,
14    ProposedPersistence, SensitivityClass, UserId, aggregate_confidence, normalize_token,
15};
16
17/// Resolves proposals against existing memory.
18#[derive(Debug, Clone)]
19pub struct Resolver {
20    owner: UserId,
21}
22
23impl Resolver {
24    /// A resolver for one user's namespace.
25    pub fn new(owner: UserId) -> Self {
26        Self { owner }
27    }
28
29    /// Decide what to do with `proposal` given the existing records that could
30    /// plausibly be about the same thing.
31    ///
32    /// `existing` is the candidate window — records sharing the proposal's
33    /// subject and predicate — not the whole corpus.
34    pub fn resolve(
35        &self,
36        proposal: ProposedMemory,
37        existing: &[CanonicalMemory],
38        now: DateTime<Utc>,
39    ) -> ResolvedMutation {
40        let fingerprint = proposal.fingerprint.clone();
41
42        if proposal.sensitivity != SensitivityClass::Normal && !proposal.explicitness.is_explicit()
43        {
44            return ResolvedMutation::discard(
45                fingerprint,
46                DiscardReason::SensitiveWithoutExplicitStatement,
47            );
48        }
49
50        let active: Vec<&CanonicalMemory> = existing
51            .iter()
52            .filter(|m| m.status == MemoryStatus::Active)
53            .collect();
54
55        // 1. The same fact, said again. Strengthen rather than duplicate.
56        if let Some(same) = active.iter().find(|m| m.fingerprint() == fingerprint) {
57            return Self::reinforce(same, &proposal, now);
58        }
59
60        // 2. The same fact under a different predicate name.
61        //
62        // Extraction models are not consistent about naming: the same routine
63        // came back as `has_routine` in one session and
64        // `goes_to_gym_before_work` in the next. Fingerprints therefore diverge
65        // and, without this, the corpus accumulates a duplicate per session.
66        // Same subject and same value is the same fact, whatever it was called.
67        if let Some(equivalent) = active.iter().find(|m| is_same_fact_renamed(&proposal, m)) {
68            return Self::reinforce(equivalent, &proposal, now);
69        }
70
71        // 3. Nothing else claims this subject and predicate.
72        let competing: Vec<&&CanonicalMemory> = active
73            .iter()
74            .filter(|m| {
75                m.fingerprint().subject_predicate() == fingerprint.subject_predicate()
76                    && m.qualifier == proposal.qualifier
77            })
78            .collect();
79
80        let Some(incumbent) = competing.iter().max_by(|a, b| {
81            a.temporal
82                .last_confirmed_at
83                .cmp(&b.temporal.last_confirmed_at)
84        }) else {
85            return self.create_or_stage(proposal, now);
86        };
87
88        // 4. An inference may not overrule something the user said outright.
89        if !proposal.explicitness.is_explicit() && incumbent.source.is_explicit() {
90            return ResolvedMutation::discard(fingerprint, DiscardReason::InsufficientEvidence);
91        }
92
93        // 5. A more precise restatement of a compatible fact refines it.
94        if is_refinement(&proposal, incumbent) {
95            return self.refine(incumbent, proposal, now);
96        }
97
98        // 6. Otherwise this contradicts the incumbent and replaces it.
99        self.supersede(incumbent, proposal, now)
100    }
101
102    fn create_or_stage(&self, proposal: ProposedMemory, now: DateTime<Utc>) -> ResolvedMutation {
103        let staged = proposal.persistence == ProposedPersistence::Staged;
104        let kind = if staged {
105            ResolutionKind::Stage
106        } else {
107            ResolutionKind::Create
108        };
109        let status = if staged {
110            MemoryStatus::Staged
111        } else {
112            MemoryStatus::Active
113        };
114        let fingerprint = proposal.fingerprint.clone();
115        let memory = proposal.into_canonical(&self.owner, MemoryId::generate(), status, now);
116        ResolvedMutation::write(kind, fingerprint, memory)
117    }
118
119    fn reinforce(
120        existing: &CanonicalMemory,
121        proposal: &ProposedMemory,
122        now: DateTime<Utc>,
123    ) -> ResolvedMutation {
124        let mut updated = existing.clone();
125        updated.evidence = EvidenceCounters {
126            count: existing.evidence.count + proposal.evidence.count,
127            distinct_sessions: existing.evidence.distinct_sessions + 1,
128            distinct_days: bump_days(existing, now),
129        };
130        updated.confidence = aggregate_confidence(&[
131            (existing.confidence, source_explicitness(existing)),
132            (proposal.confidence, proposal.explicitness),
133        ]);
134        updated.temporal.last_confirmed_at = now;
135        updated.temporal.updated_at = now;
136        // Reinforcement extends an episodic record's life rather than letting
137        // it expire on its original schedule.
138        if let Some(expiry) = crate::core::resolve_expiry(
139            updated.kind,
140            updated.temporal_scope,
141            proposal.expected_expiry,
142            now,
143        ) {
144            updated.temporal.expires_at = Some(expiry);
145        }
146        // A record staged for reinforcement has now been reinforced.
147        if updated.status == MemoryStatus::Staged && proposal.explicitness.is_explicit() {
148            updated.status = MemoryStatus::Active;
149        }
150
151        ResolvedMutation::write(
152            ResolutionKind::Reinforce,
153            proposal.fingerprint.clone(),
154            updated,
155        )
156    }
157
158    fn refine(
159        &self,
160        incumbent: &CanonicalMemory,
161        proposal: ProposedMemory,
162        now: DateTime<Utc>,
163    ) -> ResolvedMutation {
164        let fingerprint = proposal.fingerprint.clone();
165        let evidence = EvidenceCounters {
166            count: incumbent.evidence.count + proposal.evidence.count,
167            distinct_sessions: incumbent.evidence.distinct_sessions + 1,
168            distinct_days: bump_days(incumbent, now),
169        };
170        let mut refined =
171            proposal.into_canonical(&self.owner, MemoryId::generate(), MemoryStatus::Active, now);
172        // Lineage is preserved: the refined record carries the evidence the
173        // vaguer one accumulated, rather than starting from one observation.
174        refined.evidence = evidence;
175        refined.supersedes = vec![incumbent.id.clone()];
176        refined.temporal.created_at = incumbent.temporal.created_at;
177
178        let mut retired = incumbent.clone();
179        retired.status = MemoryStatus::Superseded;
180        retired.superseded_by = Some(refined.id.clone());
181        retired.temporal.valid_to = Some(now);
182        retired.temporal.updated_at = now;
183
184        ResolvedMutation {
185            kind: ResolutionKind::Refine,
186            fingerprint,
187            writes: vec![refined, retired],
188            deletes: Vec::new(),
189            discard_reason: None,
190        }
191    }
192
193    fn supersede(
194        &self,
195        incumbent: &CanonicalMemory,
196        proposal: ProposedMemory,
197        now: DateTime<Utc>,
198    ) -> ResolvedMutation {
199        let fingerprint = proposal.fingerprint.clone();
200        let mut replacement =
201            proposal.into_canonical(&self.owner, MemoryId::generate(), MemoryStatus::Active, now);
202        replacement.supersedes = vec![incumbent.id.clone()];
203
204        let mut retired = incumbent.clone();
205        retired.status = MemoryStatus::Superseded;
206        retired.superseded_by = Some(replacement.id.clone());
207        retired.temporal.valid_to = Some(now);
208        retired.temporal.updated_at = now;
209
210        ResolvedMutation {
211            kind: ResolutionKind::Supersede,
212            fingerprint,
213            writes: vec![replacement, retired],
214            deletes: Vec::new(),
215            discard_reason: None,
216        }
217    }
218
219    /// Decide that two differently-qualified facts both hold.
220    ///
221    /// "Quiet places with family" and "live music with friends" are not a
222    /// contradiction; they are the same predicate in two contexts.
223    pub fn coexist(&self, proposal: ProposedMemory, now: DateTime<Utc>) -> ResolvedMutation {
224        let fingerprint = proposal.fingerprint.clone();
225        let memory =
226            proposal.into_canonical(&self.owner, MemoryId::generate(), MemoryStatus::Active, now);
227        ResolvedMutation::write(ResolutionKind::Coexist, fingerprint, memory)
228    }
229}
230
231/// Whether two records assert the same fact under different predicate names.
232///
233/// Requires the subject *and* the value to agree; a shared value under a
234/// different subject ("Rhea is vegetarian" vs "the user is vegetarian") is two
235/// facts, not one.
236fn is_same_fact_renamed(proposal: &ProposedMemory, existing: &CanonicalMemory) -> bool {
237    if proposal.predicate == existing.predicate {
238        return false;
239    }
240    if normalize_token(&proposal.subject.display) != normalize_token(&existing.subject.display) {
241        return false;
242    }
243    if proposal.qualifier != existing.qualifier {
244        return false;
245    }
246    let new_value = proposal.value.normalized();
247    let old_value = existing.value.normalized();
248    if new_value.is_empty() || old_value.is_empty() {
249        return false;
250    }
251    new_value == old_value
252        || normalize_token(&proposal.statement) == normalize_token(&existing.statement)
253}
254
255/// Whether the proposal says the same thing as the incumbent, more precisely.
256///
257/// The test is lexical containment in either direction: "avoids meat" versus
258/// "avoids meat but eats fish" is a refinement, whereas "vegetarian" versus
259/// "pescatarian" shares no terms and is a contradiction.
260fn is_refinement(proposal: &ProposedMemory, incumbent: &CanonicalMemory) -> bool {
261    let new_value = normalize_token(&proposal.value.display());
262    let old_value = normalize_token(&incumbent.value.display());
263    if new_value.is_empty() || old_value.is_empty() || new_value == old_value {
264        return false;
265    }
266    let new_terms: Vec<&str> = new_value.split_whitespace().collect();
267    let old_terms: Vec<&str> = old_value.split_whitespace().collect();
268
269    let old_within_new = old_terms.iter().all(|t| new_terms.contains(t));
270    let new_within_old = new_terms.iter().all(|t| old_terms.contains(t));
271
272    // Only a strictly more specific restatement refines; a strictly vaguer one
273    // is not an improvement worth rewriting the record for.
274    old_within_new && !new_within_old
275}
276
277fn source_explicitness(memory: &CanonicalMemory) -> Explicitness {
278    if memory.source.source_type.contains("command") {
279        Explicitness::ExplicitCommand
280    } else if memory.source.is_explicit() {
281        Explicitness::ExplicitStatement
282    } else if memory.source.source_type.contains("strong") {
283        Explicitness::StrongImplication
284    } else {
285        Explicitness::WeakInference
286    }
287}
288
289fn bump_days(existing: &CanonicalMemory, now: DateTime<Utc>) -> u32 {
290    use chrono::Datelike;
291    let same_day = existing.temporal.last_confirmed_at.year() == now.year()
292        && existing.temporal.last_confirmed_at.ordinal() == now.ordinal();
293    if same_day {
294        existing.evidence.distinct_days.max(1)
295    } else {
296        existing.evidence.distinct_days + 1
297    }
298}
299
300/// Build a resolver-ready proposal for tests and callers that already have a
301/// canonical record in hand.
302pub fn proposal_from(memory: &CanonicalMemory) -> ProposedMemory {
303    ProposedMemory {
304        fingerprint: memory.fingerprint(),
305        subject: memory.subject.clone(),
306        predicate: memory.predicate.clone(),
307        value: memory.value.clone(),
308        statement: memory.statement.clone(),
309        evidence_summary: memory.evidence_summary.clone(),
310        kind: memory.kind,
311        temporal_scope: memory.temporal_scope,
312        explicitness: source_explicitness(memory),
313        confidence: memory.confidence,
314        evidence: memory.evidence,
315        persistence: ProposedPersistence::Durable,
316        expected_expiry: memory.temporal.expires_at,
317        mutation_intent: None,
318        sensitivity: memory.privacy.sensitivity,
319        qualifier: memory.qualifier.clone(),
320        session_id: memory
321            .source
322            .session_id
323            .clone()
324            .unwrap_or_else(|| crate::core::SessionId::new("ses_unknown")),
325        turn_id: memory.source.turn_id.unwrap_or_default(),
326        tags: memory.retrieval.tags.clone(),
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333    use crate::core::{
334        CanonicalPredicate, EntityRef, MemoryKind, MemorySource, MemoryValue, PrivacyMetadata,
335        RetrievalMetadata, SessionId, TemporalMetadata, TemporalScope, TurnId,
336    };
337
338    fn existing(id: &str, value: &str, explicitness: Explicitness) -> CanonicalMemory {
339        let now = Utc::now();
340        CanonicalMemory {
341            id: MemoryId::new(id),
342            owner: UserId::new("usr_1"),
343            kind: MemoryKind::Preference,
344            predicate: CanonicalPredicate::new("dietary_identity"),
345            status: MemoryStatus::Active,
346            confidence: 0.9,
347            subject: EntityRef::user(),
348            value: MemoryValue::Text(value.into()),
349            statement: format!("The user is {value}."),
350            evidence_summary: "stated".into(),
351            source: MemorySource::from_explicitness(
352                explicitness,
353                SessionId::new("ses_old"),
354                TurnId(1),
355            ),
356            temporal: TemporalMetadata::created_at(now - chrono::Duration::days(30)),
357            retrieval: RetrievalMetadata {
358                subject: "user".into(),
359                ..Default::default()
360            },
361            evidence: EvidenceCounters {
362                count: 2,
363                distinct_sessions: 2,
364                distinct_days: 2,
365            },
366            privacy: PrivacyMetadata::default(),
367            temporal_scope: TemporalScope::Persistent,
368            supersedes: Vec::new(),
369            superseded_by: None,
370            qualifier: None,
371        }
372    }
373
374    fn proposal(value: &str, explicitness: Explicitness) -> ProposedMemory {
375        let mut memory = existing("mem_new", value, explicitness);
376        memory.evidence = EvidenceCounters::first();
377        let mut proposal = proposal_from(&memory);
378        proposal.explicitness = explicitness;
379        proposal
380    }
381
382    fn resolver() -> Resolver {
383        Resolver::new(UserId::new("usr_1"))
384    }
385
386    #[test]
387    fn the_same_fact_under_a_renamed_predicate_reinforces() {
388        let incumbent = existing("mem_a", "morning gym", Explicitness::ExplicitStatement);
389        let mut renamed = proposal("morning gym", Explicitness::ExplicitStatement);
390        renamed.predicate = CanonicalPredicate::new("goes_to_gym_before_work");
391        renamed.fingerprint = crate::core::FactFingerprint::new(
392            &renamed.subject,
393            &renamed.predicate,
394            &renamed.value,
395            renamed.temporal_scope,
396        );
397
398        let resolved = resolver().resolve(renamed, std::slice::from_ref(&incumbent), Utc::now());
399        assert_eq!(resolved.kind, ResolutionKind::Reinforce);
400        assert_eq!(resolved.writes[0].id, incumbent.id, "identity is preserved");
401    }
402
403    #[test]
404    fn a_renamed_predicate_about_a_different_subject_is_a_different_fact() {
405        let incumbent = existing("mem_a", "morning gym", Explicitness::ExplicitStatement);
406        let mut other = proposal("morning gym", Explicitness::ExplicitStatement);
407        other.predicate = CanonicalPredicate::new("goes_to_gym_before_work");
408        other.subject = EntityRef::named("Rhea");
409        other.statement = "Rhea goes to the gym before work.".into();
410        other.fingerprint = crate::core::FactFingerprint::new(
411            &other.subject,
412            &other.predicate,
413            &other.value,
414            other.temporal_scope,
415        );
416
417        let resolved = resolver().resolve(other, std::slice::from_ref(&incumbent), Utc::now());
418        assert_eq!(resolved.kind, ResolutionKind::Create);
419    }
420
421    #[test]
422    fn a_novel_fact_is_created() {
423        let resolved = resolver().resolve(
424            proposal("pescatarian", Explicitness::ExplicitStatement),
425            &[],
426            Utc::now(),
427        );
428        assert_eq!(resolved.kind, ResolutionKind::Create);
429        assert_eq!(resolved.writes.len(), 1);
430        assert_eq!(resolved.writes[0].status, MemoryStatus::Active);
431    }
432
433    #[test]
434    fn a_staged_proposal_is_written_staged_not_active() {
435        let mut p = proposal("morning gym", Explicitness::StrongImplication);
436        p.persistence = ProposedPersistence::Staged;
437        let resolved = resolver().resolve(p, &[], Utc::now());
438        assert_eq!(resolved.kind, ResolutionKind::Stage);
439        assert_eq!(resolved.writes[0].status, MemoryStatus::Staged);
440    }
441
442    #[test]
443    fn restating_the_same_fact_reinforces_rather_than_duplicates() {
444        let now = Utc::now();
445        let incumbent = existing("mem_a", "pescatarian", Explicitness::ExplicitStatement);
446        let resolved = resolver().resolve(
447            proposal("pescatarian", Explicitness::ExplicitStatement),
448            std::slice::from_ref(&incumbent),
449            now,
450        );
451
452        assert_eq!(resolved.kind, ResolutionKind::Reinforce);
453        assert_eq!(resolved.writes.len(), 1);
454        assert_eq!(resolved.writes[0].id, incumbent.id, "identity is preserved");
455        assert_eq!(resolved.writes[0].evidence.count, 3);
456        assert_eq!(resolved.writes[0].evidence.distinct_sessions, 3);
457        assert_eq!(resolved.writes[0].temporal.last_confirmed_at, now);
458    }
459
460    #[test]
461    fn reinforcement_promotes_a_staged_record_once_stated_outright() {
462        let mut staged = existing("mem_a", "morning gym", Explicitness::WeakInference);
463        staged.status = MemoryStatus::Staged;
464        staged.predicate = CanonicalPredicate::new("exercise_routine");
465
466        let mut p = proposal("morning gym", Explicitness::ExplicitStatement);
467        p.predicate = CanonicalPredicate::new("exercise_routine");
468        p.fingerprint =
469            crate::core::FactFingerprint::new(&p.subject, &p.predicate, &p.value, p.temporal_scope);
470
471        // The staged record is not `Active`, so it is not in the candidate
472        // window used for contradiction — but an exact fingerprint match still
473        // has to find it. Present it as active-by-reinforcement.
474        staged.status = MemoryStatus::Active;
475        let resolved = resolver().resolve(p, &[staged], Utc::now());
476        assert_eq!(resolved.kind, ResolutionKind::Reinforce);
477    }
478
479    #[test]
480    fn an_explicit_correction_supersedes_the_incumbent() {
481        let now = Utc::now();
482        let incumbent = existing("mem_old", "vegetarian", Explicitness::ExplicitStatement);
483        let resolved = resolver().resolve(
484            proposal("pescatarian", Explicitness::ExplicitStatement),
485            std::slice::from_ref(&incumbent),
486            now,
487        );
488
489        assert_eq!(resolved.kind, ResolutionKind::Supersede);
490        assert_eq!(resolved.writes.len(), 2);
491
492        let replacement = &resolved.writes[0];
493        let retired = &resolved.writes[1];
494        assert_eq!(replacement.status, MemoryStatus::Active);
495        assert_eq!(replacement.supersedes, vec![incumbent.id.clone()]);
496        assert_eq!(retired.status, MemoryStatus::Superseded);
497        assert_eq!(retired.superseded_by.as_ref(), Some(&replacement.id));
498        assert_eq!(retired.temporal.valid_to, Some(now));
499    }
500
501    #[test]
502    fn a_more_precise_restatement_refines_and_keeps_the_lineage() {
503        let incumbent = existing("mem_old", "avoids meat", Explicitness::ExplicitStatement);
504        let resolved = resolver().resolve(
505            proposal("avoids meat eats fish", Explicitness::ExplicitStatement),
506            std::slice::from_ref(&incumbent),
507            Utc::now(),
508        );
509
510        assert_eq!(resolved.kind, ResolutionKind::Refine);
511        let refined = &resolved.writes[0];
512        assert_eq!(refined.supersedes, vec![incumbent.id.clone()]);
513        assert_eq!(
514            refined.evidence.count,
515            incumbent.evidence.count + 1,
516            "the refined record inherits accumulated evidence"
517        );
518        assert_eq!(refined.temporal.created_at, incumbent.temporal.created_at);
519    }
520
521    #[test]
522    fn a_vaguer_restatement_does_not_refine() {
523        let incumbent = existing(
524            "mem_old",
525            "avoids meat eats fish",
526            Explicitness::ExplicitStatement,
527        );
528        let resolved = resolver().resolve(
529            proposal("avoids meat", Explicitness::ExplicitStatement),
530            &[incumbent],
531            Utc::now(),
532        );
533        assert_eq!(resolved.kind, ResolutionKind::Supersede);
534    }
535
536    #[test]
537    fn an_inference_cannot_overrule_something_the_user_said() {
538        let incumbent = existing("mem_old", "pescatarian", Explicitness::ExplicitStatement);
539        let resolved = resolver().resolve(
540            proposal("vegan", Explicitness::WeakInference),
541            &[incumbent],
542            Utc::now(),
543        );
544        assert_eq!(resolved.kind, ResolutionKind::Discard);
545        assert_eq!(
546            resolved.discard_reason,
547            Some(DiscardReason::InsufficientEvidence)
548        );
549    }
550
551    #[test]
552    fn an_inference_may_still_supersede_another_inference() {
553        let incumbent = existing("mem_old", "vegetarian", Explicitness::WeakInference);
554        let resolved = resolver().resolve(
555            proposal("pescatarian", Explicitness::StrongImplication),
556            &[incumbent],
557            Utc::now(),
558        );
559        assert_eq!(resolved.kind, ResolutionKind::Supersede);
560    }
561
562    #[test]
563    fn differently_qualified_facts_do_not_contend() {
564        let mut incumbent = existing(
565            "mem_family",
566            "quiet places",
567            Explicitness::ExplicitStatement,
568        );
569        incumbent.qualifier = Some("with family".into());
570        incumbent.predicate = CanonicalPredicate::new("venue_preference");
571
572        let mut p = proposal("live music", Explicitness::ExplicitStatement);
573        p.predicate = CanonicalPredicate::new("venue_preference");
574        p.qualifier = Some("with friends".into());
575
576        let resolved = resolver().resolve(p, &[incumbent], Utc::now());
577        assert_eq!(
578            resolved.kind,
579            ResolutionKind::Create,
580            "a different context is a new fact, not a contradiction"
581        );
582    }
583
584    #[test]
585    fn a_sensitive_inference_is_refused_at_reconciliation_too() {
586        let mut p = proposal("a health condition", Explicitness::StrongImplication);
587        p.sensitivity = SensitivityClass::Sensitive;
588        let resolved = resolver().resolve(p, &[], Utc::now());
589        assert_eq!(resolved.kind, ResolutionKind::Discard);
590        assert_eq!(
591            resolved.discard_reason,
592            Some(DiscardReason::SensitiveWithoutExplicitStatement)
593        );
594    }
595
596    #[test]
597    fn superseded_records_are_not_treated_as_incumbents() {
598        let mut retired = existing("mem_old", "vegetarian", Explicitness::ExplicitStatement);
599        retired.status = MemoryStatus::Superseded;
600        let resolved = resolver().resolve(
601            proposal("pescatarian", Explicitness::ExplicitStatement),
602            &[retired],
603            Utc::now(),
604        );
605        assert_eq!(resolved.kind, ResolutionKind::Create);
606    }
607
608    #[test]
609    fn coexistence_writes_a_second_active_record() {
610        let resolved = resolver().coexist(
611            proposal("live music", Explicitness::ExplicitStatement),
612            Utc::now(),
613        );
614        assert_eq!(resolved.kind, ResolutionKind::Coexist);
615        assert_eq!(resolved.writes[0].status, MemoryStatus::Active);
616    }
617}