Skip to main content

aidaemon_memory/sqlite/
fact_folds.rs

1//! Which active facts carry the same knowledge, and which copy keeps it.
2//!
3//! Two rules, both pure so the maintenance pass and `db_probe`'s dry run
4//! agree on every pair:
5//!
6//! - A restatement ([`facts_are_restatements`]): one category, near-identical
7//!   text that makes one claim.
8//! - One value ([`facts_hold_one_value`]): the same normalized value under
9//!   reworded keys, in any category. Extractors file one fact under
10//!   `project` and `technical` alike, and reword its key every time.
11//!
12//! Similarity alone never decides: above 0.93 there are pairs with different
13//! values (two expiry dates), and between 0.85 and 0.93 duplicates mix with
14//! distinct facts. Both rules need the values to agree first.
15
16use super::facts::{
17    canonicalize_fact_key, fact_category_is_personal, facts_are_restatements,
18    keys_name_distinct_concepts,
19};
20
21/// Full-fact similarity at which a value of two or more words, identical
22/// under another key, is the same fact. Measured on a live store of 4,747
23/// facts: from here up pairs are reworded keys for one value; below it
24/// different things start to share a value (two sites on one platform).
25pub const ONE_VALUE_MIN_SIMILARITY: f32 = 0.80;
26
27/// The same for a one-word value (`ddev`, `Rust`), which also needs a key
28/// word in common: one word is shared by many unrelated attributes.
29pub const ONE_WORD_VALUE_MIN_SIMILARITY: f32 = 0.85;
30
31/// A value that says nothing on its own: a boolean, a bare number, a null.
32fn is_bare_scalar(normalized: &str) -> bool {
33    matches!(
34        normalized,
35        "true" | "false" | "yes" | "no" | "none" | "null" | "n a" | "unknown"
36    ) || normalized
37        .split(' ')
38        .all(|word| word.chars().all(|c| c.is_ascii_digit()))
39}
40
41/// Whether two active facts hold one piece of knowledge under different
42/// keys: the same normalized value, similar enough as whole facts, and, when
43/// either is about a person, keys naming the same attribute (`pet_name` and
44/// `daughter_name` are both `Mia`, `birth_place` and `hometown` one city).
45pub fn facts_hold_one_value(
46    (category_a, key_a, value_a): (&str, &str, &str),
47    (category_b, key_b, value_b): (&str, &str, &str),
48    similarity: f32,
49) -> bool {
50    let value = crate::text::normalize_fact_value(value_a);
51    if value.is_empty() || value != crate::text::normalize_fact_value(value_b) {
52        return false;
53    }
54    if is_bare_scalar(&value) {
55        return false;
56    }
57    let canonical_a = canonicalize_fact_key(key_a);
58    let canonical_b = canonicalize_fact_key(key_b);
59    let tokens_a: std::collections::HashSet<&str> =
60        canonical_a.split('_').filter(|t| !t.is_empty()).collect();
61    let tokens_b: std::collections::HashSet<&str> =
62        canonical_b.split('_').filter(|t| !t.is_empty()).collect();
63    let share_a_word = tokens_a.intersection(&tokens_b).next().is_some();
64    let threshold = if value.contains(' ') {
65        ONE_VALUE_MIN_SIMILARITY
66    } else {
67        if !share_a_word {
68            return false;
69        }
70        ONE_WORD_VALUE_MIN_SIMILARITY
71    };
72    if similarity < threshold {
73        return false;
74    }
75    if fact_category_is_personal(category_a) || fact_category_is_personal(category_b) {
76        return canonical_a == canonical_b
77            || share_a_word && !keys_name_distinct_concepts(&tokens_a, &tokens_b);
78    }
79    true
80}
81
82/// Who can see a fact, as far as merging copies of it goes. Two facts in one
83/// class are visible to exactly the same audiences, so one can stand in for
84/// the other without hiding or widening anything.
85#[derive(Debug, Clone, PartialEq, Eq, Hash)]
86pub enum FoldScope {
87    /// Only the owner, in their own private or internal turns: a `private`
88    /// fact (never shown anywhere else, `memory_visible`), or a `channel`
89    /// fact from an app conversation (`app:` channel), which is the owner's
90    /// own and has no other audience.
91    OwnerPrivate,
92    /// A `global` fact; its channel never changes who sees it.
93    Global,
94    /// A `channel` fact from a platform channel or group: visible to that
95    /// channel's members, so it stays per channel.
96    Channel(Option<String>),
97}
98
99/// The channel id prefix of the owner's app conversations (machine format:
100/// the session id the app writes, `app:<conversation>`).
101const APP_CHANNEL_PREFIX: &str = "app:";
102
103/// Whether a stored channel id is one of the owner's app conversations.
104pub fn is_owner_app_channel(channel_id: Option<&str>) -> bool {
105    channel_id.is_some_and(|channel| channel.starts_with(APP_CHANNEL_PREFIX))
106}
107
108/// The visibility class of a fact stored with `privacy` and `channel_id`.
109/// Every merge of facts (fold, write-time restatement, numeric conflict)
110/// compares this, never the raw columns: an owner DM's `private` fact and
111/// the same fact from an app conversation are one audience, while a group
112/// channel never merges with either.
113pub fn fold_scope_key(privacy: &str, channel_id: Option<&str>) -> FoldScope {
114    let privacy = privacy.trim();
115    if privacy.eq_ignore_ascii_case("private")
116        || privacy.eq_ignore_ascii_case("channel") && is_owner_app_channel(channel_id)
117    {
118        FoldScope::OwnerPrivate
119    } else if privacy.eq_ignore_ascii_case("global") {
120        FoldScope::Global
121    } else {
122        FoldScope::Channel(channel_id.map(str::to_string))
123    }
124}
125
126impl FoldScope {
127    /// Whether a fact in `self` can keep the knowledge of a fact in `folded`
128    /// without hiding it from anyone who could see it: the same class, or a
129    /// folded fact only the owner could see (the owner's private turns see
130    /// every scope). Never the reverse, so folding never narrows a fact.
131    pub fn can_keep(&self, folded: &FoldScope) -> bool {
132        self == folded || *folded == FoldScope::OwnerPrivate
133    }
134}
135
136/// An active fact as the fold planner sees it.
137#[derive(Debug, Clone)]
138pub struct FoldCandidate {
139    pub id: i64,
140    pub category: String,
141    pub key: String,
142    pub value: String,
143    /// [`super::facts::fact_source_rank`]: stated by the owner (2) is never
144    /// folded away; a closer source is kept over a farther one.
145    pub source_rank: u8,
146    /// Pinned in owner DMs (`user`, `preference`...): kept over a copy in an
147    /// unpinned category, so folding never unpins the knowledge.
148    pub pinned: bool,
149    pub recall_count: i64,
150    pub privacy: String,
151    pub channel_id: Option<String>,
152    pub vector: Vec<f32>,
153}
154
155/// Which rule found a fold.
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub enum FoldRule {
158    Restatement,
159    OneValue,
160}
161
162/// One fact to retire into the fact that keeps its knowledge.
163#[derive(Debug, Clone, Copy, PartialEq)]
164pub struct PlannedFold {
165    pub folded: i64,
166    pub kept: i64,
167    pub rule: FoldRule,
168    pub similarity: f32,
169}
170
171/// Plan every fold in `candidates`.
172///
173/// Star clustering in authority order: closest source (owner-stated, then
174/// quoted, then inferred), then pinned, then most recalled, then oldest (its key is the one in use). Each fact folds into
175/// the first kept fact it matches; no chaining, so a cluster never drifts
176/// from its representative. Facts fold only within one [`fold_scope_key`]
177/// class: folding a group channel's fact into a private one hides it, the
178/// reverse widens it, while a private fact and an app conversation's fact
179/// have one audience. Vectors of different lengths (another embedding model)
180/// never compare.
181pub fn plan_folds(candidates: &mut [FoldCandidate]) -> Vec<PlannedFold> {
182    candidates.sort_by(|a, b| {
183        b.source_rank
184            .cmp(&a.source_rank)
185            .then(b.pinned.cmp(&a.pinned))
186            .then(b.recall_count.cmp(&a.recall_count))
187            .then(a.id.cmp(&b.id))
188    });
189    // Candidates are compared only within a bucket that can match: a
190    // restatement needs the category, one value needs the value.
191    let mut kept_by_category: std::collections::HashMap<String, Vec<usize>> =
192        std::collections::HashMap::new();
193    let mut kept_by_value: std::collections::HashMap<String, Vec<usize>> =
194        std::collections::HashMap::new();
195    let mut folds = Vec::new();
196    for index in 0..candidates.len() {
197        let candidate = &candidates[index];
198        let category = candidate.category.trim().to_ascii_lowercase();
199        let value = crate::text::normalize_fact_value(&candidate.value);
200        let scope = fold_scope_key(&candidate.privacy, candidate.channel_id.as_deref());
201        let same_scope = |other: &FoldCandidate| {
202            fold_scope_key(&other.privacy, other.channel_id.as_deref()) == scope
203        };
204        let restated = kept_by_category
205            .get(&category)
206            .into_iter()
207            .flatten()
208            .find_map(|&kept| {
209                let rep = &candidates[kept];
210                if !same_scope(rep) {
211                    return None;
212                }
213                let similarity = crate::cosine(&candidate.vector, &rep.vector);
214                facts_are_restatements(
215                    &candidate.category,
216                    (&candidate.key, &candidate.value),
217                    (&rep.key, &rep.value),
218                    similarity,
219                )
220                .then_some((kept, FoldRule::Restatement, similarity))
221            });
222        let matched = restated.or_else(|| {
223            kept_by_value
224                .get(&value)
225                .into_iter()
226                .flatten()
227                .find_map(|&kept| {
228                    let rep = &candidates[kept];
229                    if !same_scope(rep) {
230                        return None;
231                    }
232                    let similarity = crate::cosine(&candidate.vector, &rep.vector);
233                    facts_hold_one_value(
234                        (&candidate.category, &candidate.key, &candidate.value),
235                        (&rep.category, &rep.key, &rep.value),
236                        similarity,
237                    )
238                    .then_some((kept, FoldRule::OneValue, similarity))
239                })
240        });
241        match matched {
242            Some((kept, rule, similarity)) if candidate.source_rank < 2 => {
243                folds.push(PlannedFold {
244                    folded: candidate.id,
245                    kept: candidates[kept].id,
246                    rule,
247                    similarity,
248                });
249            }
250            _ => {
251                kept_by_category.entry(category).or_default().push(index);
252                if !value.is_empty() {
253                    kept_by_value.entry(value).or_default().push(index);
254                }
255            }
256        }
257    }
258    folds
259}
260
261/// Minimum full-fact similarity to flag two active facts as a probable
262/// conceptual duplicate/overlap for UI review when they did not auto-fold
263/// (e.g. different value shapes, different ranks, or cross-scope owner DMs).
264pub const OVERLAP_REVIEW_MIN_SIMILARITY: f32 = 0.78;
265
266/// Identify active facts that look like conceptual duplicates or overlaps of
267/// another active fact so the Memory UI can highlight them for review without
268/// mutating or losing distinct constraints automatically.
269///
270/// Returns `lower_priority_id -> representative_id` (authority order: highest
271/// `source_rank`, then pinned, then most recalled, then oldest id).
272pub fn detect_overlaps(candidates: &mut [FoldCandidate]) -> std::collections::HashMap<i64, i64> {
273    detect_overlaps_excluding(candidates, &std::collections::HashSet::new())
274}
275
276/// The canonical form of an unordered fact pair: `(smaller id, larger id)`.
277pub fn overlap_pair(a: i64, b: i64) -> (i64, i64) {
278    (a.min(b), a.max(b))
279}
280
281/// [`detect_overlaps`], never pairing two facts in `distinct` (pairs in
282/// [`overlap_pair`] form a reviewer judged distinct). A fact whose only
283/// match was such a pair is checked against the next representative, so a
284/// verdict on one pair never hides a different duplicate.
285pub fn detect_overlaps_excluding(
286    candidates: &mut [FoldCandidate],
287    distinct: &std::collections::HashSet<(i64, i64)>,
288) -> std::collections::HashMap<i64, i64> {
289    use std::collections::{HashMap, HashSet};
290
291    candidates.sort_by(|a, b| {
292        b.source_rank
293            .cmp(&a.source_rank)
294            .then(b.pinned.cmp(&a.pinned))
295            .then(b.recall_count.cmp(&a.recall_count))
296            .then(a.id.cmp(&b.id))
297    });
298
299    // Every fact's normalized forms are computed once: the Memory list runs
300    // this over thousands of facts, and normalizing both sides on every
301    // comparison made it quadratic in string work (tens of seconds).
302    let n = candidates.len();
303    let cats: Vec<String> = candidates
304        .iter()
305        .map(|c| c.category.trim().to_ascii_lowercase())
306        .collect();
307    let keys: Vec<String> = candidates
308        .iter()
309        .map(|c| canonicalize_fact_key(&c.key))
310        .collect();
311    let vals: Vec<String> = candidates
312        .iter()
313        .map(|c| crate::text::normalize_fact_value(&c.value))
314        .collect();
315    let words: Vec<HashSet<&str>> = vals
316        .iter()
317        .map(|v| v.split_whitespace().filter(|w| w.len() >= 3).collect())
318        .collect();
319    // Positive owner naming facet per fact (`None` when not an owner-name fact).
320    let naming: Vec<Option<String>> = candidates
321        .iter()
322        .zip(&cats)
323        .map(|(c, cat)| {
324            (crate::text::is_owner_name_key(&c.key)
325                && matches!(cat.as_str(), "user" | "preference" | "personal" | "profile"))
326            .then(|| crate::text::canonical_personal_key(&c.key))
327        })
328        .collect();
329    let norms: Vec<f32> = candidates
330        .iter()
331        .map(|c| c.vector.iter().map(|x| x * x).sum::<f32>().sqrt())
332        .collect();
333    // `crate::cosine` with both norms precomputed.
334    let similarity = |a: usize, b: usize| -> f32 {
335        let (va, vb) = (&candidates[a].vector, &candidates[b].vector);
336        if va.len() != vb.len() || va.is_empty() {
337            return 0.0;
338        }
339        if norms[a] * norms[a] <= f32::EPSILON || norms[b] * norms[b] <= f32::EPSILON {
340            return 0.0;
341        }
342        let dot: f32 = va.iter().zip(vb).map(|(x, y)| x * y).sum();
343        dot / (norms[a] * norms[b])
344    };
345    let is_positive_naming = |facet: &str| {
346        matches!(
347            facet,
348            "name" | "full_name" | "preferred_name" | "nickname" | "addressing"
349        )
350    };
351
352    // Representatives, indexed by what each rule matches on. Every list is
353    // in push order (ascending candidate index), so the first match found in
354    // a list is that rule's earliest representative.
355    let mut naming_reps: Vec<usize> = Vec::new();
356    let mut reps_by_key: HashMap<&str, Vec<usize>> = HashMap::new();
357    let mut reps_by_val: HashMap<&str, Vec<usize>> = HashMap::new();
358    let mut reps_by_cat: HashMap<&str, Vec<usize>> = HashMap::new();
359    let mut overlaps = HashMap::new();
360    let allowed = |index: usize, rep: usize| {
361        distinct.is_empty()
362            || !distinct.contains(&overlap_pair(candidates[index].id, candidates[rep].id))
363    };
364
365    for index in 0..n {
366        // The earliest representative any rule matches, as the original
367        // single scan over all representatives in order found it.
368        let mut best: Option<usize> = None;
369        let offer = |rep: usize, best: &mut Option<usize>| {
370            if best.is_none_or(|b| rep < b) {
371                *best = Some(rep);
372            }
373        };
374
375        // 1. Two owner-name / addressing facts (e.g. `user/preferred_name = Alice`
376        // and `preference/address_as = Call the owner Alice, not Al.`) are typed
377        // overlaps when they map to the same canonical naming facet or both
378        // express positive owner naming/addressing (keeping `rejected_alias`
379        // distinct as a separate constraint).
380        if let Some(cand_facet) = &naming[index]
381            && let Some(&rep) = naming_reps.iter().find(|&&rep| {
382                let rep_facet = naming[rep].as_deref().unwrap_or_default();
383                (cand_facet == rep_facet
384                    || (is_positive_naming(cand_facet) && is_positive_naming(rep_facet)))
385                    && allowed(index, rep)
386            })
387        {
388            offer(rep, &mut best);
389        }
390
391        // 2. Same canonical key across different categories (e.g.
392        // `user/preferred_name` beside `preference/preferred_name`).
393        if !keys[index].is_empty()
394            && let Some(&rep) = reps_by_key.get(keys[index].as_str()).and_then(|list| {
395                list.iter()
396                    .find(|&&rep| cats[rep] != cats[index] && allowed(index, rep))
397            })
398        {
399            offer(rep, &mut best);
400        }
401
402        // 3. Same non-scalar normalized value across different keys or
403        // scopes (cross-writer owner-DM duplicates that could not auto-fold).
404        if !vals[index].is_empty()
405            && !is_bare_scalar(&vals[index])
406            && let Some(&rep) = reps_by_val.get(vals[index].as_str()).and_then(|list| {
407                list.iter().find(|&&rep| {
408                    (candidates[index].vector.is_empty()
409                        || candidates[rep].vector.is_empty()
410                        || similarity(index, rep) >= ONE_VALUE_MIN_SIMILARITY)
411                        && allowed(index, rep)
412                })
413            })
414        {
415            offer(rep, &mut best);
416        }
417
418        // 4. High semantic similarity within the same category where
419        // values share meaningful vocabulary (catches paraphrased or
420        // partially overlapping rules/preferences). Only representatives
421        // earlier than a match already found can change the answer.
422        if !candidates[index].vector.is_empty()
423            && !words[index].is_empty()
424            && let Some(list) = reps_by_cat.get(cats[index].as_str())
425        {
426            let personal = fact_category_is_personal(&cats[index]);
427            for &rep in list {
428                if best.is_some_and(|b| rep >= b) {
429                    break;
430                }
431                if candidates[rep].vector.is_empty()
432                    || !allowed(index, rep)
433                    || words[index].is_disjoint(&words[rep])
434                    || similarity(index, rep) < OVERLAP_REVIEW_MIN_SIMILARITY
435                {
436                    continue;
437                }
438                if personal {
439                    let cand_tokens: HashSet<&str> =
440                        keys[index].split('_').filter(|t| !t.is_empty()).collect();
441                    let rep_tokens: HashSet<&str> =
442                        keys[rep].split('_').filter(|t| !t.is_empty()).collect();
443                    if keys_name_distinct_concepts(&cand_tokens, &rep_tokens) {
444                        continue;
445                    }
446                }
447                offer(rep, &mut best);
448                break;
449            }
450        }
451
452        if let Some(rep) = best {
453            overlaps.insert(candidates[index].id, candidates[rep].id);
454        } else {
455            if naming[index].is_some() {
456                naming_reps.push(index);
457            }
458            reps_by_key
459                .entry(keys[index].as_str())
460                .or_default()
461                .push(index);
462            reps_by_val
463                .entry(vals[index].as_str())
464                .or_default()
465                .push(index);
466            reps_by_cat
467                .entry(cats[index].as_str())
468                .or_default()
469                .push(index);
470        }
471    }
472    overlaps
473}
474
475/// Whole-fact similarity at which two facts whose numbers differ are taken
476/// as one attribute holding two values (`db_probe --fact-conflict-audit`
477/// measured it on a live store).
478pub const NUMERIC_CONFLICT_MIN_SIMILARITY: f32 = 0.90;
479
480/// An active fact as the numeric-conflict planner sees it.
481#[derive(Debug, Clone)]
482pub struct ConflictCandidate {
483    pub id: i64,
484    pub category: String,
485    pub key: String,
486    pub value: String,
487    /// [`super::facts::fact_source_rank`].
488    pub source_rank: u8,
489    /// When the knowledge was first seen (`first_seen_at`, else
490    /// `updated_at`): the later of two automated values is the current one.
491    pub seen: Option<chrono::DateTime<chrono::Utc>>,
492    pub privacy: String,
493    pub channel_id: Option<String>,
494    pub vector: Vec<f32>,
495}
496
497/// A stored fact timestamp (`first_seen_at`, `updated_at`) as
498/// [`ConflictCandidate::seen`] reads it: RFC 3339, or SQLite's
499/// `datetime('now')` form.
500pub fn parse_fact_timestamp(raw: &str) -> Option<chrono::DateTime<chrono::Utc>> {
501    crate::types::parse_ts(raw)
502}
503
504/// The tokens of a value that carry a digit (`0.9.10`, `8080`, `2026`),
505/// lowercased: the part of a value an embedding barely sees.
506pub fn value_numbers(value: &str) -> std::collections::BTreeSet<String> {
507    value
508        .split(|c: char| !c.is_alphanumeric())
509        .filter(|token| token.chars().any(|c| c.is_ascii_digit()))
510        .map(str::to_lowercase)
511        .collect()
512}
513
514/// What to do with one conflicting pair.
515#[derive(Debug, Clone, Copy, PartialEq, Eq)]
516pub enum ConflictVerdict {
517    /// `kept` holds the current value; `retired` is replaced by it.
518    Resolved { kept: i64, retired: i64 },
519    /// Both were stated by the owner: only the owner can say which holds.
520    BothOwnerStated,
521    /// The keys may name two attributes (`version` / `previous_version`):
522    /// both kept, listed for review.
523    DistinctAttributes,
524}
525
526/// Two active facts that look like one attribute with two values.
527#[derive(Debug, Clone, Copy, PartialEq)]
528pub struct NumericConflict {
529    pub a: i64,
530    pub b: i64,
531    pub similarity: f32,
532    pub verdict: ConflictVerdict,
533}
534
535/// Every pair of `candidates` that may be one attribute with two values:
536/// one [`fold_scope_key`] class, not `behavior` (left to
537/// `--retire-inferred-behavior`), different numbers, and whole-fact
538/// similarity of at least [`NUMERIC_CONFLICT_MIN_SIMILARITY`].
539///
540/// The verdict never lets a farther source retire a closer one: an
541/// owner-stated fact beats an automated one; two automated facts are
542/// resolved only when their keys name the same attribute, the closer source
543/// winning, then the one seen later (then the later row). Two owner-stated
544/// facts, or keys that may name two attributes, are left for review.
545/// Sorted by similarity, highest first.
546pub fn plan_numeric_conflicts(candidates: &[ConflictCandidate]) -> Vec<NumericConflict> {
547    use std::collections::HashMap;
548    let mut by_scope: HashMap<FoldScope, Vec<usize>> = HashMap::new();
549    for (index, candidate) in candidates.iter().enumerate() {
550        if candidate.category.trim().eq_ignore_ascii_case("behavior") || candidate.vector.is_empty()
551        {
552            continue;
553        }
554        by_scope
555            .entry(fold_scope_key(
556                &candidate.privacy,
557                candidate.channel_id.as_deref(),
558            ))
559            .or_default()
560            .push(index);
561    }
562    let numbers: Vec<_> = candidates.iter().map(|c| value_numbers(&c.value)).collect();
563    let mut conflicts = Vec::new();
564    for members in by_scope.values() {
565        for (position, &i) in members.iter().enumerate() {
566            // Both sides must actually state numbers, otherwise a numberless
567            // summary ("Uses Python") could retire a specific version ("Uses Python 3.12").
568            if numbers[i].is_empty() {
569                continue;
570            }
571            for &j in &members[position + 1..] {
572                if numbers[j].is_empty() || numbers[i] == numbers[j] {
573                    continue;
574                }
575                let (a, b) = (&candidates[i], &candidates[j]);
576                if !a.category.trim().eq_ignore_ascii_case(b.category.trim()) {
577                    continue;
578                }
579                if a.vector.len() != b.vector.len() {
580                    continue;
581                }
582                let similarity = crate::cosine(&a.vector, &b.vector);
583                if similarity < NUMERIC_CONFLICT_MIN_SIMILARITY {
584                    continue;
585                }
586                conflicts.push(NumericConflict {
587                    a: a.id.min(b.id),
588                    b: a.id.max(b.id),
589                    similarity,
590                    verdict: numeric_conflict_verdict(a, b),
591                });
592            }
593        }
594    }
595    conflicts.sort_by(|x, y| {
596        y.similarity
597            .total_cmp(&x.similarity)
598            .then(x.a.cmp(&y.a))
599            .then(x.b.cmp(&y.b))
600    });
601    conflicts
602}
603
604fn numeric_conflict_verdict(a: &ConflictCandidate, b: &ConflictCandidate) -> ConflictVerdict {
605    if !super::facts::keys_name_same_attribute(&a.key, &b.key) {
606        return ConflictVerdict::DistinctAttributes;
607    }
608    let resolved =
609        |kept: &ConflictCandidate, retired: &ConflictCandidate| ConflictVerdict::Resolved {
610            kept: kept.id,
611            retired: retired.id,
612        };
613    match (a.source_rank >= 2, b.source_rank >= 2) {
614        (true, true) => ConflictVerdict::BothOwnerStated,
615        (true, false) => resolved(a, b),
616        (false, true) => resolved(b, a),
617        (false, false) => {
618            let a_wins = a
619                .source_rank
620                .cmp(&b.source_rank)
621                .then(a.seen.cmp(&b.seen))
622                .then(a.id.cmp(&b.id))
623                .is_gt();
624            if a_wins {
625                resolved(a, b)
626            } else {
627                resolved(b, a)
628            }
629        }
630    }
631}
632
633/// The retirements the resolved conflicts call for, as `(retired, kept)`:
634/// most similar pair first, each fact retired at most once, and no fact
635/// both kept and retired in one pass, so nothing is retired into a row that
636/// is itself going away (a chain resolves over later passes).
637pub fn numeric_conflict_retirements(conflicts: &[NumericConflict]) -> Vec<(i64, i64)> {
638    let mut retired = std::collections::HashSet::new();
639    let mut keepers = std::collections::HashSet::new();
640    let mut out = Vec::new();
641    for conflict in conflicts {
642        let ConflictVerdict::Resolved {
643            kept,
644            retired: loser,
645        } = conflict.verdict
646        else {
647            continue;
648        };
649        // A chain (`a` into `b`, `b` into `c`) waits for the next pass.
650        if retired.contains(&kept) || retired.contains(&loser) || keepers.contains(&loser) {
651            continue;
652        }
653        retired.insert(loser);
654        keepers.insert(kept);
655        out.push((loser, kept));
656    }
657    out
658}
659
660#[cfg(test)]
661mod tests {
662    use super::*;
663
664    #[test]
665    fn one_value_under_reworded_keys_is_one_fact() {
666        let a = ("project", "local_sites_directory", "~/projects/");
667        assert!(facts_hold_one_value(
668            a,
669            ("technical", "projects_directory", "~/projects"),
670            0.86
671        ));
672        assert!(facts_hold_one_value(
673            ("technical", "local_dev_tool", "ddev"),
674            ("project", "local_dev_tooling", "DDEV"),
675            0.878
676        ));
677    }
678
679    #[test]
680    fn a_shared_value_alone_is_not_one_fact() {
681        // Too dissimilar as whole facts.
682        assert!(!facts_hold_one_value(
683            ("project", "cars_site_platform", "Cloudflare Workers"),
684            ("project", "store_deployment_target", "Cloudflare Workers"),
685            0.75
686        ));
687        // One word, no key word in common.
688        assert!(!facts_hold_one_value(
689            ("project", "development_platform", "Drupal"),
690            ("project", "framework", "Drupal"),
691            0.9
692        ));
693        // Booleans and numbers say nothing on their own.
694        assert!(!facts_hold_one_value(
695            ("project", "tests_enabled", "true"),
696            ("project", "tests_passing", "true"),
697            0.99
698        ));
699        // Values differ.
700        assert!(!facts_hold_one_value(
701            ("project", "version", "0.9.10"),
702            ("project", "current_version", "0.9.17"),
703            0.95
704        ));
705    }
706
707    #[test]
708    fn people_keys_must_name_the_same_attribute() {
709        assert!(!facts_hold_one_value(
710            ("user", "pet_name", "Mia"),
711            ("user", "daughter_name", "Mia"),
712            0.9
713        ));
714        assert!(!facts_hold_one_value(
715            ("user", "birth_place", "Quito, Ecuador"),
716            ("user", "hometown", "Quito, Ecuador"),
717            0.9
718        ));
719        assert!(facts_hold_one_value(
720            ("user", "favorite_food", "sushi"),
721            ("user", "food", "sushi"),
722            0.9
723        ));
724    }
725
726    fn candidate(id: i64, category: &str, key: &str, value: &str) -> FoldCandidate {
727        FoldCandidate {
728            id,
729            category: category.into(),
730            key: key.into(),
731            value: value.into(),
732            source_rank: 0,
733            pinned: false,
734            recall_count: 0,
735            privacy: "channel".into(),
736            channel_id: None,
737            vector: vec![1.0, 0.0],
738        }
739    }
740
741    #[test]
742    fn the_owner_copy_then_the_pinned_one_survives() {
743        let mut candidates = vec![
744            candidate(1, "project", "editor_choice", "Helix editor"),
745            FoldCandidate {
746                pinned: true,
747                ..candidate(2, "preference", "preferred_editor", "Helix editor")
748            },
749            FoldCandidate {
750                source_rank: 2,
751                ..candidate(3, "technical", "editor", "helix editor")
752            },
753        ];
754        let folds = plan_folds(&mut candidates);
755        assert_eq!(folds.len(), 2);
756        assert!(folds.iter().all(|fold| fold.kept == 3));
757
758        let mut candidates = vec![
759            FoldCandidate {
760                recall_count: 50,
761                ..candidate(1, "project", "editor_choice", "Helix editor")
762            },
763            FoldCandidate {
764                pinned: true,
765                ..candidate(2, "preference", "preferred_editor", "Helix editor")
766            },
767        ];
768        assert_eq!(plan_folds(&mut candidates)[0].kept, 2);
769    }
770
771    #[test]
772    fn scope_and_owner_statements_are_never_folded_away() {
773        let mut candidates = vec![
774            candidate(1, "project", "sites_dir", "~/projects"),
775            FoldCandidate {
776                privacy: "private".into(),
777                ..candidate(2, "technical", "sites_directory", "~/projects")
778            },
779            FoldCandidate {
780                channel_id: Some("slack:synthetic-team".into()),
781                ..candidate(3, "technical", "sites_directory", "~/projects")
782            },
783        ];
784        assert!(plan_folds(&mut candidates).is_empty());
785
786        let mut candidates = vec![
787            FoldCandidate {
788                source_rank: 2,
789                ..candidate(1, "project", "sites_dir", "~/projects")
790            },
791            FoldCandidate {
792                source_rank: 2,
793                ..candidate(2, "technical", "sites_directory", "~/projects")
794            },
795        ];
796        assert!(plan_folds(&mut candidates).is_empty());
797    }
798
799    #[test]
800    fn other_embedding_models_never_compare() {
801        let mut candidates = vec![
802            candidate(1, "project", "sites_dir", "~/projects"),
803            FoldCandidate {
804                vector: vec![1.0, 0.0, 0.0],
805                ..candidate(2, "technical", "sites_directory", "~/projects")
806            },
807        ];
808        assert!(plan_folds(&mut candidates).is_empty());
809    }
810
811    #[test]
812    fn detect_overlaps_flags_owner_name_and_addressing_duplicates() {
813        let mut candidates = vec![
814            FoldCandidate {
815                source_rank: 2,
816                pinned: true,
817                ..candidate(-2_000_000_001, "user", "preferred_name", "Alice")
818            },
819            FoldCandidate {
820                source_rank: 0,
821                pinned: false,
822                ..candidate(
823                    42,
824                    "preference",
825                    "address_as",
826                    "Call the owner Alice. Don't call her Ally or Al.",
827                )
828            },
829            FoldCandidate {
830                source_rank: 2,
831                pinned: false,
832                vector: vec![0.0, 1.0],
833                ..candidate(43, "preference", "favorite_dish", "ramen")
834            },
835        ];
836        let overlaps = detect_overlaps(&mut candidates);
837        assert_eq!(overlaps.get(&42), Some(&-2_000_000_001));
838        assert!(!overlaps.contains_key(&43));
839    }
840
841    #[test]
842    fn fold_scope_groups_owner_only_facts() {
843        assert_eq!(fold_scope_key("private", None), FoldScope::OwnerPrivate);
844        assert_eq!(
845            fold_scope_key("Private", Some("telegram:synthetic-user-1")),
846            FoldScope::OwnerPrivate
847        );
848        assert_eq!(
849            fold_scope_key("channel", Some("app:synthetic-conv-1")),
850            FoldScope::OwnerPrivate
851        );
852        assert_eq!(fold_scope_key("global", Some("app:x")), FoldScope::Global);
853        assert_eq!(fold_scope_key("global", None), FoldScope::Global);
854        assert_eq!(
855            fold_scope_key("channel", Some("slack:synthetic-team")),
856            FoldScope::Channel(Some("slack:synthetic-team".into()))
857        );
858        // The prefix is a machine format: compared exactly.
859        assert_eq!(
860            fold_scope_key("channel", Some("APP:x")),
861            FoldScope::Channel(Some("APP:x".into()))
862        );
863        assert_eq!(fold_scope_key("channel", None), FoldScope::Channel(None));
864        // Folding never hides knowledge from an audience that saw it.
865        let group = FoldScope::Channel(Some("slack:synthetic-team".into()));
866        assert!(FoldScope::Global.can_keep(&FoldScope::OwnerPrivate));
867        assert!(group.can_keep(&FoldScope::OwnerPrivate));
868        assert!(!FoldScope::OwnerPrivate.can_keep(&FoldScope::Global));
869        assert!(!FoldScope::OwnerPrivate.can_keep(&group));
870        assert!(!FoldScope::Global.can_keep(&group));
871    }
872
873    fn scoped(id: i64, key: &str, privacy: &str, channel: Option<&str>) -> FoldCandidate {
874        FoldCandidate {
875            privacy: privacy.into(),
876            channel_id: channel.map(str::to_string),
877            ..candidate(id, "technical", key, "~/projects")
878        }
879    }
880
881    #[test]
882    fn owner_only_scopes_fold_together_and_never_with_shared_ones() {
883        let mut candidates = vec![
884            scoped(1, "sites_dir", "channel", Some("app:synthetic-conv-1")),
885            scoped(
886                2,
887                "sites_directory",
888                "channel",
889                Some("app:synthetic-conv-2"),
890            ),
891            scoped(3, "projects_dir", "private", None),
892        ];
893        let folds = plan_folds(&mut candidates);
894        assert_eq!(folds.len(), 2);
895        assert!(folds.iter().all(|fold| fold.kept == 1));
896
897        let mut candidates = vec![
898            scoped(1, "sites_dir", "private", None),
899            scoped(2, "sites_directory", "global", None),
900            scoped(3, "projects_dir", "channel", Some("slack:synthetic-team")),
901            scoped(4, "project_root", "channel", Some("discord:ch:synthetic-1")),
902        ];
903        assert!(plan_folds(&mut candidates).is_empty());
904    }
905
906    fn conflict(
907        id: i64,
908        key: &str,
909        value: &str,
910        source_rank: u8,
911        seen_days_ago: i64,
912        vector: Vec<f32>,
913    ) -> ConflictCandidate {
914        ConflictCandidate {
915            id,
916            category: "project".into(),
917            key: key.into(),
918            value: value.into(),
919            source_rank,
920            seen: Some(chrono::Utc::now() - chrono::Duration::days(seen_days_ago)),
921            privacy: "private".into(),
922            channel_id: None,
923            vector,
924        }
925    }
926
927    #[test]
928    fn numeric_conflict_verdicts_follow_source_then_recency() {
929        let near = vec![0.95, 0.312];
930        let base = vec![1.0, 0.0];
931        let pair = |a: ConflictCandidate, b: ConflictCandidate| {
932            let conflicts = plan_numeric_conflicts(&[a, b]);
933            assert_eq!(conflicts.len(), 1);
934            conflicts[0].verdict
935        };
936        // Owner beats inferred on the same attribute, however old.
937        assert_eq!(
938            pair(
939                conflict(1, "api_port", "8080", 2, 90, base.clone()),
940                conflict(2, "default_api_port", "9090", 0, 0, near.clone()),
941            ),
942            ConflictVerdict::Resolved {
943                kept: 1,
944                retired: 2
945            }
946        );
947        // Owner never retires an automated fact naming a distinct attribute
948        // (e.g. two different people's birthdays or two different ports).
949        assert_eq!(
950            pair(
951                conflict(1, "mia_birthday", "2015-03-15", 2, 90, base.clone()),
952                conflict(2, "zoe_birthday", "2018-07-22", 0, 0, near.clone()),
953            ),
954            ConflictVerdict::DistinctAttributes
955        );
956        // A numberless summary never conflicts with a specific version.
957        assert!(
958            plan_numeric_conflicts(&[
959                conflict(1, "python", "Uses Python", 2, 1, base.clone()),
960                conflict(2, "current_python", "Uses Python 3.12", 0, 2, near.clone()),
961            ])
962            .is_empty()
963        );
964        // Same attribute: newer wins between equals, a quote beats an inference.
965        assert_eq!(
966            pair(
967                conflict(1, "node_version", "18", 0, 30, base.clone()),
968                conflict(2, "current_node_version", "20", 0, 1, near.clone()),
969            ),
970            ConflictVerdict::Resolved {
971                kept: 2,
972                retired: 1
973            }
974        );
975        assert_eq!(
976            pair(
977                conflict(1, "node_version", "18", 1, 30, base.clone()),
978                conflict(2, "current_node_version", "20", 0, 1, near.clone()),
979            ),
980            ConflictVerdict::Resolved {
981                kept: 1,
982                retired: 2
983            }
984        );
985        assert_eq!(
986            pair(
987                conflict(1, "release_version", "1.2", 0, 30, base.clone()),
988                conflict(2, "build_version", "3.4", 0, 1, near.clone()),
989            ),
990            ConflictVerdict::DistinctAttributes
991        );
992        assert_eq!(
993            pair(
994                conflict(1, "deadline", "day 12", 2, 30, base.clone()),
995                conflict(2, "deadline", "day 14", 2, 1, near.clone()),
996            ),
997            ConflictVerdict::BothOwnerStated
998        );
999        // Same numbers, low similarity, behavior, or another scope: no pair.
1000        let none = |a: ConflictCandidate, b: ConflictCandidate| {
1001            assert!(plan_numeric_conflicts(&[a, b]).is_empty());
1002        };
1003        none(
1004            conflict(1, "port", "8080", 0, 1, base.clone()),
1005            conflict(2, "port_number", "port 8080", 0, 2, near.clone()),
1006        );
1007        none(
1008            conflict(1, "port", "8080", 0, 1, base.clone()),
1009            conflict(2, "port_number", "9090", 0, 2, vec![0.8, 0.6]),
1010        );
1011        none(
1012            ConflictCandidate {
1013                category: "behavior".into(),
1014                ..conflict(1, "port", "8080", 0, 1, base.clone())
1015            },
1016            conflict(2, "port_number", "9090", 0, 2, near.clone()),
1017        );
1018        none(
1019            ConflictCandidate {
1020                privacy: "global".into(),
1021                ..conflict(1, "port", "8080", 0, 1, base.clone())
1022            },
1023            conflict(2, "port_number", "9090", 0, 2, near.clone()),
1024        );
1025    }
1026
1027    #[test]
1028    fn numeric_retirements_never_chain_in_one_pass() {
1029        let resolved = |kept: i64, retired: i64, similarity: f32| NumericConflict {
1030            a: kept.min(retired),
1031            b: kept.max(retired),
1032            similarity,
1033            verdict: ConflictVerdict::Resolved { kept, retired },
1034        };
1035        let conflicts = vec![
1036            resolved(2, 1, 0.99),
1037            // 2 was kept above: not retired in the same pass.
1038            resolved(3, 2, 0.98),
1039            // 1 is already retired.
1040            resolved(4, 1, 0.97),
1041            NumericConflict {
1042                a: 5,
1043                b: 6,
1044                similarity: 0.96,
1045                verdict: ConflictVerdict::BothOwnerStated,
1046            },
1047            resolved(7, 8, 0.95),
1048        ];
1049        assert_eq!(
1050            numeric_conflict_retirements(&conflicts),
1051            vec![(1, 2), (8, 7)]
1052        );
1053    }
1054
1055    #[test]
1056    fn a_distinct_pair_falls_through_to_the_next_representative() {
1057        let value = "dark theme in every editor";
1058        let mut candidates = vec![
1059            FoldCandidate {
1060                recall_count: 9,
1061                ..candidate(1, "preference", "theme", value)
1062            },
1063            FoldCandidate {
1064                recall_count: 5,
1065                ..candidate(2, "technical", "editor_theme", value)
1066            },
1067            candidate(3, "project", "ide_theme", value),
1068        ];
1069        let all = detect_overlaps(&mut candidates.clone());
1070        assert_eq!(all.get(&3), Some(&1));
1071        assert_eq!(all.get(&2), Some(&1));
1072        // 1 and 3 judged distinct: 3 has no other representative.
1073        let distinct = [overlap_pair(3, 1)].into_iter().collect();
1074        let reviewed = detect_overlaps_excluding(&mut candidates.clone(), &distinct);
1075        assert_eq!(reviewed.get(&3), None);
1076        assert_eq!(reviewed.get(&2), Some(&1));
1077        // 2 judged distinct from 1 too: 2 represents, and 3 pairs with it.
1078        let distinct = [overlap_pair(3, 1), overlap_pair(1, 2)]
1079            .into_iter()
1080            .collect();
1081        let reviewed = detect_overlaps_excluding(&mut candidates, &distinct);
1082        assert_eq!(reviewed.get(&2), None);
1083        assert_eq!(reviewed.get(&3), Some(&2));
1084    }
1085}