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/// An active fact as the fold planner sees it.
83#[derive(Debug, Clone)]
84pub struct FoldCandidate {
85    pub id: i64,
86    pub category: String,
87    pub key: String,
88    pub value: String,
89    /// [`super::facts::fact_source_rank`]: stated by the owner (2) is never
90    /// folded away; a closer source is kept over a farther one.
91    pub source_rank: u8,
92    /// Pinned in owner DMs (`user`, `preference`...): kept over a copy in an
93    /// unpinned category, so folding never unpins the knowledge.
94    pub pinned: bool,
95    pub recall_count: i64,
96    pub privacy: String,
97    pub channel_id: Option<String>,
98    pub vector: Vec<f32>,
99}
100
101/// Which rule found a fold.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum FoldRule {
104    Restatement,
105    OneValue,
106}
107
108/// One fact to retire into the fact that keeps its knowledge.
109#[derive(Debug, Clone, Copy, PartialEq)]
110pub struct PlannedFold {
111    pub folded: i64,
112    pub kept: i64,
113    pub rule: FoldRule,
114    pub similarity: f32,
115}
116
117/// Plan every fold in `candidates`.
118///
119/// Star clustering in authority order: closest source (owner-stated, then
120/// quoted, then inferred), then pinned, then most recalled, then oldest (its key is the one in use). Each fact folds into
121/// the first kept fact it matches; no chaining, so a cluster never drifts
122/// from its representative. Facts fold only within one scope (privacy and
123/// channel): folding a channel fact into a private one hides it, the
124/// reverse widens it. Vectors of different lengths (another embedding model)
125/// never compare.
126pub fn plan_folds(candidates: &mut [FoldCandidate]) -> Vec<PlannedFold> {
127    candidates.sort_by(|a, b| {
128        b.source_rank
129            .cmp(&a.source_rank)
130            .then(b.pinned.cmp(&a.pinned))
131            .then(b.recall_count.cmp(&a.recall_count))
132            .then(a.id.cmp(&b.id))
133    });
134    // Candidates are compared only within a bucket that can match: a
135    // restatement needs the category, one value needs the value.
136    let mut kept_by_category: std::collections::HashMap<String, Vec<usize>> =
137        std::collections::HashMap::new();
138    let mut kept_by_value: std::collections::HashMap<String, Vec<usize>> =
139        std::collections::HashMap::new();
140    let mut folds = Vec::new();
141    for index in 0..candidates.len() {
142        let candidate = &candidates[index];
143        let category = candidate.category.trim().to_ascii_lowercase();
144        let value = crate::text::normalize_fact_value(&candidate.value);
145        let same_scope = |other: &FoldCandidate| {
146            other.privacy == candidate.privacy && other.channel_id == candidate.channel_id
147        };
148        let restated = kept_by_category
149            .get(&category)
150            .into_iter()
151            .flatten()
152            .find_map(|&kept| {
153                let rep = &candidates[kept];
154                if !same_scope(rep) {
155                    return None;
156                }
157                let similarity = crate::cosine(&candidate.vector, &rep.vector);
158                facts_are_restatements(
159                    &candidate.category,
160                    (&candidate.key, &candidate.value),
161                    (&rep.key, &rep.value),
162                    similarity,
163                )
164                .then_some((kept, FoldRule::Restatement, similarity))
165            });
166        let matched = restated.or_else(|| {
167            kept_by_value
168                .get(&value)
169                .into_iter()
170                .flatten()
171                .find_map(|&kept| {
172                    let rep = &candidates[kept];
173                    if !same_scope(rep) {
174                        return None;
175                    }
176                    let similarity = crate::cosine(&candidate.vector, &rep.vector);
177                    facts_hold_one_value(
178                        (&candidate.category, &candidate.key, &candidate.value),
179                        (&rep.category, &rep.key, &rep.value),
180                        similarity,
181                    )
182                    .then_some((kept, FoldRule::OneValue, similarity))
183                })
184        });
185        match matched {
186            Some((kept, rule, similarity)) if candidate.source_rank < 2 => {
187                folds.push(PlannedFold {
188                    folded: candidate.id,
189                    kept: candidates[kept].id,
190                    rule,
191                    similarity,
192                });
193            }
194            _ => {
195                kept_by_category.entry(category).or_default().push(index);
196                if !value.is_empty() {
197                    kept_by_value.entry(value).or_default().push(index);
198                }
199            }
200        }
201    }
202    folds
203}
204
205/// Minimum full-fact similarity to flag two active facts as a probable
206/// conceptual duplicate/overlap for UI review when they did not auto-fold
207/// (e.g. different value shapes, different ranks, or cross-scope owner DMs).
208pub const OVERLAP_REVIEW_MIN_SIMILARITY: f32 = 0.78;
209
210/// Identify active facts that look like conceptual duplicates or overlaps of
211/// another active fact so the Memory UI can highlight them for review without
212/// mutating or losing distinct constraints automatically.
213///
214/// Returns `lower_priority_id -> representative_id` (authority order: highest
215/// `source_rank`, then pinned, then most recalled, then oldest id).
216pub fn detect_overlaps(candidates: &mut [FoldCandidate]) -> std::collections::HashMap<i64, i64> {
217    use std::collections::{HashMap, HashSet};
218
219    candidates.sort_by(|a, b| {
220        b.source_rank
221            .cmp(&a.source_rank)
222            .then(b.pinned.cmp(&a.pinned))
223            .then(b.recall_count.cmp(&a.recall_count))
224            .then(a.id.cmp(&b.id))
225    });
226
227    // Every fact's normalized forms are computed once: the Memory list runs
228    // this over thousands of facts, and normalizing both sides on every
229    // comparison made it quadratic in string work (tens of seconds).
230    let n = candidates.len();
231    let cats: Vec<String> = candidates
232        .iter()
233        .map(|c| c.category.trim().to_ascii_lowercase())
234        .collect();
235    let keys: Vec<String> = candidates
236        .iter()
237        .map(|c| canonicalize_fact_key(&c.key))
238        .collect();
239    let vals: Vec<String> = candidates
240        .iter()
241        .map(|c| crate::text::normalize_fact_value(&c.value))
242        .collect();
243    let words: Vec<HashSet<&str>> = vals
244        .iter()
245        .map(|v| v.split_whitespace().filter(|w| w.len() >= 3).collect())
246        .collect();
247    // Positive owner naming facet per fact (`None` when not an owner-name fact).
248    let naming: Vec<Option<String>> = candidates
249        .iter()
250        .zip(&cats)
251        .map(|(c, cat)| {
252            (crate::text::is_owner_name_key(&c.key)
253                && matches!(cat.as_str(), "user" | "preference" | "personal" | "profile"))
254            .then(|| crate::text::canonical_personal_key(&c.key))
255        })
256        .collect();
257    let norms: Vec<f32> = candidates
258        .iter()
259        .map(|c| c.vector.iter().map(|x| x * x).sum::<f32>().sqrt())
260        .collect();
261    // `crate::cosine` with both norms precomputed.
262    let similarity = |a: usize, b: usize| -> f32 {
263        let (va, vb) = (&candidates[a].vector, &candidates[b].vector);
264        if va.len() != vb.len() || va.is_empty() {
265            return 0.0;
266        }
267        if norms[a] * norms[a] <= f32::EPSILON || norms[b] * norms[b] <= f32::EPSILON {
268            return 0.0;
269        }
270        let dot: f32 = va.iter().zip(vb).map(|(x, y)| x * y).sum();
271        dot / (norms[a] * norms[b])
272    };
273    let is_positive_naming = |facet: &str| {
274        matches!(
275            facet,
276            "name" | "full_name" | "preferred_name" | "nickname" | "addressing"
277        )
278    };
279
280    // Representatives, indexed by what each rule matches on. Every list is
281    // in push order (ascending candidate index), so the first match found in
282    // a list is that rule's earliest representative.
283    let mut naming_reps: Vec<usize> = Vec::new();
284    let mut reps_by_key: HashMap<&str, Vec<usize>> = HashMap::new();
285    let mut reps_by_val: HashMap<&str, Vec<usize>> = HashMap::new();
286    let mut reps_by_cat: HashMap<&str, Vec<usize>> = HashMap::new();
287    let mut overlaps = HashMap::new();
288
289    for index in 0..n {
290        // The earliest representative any rule matches, as the original
291        // single scan over all representatives in order found it.
292        let mut best: Option<usize> = None;
293        let offer = |rep: usize, best: &mut Option<usize>| {
294            if best.is_none_or(|b| rep < b) {
295                *best = Some(rep);
296            }
297        };
298
299        // 1. Two owner-name / addressing facts (e.g. `user/preferred_name = Alice`
300        // and `preference/address_as = Call the owner Alice, not Al.`) are typed
301        // overlaps when they map to the same canonical naming facet or both
302        // express positive owner naming/addressing (keeping `rejected_alias`
303        // distinct as a separate constraint).
304        if let Some(cand_facet) = &naming[index]
305            && let Some(&rep) = naming_reps.iter().find(|&&rep| {
306                let rep_facet = naming[rep].as_deref().unwrap_or_default();
307                cand_facet == rep_facet
308                    || (is_positive_naming(cand_facet) && is_positive_naming(rep_facet))
309            })
310        {
311            offer(rep, &mut best);
312        }
313
314        // 2. Same canonical key across different categories (e.g.
315        // `user/preferred_name` beside `preference/preferred_name`).
316        if !keys[index].is_empty()
317            && let Some(&rep) = reps_by_key
318                .get(keys[index].as_str())
319                .and_then(|list| list.iter().find(|&&rep| cats[rep] != cats[index]))
320        {
321            offer(rep, &mut best);
322        }
323
324        // 3. Same non-scalar normalized value across different keys or
325        // scopes (cross-writer owner-DM duplicates that could not auto-fold).
326        if !vals[index].is_empty()
327            && !is_bare_scalar(&vals[index])
328            && let Some(&rep) = reps_by_val.get(vals[index].as_str()).and_then(|list| {
329                list.iter().find(|&&rep| {
330                    candidates[index].vector.is_empty()
331                        || candidates[rep].vector.is_empty()
332                        || similarity(index, rep) >= ONE_VALUE_MIN_SIMILARITY
333                })
334            })
335        {
336            offer(rep, &mut best);
337        }
338
339        // 4. High semantic similarity within the same category where
340        // values share meaningful vocabulary (catches paraphrased or
341        // partially overlapping rules/preferences). Only representatives
342        // earlier than a match already found can change the answer.
343        if !candidates[index].vector.is_empty()
344            && !words[index].is_empty()
345            && let Some(list) = reps_by_cat.get(cats[index].as_str())
346        {
347            let personal = fact_category_is_personal(&cats[index]);
348            for &rep in list {
349                if best.is_some_and(|b| rep >= b) {
350                    break;
351                }
352                if candidates[rep].vector.is_empty()
353                    || words[index].is_disjoint(&words[rep])
354                    || similarity(index, rep) < OVERLAP_REVIEW_MIN_SIMILARITY
355                {
356                    continue;
357                }
358                if personal {
359                    let cand_tokens: HashSet<&str> =
360                        keys[index].split('_').filter(|t| !t.is_empty()).collect();
361                    let rep_tokens: HashSet<&str> =
362                        keys[rep].split('_').filter(|t| !t.is_empty()).collect();
363                    if keys_name_distinct_concepts(&cand_tokens, &rep_tokens) {
364                        continue;
365                    }
366                }
367                offer(rep, &mut best);
368                break;
369            }
370        }
371
372        if let Some(rep) = best {
373            overlaps.insert(candidates[index].id, candidates[rep].id);
374        } else {
375            if naming[index].is_some() {
376                naming_reps.push(index);
377            }
378            reps_by_key
379                .entry(keys[index].as_str())
380                .or_default()
381                .push(index);
382            reps_by_val
383                .entry(vals[index].as_str())
384                .or_default()
385                .push(index);
386            reps_by_cat
387                .entry(cats[index].as_str())
388                .or_default()
389                .push(index);
390        }
391    }
392    overlaps
393}
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398
399    #[test]
400    fn one_value_under_reworded_keys_is_one_fact() {
401        let a = ("project", "local_sites_directory", "~/projects/");
402        assert!(facts_hold_one_value(
403            a,
404            ("technical", "projects_directory", "~/projects"),
405            0.86
406        ));
407        assert!(facts_hold_one_value(
408            ("technical", "local_dev_tool", "ddev"),
409            ("project", "local_dev_tooling", "DDEV"),
410            0.878
411        ));
412    }
413
414    #[test]
415    fn a_shared_value_alone_is_not_one_fact() {
416        // Too dissimilar as whole facts.
417        assert!(!facts_hold_one_value(
418            ("project", "cars_site_platform", "Cloudflare Workers"),
419            ("project", "store_deployment_target", "Cloudflare Workers"),
420            0.75
421        ));
422        // One word, no key word in common.
423        assert!(!facts_hold_one_value(
424            ("project", "development_platform", "Drupal"),
425            ("project", "framework", "Drupal"),
426            0.9
427        ));
428        // Booleans and numbers say nothing on their own.
429        assert!(!facts_hold_one_value(
430            ("project", "tests_enabled", "true"),
431            ("project", "tests_passing", "true"),
432            0.99
433        ));
434        // Values differ.
435        assert!(!facts_hold_one_value(
436            ("project", "version", "0.9.10"),
437            ("project", "current_version", "0.9.17"),
438            0.95
439        ));
440    }
441
442    #[test]
443    fn people_keys_must_name_the_same_attribute() {
444        assert!(!facts_hold_one_value(
445            ("user", "pet_name", "Mia"),
446            ("user", "daughter_name", "Mia"),
447            0.9
448        ));
449        assert!(!facts_hold_one_value(
450            ("user", "birth_place", "Quito, Ecuador"),
451            ("user", "hometown", "Quito, Ecuador"),
452            0.9
453        ));
454        assert!(facts_hold_one_value(
455            ("user", "favorite_food", "sushi"),
456            ("user", "food", "sushi"),
457            0.9
458        ));
459    }
460
461    fn candidate(id: i64, category: &str, key: &str, value: &str) -> FoldCandidate {
462        FoldCandidate {
463            id,
464            category: category.into(),
465            key: key.into(),
466            value: value.into(),
467            source_rank: 0,
468            pinned: false,
469            recall_count: 0,
470            privacy: "channel".into(),
471            channel_id: None,
472            vector: vec![1.0, 0.0],
473        }
474    }
475
476    #[test]
477    fn the_owner_copy_then_the_pinned_one_survives() {
478        let mut candidates = vec![
479            candidate(1, "project", "editor_choice", "Helix editor"),
480            FoldCandidate {
481                pinned: true,
482                ..candidate(2, "preference", "preferred_editor", "Helix editor")
483            },
484            FoldCandidate {
485                source_rank: 2,
486                ..candidate(3, "technical", "editor", "helix editor")
487            },
488        ];
489        let folds = plan_folds(&mut candidates);
490        assert_eq!(folds.len(), 2);
491        assert!(folds.iter().all(|fold| fold.kept == 3));
492
493        let mut candidates = vec![
494            FoldCandidate {
495                recall_count: 50,
496                ..candidate(1, "project", "editor_choice", "Helix editor")
497            },
498            FoldCandidate {
499                pinned: true,
500                ..candidate(2, "preference", "preferred_editor", "Helix editor")
501            },
502        ];
503        assert_eq!(plan_folds(&mut candidates)[0].kept, 2);
504    }
505
506    #[test]
507    fn scope_and_owner_statements_are_never_folded_away() {
508        let mut candidates = vec![
509            candidate(1, "project", "sites_dir", "~/projects"),
510            FoldCandidate {
511                privacy: "private".into(),
512                ..candidate(2, "technical", "sites_directory", "~/projects")
513            },
514            FoldCandidate {
515                channel_id: Some("slack:synthetic-team".into()),
516                ..candidate(3, "technical", "sites_directory", "~/projects")
517            },
518        ];
519        assert!(plan_folds(&mut candidates).is_empty());
520
521        let mut candidates = vec![
522            FoldCandidate {
523                source_rank: 2,
524                ..candidate(1, "project", "sites_dir", "~/projects")
525            },
526            FoldCandidate {
527                source_rank: 2,
528                ..candidate(2, "technical", "sites_directory", "~/projects")
529            },
530        ];
531        assert!(plan_folds(&mut candidates).is_empty());
532    }
533
534    #[test]
535    fn other_embedding_models_never_compare() {
536        let mut candidates = vec![
537            candidate(1, "project", "sites_dir", "~/projects"),
538            FoldCandidate {
539                vector: vec![1.0, 0.0, 0.0],
540                ..candidate(2, "technical", "sites_directory", "~/projects")
541            },
542        ];
543        assert!(plan_folds(&mut candidates).is_empty());
544    }
545
546    #[test]
547    fn detect_overlaps_flags_owner_name_and_addressing_duplicates() {
548        let mut candidates = vec![
549            FoldCandidate {
550                source_rank: 2,
551                pinned: true,
552                ..candidate(-2_000_000_001, "user", "preferred_name", "Alice")
553            },
554            FoldCandidate {
555                source_rank: 0,
556                pinned: false,
557                ..candidate(
558                    42,
559                    "preference",
560                    "address_as",
561                    "Call the owner Alice. Don't call her Ally or Al.",
562                )
563            },
564            FoldCandidate {
565                source_rank: 2,
566                pinned: false,
567                vector: vec![0.0, 1.0],
568                ..candidate(43, "preference", "favorite_dish", "ramen")
569            },
570        ];
571        let overlaps = detect_overlaps(&mut candidates);
572        assert_eq!(overlaps.get(&42), Some(&-2_000_000_001));
573        assert!(!overlaps.contains_key(&43));
574    }
575}