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