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