Skip to main content

aidaemon_memory/sqlite/
facts.rs

1use super::*;
2
3const FACT_SEMANTIC_MIN_SCORE: f32 = 0.3;
4const FACT_LEXICAL_MIN_SCORE: f32 = 0.3;
5const FACT_LEXICAL_MAX_SCORE: f32 = 0.55;
6const FACT_FRESHNESS_MAX_BOOST: f32 = 0.15;
7const FACT_FRESHNESS_DECAY_HOURS: f32 = 168.0; // 7 days
8
9/// Conservative fallback for passive prompt recall when embeddings are
10/// unavailable. Returning recent facts regardless of relevance leaks unrelated
11/// context into the model; an empty result is safer because explicit memory
12/// search remains available to the agent.
13fn lexical_relevant_facts(facts: &[Fact], query: &str, max: usize) -> Vec<Fact> {
14    let query_lower = query.to_lowercase();
15    let tokens = query_tokens(&query_lower);
16    let mut scored = facts
17        .iter()
18        .filter_map(|fact| {
19            let score = lexical_fallback_score(&query_lower, &tokens, fact);
20            (score > FACT_LEXICAL_MIN_SCORE).then_some((fact, score))
21        })
22        .collect::<Vec<_>>();
23    scored.sort_by(|left, right| {
24        right
25            .1
26            .partial_cmp(&left.1)
27            .unwrap_or(std::cmp::Ordering::Equal)
28            .then_with(|| right.0.updated_at.cmp(&left.0.updated_at))
29    });
30    scored
31        .into_iter()
32        .take(max)
33        .map(|(fact, _)| fact.clone())
34        .collect()
35}
36
37/// Build a key-only embedding text for semantic dedup comparison.
38///
39/// Focuses on category + readable key (no value) so that dedup detects
40/// keys referring to the same concept regardless of their values.
41fn build_dedup_key_text(category: &str, key: &str) -> String {
42    let readable_key = key.replace(['_', '-'], " ");
43    format!(
44        "The user's {} {}. {} attribute: {}",
45        category, readable_key, category, readable_key
46    )
47}
48
49fn hybrid_fact_score(
50    fact: &Fact,
51    semantic: f32,
52    lexical: f32,
53    graph_match: bool,
54    freshness: f32,
55) -> f32 {
56    crate::HybridWeights::default().fuse(&crate::Signals {
57        semantic,
58        lexical,
59        graph: if graph_match { 1.0 } else { 0.0 },
60        freshness: (freshness / FACT_FRESHNESS_MAX_BOOST).clamp(0.0, 1.0),
61        confidence: if fact.source == "consolidation" {
62            0.7
63        } else {
64            1.0
65        },
66        provenance: if fact.source_excerpt.is_some() {
67            1.0
68        } else {
69            0.3
70        },
71    })
72}
73
74/// Build a natural-language embedding text for a fact.
75///
76/// Instead of `[project] inter_service: gRPC`, this produces something like:
77/// `"Project: inter-service communication technology is gRPC"`
78///
79/// Natural language embeds much better against natural language queries
80/// like "What tech stack does my project use?".
81pub fn build_fact_embedding_text(category: &str, key: &str, value: &str) -> String {
82    // Convert underscore/hyphen keys to readable form
83    let readable_key = key.replace(['_', '-'], " ");
84
85    // Build a natural-language sentence
86    format!(
87        "{} - {}: {}. The user's {} is {}.",
88        category, readable_key, value, readable_key, value
89    )
90}
91
92/// Whether two canonical fact keys are structurally distinct concepts that
93/// must never be merged, whatever their embeddings say.
94///
95/// Merge-safe: zero token overlap (possible synonyms), pure reordering
96/// ("company_previous" / "previous_company"), and a subset whose extra tokens
97/// are all known qualifiers ("editor" / "preferred_editor"). Distinct: two
98/// single-token keys (short keys embed too alike: "age" / "name"), partial
99/// overlap ("dog_name_old" / "dog_name_new"), and a subset whose extra token
100/// is likely an entity ("birthday" / "carlos_birthday", "age" / "child_age").
101pub(super) fn keys_name_distinct_concepts(
102    new_tokens: &std::collections::HashSet<&str>,
103    existing_tokens: &std::collections::HashSet<&str>,
104) -> bool {
105    const SAFE_MODIFIERS: &[&str] = &[
106        "preferred",
107        "favorite",
108        "fav",
109        "default",
110        "primary",
111        "current",
112        "previous",
113        "old",
114        "new",
115        "last",
116        "first",
117        "main",
118        "secondary",
119        "alternate",
120        "alt",
121        "other",
122        "work",
123        "home",
124        "personal",
125        "daily",
126        "weekly",
127        "morning",
128        "evening",
129        "night",
130    ];
131    let shared = new_tokens.intersection(existing_tokens).count();
132    let new_count = new_tokens.len();
133    let existing_count = existing_tokens.len();
134    if new_count <= 1 && existing_count <= 1 {
135        return true;
136    }
137    let is_subset = new_tokens.is_subset(existing_tokens) || existing_tokens.is_subset(new_tokens);
138    if shared > 0 && !is_subset {
139        return true;
140    }
141    if is_subset && new_count != existing_count {
142        let (larger, smaller) = if new_count > existing_count {
143            (new_tokens, existing_tokens)
144        } else {
145            (existing_tokens, new_tokens)
146        };
147        return !larger
148            .difference(smaller)
149            .all(|token| SAFE_MODIFIERS.contains(token));
150    }
151    false
152}
153
154/// Whether two keys name one attribute (`editor` / `preferred_editor`,
155/// `oauth_expiry` / `oauth_expiration`), as opposed to two attributes that
156/// share a word (`dog_name_old` / `dog_name_new`, `age` / `child_age`).
157pub fn keys_name_same_attribute(a: &str, b: &str) -> bool {
158    let (a, b) = (canonicalize_fact_key(a), canonicalize_fact_key(b));
159    a == b || {
160        let a_tokens = a.split('_').filter(|t| !t.is_empty()).collect();
161        let b_tokens = b.split('_').filter(|t| !t.is_empty()).collect();
162        !keys_name_distinct_concepts(&a_tokens, &b_tokens)
163    }
164}
165
166/// Sources that record the owner's own words. Background extractors can
167/// never overwrite these, only restate or add beside them.
168pub fn is_owner_authored_fact_source(source: &str) -> bool {
169    matches!(source, "agent" | "user_stated" | "owner" | "owner-stated")
170}
171
172/// Source of a per-turn fact the owner asserted, with a verbatim quote from
173/// their own message checked against it. Not owner-authored (the quote
174/// proves the words, not that the value follows from them, nor who wrote
175/// pasted text), but above anything a background extractor inferred.
176pub const OWNER_QUOTED_SOURCE: &str = "owner_quoted";
177
178/// How close a fact's source is to the owner's own words: 2 stated
179/// explicitly, 1 quoted from the owner's message, 0 inferred. A write may
180/// replace a different value only at equal or higher rank, and a restatement
181/// never lowers a row's rank.
182pub fn fact_source_rank(source: &str) -> u8 {
183    if is_owner_authored_fact_source(source) {
184        2
185    } else if source == OWNER_QUOTED_SOURCE {
186        1
187    } else {
188        0
189    }
190}
191
192/// Full-fact (key + value) embedding similarity at which an automated write is
193/// a restatement of an active fact rather than new knowledge. Measured on the
194/// live store: pairs at or above this are paraphrased keys for one value
195/// ("blog_deploy_stack" / "blog_deployment_stack", "tweet_account" /
196/// "twitter_account"); below it, distinct values start to appear.
197pub(crate) const FACT_RESTATEMENT_MIN_SIMILARITY: f32 = 0.93;
198
199/// Categories whose keys name a person or their attributes, where a key that
200/// differs by an entity token must stay separate even at high similarity.
201pub fn fact_category_is_personal(category: &str) -> bool {
202    matches!(
203        category.trim().to_ascii_lowercase().as_str(),
204        "user" | "people" | "relationship" | "relationships" | "family"
205    )
206}
207
208fn value_tokens(value: &str) -> std::collections::HashSet<String> {
209    crate::text::words(value).collect()
210}
211
212/// Values carry the same claim: identical numbers (versions, dates, counts,
213/// ids differ in one digit and the embedding cannot see it) and at least half
214/// of their words shared.
215fn values_make_the_same_claim(a: &str, b: &str) -> bool {
216    let (a, b) = (value_tokens(a), value_tokens(b));
217    if a.is_empty() || b.is_empty() {
218        return false;
219    }
220    let numbers = |tokens: &std::collections::HashSet<String>| {
221        tokens
222            .iter()
223            .filter(|token| token.chars().any(|c| c.is_ascii_digit()))
224            .cloned()
225            .collect::<std::collections::BTreeSet<_>>()
226    };
227    if numbers(&a) != numbers(&b) {
228        return false;
229    }
230    let shared = a.intersection(&b).count();
231    shared * 2 >= a.union(&b).count()
232}
233
234/// Whether two active facts in one category are the same knowledge.
235pub fn facts_are_restatements(
236    category: &str,
237    a: (&str, &str),
238    b: (&str, &str),
239    similarity: f32,
240) -> bool {
241    similarity >= FACT_RESTATEMENT_MIN_SIMILARITY && facts_make_the_same_claim(category, a, b)
242}
243
244/// The similarity-independent half of [`facts_are_restatements`]: similar
245/// text still has to carry one claim about one thing.
246pub(crate) fn facts_make_the_same_claim(
247    category: &str,
248    (key_a, value_a): (&str, &str),
249    (key_b, value_b): (&str, &str),
250) -> bool {
251    if !values_make_the_same_claim(value_a, value_b) {
252        return false;
253    }
254    if !fact_category_is_personal(category) {
255        return true;
256    }
257    let a = canonicalize_fact_key(key_a);
258    let b = canonicalize_fact_key(key_b);
259    let a_tokens = a.split('_').filter(|t| !t.is_empty()).collect();
260    let b_tokens = b.split('_').filter(|t| !t.is_empty()).collect();
261    a == b || !keys_name_distinct_concepts(&a_tokens, &b_tokens)
262}
263
264pub(super) use crate::text::{canonical_personal_key, canonicalize_fact_key};
265
266fn prefer_canonical_facts(
267    mut canonical: Vec<Fact>,
268    legacy: Vec<Fact>,
269    query: &str,
270    max: usize,
271) -> Vec<Fact> {
272    let query_lower = query.to_lowercase();
273    let query_words = query_tokens(&query_lower);
274    if !query.trim().is_empty() {
275        canonical.retain(|fact| {
276            lexical_fallback_score(&query_lower, &query_words, fact) > 0.0
277                || fact.value.to_lowercase().contains(query_lower.trim())
278        });
279    }
280
281    let canonical_owner_keys: std::collections::HashSet<String> = canonical
282        .iter()
283        .filter(|fact| fact.category == "user")
284        .map(|fact| canonical_personal_key(&fact.key))
285        .collect();
286    let has_relationships = canonical
287        .iter()
288        .any(|fact| fact.category == "relationships");
289    canonical.extend(legacy.into_iter().filter(|fact| {
290        !(fact.category == "user"
291            && canonical_owner_keys.contains(&canonical_personal_key(&fact.key))
292            || has_relationships
293                && matches!(
294                    canonicalize_fact_key(&fact.key).as_str(),
295                    "daughter"
296                        | "son"
297                        | "child"
298                        | "mother"
299                        | "father"
300                        | "parent"
301                        | "daughter_name"
302                        | "son_name"
303                        | "child_name"
304                        | "mother_name"
305                        | "father_name"
306                ))
307    }));
308    // Preserve semantic/graph ranking within each group, but always surface an
309    // exact structured-key hit before loosely related embedding matches. This
310    // is critical for short profile questions such as "my dad" (`dad_name`) or
311    // "my mom" (`mom_name`), where generic identity facts otherwise outrank the
312    // answer-bearing record.
313    canonical.sort_by_key(|fact| {
314        let key = fact.key.to_ascii_lowercase();
315        std::cmp::Reverse(
316            query_words
317                .iter()
318                .filter(|word| contains_word(&key, word))
319                .count(),
320        )
321    });
322    canonical.truncate(max);
323    canonical
324}
325
326fn fact_freshness_boost(now: DateTime<Utc>, updated_at: DateTime<Utc>) -> f32 {
327    let age_hours = (now - updated_at).num_hours().max(0) as f32;
328    FACT_FRESHNESS_MAX_BOOST * (1.0 - (age_hours / FACT_FRESHNESS_DECAY_HOURS).min(1.0))
329}
330
331pub(super) use crate::scoring::is_stopword;
332
333fn query_tokens(query_lower: &str) -> Vec<&str> {
334    query_lower
335        .split(|c: char| !c.is_alphanumeric())
336        .filter(|t| t.len() >= 3)
337        .filter(|t| !is_stopword(t))
338        .collect()
339}
340
341fn contains_word(haystack_lower: &str, needle: &str) -> bool {
342    if needle.is_empty() {
343        return false;
344    }
345    haystack_lower
346        .split(|c: char| !c.is_alphanumeric())
347        .any(|w| w == needle)
348}
349
350fn lexical_fallback_score(query_lower: &str, tokens: &[&str], fact: &Fact) -> f32 {
351    let q = query_lower.trim();
352    if q.is_empty() || tokens.is_empty() {
353        return 0.0;
354    }
355
356    let key = fact.key.to_lowercase();
357    let value = fact.value.to_lowercase();
358    let category = fact.category.to_lowercase();
359
360    let q_is_token = q.chars().all(|c| c.is_alphanumeric());
361    let value_has_q = q_is_token && contains_word(&value, q);
362
363    // Keys/categories are structured; substring matching is fine.
364    // Values are natural language; prefer word-boundary matching to avoid
365    // false positives like "dog" matching "dodger".
366    if key.contains(q) || category.contains(q) || value_has_q {
367        return FACT_LEXICAL_MAX_SCORE;
368    }
369
370    // If any query token matches the structured key exactly (word boundary),
371    // treat as high-confidence lexical relevance.
372    if tokens.iter().any(|t| contains_word(&key, t)) {
373        return FACT_LEXICAL_MAX_SCORE;
374    }
375
376    let mut matched = 0usize;
377    for t in tokens {
378        if key.contains(t) || category.contains(t) || contains_word(&value, t) {
379            matched += 1;
380        }
381    }
382    (matched as f32 / tokens.len() as f32) * FACT_LEXICAL_MAX_SCORE
383}
384
385impl SqliteMemory {
386    /// Cosine scores for the facts in `ids` that `indexed` has no score for,
387    /// from each fact's own stored vector. Usually none: every fact with a
388    /// claim is in the embedding index. Read in chunks, so a recall never
389    /// loads every fact's blob.
390    async fn unindexed_fact_scores(
391        &self,
392        query_vec: &[f32],
393        ids: impl Iterator<Item = i64>,
394        indexed: &std::collections::HashMap<i64, f32>,
395    ) -> std::collections::HashMap<i64, f32> {
396        let missing: Vec<i64> = ids.filter(|id| !indexed.contains_key(id)).collect();
397        let mut scores = std::collections::HashMap::new();
398        for chunk in missing.chunks(500) {
399            let mut builder = sqlx::QueryBuilder::<sqlx::Sqlite>::new(
400                "SELECT id, embedding FROM facts WHERE embedding IS NOT NULL AND id IN (",
401            );
402            let mut separated = builder.separated(", ");
403            for id in chunk {
404                separated.push_bind(*id);
405            }
406            separated.push_unseparated(")");
407            let rows = match builder.build().fetch_all(&self.pool).await {
408                Ok(rows) => rows,
409                Err(error) => {
410                    tracing::warn!(%error, "could not read fact vectors for recall");
411                    return scores;
412                }
413            };
414            for row in rows {
415                let blob: Vec<u8> = row.get("embedding");
416                if let Ok(vector) = self.embedding_service.decode(&blob) {
417                    scores.insert(row.get("id"), cosine_similarity(query_vec, &vector));
418                }
419            }
420        }
421        scores
422    }
423
424    /// The active fact a key with no active row was folded into, following
425    /// later folds of that fact. None for a key that is active, never
426    /// existed, or was retired any other way.
427    async fn folded_survivor(
428        &self,
429        category: &str,
430        key: &str,
431    ) -> anyhow::Result<Option<(String, String)>> {
432        let canonical = canonicalize_fact_key(key);
433        let active: Option<i64> = sqlx::query_scalar(
434            "SELECT id FROM facts WHERE category = ? AND key IN (?, ?) AND superseded_at IS NULL",
435        )
436        .bind(category)
437        .bind(key)
438        .bind(&canonical)
439        .fetch_optional(&self.pool)
440        .await?;
441        if active.is_some() {
442            return Ok(None);
443        }
444        let mut next: Option<i64> = sqlx::query_scalar(
445            "SELECT folded_into FROM facts
446             WHERE category = ? AND key IN (?, ?) AND superseded_reason = 'folded'
447               AND folded_into IS NOT NULL
448             ORDER BY superseded_at DESC LIMIT 1",
449        )
450        .bind(category)
451        .bind(key)
452        .bind(&canonical)
453        .fetch_optional(&self.pool)
454        .await?
455        .flatten();
456        // A survivor folded later points on; a short chain, never a loop.
457        for _ in 0..8 {
458            let Some(id) = next else {
459                return Ok(None);
460            };
461            let row: Option<FoldLink> = sqlx::query_as(
462                "SELECT category, key, superseded_at, folded_into, superseded_reason
463                     FROM facts WHERE id = ?",
464            )
465            .bind(id)
466            .fetch_optional(&self.pool)
467            .await?;
468            match row {
469                Some((category, key, None, _, _)) => return Ok(Some((category, key))),
470                Some((_, _, Some(_), Some(into), Some(reason)))
471                    if reason == SupersededReason::Folded.as_str() =>
472                {
473                    next = Some(into)
474                }
475                _ => return Ok(None),
476            }
477        }
478        Ok(None)
479    }
480
481    /// Every active fact with a vector, as the fold planner reads it.
482    pub async fn fold_candidates(&self) -> anyhow::Result<Vec<super::fact_folds::FoldCandidate>> {
483        let rows = sqlx::query(
484            "SELECT id, category, key, value, source, COALESCE(recall_count, 0) AS recall_count,
485                    COALESCE(privacy, 'global') AS privacy, channel_id, embedding
486             FROM facts
487             WHERE superseded_at IS NULL AND embedding IS NOT NULL
488             ORDER BY id ASC",
489        )
490        .fetch_all(&self.pool)
491        .await?;
492        Ok(rows
493            .into_iter()
494            .filter_map(|row| {
495                let blob: Vec<u8> = row.get("embedding");
496                let vector = self.embedding_service.decode(&blob).ok()?;
497                let category: String = row.get("category");
498                let source: String = row.get("source");
499                Some(super::fact_folds::FoldCandidate {
500                    id: row.get("id"),
501                    pinned: crate::full::recall::IDENTITY_CATEGORIES
502                        .contains(&category.trim().to_ascii_lowercase().as_str()),
503                    category,
504                    key: row.get("key"),
505                    value: row.get("value"),
506                    source_rank: fact_source_rank(&source),
507                    recall_count: row.get("recall_count"),
508                    privacy: row.get("privacy"),
509                    channel_id: row.get("channel_id"),
510                    vector,
511                })
512            })
513            .collect())
514    }
515
516    /// Retired rows, with no active row left for their key, that cover an
517    /// automated write of one of `keys = value` in `category`
518    /// ([`retirement_covers`]).
519    /// Whether a fact under one of `keys` (any category) took a value other
520    /// than `value` after `seen`: evidence from `seen` is older than it.
521    async fn corrected_since(
522        &self,
523        keys: &[&str],
524        value: &str,
525        seen: DateTime<Utc>,
526    ) -> anyhow::Result<bool> {
527        let keys: Vec<&str> = keys
528            .iter()
529            .map(|key| key.trim())
530            .filter(|key| !key.is_empty())
531            .collect();
532        if keys.is_empty() {
533            return Ok(false);
534        }
535        // At most three spellings of one key; repeat the first to fill.
536        let key = |i: usize| keys.get(i).copied().unwrap_or(keys[0]);
537        let rows: Vec<(String, String)> =
538            sqlx::query_as("SELECT value, created_at FROM facts WHERE key IN (?, ?, ?)")
539                .bind(key(0))
540                .bind(key(1))
541                .bind(key(2))
542                .fetch_all(&self.pool)
543                .await?;
544        let new_value = crate::text::normalize_fact_value(value);
545        Ok(rows.into_iter().any(|(other, created_at)| {
546            crate::types::parse_ts(&created_at).is_some_and(|at| at > seen)
547                && crate::text::normalize_fact_value(&other) != new_value
548        }))
549    }
550
551    async fn retired_knowledge(
552        &self,
553        category: &str,
554        keys: &[&str],
555        value: &str,
556    ) -> anyhow::Result<Vec<RetiredKnowledge>> {
557        let rows: Vec<(String, String, String, String, Option<String>)> = sqlx::query_as(
558            "SELECT f.category, f.key, f.value, f.superseded_at, f.superseded_reason
559             FROM facts f
560             WHERE f.superseded_at IS NOT NULL
561               AND NOT EXISTS (SELECT 1 FROM facts a WHERE a.superseded_at IS NULL
562                                AND a.category = f.category AND a.key = f.key)
563             ORDER BY f.superseded_at DESC",
564        )
565        .fetch_all(&self.pool)
566        .await?;
567        Ok(rows
568            .into_iter()
569            .filter(
570                |(retired_category, retired_key, retired_value, _, reason)| {
571                    retirement_covers(
572                        (category, keys, value),
573                        (retired_category, retired_key, retired_value),
574                        reason.as_deref(),
575                    )
576                },
577            )
578            .map(|(category, key, _, retired_at, _)| RetiredKnowledge {
579                category,
580                key,
581                // An unreadable time still retires: no evidence is newer.
582                retired_at: crate::types::parse_ts(&retired_at).unwrap_or(DateTime::<Utc>::MAX_UTC),
583            })
584            .collect())
585    }
586
587    /// Ends the active copies of a fact the owner just changed or forgot:
588    /// facts in any category that hold the same value under a key whose words
589    /// contain, or are contained in, those of `key` (`favorite_tea` beside `test_favorite_tea`,
590    /// `user/marker` beside `personal/marker`). Background extraction stores
591    /// such copies; left active, the old value survived the change.
592    async fn supersede_copies(
593        &self,
594        changed_id: i64,
595        key: &str,
596        value: &str,
597        reason: SupersededReason,
598        max_source_rank: u8,
599    ) -> anyhow::Result<()> {
600        let value = value.trim();
601        if value.is_empty() {
602            return Ok(());
603        }
604        let canonical = canonicalize_fact_key(key);
605        let tokens: std::collections::HashSet<&str> =
606            canonical.split('_').filter(|t| !t.is_empty()).collect();
607        let rows: Vec<(i64, String, String)> = sqlx::query_as(
608            "SELECT id, key, source FROM facts
609             WHERE superseded_at IS NULL AND id <> ? AND LOWER(TRIM(value)) = LOWER(?)",
610        )
611        .bind(changed_id)
612        .bind(value)
613        .fetch_all(&self.pool)
614        .await?;
615        let now = Utc::now().to_rfc3339();
616        for (id, other_key, other_source) in rows {
617            // A quoted change never retires what the owner stated.
618            if fact_source_rank(&other_source) > max_source_rank {
619                continue;
620            }
621            let other = canonicalize_fact_key(&other_key);
622            let other: std::collections::HashSet<&str> =
623                other.split('_').filter(|t| !t.is_empty()).collect();
624            // One key must name the other with modifiers added: a shared
625            // word alone (`pet_name`, `daughter_name`) is a different fact.
626            if !(tokens.is_subset(&other) || other.is_subset(&tokens)) {
627                continue;
628            }
629            sqlx::query(
630                "UPDATE facts SET superseded_at = ?, superseded_reason = ?
631                 WHERE id = ? AND superseded_at IS NULL",
632            )
633            .bind(&now)
634            .bind(reason.as_str())
635            .bind(id)
636            .execute(&self.pool)
637            .await?;
638            if let Err(error) = self.project_fact_memory(id).await {
639                tracing::warn!(%error, fact_id = id, "Deferred superseded-copy projection");
640            }
641        }
642        Ok(())
643    }
644}
645
646fn key_tokens(canonical: &str) -> std::collections::HashSet<&str> {
647    canonical.split('_').filter(|t| !t.is_empty()).collect()
648}
649
650/// A row's category, key, retirement time, fold target and reason.
651type FoldLink = (String, String, Option<String>, Option<i64>, Option<String>);
652
653/// A retired fact row that an automated write would bring back.
654#[derive(Debug, Clone)]
655pub(crate) struct RetiredKnowledge {
656    pub category: String,
657    pub key: String,
658    pub retired_at: DateTime<Utc>,
659}
660
661/// Whether a retired row (`retired_*`, with no active row for its key)
662/// covers an automated write of `key = value` in `category`.
663///
664/// - Same category, same canonical key: always, whatever the reason.
665/// - Another category, only with the same value: `project/status` and
666///   `technical/status` are different facts. Deleted by the owner: the same
667///   canonical key, or one naming the other with words added. Retired before
668///   reasons were recorded: the same canonical key only, since the row may
669///   be a fold or a value change rather than a deletion.
670///
671/// A value alone never matches: `true` or `main` under unrelated keys are
672/// different facts.
673fn retirement_covers(
674    (category, key, value): (&str, &[&str], &str),
675    (retired_category, retired_key, retired_value): (&str, &str, &str),
676    reason: Option<&str>,
677) -> bool {
678    let retired_canonical = canonicalize_fact_key(retired_key);
679    let same_key = key
680        .iter()
681        .any(|key| canonicalize_fact_key(key) == retired_canonical);
682    if retired_category
683        .trim()
684        .eq_ignore_ascii_case(category.trim())
685    {
686        return same_key;
687    }
688    let value = crate::text::normalize_fact_value(value);
689    if value.is_empty() || value != crate::text::normalize_fact_value(retired_value) {
690        return false;
691    }
692    match reason {
693        Some("deleted") => {
694            same_key
695                || key.iter().any(|key| {
696                    let canonical = canonicalize_fact_key(key);
697                    let (a, b) = (key_tokens(&canonical), key_tokens(&retired_canonical));
698                    !a.is_empty() && !b.is_empty() && (a.is_subset(&b) || b.is_subset(&a))
699                })
700        }
701        None => same_key,
702        Some(_) => false,
703    }
704}
705
706/// Why a fact row stopped being active, stored in `facts.superseded_reason`.
707/// Rows retired before the column existed have none, and are read as
708/// "unknown": a deletion, a fold or a value change. Operator cleanups
709/// (`db_probe --retire-inferred-behavior`, `--fact-conflict-audit --apply`)
710/// write `retired` and `replaced`.
711#[derive(Debug, Clone, Copy, PartialEq, Eq)]
712pub(crate) enum SupersededReason {
713    /// The owner forgot it (or a copy of what they forgot).
714    Deleted,
715    /// A newer value replaced it.
716    Replaced,
717    /// It restated another active fact (`folded_into`).
718    Folded,
719}
720
721impl SupersededReason {
722    pub(crate) fn as_str(self) -> &'static str {
723        match self {
724            Self::Deleted => "deleted",
725            Self::Replaced => "replaced",
726            Self::Folded => "folded",
727        }
728    }
729}
730
731/// Owner type of the cached key-text vectors fact dedup compares. The fact
732/// row owns its vector, so retention drops it with the fact; lookups go by
733/// the key text's hash.
734const DEDUP_KEY_OWNER: &str = "fact_key";
735const DEDUP_KEY_PURPOSE: &str = "dedup";
736
737impl SqliteMemory {
738    /// Vectors for fact-dedup key texts, in order. `texts` pairs each text
739    /// with the fact row it belongs to, if any; a stored row's vector is
740    /// cached under that row and read back next time: a category holds
741    /// thousands of keys, and embedding them all on every write took
742    /// seconds.
743    async fn dedup_key_vectors(
744        &self,
745        texts: Vec<(Option<i64>, String)>,
746    ) -> anyhow::Result<Vec<Vec<f32>>> {
747        use crate::embedding_index::content_hash;
748        let model = self.embedding_service.model_id();
749        let hashes: Vec<String> = texts.iter().map(|(_, t)| content_hash(t)).collect();
750        let mut cached: std::collections::HashMap<String, Vec<f32>> =
751            std::collections::HashMap::new();
752        let mut unique: Vec<&String> = hashes.iter().collect();
753        unique.sort();
754        unique.dedup();
755        for chunk in unique.chunks(500) {
756            let mut builder = sqlx::QueryBuilder::<sqlx::Sqlite>::new(
757                "SELECT content_hash, embedding FROM memory_embeddings
758                 WHERE owner_type = ",
759            );
760            builder
761                .push_bind(DEDUP_KEY_OWNER)
762                .push(" AND embedding_purpose = ")
763                .push_bind(DEDUP_KEY_PURPOSE)
764                .push(" AND embedding_model = ")
765                .push_bind(&model)
766                .push(" AND stale_at IS NULL AND content_hash IN (");
767            let mut separated = builder.separated(", ");
768            for hash in chunk {
769                separated.push_bind(*hash);
770            }
771            separated.push_unseparated(")");
772            for row in builder.build().fetch_all(&self.pool).await? {
773                let blob: Vec<u8> = row.get("embedding");
774                if let Ok(vector) = self.embedding_service.decode(&blob) {
775                    cached.insert(row.get("content_hash"), vector);
776                }
777            }
778        }
779
780        // (hash, owning fact, text)
781        let mut missing: Vec<(String, Option<i64>, String)> = Vec::new();
782        let mut queued = std::collections::HashSet::new();
783        for ((owner, text), hash) in texts.iter().zip(&hashes) {
784            if !cached.contains_key(hash) && queued.insert(hash.clone()) {
785                missing.push((hash.clone(), *owner, text.clone()));
786            }
787        }
788        if !missing.is_empty() {
789            let vectors = self
790                .embedding_service
791                .embed_many(missing.iter().map(|(_, _, text)| text.clone()).collect())
792                .await?;
793            let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
794            for ((hash, owner, _), vector) in missing.iter().zip(&vectors) {
795                let Some(owner) = owner else {
796                    continue;
797                };
798                sqlx::query(
799                    "INSERT INTO memory_embeddings
800                        (owner_type, owner_id, embedding_purpose, embedding_model,
801                         embedding_dim, content_hash, embedding, created_at, updated_at)
802                     VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'))
803                     ON CONFLICT(owner_type, owner_id, embedding_purpose, embedding_model, content_hash)
804                     DO UPDATE SET embedding = excluded.embedding, stale_at = NULL,
805                                   updated_at = datetime('now')",
806                )
807                .bind(DEDUP_KEY_OWNER)
808                .bind(owner.to_string())
809                .bind(DEDUP_KEY_PURPOSE)
810                .bind(&model)
811                .bind(vector.len() as i64)
812                .bind(hash)
813                .bind(encode_embedding(vector))
814                .execute(&mut *tx)
815                .await?;
816            }
817            tx.commit().await?;
818            for ((hash, _, _), vector) in missing.into_iter().zip(vectors) {
819                cached.insert(hash, vector);
820            }
821        }
822        hashes
823            .iter()
824            .map(|hash| {
825                cached
826                    .get(hash)
827                    .cloned()
828                    .ok_or_else(|| anyhow::anyhow!("no dedup vector for a key"))
829            })
830            .collect()
831    }
832
833    /// Every fact an explicit search ranks, loaded once: canonical
834    /// projections, then active rows, minus owner rows a projection already
835    /// covers. The map sends each such projection to the raw row it
836    /// replaced, whose vector stands in for it: projections have no vector
837    /// of their own, and without one they would be reachable by keyword only.
838    async fn explicit_search_facts(
839        &self,
840    ) -> anyhow::Result<(Vec<Fact>, std::collections::HashMap<i64, i64>)> {
841        let mut facts = self.canonical_personal_facts().await?;
842        let projection_by_key: std::collections::HashMap<String, i64> = facts
843            .iter()
844            .filter(|fact| fact.category == "user")
845            .map(|fact| (canonical_personal_key(&fact.key), fact.id))
846            .collect();
847        // The newest covered row stands in.
848        let mut newest: std::collections::HashMap<i64, (i64, DateTime<Utc>)> =
849            std::collections::HashMap::new();
850        for fact in self.get_all_facts_with_provenance().await? {
851            let covering = (fact.category == "user")
852                .then(|| projection_by_key.get(&canonical_personal_key(&fact.key)))
853                .flatten();
854            match covering {
855                Some(projection) => {
856                    let slot = newest
857                        .entry(*projection)
858                        .or_insert((fact.id, fact.updated_at));
859                    if fact.updated_at > slot.1 {
860                        *slot = (fact.id, fact.updated_at);
861                    }
862                }
863                None => facts.push(fact),
864            }
865        }
866        let stand_ins = newest.into_iter().map(|(p, (id, _))| (p, id)).collect();
867        Ok((facts, stand_ins))
868    }
869
870    /// Cosine of the query against every fact with a current vector, by
871    /// position in `facts`. Empty when the query cannot be embedded.
872    async fn explicit_search_cosine(
873        &self,
874        query: &str,
875        facts: &[Fact],
876        stand_ins: &std::collections::HashMap<i64, i64>,
877    ) -> Vec<(usize, f32)> {
878        let query_vec = match self.embedding_service.embed(query.to_string()).await {
879            Ok(vector) => vector,
880            Err(error) => {
881                tracing::warn!(target: "memory_recall", %error, "explicit fact search: query embedding failed; lexical only");
882                return Vec::new();
883            }
884        };
885        let vector_id = |fact: &Fact| stand_ins.get(&fact.id).copied().unwrap_or(fact.id);
886        let indexed = self
887            .fact_embedding_scores(&query_vec, facts.len() + stand_ins.len())
888            .await
889            .unwrap_or_default();
890        let fallback = self
891            .unindexed_fact_scores(
892                &query_vec,
893                facts.iter().map(vector_id).filter(|id| *id > 0),
894                &indexed,
895            )
896            .await;
897        facts
898            .iter()
899            .enumerate()
900            .filter_map(|(i, fact)| {
901                let id = vector_id(fact);
902                indexed
903                    .get(&id)
904                    .or_else(|| fallback.get(&id))
905                    .map(|score| (i, *score))
906            })
907            .collect()
908    }
909}
910
911#[async_trait]
912impl FactStore for SqliteMemory {
913    async fn search_facts(
914        &self,
915        query: &str,
916        limit: usize,
917        config: &crate::search::FactSearchConfig,
918    ) -> anyhow::Result<crate::search::FactSearchReport> {
919        use crate::neighborhood::{eligible_neighbors, is_relationship_key, seeds_from_hits};
920        use crate::search::{self, LexicalIndex};
921
922        if query.trim().is_empty() || limit == 0 {
923            return Ok(search::FactSearchReport::default());
924        }
925        let started = std::time::Instant::now();
926        let (facts, stand_ins) = self.explicit_search_facts().await?;
927        let load_ms = started.elapsed().as_millis() as u64;
928
929        let stage = std::time::Instant::now();
930        let lexical = LexicalIndex::build(&facts).score(query);
931        let lexical_ms = stage.elapsed().as_millis() as u64;
932
933        let stage = std::time::Instant::now();
934        let cosine = self.explicit_search_cosine(query, &facts, &stand_ins).await;
935        let embed_ms = stage.elapsed().as_millis() as u64;
936
937        let stage = std::time::Instant::now();
938        let pool = search::candidates(&facts, &lexical, &cosine, config);
939        let mut report = search::rank(&facts, &pool, limit, config);
940        let rank_ms = stage.elapsed().as_millis() as u64;
941
942        // Expansion seeds come only from the hits actually returned.
943        let stage = std::time::Instant::now();
944        let hit_facts: Vec<Fact> = report.hits.iter().map(|h| h.fact.clone()).collect();
945        let known_people: Vec<String> = PeopleStore::get_all_people(self)
946            .await
947            .unwrap_or_default()
948            .into_iter()
949            .flat_map(|p| std::iter::once(p.name).chain(p.aliases))
950            .collect();
951        let seeds = seeds_from_hits(&hit_facts, &known_people);
952        let relationship_cluster = hit_facts.iter().any(|f| is_relationship_key(&f.key));
953        if !seeds.is_empty() || relationship_cluster {
954            let exclude: std::collections::HashSet<i64> = hit_facts.iter().map(|f| f.id).collect();
955            let mut neighbors = eligible_neighbors(&facts, &seeds, relationship_cluster, &exclude);
956            // A neighbor duplicating a hit's content is not new context.
957            let shown: std::collections::HashSet<(&str, &str, &str)> = hit_facts
958                .iter()
959                .map(|f| (f.category.as_str(), f.key.as_str(), f.value.as_str()))
960                .collect();
961            neighbors.retain(|f| {
962                !shown.contains(&(f.category.as_str(), f.key.as_str(), f.value.as_str()))
963            });
964
965            let position: std::collections::HashMap<i64, usize> =
966                facts.iter().enumerate().map(|(i, f)| (f.id, i)).collect();
967            let cosine_by_index: std::collections::HashMap<usize, f32> =
968                cosine.iter().copied().collect();
969            let lexical_by_index: std::collections::HashMap<usize, f32> =
970                lexical.iter().map(|h| (h.index, h.score)).collect();
971            let prior = |f: &Fact| -> f32 {
972                let index = position[&f.id];
973                if cosine.is_empty() {
974                    lexical_by_index.get(&index).copied().unwrap_or(0.0)
975                } else {
976                    cosine_by_index.get(&index).copied().unwrap_or(0.0)
977                }
978            };
979            if neighbors.len() > config.related_pool {
980                neighbors.sort_by(|a, b| prior(b).total_cmp(&prior(a)).then(a.id.cmp(&b.id)));
981                neighbors.truncate(config.related_pool);
982            }
983            let scores: Vec<(usize, f32)> = neighbors
984                .iter()
985                .enumerate()
986                .map(|(i, f)| (i, prior(f)))
987                .collect();
988            report.related = search::rank_related(&neighbors, &scores, config);
989        }
990        let expand_ms = stage.elapsed().as_millis() as u64;
991
992        // Scores of the leading hits: `key=score (kind)`.
993        let summarize = |hits: &[search::SearchHit]| {
994            hits.iter()
995                .take(3)
996                .map(|h| format!("{}={:.3} ({:?})", h.fact.key, h.score, h.kind))
997                .collect::<Vec<_>>()
998                .join(", ")
999        };
1000        let top = summarize(&report.hits);
1001        let related_top = summarize(&report.related);
1002        tracing::info!(
1003            target: "memory_recall",
1004            load_ms,
1005            lexical_ms,
1006            embed_ms,
1007            rank_ms,
1008            expand_ms,
1009            considered = report.considered,
1010            returned = report.hits.len(),
1011            related = report.related.len(),
1012            top = %top,
1013            related_top = %related_top,
1014            "explicit fact search"
1015        );
1016        Ok(report)
1017    }
1018
1019    async fn stamp_fact_provenance(
1020        &self,
1021        category: &str,
1022        key: &str,
1023        source: &str,
1024        first_seen_at: Option<DateTime<Utc>>,
1025        source_excerpt: Option<&str>,
1026    ) -> anyhow::Result<()> {
1027        sqlx::query(
1028            "UPDATE facts
1029             SET source = ?, first_seen_at = ?, source_excerpt = ?
1030             WHERE category = ? AND key = ? AND superseded_at IS NULL",
1031        )
1032        .bind(source)
1033        .bind(first_seen_at.map(|at| at.to_rfc3339()))
1034        .bind(source_excerpt)
1035        .bind(category)
1036        .bind(key)
1037        .execute(&self.pool)
1038        .await?;
1039        Ok(())
1040    }
1041
1042    async fn reconcile_personal_memory(
1043        &self,
1044        write: &crate::records::PersonalMemoryWrite,
1045        source: &str,
1046        source_excerpt: Option<&str>,
1047        channel_id: Option<&str>,
1048        privacy: FactPrivacy,
1049    ) -> anyhow::Result<crate::records::PersonalMemoryWriteResult> {
1050        self.reconcile_structured_personal_memory(
1051            write,
1052            source,
1053            source_excerpt,
1054            channel_id,
1055            privacy,
1056        )
1057        .await
1058    }
1059
1060    async fn get_canonical_memory_facts(&self) -> anyhow::Result<Vec<Fact>> {
1061        self.canonical_personal_facts().await
1062    }
1063
1064    async fn record_memory_recall(
1065        &self,
1066        fact_ids: &[i64],
1067        episode_ids: &[i64],
1068    ) -> anyhow::Result<()> {
1069        // Canonical projections carry synthetic negative ids; they have no
1070        // row to count against.
1071        let now = Utc::now().to_rfc3339();
1072        for (table, ids) in [("facts", fact_ids), ("episodes", episode_ids)] {
1073            let ids: Vec<i64> = ids.iter().copied().filter(|id| *id > 0).collect();
1074            if ids.is_empty() {
1075                continue;
1076            }
1077            let placeholders = vec!["?"; ids.len()].join(", ");
1078            let sql = format!(
1079                "UPDATE {table} SET recall_count = COALESCE(recall_count, 0) + 1, last_recalled_at = ? WHERE id IN ({placeholders})"
1080            );
1081            let mut query = sqlx::query(sqlx::AssertSqlSafe(&*sql)).bind(&now);
1082            for id in &ids {
1083                query = query.bind(id);
1084            }
1085            query.execute(&self.pool).await?;
1086        }
1087        Ok(())
1088    }
1089
1090    async fn fold_restated_facts(&self) -> anyhow::Result<usize> {
1091        let _upsert_guard = self.fact_upsert_lock.lock().await;
1092        let mut candidates = self.fold_candidates().await?;
1093        let folded: Vec<(i64, i64)> = super::fact_folds::plan_folds(&mut candidates)
1094            .into_iter()
1095            .map(|fold| (fold.folded, fold.kept))
1096            .collect();
1097        if folded.is_empty() {
1098            return Ok(0);
1099        }
1100        let now = Utc::now().to_rfc3339();
1101        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1102        for (folded_id, kept_id) in &folded {
1103            sqlx::query(
1104                "UPDATE facts SET superseded_at = ?, superseded_reason = ?, folded_into = ?
1105                 WHERE id = ? AND superseded_at IS NULL",
1106            )
1107            .bind(&now)
1108            .bind(SupersededReason::Folded.as_str())
1109            .bind(kept_id)
1110            .bind(folded_id)
1111            .execute(&mut *tx)
1112            .await?;
1113            sqlx::query(
1114                "UPDATE facts SET recall_count = MAX(COALESCE(recall_count, 0),
1115                     (SELECT COALESCE(recall_count, 0) FROM facts WHERE id = ?))
1116                 WHERE id = ?",
1117            )
1118            .bind(folded_id)
1119            .bind(kept_id)
1120            .execute(&mut *tx)
1121            .await?;
1122        }
1123        tx.commit().await?;
1124        // A folded row leaves recall's projections too, as a copy does.
1125        for (folded_id, _) in &folded {
1126            if let Err(error) = self.project_fact_memory(*folded_id).await {
1127                tracing::warn!(%error, fact_id = folded_id, "Deferred folded-fact projection");
1128            }
1129        }
1130        tracing::info!(
1131            folded = folded.len(),
1132            "Folded restated facts into their representatives"
1133        );
1134        Ok(folded.len())
1135    }
1136
1137    async fn memory_health_report(&self) -> anyhow::Result<crate::records::MemoryHealthReport> {
1138        self.canonical_memory_health().await
1139    }
1140
1141    async fn repair_memory_projections(
1142        &self,
1143    ) -> anyhow::Result<crate::records::MemoryHealthReport> {
1144        self.backfill_missing_memory_projections().await?;
1145        self.canonical_memory_health().await
1146    }
1147
1148    async fn refresh_fact_memory(&self, category: &str, key: &str) -> anyhow::Result<()> {
1149        if let Some(id) = sqlx::query_scalar::<_, i64>(
1150            "SELECT id FROM facts WHERE lower(category) = lower(?) AND lower(key) = lower(?)
1151             AND superseded_at IS NULL ORDER BY updated_at DESC LIMIT 1",
1152        )
1153        .bind(category)
1154        .bind(key)
1155        .fetch_optional(&self.pool)
1156        .await?
1157        {
1158            self.project_fact_memory(id).await?;
1159        }
1160        Ok(())
1161    }
1162
1163    async fn project_extracted_fact_graph(
1164        &self,
1165        category: &str,
1166        key: &str,
1167        source_excerpt: &str,
1168        graph: &crate::records::ExtractedMemoryGraph,
1169    ) -> anyhow::Result<()> {
1170        self.persist_extracted_fact_graph(category, key, source_excerpt, graph)
1171            .await
1172    }
1173
1174    #[allow(clippy::too_many_arguments)]
1175    async fn upsert_fact_with_provenance(
1176        &self,
1177        category: &str,
1178        key: &str,
1179        value: &str,
1180        source: &str,
1181        channel_id: Option<&str>,
1182        privacy: FactPrivacy,
1183        first_seen_at: Option<DateTime<Utc>>,
1184        source_excerpt: Option<&str>,
1185    ) -> anyhow::Result<()> {
1186        // The legacy flat-fact API performs a read/reconcile/write sequence.
1187        // Serialize that sequence so two concurrent writes for the same key
1188        // cannot both supersede the active row and race through the unique
1189        // active-fact constraint. Structured personal-memory writes use their
1190        // own explicit SQL transaction and do not take this compatibility lock.
1191        // A key folded into another fact writes through to that fact: a later
1192        // value for the folded key is an update of the knowledge it carries,
1193        // not a resurrection to refuse.
1194        if let Some((survivor_category, survivor_key)) =
1195            self.folded_survivor(category.trim(), key.trim()).await?
1196        {
1197            tracing::debug!(
1198                category,
1199                key,
1200                survivor_category = survivor_category.as_str(),
1201                survivor_key = survivor_key.as_str(),
1202                "Fact write redirected to the fact its key was folded into"
1203            );
1204            return self
1205                .upsert_fact_with_provenance(
1206                    &survivor_category,
1207                    &survivor_key,
1208                    value,
1209                    source,
1210                    channel_id,
1211                    privacy,
1212                    first_seen_at,
1213                    source_excerpt,
1214                )
1215                .await;
1216        }
1217        let _upsert_guard = self.fact_upsert_lock.lock().await;
1218        let now = Utc::now().to_rfc3339();
1219        let privacy_str = privacy.to_string();
1220
1221        let category_clean = category.trim();
1222        let key_clean = key.trim();
1223        let canonical_key = canonicalize_fact_key(key_clean);
1224
1225        // Find existing current fact (not superseded).
1226        // Prefer exact match; fall back to canonical match to avoid key drift
1227        // ("dog name" vs "dog_name") creating duplicates.
1228        let mut existing: Option<(i64, String, String)> = None;
1229
1230        if let Some(row) = sqlx::query(
1231            "SELECT id, key, value FROM facts WHERE category = ? AND key = ? AND superseded_at IS NULL",
1232        )
1233        .bind(category_clean)
1234        .bind(key_clean)
1235        .fetch_optional(&self.pool)
1236        .await?
1237        {
1238            existing = Some((row.get("id"), row.get("key"), row.get("value")));
1239        } else {
1240            if canonical_key != key_clean
1241                && let Some(row) = sqlx::query(
1242                    "SELECT id, key, value FROM facts WHERE category = ? AND key = ? AND superseded_at IS NULL",
1243                )
1244                .bind(category_clean)
1245                .bind(&canonical_key)
1246                .fetch_optional(&self.pool)
1247                .await?
1248                {
1249                    existing = Some((row.get("id"), row.get("key"), row.get("value")));
1250                }
1251
1252            if existing.is_none() && !canonical_key.is_empty() {
1253                // Canonical scan: match an existing key by canonical form.
1254                // Limits churn when historical keys were not canonicalized.
1255                let rows = sqlx::query(
1256                    "SELECT id, key, value FROM facts WHERE category = ? AND superseded_at IS NULL ORDER BY updated_at DESC",
1257                )
1258                .bind(category_clean)
1259                .fetch_all(&self.pool)
1260                .await?;
1261                for row in rows {
1262                    let existing_key: String = row.get("key");
1263                    if canonicalize_fact_key(&existing_key) == canonical_key {
1264                        existing = Some((row.get("id"), existing_key, row.get("value")));
1265                        break;
1266                    }
1267                }
1268            }
1269        }
1270
1271        // Semantic dedup: if key-based matching found nothing, check if any active
1272        // fact in the same category is semantically equivalent (different key, same
1273        // concept). Catches synonym keys like "editor" vs "preferred_editor".
1274        //
1275        // We compare key-only embeddings (category + readable key) rather than
1276        // full fact embeddings (which include value), because dedup should detect
1277        // that two keys refer to the same concept regardless of their values.
1278        if existing.is_none() {
1279            let category_facts = sqlx::query(
1280                "SELECT id, key, value FROM facts
1281                 WHERE category = ? AND superseded_at IS NULL",
1282            )
1283            .bind(category_clean)
1284            .fetch_all(&self.pool)
1285            .await?;
1286
1287            let new_tokens: std::collections::HashSet<&str> =
1288                canonical_key.split('_').filter(|t| !t.is_empty()).collect();
1289
1290            // Guard against false semantic matches for keys that are
1291            // structurally similar but intentionally distinct.
1292            //
1293            // If keys share SOME tokens, have the same token count, but
1294            // differ in at least one token, they're variants of the same
1295            // base concept (e.g., "dog_name_old" vs "dog_name_new") — skip.
1296            //
1297            // But allow through:
1298            // - Keys that are a subset/superset (modifier pattern):
1299            //   "editor" vs "preferred_editor" — different count, proceed.
1300            // - Keys that are just reordered (same tokens, same count):
1301            //   "company_previous" vs "previous_company" — all shared, proceed.
1302            // - Keys with zero overlap: completely different concepts.
1303            let comparable: Vec<&sqlx::sqlite::SqliteRow> = category_facts
1304                .iter()
1305                .filter(|row| {
1306                    let existing_canonical = canonicalize_fact_key(&row.get::<String, _>("key"));
1307                    let existing_tokens: std::collections::HashSet<&str> = existing_canonical
1308                        .split('_')
1309                        .filter(|t| !t.is_empty())
1310                        .collect();
1311                    !keys_name_distinct_concepts(&new_tokens, &existing_tokens)
1312                })
1313                .collect();
1314
1315            // One embedder call for the new key and every comparable key: a
1316            // call per row costs a model hop each and made one write into a
1317            // large category take seconds.
1318            if !comparable.is_empty() {
1319                let mut texts = Vec::with_capacity(comparable.len() + 1);
1320                texts.push((None, build_dedup_key_text(category_clean, key_clean)));
1321                texts.extend(comparable.iter().map(|row| {
1322                    (
1323                        Some(row.get::<i64, _>("id")),
1324                        build_dedup_key_text(category_clean, &row.get::<String, _>("key")),
1325                    )
1326                }));
1327                if let Ok(vectors) = self.dedup_key_vectors(texts).await {
1328                    let new_vec = &vectors[0];
1329                    let mut best_match: Option<(i64, String, String, f32)> = None;
1330                    for (row, existing_vec) in comparable.iter().zip(&vectors[1..]) {
1331                        let sim = cosine_similarity(new_vec, existing_vec);
1332                        if sim > 0.85 && sim > best_match.as_ref().map_or(0.0, |m| m.3) {
1333                            best_match = Some((
1334                                row.get("id"),
1335                                row.get::<String, _>("key"),
1336                                row.get::<String, _>("value"),
1337                                sim,
1338                            ));
1339                        }
1340                    }
1341
1342                    if let Some((id, matched_key, matched_value, sim)) = best_match {
1343                        tracing::info!(
1344                            category = category_clean,
1345                            new_key = key_clean,
1346                            matched_key = matched_key.as_str(),
1347                            similarity = sim,
1348                            "Semantic dedup: matched existing fact by embedding similarity"
1349                        );
1350                        existing = Some((id, matched_key, matched_value));
1351                    }
1352                }
1353            }
1354        }
1355
1356        let key_for_write = existing
1357            .as_ref()
1358            .map(|(_, k, _)| k.clone())
1359            .unwrap_or_else(|| {
1360                if canonical_key.is_empty() {
1361                    key_clean.to_string()
1362                } else {
1363                    canonical_key.clone()
1364                }
1365            });
1366
1367        // Pre-compute embedding for the fact text (best-effort).
1368        let fact_text = build_fact_embedding_text(category_clean, &key_for_write, value);
1369        let embedding_blob = self
1370            .embedding_service
1371            .embed(fact_text)
1372            .await
1373            .ok()
1374            .map(|v| encode_embedding(&v));
1375
1376        let automated_source = !is_owner_authored_fact_source(source);
1377        // Background extraction reads conversations after the fact: evidence
1378        // older than a later, different value of the same knowledge (its key,
1379        // in any category) is what the owner corrected since, and must not
1380        // replace or compete with the correction.
1381        if automated_source
1382            && let Some(seen) = first_seen_at
1383            && self
1384                .corrected_since(&[key_clean, &canonical_key, &key_for_write], value, seen)
1385                .await?
1386        {
1387            tracing::debug!(
1388                category = category_clean,
1389                key = key_clean,
1390                source,
1391                "Automated fact write skipped: a later value of this knowledge replaced it"
1392            );
1393            return Ok(());
1394        }
1395        if existing.is_none() && automated_source {
1396            // Knowledge the owner deleted, or a key merged away, must not be
1397            // brought back by background extraction, in any category the
1398            // extractor picks. Evidence newer than the retirement is the
1399            // owner saying it again, and is let through.
1400            if let Some(tombstone) = self
1401                .retired_knowledge(category_clean, &[key_clean, &key_for_write], value)
1402                .await?
1403                .into_iter()
1404                .find(|tombstone| first_seen_at.is_none_or(|seen| seen <= tombstone.retired_at))
1405            {
1406                tracing::debug!(
1407                    category = category_clean,
1408                    key = key_clean,
1409                    source,
1410                    retired_category = tombstone.category.as_str(),
1411                    retired_key = tombstone.key.as_str(),
1412                    "Automated fact write skipped: that knowledge was deleted or merged"
1413                );
1414                return Ok(());
1415            }
1416            // Paraphrased key, same knowledge: refresh the active fact rather
1417            // than storing a second copy that competes for recall slots. A
1418            // restatement is looked for in this category; the same value
1419            // under a reworded key in any category. Never across scopes.
1420            if let Some(new_vec) = embedding_blob
1421                .as_deref()
1422                .and_then(|blob| self.embedding_service.decode(blob).ok())
1423            {
1424                let candidates = sqlx::query(
1425                    "SELECT id, category, key, value, source, embedding FROM facts
1426                     WHERE superseded_at IS NULL AND embedding IS NOT NULL
1427                       AND COALESCE(privacy, 'global') = ? AND channel_id IS ?",
1428                )
1429                .bind(&privacy_str)
1430                .bind(channel_id)
1431                .fetch_all(&self.pool)
1432                .await?;
1433                let new_value = crate::text::normalize_fact_value(value);
1434                let restated = candidates.iter().find_map(|row| {
1435                    let other_category: String = row.get("category");
1436                    let other_key: String = row.get("key");
1437                    let other_value: String = row.get("value");
1438                    let same_category = other_category.trim() == category_clean;
1439                    // Decode only what either rule could match.
1440                    if !same_category
1441                        && crate::text::normalize_fact_value(&other_value) != new_value
1442                    {
1443                        return None;
1444                    }
1445                    let blob: Vec<u8> = row.get("embedding");
1446                    let other_vec = self.embedding_service.decode(&blob).ok()?;
1447                    let sim = cosine_similarity(&new_vec, &other_vec);
1448                    let restates = same_category
1449                        && facts_are_restatements(
1450                            category_clean,
1451                            (key_clean, value),
1452                            (&other_key, &other_value),
1453                            sim,
1454                        );
1455                    (restates
1456                        || super::fact_folds::facts_hold_one_value(
1457                            (category_clean, key_clean, value),
1458                            (&other_category, &other_key, &other_value),
1459                            sim,
1460                        ))
1461                    .then(|| {
1462                        (
1463                            row.get::<i64, _>("id"),
1464                            other_key,
1465                            sim,
1466                            row.get::<String, _>("source"),
1467                        )
1468                    })
1469                });
1470                if let Some((id, matched_key, sim, matched_source)) = restated {
1471                    tracing::info!(
1472                        category = category_clean,
1473                        new_key = key_clean,
1474                        matched_key = matched_key.as_str(),
1475                        similarity = sim,
1476                        source,
1477                        "Automated fact write folded into existing restatement"
1478                    );
1479                    // The owner quoting what an extractor inferred raises the
1480                    // kept fact to the quote's rank, with the quote.
1481                    if fact_source_rank(source) > fact_source_rank(&matched_source) {
1482                        sqlx::query(
1483                            "UPDATE facts SET updated_at = ?, source = ?,
1484                                 source_excerpt = COALESCE(?, source_excerpt) WHERE id = ?",
1485                        )
1486                        .bind(&now)
1487                        .bind(source)
1488                        .bind(source_excerpt)
1489                        .bind(id)
1490                        .execute(&self.pool)
1491                        .await?;
1492                    } else {
1493                        sqlx::query("UPDATE facts SET updated_at = ? WHERE id = ?")
1494                            .bind(&now)
1495                            .bind(id)
1496                            .execute(&self.pool)
1497                            .await?;
1498                    }
1499                    return Ok(());
1500                }
1501            }
1502        }
1503
1504        if let Some((old_id, _old_key, old_value)) = &existing {
1505            // Spacing and punctuation are not a new value: rewriting
1506            // "~/projects/" as "~/projects" refreshes the row instead of
1507            // replacing it and resetting its recall history. Case is kept
1508            // (paths and handles can be case-sensitive).
1509            let words = |text: &str| -> Vec<String> {
1510                text.split(|c: char| !c.is_alphanumeric())
1511                    .filter(|word| !word.is_empty())
1512                    .map(str::to_string)
1513                    .collect()
1514            };
1515            let old_value = if !words(value).is_empty() && words(old_value) == words(value) {
1516                value
1517            } else {
1518                old_value.as_str()
1519            };
1520            // If the value is different, mark old as superseded and insert new.
1521            //
1522            // Source priority guard: a write replaces a different value only
1523            // at equal or higher source rank. Background extractors read tool
1524            // output and paraphrase; they can lift a wrong value from a
1525            // hallucinated or stale message, so they never replace what the
1526            // owner stated or a value quoted from the owner's message (an
1527            // hour-old consolidation batch cannot revert a fresh correction).
1528            if old_value != value {
1529                let existing_source: Option<String> =
1530                    sqlx::query_scalar("SELECT source FROM facts WHERE id = ?")
1531                        .bind(old_id)
1532                        .fetch_optional(&self.pool)
1533                        .await?;
1534                if existing_source
1535                    .as_deref()
1536                    .is_some_and(|existing| fact_source_rank(existing) > fact_source_rank(source))
1537                {
1538                    tracing::info!(
1539                        category = category_clean,
1540                        key = key_clean,
1541                        existing_source = ?existing_source,
1542                        source,
1543                        "Fact write skipped: refusing to overwrite a fact from a closer source"
1544                    );
1545                    return Ok(());
1546                }
1547            }
1548            if old_value != value {
1549                sqlx::query("UPDATE facts SET superseded_at = ?, superseded_reason = 'replaced' WHERE id = ?")
1550                    .bind(&now)
1551                    .bind(old_id)
1552                    .execute(&self.pool)
1553                    .await?;
1554
1555                // Insert new fact with embedding — ignore duplicate entry errors (code 2067)
1556                // that can occur due to active-unique constraint race conditions.
1557                let insert_result = sqlx::query(
1558                    "INSERT INTO facts (category, key, value, source, created_at, updated_at, recall_count, channel_id, privacy, embedding, first_seen_at, source_excerpt)
1559                     VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?)",
1560                )
1561                .bind(category_clean)
1562                .bind(&key_for_write)
1563                .bind(value)
1564                .bind(source)
1565                .bind(&now)
1566                .bind(&now)
1567                .bind(channel_id)
1568                .bind(&privacy_str)
1569                .bind(&embedding_blob)
1570                .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1571                .bind(source_excerpt)
1572                .execute(&self.pool)
1573                .await;
1574
1575                match insert_result {
1576                    Ok(_) => {}
1577                    Err(sqlx::Error::Database(ref db_err))
1578                        if db_err.code().as_deref() == Some("2067") =>
1579                    {
1580                        // Duplicate entry — another active row already exists (concurrent upsert).
1581                        // Update the active row to "last write wins" without resurrecting the
1582                        // superseded row (which would violate partial unique indexes).
1583                        let updated = sqlx::query(
1584                            "UPDATE facts
1585                             SET value = ?, source = ?, updated_at = ?,
1586                                 channel_id = ?, privacy = ?,
1587                                 embedding = COALESCE(?, embedding),
1588                                 first_seen_at = COALESCE(?, first_seen_at),
1589                                 source_excerpt = COALESCE(?, source_excerpt)
1590                             WHERE category = ? AND key = ? AND superseded_at IS NULL",
1591                        )
1592                        .bind(value)
1593                        .bind(source)
1594                        .bind(&now)
1595                        .bind(channel_id)
1596                        .bind(&privacy_str)
1597                        .bind(&embedding_blob)
1598                        .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1599                        .bind(source_excerpt)
1600                        .bind(category_clean)
1601                        .bind(&key_for_write)
1602                        .execute(&self.pool)
1603                        .await?;
1604
1605                        // Legacy fallback: if no active row exists (e.g., old UNIQUE(category,key)
1606                        // constraint), keep data consistent by updating in-place.
1607                        if updated.rows_affected() == 0 {
1608                            sqlx::query(
1609                                "UPDATE facts
1610                                 SET value = ?, source = ?, updated_at = ?, superseded_at = NULL, superseded_reason = NULL, folded_into = NULL,
1611                                     channel_id = ?, privacy = ?,
1612                                     embedding = COALESCE(?, embedding),
1613                                     first_seen_at = COALESCE(?, first_seen_at),
1614                                     source_excerpt = COALESCE(?, source_excerpt)
1615                                 WHERE id = ?",
1616                            )
1617                            .bind(value)
1618                            .bind(source)
1619                            .bind(&now)
1620                            .bind(channel_id)
1621                            .bind(&privacy_str)
1622                            .bind(&embedding_blob)
1623                            .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1624                            .bind(source_excerpt)
1625                            .bind(old_id)
1626                            .execute(&self.pool)
1627                            .await?;
1628                        }
1629                    }
1630                    Err(e) => return Err(e.into()),
1631                }
1632                if fact_source_rank(source) > 0 {
1633                    self.supersede_copies(
1634                        *old_id,
1635                        &key_for_write,
1636                        old_value,
1637                        SupersededReason::Replaced,
1638                        fact_source_rank(source),
1639                    )
1640                    .await?;
1641                }
1642            } else {
1643                // Same value — update timestamp and backfill embedding.
1644                // A restatement never lowers the row's source rank; a closer
1645                // source raises it and brings its quote.
1646                let existing_source: Option<String> =
1647                    sqlx::query_scalar("SELECT source FROM facts WHERE id = ?")
1648                        .bind(old_id)
1649                        .fetch_optional(&self.pool)
1650                        .await?;
1651                let existing_rank = existing_source.as_deref().map_or(0, fact_source_rank);
1652                if fact_source_rank(source) < existing_rank {
1653                    sqlx::query(
1654                        "UPDATE facts SET updated_at = ?, embedding = COALESCE(embedding, ?) WHERE id = ?",
1655                    )
1656                    .bind(&now)
1657                    .bind(&embedding_blob)
1658                    .bind(old_id)
1659                    .execute(&self.pool)
1660                    .await?;
1661                } else if fact_source_rank(source) > existing_rank {
1662                    sqlx::query(
1663                        "UPDATE facts SET source = ?, updated_at = ?, embedding = COALESCE(embedding, ?), first_seen_at = COALESCE(first_seen_at, ?), source_excerpt = COALESCE(?, source_excerpt) WHERE id = ?",
1664                    )
1665                    .bind(source)
1666                    .bind(&now)
1667                    .bind(&embedding_blob)
1668                    .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1669                    .bind(source_excerpt)
1670                    .bind(old_id)
1671                    .execute(&self.pool)
1672                    .await?;
1673                } else {
1674                    sqlx::query(
1675                        "UPDATE facts SET source = ?, updated_at = ?, embedding = COALESCE(embedding, ?), first_seen_at = COALESCE(first_seen_at, ?), source_excerpt = COALESCE(source_excerpt, ?) WHERE id = ?",
1676                    )
1677                    .bind(source)
1678                    .bind(&now)
1679                    .bind(&embedding_blob)
1680                    .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1681                    .bind(source_excerpt)
1682                    .bind(old_id)
1683                    .execute(&self.pool)
1684                    .await?;
1685                }
1686            }
1687        } else {
1688            // No existing fact - insert new with embedding
1689            // Ignore duplicate entry errors (code 2067) from concurrent inserts
1690            let insert_result = sqlx::query(
1691                "INSERT INTO facts (category, key, value, source, created_at, updated_at, recall_count, channel_id, privacy, embedding, first_seen_at, source_excerpt)
1692                 VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?)",
1693            )
1694            .bind(category_clean)
1695            .bind(&key_for_write)
1696            .bind(value)
1697            .bind(source)
1698            .bind(&now)
1699            .bind(&now)
1700            .bind(channel_id)
1701            .bind(&privacy_str)
1702            .bind(&embedding_blob)
1703            .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1704            .bind(source_excerpt)
1705            .execute(&self.pool)
1706            .await;
1707
1708            match insert_result {
1709                Ok(_) => {}
1710                Err(sqlx::Error::Database(ref db_err))
1711                    if db_err.code().as_deref() == Some("2067") =>
1712                {
1713                    // Duplicate entry — another active row already exists (concurrent upsert).
1714                    // Update the active row to "last write wins".
1715                    let updated = sqlx::query(
1716                        "UPDATE facts
1717                         SET value = ?, source = ?, updated_at = ?,
1718                             channel_id = ?, privacy = ?,
1719                             embedding = COALESCE(?, embedding),
1720                             first_seen_at = COALESCE(?, first_seen_at),
1721                             source_excerpt = COALESCE(?, source_excerpt)
1722                         WHERE category = ? AND key = ? AND superseded_at IS NULL",
1723                    )
1724                    .bind(value)
1725                    .bind(source)
1726                    .bind(&now)
1727                    .bind(channel_id)
1728                    .bind(&privacy_str)
1729                    .bind(&embedding_blob)
1730                    .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1731                    .bind(source_excerpt)
1732                    .bind(category_clean)
1733                    .bind(&key_for_write)
1734                    .execute(&self.pool)
1735                    .await?;
1736
1737                    if updated.rows_affected() == 0 {
1738                        // If there is no active row, update the most recent version in-place.
1739                        // This can happen on legacy schemas where a superseded row still blocks
1740                        // inserts (old UNIQUE(category,key) constraint).
1741                        if let Some(row) = sqlx::query(
1742                            "SELECT id FROM facts WHERE category = ? AND key = ? ORDER BY updated_at DESC LIMIT 1",
1743                        )
1744                        .bind(category_clean)
1745                        .bind(&key_for_write)
1746                        .fetch_optional(&self.pool)
1747                        .await?
1748                        {
1749                            let id: i64 = row.get("id");
1750                            sqlx::query(
1751                                "UPDATE facts
1752                                 SET value = ?, source = ?, updated_at = ?, superseded_at = NULL, superseded_reason = NULL, folded_into = NULL,
1753                                     channel_id = ?, privacy = ?,
1754                                     embedding = COALESCE(?, embedding),
1755                                     first_seen_at = COALESCE(?, first_seen_at),
1756                                     source_excerpt = COALESCE(?, source_excerpt)
1757                                 WHERE id = ?",
1758                            )
1759                            .bind(value)
1760                            .bind(source)
1761                            .bind(&now)
1762                            .bind(channel_id)
1763                            .bind(&privacy_str)
1764                            .bind(&embedding_blob)
1765                            .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1766                            .bind(source_excerpt)
1767                            .bind(id)
1768                            .execute(&self.pool)
1769                            .await?;
1770                        }
1771                    }
1772                }
1773                Err(e) => return Err(e.into()),
1774            }
1775        }
1776
1777        // ── Post-store conflict sweep ──────────────────────────────────
1778        //
1779        // When the owner stores a fact through remember_fact (source ==
1780        // "agent"), an active row in the same category whose key names the
1781        // same attribute in canonical form ("dog name" / "dog_name" left by
1782        // an older, uncanonicalized write) and holds another value is stale:
1783        // it is superseded. Identity is the canonical key only. Facts under
1784        // different keys are never superseded here, whatever words or
1785        // embedding they share ("favorite_drink: green tea" must never
1786        // retire "allergy: green tea").
1787        if source == "agent" {
1788            let canonical_written = canonicalize_fact_key(&key_for_write);
1789            let others = sqlx::query(
1790                "SELECT id, key, value FROM facts
1791                         WHERE category = ? AND superseded_at IS NULL
1792                           AND key != ?",
1793            )
1794            .bind(category_clean)
1795            .bind(&key_for_write)
1796            .fetch_all(&self.pool)
1797            .await
1798            .unwrap_or_default();
1799
1800            for row in &others {
1801                let other_id: i64 = row.get("id");
1802                let other_key: String = row.get("key");
1803                let other_value: String = row.get("value");
1804                if canonicalize_fact_key(&other_key) != canonical_written || other_value == value {
1805                    continue;
1806                }
1807                tracing::info!(
1808                    category = category_clean,
1809                    new_key = key_clean,
1810                    new_value = value,
1811                    conflicting_key = other_key.as_str(),
1812                    conflicting_value = other_value.as_str(),
1813                    "Conflict sweep: superseding stale fact under the same canonical key"
1814                );
1815                let _ = sqlx::query(
1816                    "UPDATE facts SET superseded_at = ?, superseded_reason = 'replaced' WHERE id = ?",
1817                )
1818                .bind(&now)
1819                .bind(other_id)
1820                .execute(&self.pool)
1821                .await;
1822            }
1823        }
1824
1825        if let Err(error) = self.sync_fact_memory_written_at(category_clean, &now).await {
1826            tracing::warn!(%error, category = category_clean, "Deferred fact memory projection");
1827        }
1828        Ok(())
1829    }
1830
1831    async fn get_facts(&self, category: Option<&str>) -> anyhow::Result<Vec<Fact>> {
1832        // Only return current (non-superseded) facts
1833        let rows = if let Some(cat) = category {
1834            sqlx::query("SELECT id, category, key, value, source, created_at, updated_at, superseded_at, recall_count, last_recalled_at, channel_id, privacy, first_seen_at, source_excerpt FROM facts WHERE category = ? AND superseded_at IS NULL ORDER BY updated_at DESC")
1835                .bind(cat)
1836                .fetch_all(&self.pool)
1837                .await?
1838        } else {
1839            sqlx::query("SELECT id, category, key, value, source, created_at, updated_at, superseded_at, recall_count, last_recalled_at, channel_id, privacy, first_seen_at, source_excerpt FROM facts WHERE superseded_at IS NULL ORDER BY updated_at DESC")
1840                .fetch_all(&self.pool)
1841                .await?
1842        };
1843
1844        let mut facts = Vec::with_capacity(rows.len());
1845        for row in rows {
1846            facts.push(Self::row_to_fact(&row));
1847        }
1848        Ok(facts)
1849    }
1850
1851    async fn get_relevant_facts(&self, query: &str, max: usize) -> anyhow::Result<Vec<Fact>> {
1852        // Load facts; vectors come from the embedding index, and only facts
1853        // it has none for read their own blob (`unindexed_fact_scores`).
1854        let rows = sqlx::query(
1855            "SELECT id, category, key, value, source, created_at, updated_at, superseded_at, recall_count, last_recalled_at, channel_id, privacy, first_seen_at, source_excerpt
1856             FROM facts WHERE superseded_at IS NULL ORDER BY updated_at DESC",
1857        )
1858        .fetch_all(&self.pool)
1859        .await?;
1860
1861        let all_facts: Vec<Fact> = rows.iter().map(Self::row_to_fact).collect();
1862
1863        if all_facts.is_empty() || query.trim().is_empty() {
1864            let mut facts = all_facts;
1865            facts.truncate(max);
1866            let canonical = self.canonical_personal_facts().await.unwrap_or_default();
1867            return Ok(prefer_canonical_facts(canonical, facts, query, max));
1868        }
1869
1870        // Embed the query
1871        let query_vec = match self.embedding_service.embed(query.to_string()).await {
1872            Ok(v) => v,
1873            Err(e) => {
1874                tracing::warn!(
1875                    "Failed to embed query for passive fact filtering; using lexical matches: {}",
1876                    e
1877                );
1878                let facts = lexical_relevant_facts(&all_facts, query, max);
1879                let canonical = self.canonical_personal_facts().await.unwrap_or_default();
1880                return Ok(prefer_canonical_facts(canonical, facts, query, max));
1881            }
1882        };
1883
1884        let now = Utc::now();
1885        let query_lower = query.to_lowercase();
1886        let tokens = query_tokens(&query_lower);
1887        let indexed_scores = self
1888            .fact_embedding_scores(&query_vec, rows.len())
1889            .await
1890            .unwrap_or_default();
1891        let fts_fact_ids: std::collections::HashSet<i64> = self
1892            .search_memory_claims(
1893                query,
1894                None,
1895                ChannelVisibility::Internal,
1896                true,
1897                max.saturating_mul(4).max(16),
1898            )
1899            .await
1900            .unwrap_or_default()
1901            .into_iter()
1902            .filter_map(|claim| claim.source_fact_id)
1903            .collect();
1904        let graph_fact_ids = self
1905            .graph_fact_ids_for_query(query)
1906            .await
1907            .unwrap_or_default();
1908
1909        // Score facts using stored embeddings, with a small recency boost for sorting.
1910        // IMPORTANT: the recency boost must not change which facts pass the semantic threshold.
1911        let fallback_scores = self
1912            .unindexed_fact_scores(&query_vec, all_facts.iter().map(|f| f.id), &indexed_scores)
1913            .await;
1914        let mut candidates: Vec<(usize, f32, f32, bool)> = Vec::with_capacity(rows.len());
1915        for (i, fact) in all_facts.iter().enumerate() {
1916            let freshness = fact_freshness_boost(now, fact.updated_at);
1917
1918            let semantic = indexed_scores
1919                .get(&fact.id)
1920                .or_else(|| fallback_scores.get(&fact.id))
1921                .copied();
1922            let lexical = if fts_fact_ids.contains(&fact.id) {
1923                FACT_LEXICAL_MAX_SCORE
1924            } else {
1925                lexical_fallback_score(&query_lower, &tokens, fact)
1926            };
1927            if let Some(semantic) = semantic {
1928                if semantic > FACT_SEMANTIC_MIN_SCORE {
1929                    candidates.push((
1930                        i,
1931                        semantic,
1932                        hybrid_fact_score(
1933                            fact,
1934                            semantic,
1935                            lexical,
1936                            graph_fact_ids.contains(&fact.id),
1937                            freshness,
1938                        ),
1939                        true,
1940                    ));
1941                    continue;
1942                }
1943                // Below semantic threshold — try lexical as fallback for keyword matches
1944                let best = semantic.max(lexical);
1945                let is_semantic = best == semantic;
1946                candidates.push((
1947                    i,
1948                    best,
1949                    hybrid_fact_score(
1950                        fact,
1951                        semantic,
1952                        lexical,
1953                        graph_fact_ids.contains(&fact.id),
1954                        freshness,
1955                    ),
1956                    is_semantic,
1957                ));
1958                continue;
1959            }
1960
1961            // Missing/invalid embedding: fall back to cheap lexical relevance so
1962            // freshly saved facts can still be retrieved during embedding backfill.
1963            candidates.push((
1964                i,
1965                lexical,
1966                hybrid_fact_score(
1967                    fact,
1968                    0.0,
1969                    lexical,
1970                    graph_fact_ids.contains(&fact.id),
1971                    freshness,
1972                ),
1973                false,
1974            ));
1975        }
1976        candidates.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));
1977
1978        let mut relevant: Vec<Fact> = Vec::with_capacity(max.min(all_facts.len()));
1979        let mut seen_ids: std::collections::HashSet<i64> = std::collections::HashSet::new();
1980        for (i, base_score, _sort_score, is_semantic) in candidates.into_iter() {
1981            if relevant.len() >= max {
1982                break;
1983            }
1984            let min_score = if is_semantic {
1985                FACT_SEMANTIC_MIN_SCORE
1986            } else {
1987                FACT_LEXICAL_MIN_SCORE
1988            };
1989            if base_score > min_score {
1990                let fact = all_facts[i].clone();
1991                if seen_ids.insert(fact.id) {
1992                    relevant.push(fact);
1993                }
1994            }
1995        }
1996
1997        let canonical = self.canonical_personal_facts().await.unwrap_or_default();
1998        Ok(prefer_canonical_facts(canonical, relevant, query, max))
1999    }
2000
2001    async fn get_relevant_facts_for_channel(
2002        &self,
2003        query: &str,
2004        max: usize,
2005        channel_id: Option<&str>,
2006        visibility: ChannelVisibility,
2007        requester_is_owner: bool,
2008    ) -> anyhow::Result<Vec<Fact>> {
2009        // In DM/Internal contexts, use semantic relevance search so that only
2010        // facts related to the current query are injected into the prompt.
2011        // Previously this called get_facts(None) which returned ALL facts
2012        // without filtering, causing unrelated facts to bleed into context.
2013        //
2014        // SECURITY: only the OWNER gets the unfiltered graph in a DM. A non-owner
2015        // (allowlisted Guest) DMing the bot must NOT receive Private or
2016        // other-channel facts — fall through to the privacy filter below, same as
2017        // a group channel. Without this gate, a guest's prompt would be injected
2018        // with the owner's private memory.
2019        if requester_is_owner
2020            && matches!(
2021                visibility,
2022                ChannelVisibility::Private | ChannelVisibility::Internal
2023            )
2024        {
2025            return self.get_relevant_facts(query, max).await;
2026        }
2027
2028        // PublicExternal: do NOT inject any stored facts (treat as untrusted).
2029        if matches!(visibility, ChannelVisibility::PublicExternal) {
2030            return Ok(vec![]);
2031        }
2032
2033        // Public/PrivateGroup: global + same-channel facts (no private, no other-channel)
2034        let rows = sqlx::query(
2035            "SELECT id, category, key, value, source, created_at, updated_at, superseded_at, recall_count, last_recalled_at, channel_id, privacy, first_seen_at, source_excerpt
2036             FROM facts WHERE superseded_at IS NULL ORDER BY updated_at DESC",
2037        )
2038        .fetch_all(&self.pool)
2039        .await?;
2040
2041        // One visibility rule for every surface that shows a fact
2042        // (`memory_visible`): what the prompt is given here is what a
2043        // memory search would show this audience.
2044        let all_facts: Vec<Fact> = rows.iter().map(Self::row_to_fact).collect();
2045        let filtered_indices: Vec<usize> = all_facts
2046            .iter()
2047            .enumerate()
2048            .filter(|(_, f)| {
2049                super::memory_visible(
2050                    self.channels.as_ref(),
2051                    f.privacy,
2052                    f.channel_id.as_deref(),
2053                    channel_id,
2054                    visibility,
2055                    requester_is_owner,
2056                )
2057            })
2058            .map(|(i, _)| i)
2059            .collect();
2060
2061        let filtered: Vec<Fact> = filtered_indices
2062            .iter()
2063            .map(|&i| all_facts[i].clone())
2064            .collect();
2065
2066        if filtered.is_empty() || query.trim().is_empty() {
2067            let mut facts = filtered;
2068            facts.truncate(max);
2069            return Ok(facts);
2070        }
2071
2072        // Apply semantic filtering using stored embeddings
2073        let query_vec = match self.embedding_service.embed(query.to_string()).await {
2074            Ok(v) => v,
2075            Err(_) => {
2076                let facts = lexical_relevant_facts(&filtered, query, max);
2077                return Ok(facts);
2078            }
2079        };
2080
2081        let now = Utc::now();
2082        let query_lower = query.to_lowercase();
2083        let tokens = query_tokens(&query_lower);
2084        let indexed_scores = self
2085            .fact_embedding_scores(&query_vec, rows.len())
2086            .await
2087            .unwrap_or_default();
2088        let fts_fact_ids: std::collections::HashSet<i64> = self
2089            .search_memory_claims(
2090                query,
2091                channel_id,
2092                visibility,
2093                requester_is_owner,
2094                max.saturating_mul(4).max(16),
2095            )
2096            .await
2097            .unwrap_or_default()
2098            .into_iter()
2099            .filter_map(|claim| claim.source_fact_id)
2100            .collect();
2101        let graph_fact_ids = self
2102            .graph_fact_ids_for_query(query)
2103            .await
2104            .unwrap_or_default();
2105
2106        let fallback_scores = self
2107            .unindexed_fact_scores(&query_vec, filtered.iter().map(|f| f.id), &indexed_scores)
2108            .await;
2109        let mut candidates: Vec<(usize, f32, f32, bool)> = Vec::with_capacity(filtered.len());
2110        for (fi, fact) in filtered.iter().enumerate() {
2111            let freshness = fact_freshness_boost(now, fact.updated_at);
2112
2113            let semantic = indexed_scores
2114                .get(&fact.id)
2115                .or_else(|| fallback_scores.get(&fact.id))
2116                .copied();
2117            let lexical = if fts_fact_ids.contains(&fact.id) {
2118                FACT_LEXICAL_MAX_SCORE
2119            } else {
2120                lexical_fallback_score(&query_lower, &tokens, fact)
2121            };
2122            if let Some(semantic) = semantic {
2123                if semantic > FACT_SEMANTIC_MIN_SCORE {
2124                    candidates.push((
2125                        fi,
2126                        semantic,
2127                        hybrid_fact_score(
2128                            fact,
2129                            semantic,
2130                            lexical,
2131                            graph_fact_ids.contains(&fact.id),
2132                            freshness,
2133                        ),
2134                        true,
2135                    ));
2136                    continue;
2137                }
2138                // Below semantic threshold — try lexical as fallback for keyword matches
2139                let best = semantic.max(lexical);
2140                let is_semantic = best == semantic;
2141                candidates.push((
2142                    fi,
2143                    best,
2144                    hybrid_fact_score(
2145                        fact,
2146                        semantic,
2147                        lexical,
2148                        graph_fact_ids.contains(&fact.id),
2149                        freshness,
2150                    ),
2151                    is_semantic,
2152                ));
2153                continue;
2154            }
2155
2156            candidates.push((
2157                fi,
2158                lexical,
2159                hybrid_fact_score(
2160                    fact,
2161                    0.0,
2162                    lexical,
2163                    graph_fact_ids.contains(&fact.id),
2164                    freshness,
2165                ),
2166                false,
2167            ));
2168        }
2169        candidates.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));
2170
2171        let mut relevant: Vec<Fact> = Vec::with_capacity(max.min(filtered.len()));
2172        let mut seen_ids: std::collections::HashSet<i64> = std::collections::HashSet::new();
2173        for (fi, base_score, _sort_score, is_semantic) in candidates.into_iter() {
2174            if relevant.len() >= max {
2175                break;
2176            }
2177            let min_score = if is_semantic {
2178                FACT_SEMANTIC_MIN_SCORE
2179            } else {
2180                FACT_LEXICAL_MIN_SCORE
2181            };
2182            if base_score > min_score {
2183                let fact = filtered[fi].clone();
2184                if seen_ids.insert(fact.id) {
2185                    relevant.push(fact);
2186                }
2187            }
2188        }
2189
2190        Ok(relevant)
2191    }
2192
2193    async fn update_fact_privacy(&self, fact_id: i64, privacy: FactPrivacy) -> anyhow::Result<()> {
2194        sqlx::query("UPDATE facts SET privacy = ? WHERE id = ?")
2195            .bind(privacy.to_string())
2196            .bind(fact_id)
2197            .execute(&self.pool)
2198            .await?;
2199        if let Err(error) = self.project_fact_memory(fact_id).await {
2200            tracing::warn!(%error, fact_id, "Deferred fact privacy projection");
2201        }
2202        Ok(())
2203    }
2204
2205    async fn delete_fact(&self, fact_id: i64) -> anyhow::Result<()> {
2206        // A canonical personal-memory record reaches the model under a
2207        // synthetic negative id; forgetting it retracts that record.
2208        if fact_id < 0 {
2209            self.retract_canonical_projection(fact_id, "owner_forget")
2210                .await?;
2211            return Ok(());
2212        }
2213        let now = Utc::now().to_rfc3339();
2214        let forgotten: Option<(String, String, String)> = sqlx::query_as(
2215            "SELECT LOWER(TRIM(category)), LOWER(TRIM(key)), value FROM facts
2216             WHERE id = ? AND superseded_at IS NULL",
2217        )
2218        .bind(fact_id)
2219        .fetch_optional(&self.pool)
2220        .await?;
2221        sqlx::query(
2222            "UPDATE facts SET superseded_at = ?, superseded_reason = 'deleted' WHERE id = ?",
2223        )
2224        .bind(&now)
2225        .bind(fact_id)
2226        .execute(&self.pool)
2227        .await?;
2228        if let Err(error) = self.project_fact_memory(fact_id).await {
2229            tracing::warn!(%error, fact_id, "Deferred deleted-fact projection");
2230        }
2231        if let Some((category, key, value)) = forgotten {
2232            self.supersede_copies(fact_id, &key, &value, SupersededReason::Deleted, 2)
2233                .await?;
2234            if is_owner_profile_category(&category) {
2235                self.retract_owner_profile_key(&key, "owner_forget").await?;
2236            }
2237        }
2238        Ok(())
2239    }
2240
2241    async fn delete_fact_by_key(&self, category: &str, key: &str) -> anyhow::Result<bool> {
2242        let now = Utc::now().to_rfc3339();
2243        // Canonicalize: lowercase, trim, strip [brackets]
2244        let cat_clean = category.trim().to_lowercase();
2245        let key_clean = key.trim().to_lowercase();
2246        let deleted: Vec<(i64, String, String)> = sqlx::query_as(
2247            "SELECT id, key, value FROM facts WHERE LOWER(TRIM(category)) = ? AND LOWER(TRIM(key)) = ? AND superseded_at IS NULL",
2248        )
2249        .bind(&cat_clean)
2250        .bind(&key_clean)
2251        .fetch_all(&self.pool)
2252        .await?;
2253        let ids: Vec<i64> = deleted.iter().map(|(id, _, _)| *id).collect();
2254        let result = sqlx::query(
2255            "UPDATE facts SET superseded_at = ?, superseded_reason = 'deleted' WHERE LOWER(TRIM(category)) = ? AND LOWER(TRIM(key)) = ? AND superseded_at IS NULL",
2256        )
2257        .bind(&now)
2258        .bind(&cat_clean)
2259        .bind(&key_clean)
2260        .execute(&self.pool)
2261        .await?;
2262        for id in ids {
2263            if let Err(error) = self.project_fact_memory(id).await {
2264                tracing::warn!(%error, fact_id = id, "Deferred deleted-fact projection");
2265            }
2266        }
2267        // The owner's profile also lives in the canonical store, which the
2268        // prompt renders as its own block: forgetting the legacy row alone
2269        // left the old value in front of the model.
2270        for (id, key, value) in &deleted {
2271            self.supersede_copies(*id, key, value, SupersededReason::Deleted, 2)
2272                .await?;
2273        }
2274        let canonical = is_owner_profile_category(&cat_clean)
2275            && self
2276                .retract_owner_profile_key(&key_clean, "owner_forget")
2277                .await?;
2278        Ok(result.rows_affected() > 0 || canonical)
2279    }
2280
2281    async fn get_all_facts_with_provenance(&self) -> anyhow::Result<Vec<Fact>> {
2282        let rows = sqlx::query(
2283            "SELECT id, category, key, value, source, created_at, updated_at, superseded_at, recall_count, last_recalled_at, channel_id, privacy, first_seen_at, source_excerpt
2284             FROM facts WHERE superseded_at IS NULL ORDER BY category, key"
2285        )
2286        .fetch_all(&self.pool)
2287        .await?;
2288
2289        Ok(rows.iter().map(Self::row_to_fact).collect())
2290    }
2291}
2292
2293/// Legacy categories whose keys describe the owner, as the canonical store
2294/// projects them (`user`) and as writers name them.
2295fn is_owner_profile_category(category: &str) -> bool {
2296    matches!(category, "user" | "personal" | "profile")
2297}