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#[cfg(test)]
206mod tests {
207    use super::*;
208
209    #[test]
210    fn one_value_under_reworded_keys_is_one_fact() {
211        let a = ("project", "local_sites_directory", "~/projects/");
212        assert!(facts_hold_one_value(
213            a,
214            ("technical", "projects_directory", "~/projects"),
215            0.86
216        ));
217        assert!(facts_hold_one_value(
218            ("technical", "local_dev_tool", "ddev"),
219            ("project", "local_dev_tooling", "DDEV"),
220            0.878
221        ));
222    }
223
224    #[test]
225    fn a_shared_value_alone_is_not_one_fact() {
226        // Too dissimilar as whole facts.
227        assert!(!facts_hold_one_value(
228            ("project", "cars_site_platform", "Cloudflare Workers"),
229            ("project", "store_deployment_target", "Cloudflare Workers"),
230            0.75
231        ));
232        // One word, no key word in common.
233        assert!(!facts_hold_one_value(
234            ("project", "development_platform", "Drupal"),
235            ("project", "framework", "Drupal"),
236            0.9
237        ));
238        // Booleans and numbers say nothing on their own.
239        assert!(!facts_hold_one_value(
240            ("project", "tests_enabled", "true"),
241            ("project", "tests_passing", "true"),
242            0.99
243        ));
244        // Values differ.
245        assert!(!facts_hold_one_value(
246            ("project", "version", "0.9.10"),
247            ("project", "current_version", "0.9.17"),
248            0.95
249        ));
250    }
251
252    #[test]
253    fn people_keys_must_name_the_same_attribute() {
254        assert!(!facts_hold_one_value(
255            ("user", "pet_name", "Mia"),
256            ("user", "daughter_name", "Mia"),
257            0.9
258        ));
259        assert!(!facts_hold_one_value(
260            ("user", "birth_place", "Quito, Ecuador"),
261            ("user", "hometown", "Quito, Ecuador"),
262            0.9
263        ));
264        assert!(facts_hold_one_value(
265            ("user", "favorite_food", "sushi"),
266            ("user", "food", "sushi"),
267            0.9
268        ));
269    }
270
271    fn candidate(id: i64, category: &str, key: &str, value: &str) -> FoldCandidate {
272        FoldCandidate {
273            id,
274            category: category.into(),
275            key: key.into(),
276            value: value.into(),
277            source_rank: 0,
278            pinned: false,
279            recall_count: 0,
280            privacy: "channel".into(),
281            channel_id: None,
282            vector: vec![1.0, 0.0],
283        }
284    }
285
286    #[test]
287    fn the_owner_copy_then_the_pinned_one_survives() {
288        let mut candidates = vec![
289            candidate(1, "project", "editor_choice", "Helix editor"),
290            FoldCandidate {
291                pinned: true,
292                ..candidate(2, "preference", "preferred_editor", "Helix editor")
293            },
294            FoldCandidate {
295                source_rank: 2,
296                ..candidate(3, "technical", "editor", "helix editor")
297            },
298        ];
299        let folds = plan_folds(&mut candidates);
300        assert_eq!(folds.len(), 2);
301        assert!(folds.iter().all(|fold| fold.kept == 3));
302
303        let mut candidates = vec![
304            FoldCandidate {
305                recall_count: 50,
306                ..candidate(1, "project", "editor_choice", "Helix editor")
307            },
308            FoldCandidate {
309                pinned: true,
310                ..candidate(2, "preference", "preferred_editor", "Helix editor")
311            },
312        ];
313        assert_eq!(plan_folds(&mut candidates)[0].kept, 2);
314    }
315
316    #[test]
317    fn scope_and_owner_statements_are_never_folded_away() {
318        let mut candidates = vec![
319            candidate(1, "project", "sites_dir", "~/projects"),
320            FoldCandidate {
321                privacy: "private".into(),
322                ..candidate(2, "technical", "sites_directory", "~/projects")
323            },
324            FoldCandidate {
325                channel_id: Some("slack:synthetic-team".into()),
326                ..candidate(3, "technical", "sites_directory", "~/projects")
327            },
328        ];
329        assert!(plan_folds(&mut candidates).is_empty());
330
331        let mut candidates = vec![
332            FoldCandidate {
333                source_rank: 2,
334                ..candidate(1, "project", "sites_dir", "~/projects")
335            },
336            FoldCandidate {
337                source_rank: 2,
338                ..candidate(2, "technical", "sites_directory", "~/projects")
339            },
340        ];
341        assert!(plan_folds(&mut candidates).is_empty());
342    }
343
344    #[test]
345    fn other_embedding_models_never_compare() {
346        let mut candidates = vec![
347            candidate(1, "project", "sites_dir", "~/projects"),
348            FoldCandidate {
349                vector: vec![1.0, 0.0, 0.0],
350                ..candidate(2, "technical", "sites_directory", "~/projects")
351            },
352        ];
353        assert!(plan_folds(&mut candidates).is_empty());
354    }
355}