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