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        insert_tombstone(&self.pool, category, key, value, reason, retired_at).await
570    }
571
572    async fn retired_knowledge(
573        &self,
574        category: &str,
575        keys: &[&str],
576        value: &str,
577    ) -> anyhow::Result<Vec<RetiredKnowledge>> {
578        let mut rows: Vec<(String, String, String, String, Option<String>)> = sqlx::query_as(
579            "SELECT f.category, f.key, f.value, f.superseded_at, f.superseded_reason
580             FROM facts f
581             WHERE f.superseded_at IS NOT NULL
582               AND NOT EXISTS (SELECT 1 FROM facts a WHERE a.superseded_at IS NULL AND a.archived_at IS NULL
583                                AND a.category = f.category AND a.key = f.key)
584             ORDER BY f.superseded_at DESC",
585        )
586        .fetch_all(&self.pool)
587        .await?;
588        let tombstones: Vec<(String, String, String, String, String)> = sqlx::query_as(
589            "SELECT t.category, t.canonical_key, t.normalized_value, t.retired_at, t.reason
590             FROM memory_fact_tombstones t
591             WHERE NOT EXISTS (SELECT 1 FROM facts a WHERE a.superseded_at IS NULL AND a.archived_at IS NULL
592                                AND LOWER(TRIM(a.category)) = LOWER(TRIM(t.category))
593                                AND LOWER(TRIM(a.key)) = LOWER(TRIM(t.canonical_key)))
594             ORDER BY t.retired_at DESC",
595        )
596        .fetch_all(&self.pool)
597        .await
598        .unwrap_or_default();
599        for (t_cat, t_key, t_val, t_at, t_reason) in tombstones {
600            let reason = if t_reason == "unknown" {
601                None
602            } else {
603                Some(t_reason)
604            };
605            rows.push((t_cat, t_key, t_val, t_at, reason));
606        }
607        Ok(rows
608            .into_iter()
609            .filter(
610                |(retired_category, retired_key, retired_value, _, reason)| {
611                    retirement_covers(
612                        (category, keys, value),
613                        (retired_category, retired_key, retired_value),
614                        reason.as_deref(),
615                    )
616                },
617            )
618            .map(|(category, key, _, retired_at, _)| RetiredKnowledge {
619                category,
620                key,
621                // An unreadable time still retires: no evidence is newer.
622                retired_at: crate::types::parse_ts(&retired_at).unwrap_or(DateTime::<Utc>::MAX_UTC),
623            })
624            .collect())
625    }
626
627    /// Ends the active copies of a fact the owner just changed or forgot:
628    /// facts in any category that hold the same value under a key whose words
629    /// contain, or are contained in, those of `key` (`favorite_tea` beside `test_favorite_tea`,
630    /// `user/marker` beside `personal/marker`). Background extraction stores
631    /// such copies; left active, the old value survived the change.
632    async fn supersede_copies(
633        &self,
634        changed_id: i64,
635        key: &str,
636        value: &str,
637        reason: SupersededReason,
638        max_source_rank: u8,
639    ) -> anyhow::Result<()> {
640        let value = value.trim();
641        if value.is_empty() {
642            return Ok(());
643        }
644        let canonical = canonicalize_fact_key(key);
645        let tokens: std::collections::HashSet<&str> =
646            canonical.split('_').filter(|t| !t.is_empty()).collect();
647        let rows: Vec<(i64, String, String, String)> = sqlx::query_as(
648            "SELECT id, category, key, source FROM facts
649             WHERE superseded_at IS NULL AND archived_at IS NULL AND id <> ? AND LOWER(TRIM(value)) = LOWER(?)",
650        )
651        .bind(changed_id)
652        .bind(value)
653        .fetch_all(&self.pool)
654        .await?;
655        let now = Utc::now().to_rfc3339();
656        for (id, other_cat, other_key, other_source) in rows {
657            // A quoted change never retires what the owner stated.
658            if fact_source_rank(&other_source) > max_source_rank {
659                continue;
660            }
661            let other = canonicalize_fact_key(&other_key);
662            let other: std::collections::HashSet<&str> =
663                other.split('_').filter(|t| !t.is_empty()).collect();
664            // One key must name the other with modifiers added: a shared
665            // word alone (`pet_name`, `daughter_name`) is a different fact.
666            if !(tokens.is_subset(&other) || other.is_subset(&tokens)) {
667                continue;
668            }
669            sqlx::query(
670                "UPDATE facts SET superseded_at = ?, superseded_reason = ?
671                 WHERE id = ? AND superseded_at IS NULL",
672            )
673            .bind(&now)
674            .bind(reason.as_str())
675            .bind(id)
676            .execute(&self.pool)
677            .await?;
678            if reason == SupersededReason::Deleted {
679                let _ = self
680                    .record_tombstone(&other_cat, &other_key, value, reason, &now)
681                    .await;
682            }
683            if let Err(error) = self.project_fact_memory(id).await {
684                tracing::warn!(%error, fact_id = id, "Deferred superseded-copy projection");
685            }
686        }
687        Ok(())
688    }
689}
690
691/// Write a tombstone (see `SqliteMemory::record_tombstone`) on `executor`,
692/// so a write transaction can retire a fact and its tombstone together.
693async fn insert_tombstone<'e, E>(
694    executor: E,
695    category: &str,
696    key: &str,
697    value: &str,
698    reason: SupersededReason,
699    retired_at: &str,
700) -> anyhow::Result<()>
701where
702    E: sqlx::Executor<'e, Database = sqlx::Sqlite>,
703{
704    let canonical_key = canonicalize_fact_key(key);
705    if canonical_key.is_empty() {
706        return Ok(());
707    }
708    let normalized_value = crate::text::normalize_fact_value(value);
709    sqlx::query(
710        "INSERT INTO memory_fact_tombstones
711            (category, canonical_key, normalized_value, reason, retired_at)
712         VALUES (?, ?, ?, ?, ?)
713         ON CONFLICT(category, canonical_key, normalized_value, reason)
714         DO UPDATE SET retired_at = MAX(retired_at, excluded.retired_at)",
715    )
716    .bind(category.trim().to_ascii_lowercase())
717    .bind(&canonical_key)
718    .bind(&normalized_value)
719    .bind(reason.as_str())
720    .bind(retired_at)
721    .execute(executor)
722    .await?;
723    Ok(())
724}
725
726fn key_tokens(canonical: &str) -> std::collections::HashSet<&str> {
727    canonical.split('_').filter(|t| !t.is_empty()).collect()
728}
729
730/// A row's category, key, retirement time, fold target and reason.
731type FoldLink = (String, String, Option<String>, Option<i64>, Option<String>);
732
733/// A retired fact row that an automated write would bring back.
734#[derive(Debug, Clone)]
735pub(crate) struct RetiredKnowledge {
736    pub category: String,
737    pub key: String,
738    pub retired_at: DateTime<Utc>,
739}
740
741/// Whether a retired row (`retired_*`, with no active row for its key)
742/// covers an automated write of `key = value` in `category`.
743///
744/// - Same category, same canonical key: always, whatever the reason.
745/// - Another category, only with the same value: `project/status` and
746///   `technical/status` are different facts. Deleted by the owner: the same
747///   canonical key, or one naming the other with words added. Retired before
748///   reasons were recorded: the same canonical key only, since the row may
749///   be a fold or a value change rather than a deletion.
750///
751/// A value alone never matches: `true` or `main` under unrelated keys are
752/// different facts.
753fn retirement_covers(
754    (category, key, value): (&str, &[&str], &str),
755    (retired_category, retired_key, retired_value): (&str, &str, &str),
756    reason: Option<&str>,
757) -> bool {
758    let retired_canonical = canonicalize_fact_key(retired_key);
759    let same_key = key
760        .iter()
761        .any(|key| canonicalize_fact_key(key) == retired_canonical);
762    if retired_category
763        .trim()
764        .eq_ignore_ascii_case(category.trim())
765    {
766        return same_key;
767    }
768    let value = crate::text::normalize_fact_value(value);
769    if value.is_empty() || value != crate::text::normalize_fact_value(retired_value) {
770        return false;
771    }
772    match reason {
773        Some("deleted") => {
774            same_key
775                || key.iter().any(|key| {
776                    let canonical = canonicalize_fact_key(key);
777                    let (a, b) = (key_tokens(&canonical), key_tokens(&retired_canonical));
778                    !a.is_empty() && !b.is_empty() && (a.is_subset(&b) || b.is_subset(&a))
779                })
780        }
781        None => same_key,
782        Some(_) => false,
783    }
784}
785
786/// Why a fact row stopped being active, stored in `facts.superseded_reason`.
787/// Rows retired before the column existed have none, and are read as
788/// "unknown": a deletion, a fold or a value change. Operator cleanups
789/// (`db_probe --retire-inferred-behavior`, `--fact-conflict-audit --apply`)
790/// write `retired` and `replaced`.
791#[derive(Debug, Clone, Copy, PartialEq, Eq)]
792pub(crate) enum SupersededReason {
793    /// The owner forgot it (or a copy of what they forgot).
794    Deleted,
795    /// A newer value replaced it.
796    Replaced,
797    /// It restated another active fact (`folded_into`).
798    Folded,
799}
800
801impl SupersededReason {
802    pub(crate) fn as_str(self) -> &'static str {
803        match self {
804            Self::Deleted => "deleted",
805            Self::Replaced => "replaced",
806            Self::Folded => "folded",
807        }
808    }
809}
810
811/// Owner type of the cached key-text vectors fact dedup compares. The fact
812/// row owns its vector, so retention drops it with the fact; lookups go by
813/// the key text's hash.
814const DEDUP_KEY_OWNER: &str = "fact_key";
815const DEDUP_KEY_PURPOSE: &str = "dedup";
816
817impl SqliteMemory {
818    /// Vectors for fact-dedup key texts, in order. `texts` pairs each text
819    /// with the fact row it belongs to, if any; a stored row's vector is
820    /// cached under that row and read back next time: a category holds
821    /// thousands of keys, and embedding them all on every write took
822    /// seconds.
823    async fn dedup_key_vectors(
824        &self,
825        texts: Vec<(Option<i64>, String)>,
826    ) -> anyhow::Result<Vec<Vec<f32>>> {
827        use crate::embedding_index::content_hash;
828        let model = self.embedding_service.model_id();
829        let hashes: Vec<String> = texts.iter().map(|(_, t)| content_hash(t)).collect();
830        let mut cached: std::collections::HashMap<String, Vec<f32>> =
831            std::collections::HashMap::new();
832        let mut unique: Vec<&String> = hashes.iter().collect();
833        unique.sort();
834        unique.dedup();
835        for chunk in unique.chunks(500) {
836            let mut builder = sqlx::QueryBuilder::<sqlx::Sqlite>::new(
837                "SELECT content_hash, embedding FROM memory_embeddings
838                 WHERE owner_type = ",
839            );
840            builder
841                .push_bind(DEDUP_KEY_OWNER)
842                .push(" AND embedding_purpose = ")
843                .push_bind(DEDUP_KEY_PURPOSE)
844                .push(" AND embedding_model = ")
845                .push_bind(&model)
846                .push(" AND stale_at IS NULL AND content_hash IN (");
847            let mut separated = builder.separated(", ");
848            for hash in chunk {
849                separated.push_bind(*hash);
850            }
851            separated.push_unseparated(")");
852            for row in builder.build().fetch_all(&self.pool).await? {
853                let blob: Vec<u8> = row.get("embedding");
854                if let Ok(vector) = self.embedding_service.decode(&blob) {
855                    cached.insert(row.get("content_hash"), vector);
856                }
857            }
858        }
859
860        // (hash, owning fact, text)
861        let mut missing: Vec<(String, Option<i64>, String)> = Vec::new();
862        let mut queued = std::collections::HashSet::new();
863        for ((owner, text), hash) in texts.iter().zip(&hashes) {
864            if !cached.contains_key(hash) && queued.insert(hash.clone()) {
865                missing.push((hash.clone(), *owner, text.clone()));
866            }
867        }
868        if !missing.is_empty() {
869            let vectors = self
870                .embedding_service
871                .embed_many(missing.iter().map(|(_, _, text)| text.clone()).collect())
872                .await?;
873            let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
874            for ((hash, owner, _), vector) in missing.iter().zip(&vectors) {
875                let Some(owner) = owner else {
876                    continue;
877                };
878                sqlx::query(
879                    "INSERT INTO memory_embeddings
880                        (owner_type, owner_id, embedding_purpose, embedding_model,
881                         embedding_dim, content_hash, embedding, created_at, updated_at)
882                     VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'))
883                     ON CONFLICT(owner_type, owner_id, embedding_purpose, embedding_model, content_hash)
884                     DO UPDATE SET embedding = excluded.embedding, stale_at = NULL,
885                                   updated_at = datetime('now')",
886                )
887                .bind(DEDUP_KEY_OWNER)
888                .bind(owner.to_string())
889                .bind(DEDUP_KEY_PURPOSE)
890                .bind(&model)
891                .bind(vector.len() as i64)
892                .bind(hash)
893                .bind(encode_embedding(vector))
894                .execute(&mut *tx)
895                .await?;
896            }
897            tx.commit().await?;
898            for ((hash, _, _), vector) in missing.into_iter().zip(vectors) {
899                cached.insert(hash, vector);
900            }
901        }
902        hashes
903            .iter()
904            .map(|hash| {
905                cached
906                    .get(hash)
907                    .cloned()
908                    .ok_or_else(|| anyhow::anyhow!("no dedup vector for a key"))
909            })
910            .collect()
911    }
912
913    /// Every fact an explicit search ranks, loaded once: canonical
914    /// projections, then active rows, minus owner rows a projection already
915    /// covers. The map sends each such projection to the raw row it
916    /// replaced, whose vector stands in for it: projections have no vector
917    /// of their own, and without one they would be reachable by keyword only.
918    async fn explicit_search_facts(
919        &self,
920    ) -> anyhow::Result<(Vec<Fact>, std::collections::HashMap<i64, i64>)> {
921        let mut facts = self.canonical_personal_facts().await?;
922        let projection_by_key: std::collections::HashMap<String, i64> = facts
923            .iter()
924            .filter(|fact| fact.category == "user")
925            .map(|fact| (crate::text::owner_projection_family(&fact.key), fact.id))
926            .collect();
927        // The newest covered row stands in.
928        let mut newest: std::collections::HashMap<i64, (i64, DateTime<Utc>)> =
929            std::collections::HashMap::new();
930        for fact in self.get_all_facts_with_provenance().await? {
931            let cat_lower = fact.category.trim().to_ascii_lowercase();
932            let is_owner_cat = is_owner_profile_category(&cat_lower)
933                || (cat_lower == "preference" && crate::text::is_owner_profile_key(&fact.key));
934            let covering = is_owner_cat
935                .then(|| projection_by_key.get(&crate::text::owner_projection_family(&fact.key)))
936                .flatten();
937            match covering {
938                Some(projection) => {
939                    let slot = newest
940                        .entry(*projection)
941                        .or_insert((fact.id, fact.updated_at));
942                    if fact.updated_at > slot.1 {
943                        *slot = (fact.id, fact.updated_at);
944                    }
945                }
946                None => facts.push(fact),
947            }
948        }
949        let stand_ins = newest.into_iter().map(|(p, (id, _))| (p, id)).collect();
950        Ok((facts, stand_ins))
951    }
952
953    /// Cosine of the query against every fact with a current vector, by
954    /// position in `facts`. Empty when the query cannot be embedded.
955    async fn explicit_search_cosine(
956        &self,
957        query: &str,
958        facts: &[Fact],
959        stand_ins: &std::collections::HashMap<i64, i64>,
960    ) -> Vec<(usize, f32)> {
961        let query_vec = match self.embedding_service.embed(query.to_string()).await {
962            Ok(vector) => vector,
963            Err(error) => {
964                tracing::warn!(target: "memory_recall", %error, "explicit fact search: query embedding failed; lexical only");
965                return Vec::new();
966            }
967        };
968        let vector_id = |fact: &Fact| stand_ins.get(&fact.id).copied().unwrap_or(fact.id);
969        let indexed = self
970            .fact_embedding_scores(&query_vec, facts.len() + stand_ins.len())
971            .await
972            .unwrap_or_default();
973        let fallback = self
974            .unindexed_fact_scores(
975                &query_vec,
976                facts.iter().map(vector_id).filter(|id| *id > 0),
977                &indexed,
978            )
979            .await;
980        facts
981            .iter()
982            .enumerate()
983            .filter_map(|(i, fact)| {
984                let id = vector_id(fact);
985                indexed
986                    .get(&id)
987                    .or_else(|| fallback.get(&id))
988                    .map(|score| (i, *score))
989            })
990            .collect()
991    }
992}
993
994#[async_trait]
995impl FactStore for SqliteMemory {
996    async fn search_facts(
997        &self,
998        query: &str,
999        limit: usize,
1000        config: &crate::search::FactSearchConfig,
1001    ) -> anyhow::Result<crate::search::FactSearchReport> {
1002        use crate::neighborhood::{eligible_neighbors, is_relationship_key, seeds_from_hits};
1003        use crate::search::{self, LexicalIndex};
1004
1005        if query.trim().is_empty() || limit == 0 {
1006            return Ok(search::FactSearchReport::default());
1007        }
1008        let started = std::time::Instant::now();
1009        let (facts, stand_ins) = self.explicit_search_facts().await?;
1010        let load_ms = started.elapsed().as_millis() as u64;
1011
1012        let stage = std::time::Instant::now();
1013        let lexical = LexicalIndex::build(&facts).score(query);
1014        let lexical_ms = stage.elapsed().as_millis() as u64;
1015
1016        let stage = std::time::Instant::now();
1017        let cosine = self.explicit_search_cosine(query, &facts, &stand_ins).await;
1018        let embed_ms = stage.elapsed().as_millis() as u64;
1019
1020        let stage = std::time::Instant::now();
1021        let pool = search::candidates(&facts, &lexical, &cosine, config);
1022        let mut report = search::rank(&facts, &pool, limit, config);
1023        let rank_ms = stage.elapsed().as_millis() as u64;
1024
1025        // Expansion seeds come only from the hits actually returned.
1026        let stage = std::time::Instant::now();
1027        let hit_facts: Vec<Fact> = report.hits.iter().map(|h| h.fact.clone()).collect();
1028        let known_people: Vec<String> = PeopleStore::get_all_people(self)
1029            .await
1030            .unwrap_or_default()
1031            .into_iter()
1032            .flat_map(|p| std::iter::once(p.name).chain(p.aliases))
1033            .collect();
1034        let seeds = seeds_from_hits(&hit_facts, &known_people);
1035        let relationship_cluster = hit_facts.iter().any(|f| is_relationship_key(&f.key));
1036        if !seeds.is_empty() || relationship_cluster {
1037            let exclude: std::collections::HashSet<i64> = hit_facts.iter().map(|f| f.id).collect();
1038            let mut neighbors = eligible_neighbors(&facts, &seeds, relationship_cluster, &exclude);
1039            // A neighbor duplicating a hit's content is not new context.
1040            let shown: std::collections::HashSet<(&str, &str, &str)> = hit_facts
1041                .iter()
1042                .map(|f| (f.category.as_str(), f.key.as_str(), f.value.as_str()))
1043                .collect();
1044            neighbors.retain(|f| {
1045                !shown.contains(&(f.category.as_str(), f.key.as_str(), f.value.as_str()))
1046            });
1047
1048            let position: std::collections::HashMap<i64, usize> =
1049                facts.iter().enumerate().map(|(i, f)| (f.id, i)).collect();
1050            let cosine_by_index: std::collections::HashMap<usize, f32> =
1051                cosine.iter().copied().collect();
1052            let lexical_by_index: std::collections::HashMap<usize, f32> =
1053                lexical.iter().map(|h| (h.index, h.score)).collect();
1054            let prior = |f: &Fact| -> f32 {
1055                let index = position[&f.id];
1056                if cosine.is_empty() {
1057                    lexical_by_index.get(&index).copied().unwrap_or(0.0)
1058                } else {
1059                    cosine_by_index.get(&index).copied().unwrap_or(0.0)
1060                }
1061            };
1062            if neighbors.len() > config.related_pool {
1063                neighbors.sort_by(|a, b| prior(b).total_cmp(&prior(a)).then(a.id.cmp(&b.id)));
1064                neighbors.truncate(config.related_pool);
1065            }
1066            let scores: Vec<(usize, f32)> = neighbors
1067                .iter()
1068                .enumerate()
1069                .map(|(i, f)| (i, prior(f)))
1070                .collect();
1071            report.related = search::rank_related(&neighbors, &scores, config);
1072        }
1073        let expand_ms = stage.elapsed().as_millis() as u64;
1074
1075        // Scores of the leading hits: `key=score (kind)`.
1076        let summarize = |hits: &[search::SearchHit]| {
1077            hits.iter()
1078                .take(3)
1079                .map(|h| format!("{}={:.3} ({:?})", h.fact.key, h.score, h.kind))
1080                .collect::<Vec<_>>()
1081                .join(", ")
1082        };
1083        let top = summarize(&report.hits);
1084        let related_top = summarize(&report.related);
1085        tracing::info!(
1086            target: "memory_recall",
1087            load_ms,
1088            lexical_ms,
1089            embed_ms,
1090            rank_ms,
1091            expand_ms,
1092            considered = report.considered,
1093            returned = report.hits.len(),
1094            related = report.related.len(),
1095            top = %top,
1096            related_top = %related_top,
1097            "explicit fact search"
1098        );
1099        Ok(report)
1100    }
1101
1102    async fn stamp_fact_provenance(
1103        &self,
1104        category: &str,
1105        key: &str,
1106        source: &str,
1107        first_seen_at: Option<DateTime<Utc>>,
1108        source_excerpt: Option<&str>,
1109    ) -> anyhow::Result<()> {
1110        let canonical = canonicalize_fact_key(key);
1111        // Only classify rows still awaiting post-run provenance (`source = 'agent'`),
1112        // or rows being upgraded to a strictly closer rank — never downgrade an
1113        // already-stamped `user_stated` or `owner_quoted` fact to `derived`.
1114        let new_rank = fact_source_rank(source);
1115        let rows: Vec<(i64, String)> = sqlx::query_as(
1116            "SELECT id, source FROM facts
1117             WHERE LOWER(TRIM(category)) = LOWER(TRIM(?))
1118               AND (key = ? OR key = ?)
1119               AND superseded_at IS NULL
1120               AND archived_at IS NULL",
1121        )
1122        .bind(category)
1123        .bind(key)
1124        .bind(&canonical)
1125        .fetch_all(&self.pool)
1126        .await?;
1127        for (id, existing_source) in rows {
1128            if existing_source != "agent" && fact_source_rank(&existing_source) >= new_rank {
1129                continue;
1130            }
1131            sqlx::query(
1132                "UPDATE facts
1133                 SET source = ?,
1134                     first_seen_at = COALESCE(?, first_seen_at),
1135                     source_excerpt = COALESCE(?, source_excerpt)
1136                 WHERE id = ?",
1137            )
1138            .bind(source)
1139            .bind(first_seen_at.map(|at| at.to_rfc3339()))
1140            .bind(source_excerpt)
1141            .bind(id)
1142            .execute(&self.pool)
1143            .await?;
1144        }
1145        Ok(())
1146    }
1147
1148    async fn reconcile_personal_memory(
1149        &self,
1150        write: &crate::records::PersonalMemoryWrite,
1151        source: &str,
1152        source_excerpt: Option<&str>,
1153        channel_id: Option<&str>,
1154        privacy: FactPrivacy,
1155    ) -> anyhow::Result<crate::records::PersonalMemoryWriteResult> {
1156        self.reconcile_structured_personal_memory(
1157            write,
1158            source,
1159            source_excerpt,
1160            channel_id,
1161            privacy,
1162        )
1163        .await
1164    }
1165
1166    async fn get_canonical_memory_facts(&self) -> anyhow::Result<Vec<Fact>> {
1167        self.canonical_personal_facts().await
1168    }
1169
1170    async fn record_memory_recall(
1171        &self,
1172        fact_ids: &[i64],
1173        episode_ids: &[i64],
1174    ) -> anyhow::Result<()> {
1175        // Canonical projections carry synthetic negative ids; they have no
1176        // row to count against.
1177        let now = Utc::now().to_rfc3339();
1178        for (table, ids) in [("facts", fact_ids), ("episodes", episode_ids)] {
1179            let ids: Vec<i64> = ids.iter().copied().filter(|id| *id > 0).collect();
1180            if ids.is_empty() {
1181                continue;
1182            }
1183            let placeholders = vec!["?"; ids.len()].join(", ");
1184            let sql = format!(
1185                "UPDATE {table} SET recall_count = COALESCE(recall_count, 0) + 1, last_recalled_at = ? WHERE id IN ({placeholders})"
1186            );
1187            let mut query = sqlx::query(sqlx::AssertSqlSafe(&*sql)).bind(&now);
1188            for id in &ids {
1189                query = query.bind(id);
1190            }
1191            query.execute(&self.pool).await?;
1192        }
1193        Ok(())
1194    }
1195
1196    async fn fold_restated_facts(&self) -> anyhow::Result<usize> {
1197        let _upsert_guard = self.fact_upsert_lock.lock().await;
1198        let mut candidates = self.fold_candidates().await?;
1199        let folded: Vec<(i64, i64)> = super::fact_folds::plan_folds(&mut candidates)
1200            .into_iter()
1201            .map(|fold| (fold.folded, fold.kept))
1202            .collect();
1203        if folded.is_empty() {
1204            return Ok(0);
1205        }
1206        let now = Utc::now().to_rfc3339();
1207        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
1208        for (folded_id, kept_id) in &folded {
1209            sqlx::query(
1210                "UPDATE facts SET superseded_at = ?, superseded_reason = ?, folded_into = ?
1211                 WHERE id = ? AND superseded_at IS NULL",
1212            )
1213            .bind(&now)
1214            .bind(SupersededReason::Folded.as_str())
1215            .bind(kept_id)
1216            .bind(folded_id)
1217            .execute(&mut *tx)
1218            .await?;
1219            sqlx::query(
1220                "UPDATE facts SET recall_count = MAX(COALESCE(recall_count, 0),
1221                     (SELECT COALESCE(recall_count, 0) FROM facts WHERE id = ?))
1222                 WHERE id = ?",
1223            )
1224            .bind(folded_id)
1225            .bind(kept_id)
1226            .execute(&mut *tx)
1227            .await?;
1228        }
1229        tx.commit().await?;
1230        // Record durable tombstones for folded rows so retention cleanup cannot
1231        // later reopen them to background resurrection.
1232        for (folded_id, _) in &folded {
1233            if let Some(cand) = candidates.iter().find(|c| c.id == *folded_id) {
1234                let _ = self
1235                    .record_tombstone(
1236                        &cand.category,
1237                        &cand.key,
1238                        &cand.value,
1239                        SupersededReason::Folded,
1240                        &now,
1241                    )
1242                    .await;
1243            }
1244            if let Err(error) = self.project_fact_memory(*folded_id).await {
1245                tracing::warn!(%error, fact_id = folded_id, "Deferred folded-fact projection");
1246            }
1247        }
1248        tracing::info!(
1249            folded = folded.len(),
1250            "Folded restated facts into their representatives"
1251        );
1252        Ok(folded.len())
1253    }
1254
1255    async fn memory_health_report(&self) -> anyhow::Result<crate::records::MemoryHealthReport> {
1256        self.canonical_memory_health().await
1257    }
1258
1259    async fn repair_memory_projections(
1260        &self,
1261    ) -> anyhow::Result<crate::records::MemoryHealthReport> {
1262        self.backfill_missing_memory_projections().await?;
1263        self.canonical_memory_health().await
1264    }
1265
1266    async fn refresh_fact_memory(&self, category: &str, key: &str) -> anyhow::Result<()> {
1267        if let Some(id) = sqlx::query_scalar::<_, i64>(
1268            "SELECT id FROM facts WHERE lower(category) = lower(?) AND lower(key) = lower(?)
1269             AND superseded_at IS NULL AND archived_at IS NULL ORDER BY updated_at DESC LIMIT 1",
1270        )
1271        .bind(category)
1272        .bind(key)
1273        .fetch_optional(&self.pool)
1274        .await?
1275        {
1276            self.project_fact_memory(id).await?;
1277        }
1278        Ok(())
1279    }
1280
1281    async fn project_extracted_fact_graph(
1282        &self,
1283        category: &str,
1284        key: &str,
1285        source_excerpt: &str,
1286        graph: &crate::records::ExtractedMemoryGraph,
1287    ) -> anyhow::Result<()> {
1288        self.persist_extracted_fact_graph(category, key, source_excerpt, graph)
1289            .await
1290    }
1291
1292    #[allow(clippy::too_many_arguments)]
1293    async fn upsert_fact_with_provenance(
1294        &self,
1295        category: &str,
1296        key: &str,
1297        value: &str,
1298        source: &str,
1299        channel_id: Option<&str>,
1300        privacy: FactPrivacy,
1301        first_seen_at: Option<DateTime<Utc>>,
1302        source_excerpt: Option<&str>,
1303    ) -> anyhow::Result<()> {
1304        // The legacy flat-fact API performs a read/reconcile/write sequence.
1305        // Serialize that sequence so two concurrent writes for the same key
1306        // cannot both supersede the active row and race through the unique
1307        // active-fact constraint. Structured personal-memory writes use their
1308        // own explicit SQL transaction and do not take this compatibility lock.
1309        // A key folded into another fact writes through to that fact: a later
1310        // value for the folded key is an update of the knowledge it carries,
1311        // not a resurrection to refuse.
1312        if let Some((survivor_category, survivor_key)) =
1313            self.folded_survivor(category.trim(), key.trim()).await?
1314        {
1315            tracing::debug!(
1316                category,
1317                key,
1318                survivor_category = survivor_category.as_str(),
1319                survivor_key = survivor_key.as_str(),
1320                "Fact write redirected to the fact its key was folded into"
1321            );
1322            return self
1323                .upsert_fact_with_provenance(
1324                    &survivor_category,
1325                    &survivor_key,
1326                    value,
1327                    source,
1328                    channel_id,
1329                    privacy,
1330                    first_seen_at,
1331                    source_excerpt,
1332                )
1333                .await;
1334        }
1335        let _upsert_guard = self.fact_upsert_lock.lock().await;
1336        let now = Utc::now().to_rfc3339();
1337        let privacy_str = privacy.to_string();
1338
1339        let category_owned = category.trim().to_ascii_lowercase();
1340        let category_clean = category_owned.as_str();
1341        let key_clean = key.trim();
1342        let canonical_key = canonicalize_fact_key(key_clean);
1343
1344        // Find existing current fact (not superseded, not archived).
1345        // Prefer exact match; fall back to canonical match to avoid key drift
1346        // ("dog name" vs "dog_name") creating duplicates.
1347        let mut existing: Option<(i64, String, String)> = None;
1348
1349        if let Some(row) = sqlx::query(
1350            "SELECT id, key, value FROM facts WHERE LOWER(TRIM(category)) = ? AND key = ? AND superseded_at IS NULL AND archived_at IS NULL",
1351        )
1352        .bind(category_clean)
1353        .bind(key_clean)
1354        .fetch_optional(&self.pool)
1355        .await?
1356        {
1357            existing = Some((row.get("id"), row.get("key"), row.get("value")));
1358        } else {
1359            if canonical_key != key_clean
1360                && let Some(row) = sqlx::query(
1361                    "SELECT id, key, value FROM facts WHERE LOWER(TRIM(category)) = ? AND key = ? AND superseded_at IS NULL AND archived_at IS NULL",
1362                )
1363                .bind(category_clean)
1364                .bind(&canonical_key)
1365                .fetch_optional(&self.pool)
1366                .await?
1367                {
1368                    existing = Some((row.get("id"), row.get("key"), row.get("value")));
1369                }
1370
1371            if existing.is_none() && !canonical_key.is_empty() {
1372                // Canonical scan: match an existing key by canonical form.
1373                // Limits churn when historical keys were not canonicalized.
1374                let rows = sqlx::query(
1375                    "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",
1376                )
1377                .bind(category_clean)
1378                .fetch_all(&self.pool)
1379                .await?;
1380                for row in rows {
1381                    let existing_key: String = row.get("key");
1382                    if canonicalize_fact_key(&existing_key) == canonical_key {
1383                        existing = Some((row.get("id"), existing_key, row.get("value")));
1384                        break;
1385                    }
1386                }
1387            }
1388        }
1389
1390        // Semantic dedup: if key-based matching found nothing, check if any active
1391        // fact in the same category is semantically equivalent (different key, same
1392        // concept). Catches synonym keys like "editor" vs "preferred_editor".
1393        //
1394        // We compare key-only embeddings (category + readable key) rather than
1395        // full fact embeddings (which include value), because dedup should detect
1396        // that two keys refer to the same concept regardless of their values.
1397        if existing.is_none() {
1398            let category_facts = sqlx::query(
1399                "SELECT id, key, value FROM facts
1400                 WHERE LOWER(TRIM(category)) = ? AND superseded_at IS NULL AND archived_at IS NULL",
1401            )
1402            .bind(category_clean)
1403            .fetch_all(&self.pool)
1404            .await?;
1405
1406            let new_tokens: std::collections::HashSet<&str> =
1407                canonical_key.split('_').filter(|t| !t.is_empty()).collect();
1408
1409            // Guard against false semantic matches for keys that are
1410            // structurally similar but intentionally distinct.
1411            //
1412            // If keys share SOME tokens, have the same token count, but
1413            // differ in at least one token, they're variants of the same
1414            // base concept (e.g., "dog_name_old" vs "dog_name_new") — skip.
1415            //
1416            // But allow through:
1417            // - Keys that are a subset/superset (modifier pattern):
1418            //   "editor" vs "preferred_editor" — different count, proceed.
1419            // - Keys that are just reordered (same tokens, same count):
1420            //   "company_previous" vs "previous_company" — all shared, proceed.
1421            // - Keys with zero overlap: completely different concepts.
1422            let comparable: Vec<&sqlx::sqlite::SqliteRow> = category_facts
1423                .iter()
1424                .filter(|row| {
1425                    let existing_canonical = canonicalize_fact_key(&row.get::<String, _>("key"));
1426                    let existing_tokens: std::collections::HashSet<&str> = existing_canonical
1427                        .split('_')
1428                        .filter(|t| !t.is_empty())
1429                        .collect();
1430                    !keys_name_distinct_concepts(&new_tokens, &existing_tokens)
1431                })
1432                .collect();
1433
1434            // One embedder call for the new key and every comparable key: a
1435            // call per row costs a model hop each and made one write into a
1436            // large category take seconds.
1437            if !comparable.is_empty() {
1438                let mut texts = Vec::with_capacity(comparable.len() + 1);
1439                texts.push((None, build_dedup_key_text(category_clean, key_clean)));
1440                texts.extend(comparable.iter().map(|row| {
1441                    (
1442                        Some(row.get::<i64, _>("id")),
1443                        build_dedup_key_text(category_clean, &row.get::<String, _>("key")),
1444                    )
1445                }));
1446                if let Ok(vectors) = self.dedup_key_vectors(texts).await {
1447                    let new_vec = &vectors[0];
1448                    let mut best_match: Option<(i64, String, String, f32)> = None;
1449                    for (row, existing_vec) in comparable.iter().zip(&vectors[1..]) {
1450                        let sim = cosine_similarity(new_vec, existing_vec);
1451                        if sim > 0.85 && sim > best_match.as_ref().map_or(0.0, |m| m.3) {
1452                            best_match = Some((
1453                                row.get("id"),
1454                                row.get::<String, _>("key"),
1455                                row.get::<String, _>("value"),
1456                                sim,
1457                            ));
1458                        }
1459                    }
1460
1461                    if let Some((id, matched_key, matched_value, sim)) = best_match {
1462                        tracing::info!(
1463                            category = category_clean,
1464                            new_key = key_clean,
1465                            matched_key = matched_key.as_str(),
1466                            similarity = sim,
1467                            "Semantic dedup: matched existing fact by embedding similarity"
1468                        );
1469                        existing = Some((id, matched_key, matched_value));
1470                    }
1471                }
1472            }
1473        }
1474
1475        let key_for_write = existing
1476            .as_ref()
1477            .map(|(_, k, _)| k.clone())
1478            .unwrap_or_else(|| {
1479                if canonical_key.is_empty() {
1480                    key_clean.to_string()
1481                } else {
1482                    canonical_key.clone()
1483                }
1484            });
1485
1486        // Pre-compute embedding for the fact text (best-effort).
1487        let fact_text = build_fact_embedding_text(category_clean, &key_for_write, value);
1488        let embedding_blob = self
1489            .embedding_service
1490            .embed(fact_text)
1491            .await
1492            .ok()
1493            .map(|v| encode_embedding(&v));
1494
1495        let automated_source = !is_owner_authored_fact_source(source);
1496        // If an archived row already holds this (category, key):
1497        // - An automated extractor never resurrects an archived fact.
1498        // - An explicit owner write supersedes the archived row so the new
1499        //   active value inserts cleanly under `idx_facts_active_unique`.
1500        if existing.is_none() {
1501            let archived_id: Option<i64> = sqlx::query_scalar(
1502                "SELECT id FROM facts
1503                 WHERE LOWER(TRIM(category)) = ? AND key IN (?, ?)
1504                   AND superseded_at IS NULL AND archived_at IS NOT NULL
1505                 LIMIT 1",
1506            )
1507            .bind(category_clean)
1508            .bind(key_clean)
1509            .bind(&key_for_write)
1510            .fetch_optional(&self.pool)
1511            .await?;
1512            if let Some(archived_id) = archived_id {
1513                if automated_source {
1514                    tracing::debug!(
1515                        category = category_clean,
1516                        key = key_clean,
1517                        source,
1518                        "Automated fact write skipped: an archived fact exists for this key"
1519                    );
1520                    return Ok(());
1521                }
1522                sqlx::query(
1523                    "UPDATE facts SET superseded_at = ?, superseded_reason = 'replaced'
1524                     WHERE id = ? AND superseded_at IS NULL",
1525                )
1526                .bind(&now)
1527                .bind(archived_id)
1528                .execute(&self.pool)
1529                .await?;
1530            }
1531        }
1532        // Background extraction reads conversations after the fact: evidence
1533        // older than a later, different value of the same knowledge (its key,
1534        // in any category) is what the owner corrected since, and must not
1535        // replace or compete with the correction.
1536        if automated_source
1537            && let Some(seen) = first_seen_at
1538            && self
1539                .corrected_since(&[key_clean, &canonical_key, &key_for_write], value, seen)
1540                .await?
1541        {
1542            tracing::debug!(
1543                category = category_clean,
1544                key = key_clean,
1545                source,
1546                "Automated fact write skipped: a later value of this knowledge replaced it"
1547            );
1548            return Ok(());
1549        }
1550        if existing.is_none() && automated_source {
1551            // Knowledge the owner deleted, or a key merged away, must not be
1552            // brought back by background extraction, in any category the
1553            // extractor picks. Evidence newer than the retirement is the
1554            // owner saying it again, and is let through.
1555            if let Some(tombstone) = self
1556                .retired_knowledge(category_clean, &[key_clean, &key_for_write], value)
1557                .await?
1558                .into_iter()
1559                .find(|tombstone| first_seen_at.is_none_or(|seen| seen <= tombstone.retired_at))
1560            {
1561                tracing::debug!(
1562                    category = category_clean,
1563                    key = key_clean,
1564                    source,
1565                    retired_category = tombstone.category.as_str(),
1566                    retired_key = tombstone.key.as_str(),
1567                    "Automated fact write skipped: that knowledge was deleted or merged"
1568                );
1569                return Ok(());
1570            }
1571            // Paraphrased key, same knowledge: refresh the active fact rather
1572            // than storing a second copy that competes for recall slots. A
1573            // restatement is looked for in this category; the same value
1574            // under a reworded key in any category. Never across visibility
1575            // classes (`fold_scope_key`): an owner DM's private fact and an
1576            // app conversation's are one audience, a group channel its own.
1577            if let Some(new_vec) = embedding_blob
1578                .as_deref()
1579                .and_then(|blob| self.embedding_service.decode(blob).ok())
1580            {
1581                const ACTIVE_WITH_VECTOR: &str =
1582                    "SELECT id, category, key, value, source, embedding FROM facts
1583                     WHERE superseded_at IS NULL AND archived_at IS NULL AND embedding IS NOT NULL";
1584                let candidates = match super::fact_folds::fold_scope_key(&privacy_str, channel_id)
1585                {
1586                    super::fact_folds::FoldScope::OwnerPrivate => {
1587                        sqlx::query(sqlx::AssertSqlSafe(format!(
1588                            "{ACTIVE_WITH_VECTOR} AND {OWNER_PRIVATE_SCOPE_SQL}"
1589                        )))
1590                        .fetch_all(&self.pool)
1591                        .await?
1592                    }
1593                    super::fact_folds::FoldScope::Global => {
1594                        sqlx::query(sqlx::AssertSqlSafe(format!(
1595                            "{ACTIVE_WITH_VECTOR} AND LOWER(COALESCE(privacy, 'global')) = 'global'"
1596                        )))
1597                        .fetch_all(&self.pool)
1598                        .await?
1599                    }
1600                    super::fact_folds::FoldScope::Channel(channel) => {
1601                        sqlx::query(sqlx::AssertSqlSafe(format!(
1602                            "{ACTIVE_WITH_VECTOR} AND LOWER(COALESCE(privacy, 'global')) = ? AND channel_id IS ?"
1603                        )))
1604                        .bind(privacy_str.to_ascii_lowercase())
1605                        .bind(channel)
1606                        .fetch_all(&self.pool)
1607                        .await?
1608                    }
1609                };
1610                let new_value = crate::text::normalize_fact_value(value);
1611                let restated = candidates.iter().find_map(|row| {
1612                    let other_category: String = row.get("category");
1613                    let other_key: String = row.get("key");
1614                    let other_value: String = row.get("value");
1615                    let same_category = other_category.trim() == category_clean;
1616                    // Decode only what either rule could match.
1617                    if !same_category
1618                        && crate::text::normalize_fact_value(&other_value) != new_value
1619                    {
1620                        return None;
1621                    }
1622                    let blob: Vec<u8> = row.get("embedding");
1623                    let other_vec = self.embedding_service.decode(&blob).ok()?;
1624                    let sim = cosine_similarity(&new_vec, &other_vec);
1625                    let restates = same_category
1626                        && facts_are_restatements(
1627                            category_clean,
1628                            (key_clean, value),
1629                            (&other_key, &other_value),
1630                            sim,
1631                        );
1632                    (restates
1633                        || super::fact_folds::facts_hold_one_value(
1634                            (category_clean, key_clean, value),
1635                            (&other_category, &other_key, &other_value),
1636                            sim,
1637                        ))
1638                    .then(|| {
1639                        (
1640                            row.get::<i64, _>("id"),
1641                            other_key,
1642                            sim,
1643                            row.get::<String, _>("source"),
1644                        )
1645                    })
1646                });
1647                if let Some((id, matched_key, sim, matched_source)) = restated {
1648                    tracing::info!(
1649                        category = category_clean,
1650                        new_key = key_clean,
1651                        matched_key = matched_key.as_str(),
1652                        similarity = sim,
1653                        source,
1654                        "Automated fact write folded into existing restatement"
1655                    );
1656                    // The owner quoting what an extractor inferred raises the
1657                    // kept fact to the quote's rank, with the quote. A lower-
1658                    // or equal-rank automated restatement does NOT bump
1659                    // `updated_at` so background repetition cannot fake
1660                    // freshness or push old facts to the top of the UI.
1661                    if fact_source_rank(source) > fact_source_rank(&matched_source) {
1662                        sqlx::query(
1663                            "UPDATE facts SET updated_at = ?, source = ?,
1664                                 source_excerpt = COALESCE(?, source_excerpt) WHERE id = ?",
1665                        )
1666                        .bind(&now)
1667                        .bind(source)
1668                        .bind(source_excerpt)
1669                        .bind(id)
1670                        .execute(&self.pool)
1671                        .await?;
1672                    }
1673                    return Ok(());
1674                }
1675            }
1676        }
1677
1678        if let Some((old_id, _old_key, old_value)) = &existing {
1679            // Spacing and punctuation are not a new value: rewriting
1680            // "~/projects/" as "~/projects" refreshes the row instead of
1681            // replacing it and resetting its recall history. Case is kept
1682            // (paths and handles can be case-sensitive).
1683            let words = |text: &str| -> Vec<String> {
1684                text.split(|c: char| !c.is_alphanumeric())
1685                    .filter(|word| !word.is_empty())
1686                    .map(str::to_string)
1687                    .collect()
1688            };
1689            let old_value = if !words(value).is_empty() && words(old_value) == words(value) {
1690                value
1691            } else {
1692                old_value.as_str()
1693            };
1694            // If the value is different, mark old as superseded and insert new.
1695            //
1696            // Source priority guard: a write replaces a different value only
1697            // at equal or higher source rank. Background extractors read tool
1698            // output and paraphrase; they can lift a wrong value from a
1699            // hallucinated or stale message, so they never replace what the
1700            // owner stated or a value quoted from the owner's message (an
1701            // hour-old consolidation batch cannot revert a fresh correction).
1702            if old_value != value {
1703                let existing_source: Option<String> =
1704                    sqlx::query_scalar("SELECT source FROM facts WHERE id = ?")
1705                        .bind(old_id)
1706                        .fetch_optional(&self.pool)
1707                        .await?;
1708                if existing_source
1709                    .as_deref()
1710                    .is_some_and(|existing| fact_source_rank(existing) > fact_source_rank(source))
1711                {
1712                    tracing::info!(
1713                        category = category_clean,
1714                        key = key_clean,
1715                        existing_source = ?existing_source,
1716                        source,
1717                        "Fact write skipped: refusing to overwrite a fact from a closer source"
1718                    );
1719                    return Ok(());
1720                }
1721            }
1722            if old_value != value {
1723                sqlx::query("UPDATE facts SET superseded_at = ?, superseded_reason = 'replaced' WHERE id = ?")
1724                    .bind(&now)
1725                    .bind(old_id)
1726                    .execute(&self.pool)
1727                    .await?;
1728
1729                // Insert new fact with embedding — ignore duplicate entry errors (code 2067)
1730                // that can occur due to active-unique constraint race conditions.
1731                let insert_result = sqlx::query(
1732                    "INSERT INTO facts (category, key, value, source, created_at, updated_at, recall_count, channel_id, privacy, embedding, first_seen_at, source_excerpt)
1733                     VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?)",
1734                )
1735                .bind(category_clean)
1736                .bind(&key_for_write)
1737                .bind(value)
1738                .bind(source)
1739                .bind(&now)
1740                .bind(&now)
1741                .bind(channel_id)
1742                .bind(&privacy_str)
1743                .bind(&embedding_blob)
1744                .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1745                .bind(source_excerpt)
1746                .execute(&self.pool)
1747                .await;
1748
1749                match insert_result {
1750                    Ok(_) => {}
1751                    Err(sqlx::Error::Database(ref db_err))
1752                        if db_err.code().as_deref() == Some("2067") =>
1753                    {
1754                        // Duplicate entry — another active row already exists (concurrent upsert).
1755                        // Update the active row to "last write wins" without resurrecting the
1756                        // superseded row (which would violate partial unique indexes).
1757                        let updated = sqlx::query(
1758                            "UPDATE facts
1759                             SET value = ?, source = ?, updated_at = ?,
1760                                 channel_id = ?, privacy = ?,
1761                                 embedding = COALESCE(?, embedding),
1762                                 first_seen_at = COALESCE(?, first_seen_at),
1763                                 source_excerpt = COALESCE(?, source_excerpt)
1764                             WHERE category = ? AND key = ? AND superseded_at IS NULL",
1765                        )
1766                        .bind(value)
1767                        .bind(source)
1768                        .bind(&now)
1769                        .bind(channel_id)
1770                        .bind(&privacy_str)
1771                        .bind(&embedding_blob)
1772                        .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1773                        .bind(source_excerpt)
1774                        .bind(category_clean)
1775                        .bind(&key_for_write)
1776                        .execute(&self.pool)
1777                        .await?;
1778
1779                        // Legacy fallback: if no active row exists (e.g., old UNIQUE(category,key)
1780                        // constraint), keep data consistent by updating in-place.
1781                        if updated.rows_affected() == 0 {
1782                            sqlx::query(
1783                                "UPDATE facts
1784                                 SET value = ?, source = ?, updated_at = ?, superseded_at = NULL, superseded_reason = NULL, folded_into = NULL,
1785                                     channel_id = ?, privacy = ?,
1786                                     embedding = COALESCE(?, embedding),
1787                                     first_seen_at = COALESCE(?, first_seen_at),
1788                                     source_excerpt = COALESCE(?, source_excerpt)
1789                                 WHERE id = ?",
1790                            )
1791                            .bind(value)
1792                            .bind(source)
1793                            .bind(&now)
1794                            .bind(channel_id)
1795                            .bind(&privacy_str)
1796                            .bind(&embedding_blob)
1797                            .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1798                            .bind(source_excerpt)
1799                            .bind(old_id)
1800                            .execute(&self.pool)
1801                            .await?;
1802                        }
1803                    }
1804                    Err(e) => return Err(e.into()),
1805                }
1806                if fact_source_rank(source) > 0 {
1807                    self.supersede_copies(
1808                        *old_id,
1809                        &key_for_write,
1810                        old_value,
1811                        SupersededReason::Replaced,
1812                        fact_source_rank(source),
1813                    )
1814                    .await?;
1815                }
1816            } else {
1817                // Same value — update timestamp and backfill embedding.
1818                // A restatement never lowers the row's source rank; a closer
1819                // source raises it and brings its quote.
1820                let existing_source: Option<String> =
1821                    sqlx::query_scalar("SELECT source FROM facts WHERE id = ?")
1822                        .bind(old_id)
1823                        .fetch_optional(&self.pool)
1824                        .await?;
1825                let existing_rank = existing_source.as_deref().map_or(0, fact_source_rank);
1826                if fact_source_rank(source) < existing_rank {
1827                    // Lower-rank automated restatement: backfill a missing
1828                    // embedding, but do NOT bump `updated_at` so background
1829                    // re-extraction does not artificially renew freshness.
1830                    sqlx::query("UPDATE facts SET embedding = COALESCE(embedding, ?) WHERE id = ?")
1831                        .bind(&embedding_blob)
1832                        .bind(old_id)
1833                        .execute(&self.pool)
1834                        .await?;
1835                } else if fact_source_rank(source) > existing_rank {
1836                    sqlx::query(
1837                        "UPDATE facts SET source = ?, updated_at = ?, embedding = COALESCE(embedding, ?), first_seen_at = COALESCE(first_seen_at, ?), source_excerpt = COALESCE(?, source_excerpt) WHERE id = ?",
1838                    )
1839                    .bind(source)
1840                    .bind(&now)
1841                    .bind(&embedding_blob)
1842                    .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1843                    .bind(source_excerpt)
1844                    .bind(old_id)
1845                    .execute(&self.pool)
1846                    .await?;
1847                } else {
1848                    sqlx::query(
1849                        "UPDATE facts SET source = ?, updated_at = ?, embedding = COALESCE(embedding, ?), first_seen_at = COALESCE(first_seen_at, ?), source_excerpt = COALESCE(source_excerpt, ?) WHERE id = ?",
1850                    )
1851                    .bind(source)
1852                    .bind(&now)
1853                    .bind(&embedding_blob)
1854                    .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1855                    .bind(source_excerpt)
1856                    .bind(old_id)
1857                    .execute(&self.pool)
1858                    .await?;
1859                }
1860            }
1861        } else {
1862            // No existing fact - insert new with embedding
1863            // Ignore duplicate entry errors (code 2067) from concurrent inserts
1864            let insert_result = sqlx::query(
1865                "INSERT INTO facts (category, key, value, source, created_at, updated_at, recall_count, channel_id, privacy, embedding, first_seen_at, source_excerpt)
1866                 VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?)",
1867            )
1868            .bind(category_clean)
1869            .bind(&key_for_write)
1870            .bind(value)
1871            .bind(source)
1872            .bind(&now)
1873            .bind(&now)
1874            .bind(channel_id)
1875            .bind(&privacy_str)
1876            .bind(&embedding_blob)
1877            .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1878            .bind(source_excerpt)
1879            .execute(&self.pool)
1880            .await;
1881
1882            match insert_result {
1883                Ok(_) => {}
1884                Err(sqlx::Error::Database(ref db_err))
1885                    if db_err.code().as_deref() == Some("2067") =>
1886                {
1887                    // Duplicate entry — another active row already exists (concurrent upsert).
1888                    // Update the active row to "last write wins".
1889                    let updated = sqlx::query(
1890                        "UPDATE facts
1891                         SET value = ?, source = ?, updated_at = ?,
1892                             channel_id = ?, privacy = ?,
1893                             embedding = COALESCE(?, embedding),
1894                             first_seen_at = COALESCE(?, first_seen_at),
1895                             source_excerpt = COALESCE(?, source_excerpt)
1896                         WHERE category = ? AND key = ? AND superseded_at IS NULL",
1897                    )
1898                    .bind(value)
1899                    .bind(source)
1900                    .bind(&now)
1901                    .bind(channel_id)
1902                    .bind(&privacy_str)
1903                    .bind(&embedding_blob)
1904                    .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1905                    .bind(source_excerpt)
1906                    .bind(category_clean)
1907                    .bind(&key_for_write)
1908                    .execute(&self.pool)
1909                    .await?;
1910
1911                    if updated.rows_affected() == 0 {
1912                        // If there is no active row, update the most recent version in-place.
1913                        // This can happen on legacy schemas where a superseded row still blocks
1914                        // inserts (old UNIQUE(category,key) constraint).
1915                        if let Some(row) = sqlx::query(
1916                            "SELECT id FROM facts WHERE category = ? AND key = ? ORDER BY updated_at DESC LIMIT 1",
1917                        )
1918                        .bind(category_clean)
1919                        .bind(&key_for_write)
1920                        .fetch_optional(&self.pool)
1921                        .await?
1922                        {
1923                            let id: i64 = row.get("id");
1924                            sqlx::query(
1925                                "UPDATE facts
1926                                 SET value = ?, source = ?, updated_at = ?, superseded_at = NULL, superseded_reason = NULL, folded_into = NULL,
1927                                     channel_id = ?, privacy = ?,
1928                                     embedding = COALESCE(?, embedding),
1929                                     first_seen_at = COALESCE(?, first_seen_at),
1930                                     source_excerpt = COALESCE(?, source_excerpt)
1931                                 WHERE id = ?",
1932                            )
1933                            .bind(value)
1934                            .bind(source)
1935                            .bind(&now)
1936                            .bind(channel_id)
1937                            .bind(&privacy_str)
1938                            .bind(&embedding_blob)
1939                            .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
1940                            .bind(source_excerpt)
1941                            .bind(id)
1942                            .execute(&self.pool)
1943                            .await?;
1944                        }
1945                    }
1946                }
1947                Err(e) => return Err(e.into()),
1948            }
1949        }
1950
1951        // ── Post-store conflict sweep ──────────────────────────────────
1952        //
1953        // When the owner stores a fact through remember_fact (source ==
1954        // "agent"), an active row in the same category whose key names the
1955        // same attribute in canonical form ("dog name" / "dog_name" left by
1956        // an older, uncanonicalized write) and holds another value is stale:
1957        // it is superseded. Identity is the canonical key only. Facts under
1958        // different keys are never superseded here, whatever words or
1959        // embedding they share ("favorite_drink: green tea" must never
1960        // retire "allergy: green tea").
1961        if matches!(source, "agent" | "user_stated") {
1962            let canonical_written = canonicalize_fact_key(&key_for_write);
1963            let others = sqlx::query(
1964                "SELECT id, key, value FROM facts
1965                         WHERE LOWER(TRIM(category)) = ? AND superseded_at IS NULL AND archived_at IS NULL
1966                           AND key != ?",
1967            )
1968            .bind(category_clean)
1969            .bind(&key_for_write)
1970            .fetch_all(&self.pool)
1971            .await
1972            .unwrap_or_default();
1973
1974            for row in &others {
1975                let other_id: i64 = row.get("id");
1976                let other_key: String = row.get("key");
1977                let other_value: String = row.get("value");
1978                if canonicalize_fact_key(&other_key) != canonical_written || other_value == value {
1979                    continue;
1980                }
1981                tracing::info!(
1982                    category = category_clean,
1983                    new_key = key_clean,
1984                    new_value = value,
1985                    conflicting_key = other_key.as_str(),
1986                    conflicting_value = other_value.as_str(),
1987                    "Conflict sweep: superseding stale fact under the same canonical key"
1988                );
1989                let _ = sqlx::query(
1990                    "UPDATE facts SET superseded_at = ?, superseded_reason = 'replaced' WHERE id = ?",
1991                )
1992                .bind(&now)
1993                .bind(other_id)
1994                .execute(&self.pool)
1995                .await;
1996            }
1997        }
1998
1999        if let Err(error) = self.sync_fact_memory_written_at(category_clean, &now).await {
2000            tracing::warn!(%error, category = category_clean, "Deferred fact memory projection");
2001        }
2002        Ok(())
2003    }
2004
2005    async fn get_facts(&self, category: Option<&str>) -> anyhow::Result<Vec<Fact>> {
2006        // Only return current (non-superseded, non-archived) facts
2007        let rows = if let Some(cat) = category {
2008            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")
2009                .bind(cat)
2010                .fetch_all(&self.pool)
2011                .await?
2012        } else {
2013            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")
2014                .fetch_all(&self.pool)
2015                .await?
2016        };
2017
2018        let mut facts = Vec::with_capacity(rows.len());
2019        for row in rows {
2020            facts.push(Self::row_to_fact(&row));
2021        }
2022        Ok(facts)
2023    }
2024
2025    async fn get_relevant_facts(&self, query: &str, max: usize) -> anyhow::Result<Vec<Fact>> {
2026        // Load facts; vectors come from the embedding index, and only facts
2027        // it has none for read their own blob (`unindexed_fact_scores`).
2028        let rows = sqlx::query(
2029            "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
2030             FROM facts WHERE superseded_at IS NULL AND archived_at IS NULL ORDER BY updated_at DESC",
2031        )
2032        .fetch_all(&self.pool)
2033        .await?;
2034
2035        let all_facts: Vec<Fact> = rows.iter().map(Self::row_to_fact).collect();
2036
2037        if all_facts.is_empty() || query.trim().is_empty() {
2038            let mut facts = all_facts;
2039            facts.truncate(max);
2040            let canonical = self.canonical_personal_facts().await.unwrap_or_default();
2041            return Ok(prefer_canonical_facts(canonical, facts, query, max));
2042        }
2043
2044        // Embed the query
2045        let query_vec = match self.embedding_service.embed(query.to_string()).await {
2046            Ok(v) => v,
2047            Err(e) => {
2048                tracing::warn!(
2049                    "Failed to embed query for passive fact filtering; using lexical matches: {}",
2050                    e
2051                );
2052                let facts = lexical_relevant_facts(&all_facts, query, max);
2053                let canonical = self.canonical_personal_facts().await.unwrap_or_default();
2054                return Ok(prefer_canonical_facts(canonical, facts, query, max));
2055            }
2056        };
2057
2058        let now = Utc::now();
2059        let query_lower = query.to_lowercase();
2060        let tokens = query_tokens(&query_lower);
2061        let indexed_scores = self
2062            .fact_embedding_scores(&query_vec, rows.len())
2063            .await
2064            .unwrap_or_default();
2065        let fts_fact_ids: std::collections::HashSet<i64> = self
2066            .search_memory_claims(
2067                query,
2068                None,
2069                ChannelVisibility::Internal,
2070                true,
2071                max.saturating_mul(4).max(16),
2072            )
2073            .await
2074            .unwrap_or_default()
2075            .into_iter()
2076            .filter_map(|claim| claim.source_fact_id)
2077            .collect();
2078        let graph_fact_ids = self
2079            .graph_fact_ids_for_query(query)
2080            .await
2081            .unwrap_or_default();
2082
2083        // Score facts using stored embeddings, with a small recency boost for sorting.
2084        // IMPORTANT: the recency boost must not change which facts pass the semantic threshold.
2085        let fallback_scores = self
2086            .unindexed_fact_scores(&query_vec, all_facts.iter().map(|f| f.id), &indexed_scores)
2087            .await;
2088        let mut candidates: Vec<(usize, f32, f32, bool)> = Vec::with_capacity(rows.len());
2089        for (i, fact) in all_facts.iter().enumerate() {
2090            let freshness = fact_freshness_boost(now, fact.updated_at);
2091
2092            let semantic = indexed_scores
2093                .get(&fact.id)
2094                .or_else(|| fallback_scores.get(&fact.id))
2095                .copied();
2096            let lexical = if fts_fact_ids.contains(&fact.id) {
2097                FACT_LEXICAL_MAX_SCORE
2098            } else {
2099                lexical_fallback_score(&query_lower, &tokens, fact)
2100            };
2101            if let Some(semantic) = semantic {
2102                if semantic > FACT_SEMANTIC_MIN_SCORE {
2103                    candidates.push((
2104                        i,
2105                        semantic,
2106                        hybrid_fact_score(
2107                            fact,
2108                            semantic,
2109                            lexical,
2110                            graph_fact_ids.contains(&fact.id),
2111                            freshness,
2112                        ),
2113                        true,
2114                    ));
2115                    continue;
2116                }
2117                // Below semantic threshold — try lexical as fallback for keyword matches
2118                let best = semantic.max(lexical);
2119                let is_semantic = best == semantic;
2120                candidates.push((
2121                    i,
2122                    best,
2123                    hybrid_fact_score(
2124                        fact,
2125                        semantic,
2126                        lexical,
2127                        graph_fact_ids.contains(&fact.id),
2128                        freshness,
2129                    ),
2130                    is_semantic,
2131                ));
2132                continue;
2133            }
2134
2135            // Missing/invalid embedding: fall back to cheap lexical relevance so
2136            // freshly saved facts can still be retrieved during embedding backfill.
2137            candidates.push((
2138                i,
2139                lexical,
2140                hybrid_fact_score(
2141                    fact,
2142                    0.0,
2143                    lexical,
2144                    graph_fact_ids.contains(&fact.id),
2145                    freshness,
2146                ),
2147                false,
2148            ));
2149        }
2150        candidates.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));
2151
2152        // Overfetch, then drop paraphrases of a fact ranked above them, so
2153        // copies of one preference do not fill the slots of distinct facts.
2154        let overfetch = max.saturating_mul(RECALL_DIVERSITY_OVERFETCH);
2155        let mut relevant: Vec<Fact> = Vec::with_capacity(overfetch.min(all_facts.len()));
2156        let mut seen_ids: std::collections::HashSet<i64> = std::collections::HashSet::new();
2157        for (i, base_score, _sort_score, is_semantic) in candidates.into_iter() {
2158            if relevant.len() >= overfetch {
2159                break;
2160            }
2161            let min_score = if is_semantic {
2162                FACT_SEMANTIC_MIN_SCORE
2163            } else {
2164                FACT_LEXICAL_MIN_SCORE
2165            };
2166            if base_score > min_score {
2167                let fact = all_facts[i].clone();
2168                if seen_ids.insert(fact.id) {
2169                    relevant.push(fact);
2170                }
2171            }
2172        }
2173        let relevant = self.diverse_facts(relevant, max).await;
2174
2175        let canonical = self.canonical_personal_facts().await.unwrap_or_default();
2176        Ok(prefer_canonical_facts(canonical, relevant, query, max))
2177    }
2178
2179    async fn get_relevant_facts_for_channel(
2180        &self,
2181        query: &str,
2182        max: usize,
2183        channel_id: Option<&str>,
2184        visibility: ChannelVisibility,
2185        requester_is_owner: bool,
2186    ) -> anyhow::Result<Vec<Fact>> {
2187        // In DM/Internal contexts, use semantic relevance search so that only
2188        // facts related to the current query are injected into the prompt.
2189        // Previously this called get_facts(None) which returned ALL facts
2190        // without filtering, causing unrelated facts to bleed into context.
2191        //
2192        // SECURITY: only the OWNER gets the unfiltered graph in a DM. A non-owner
2193        // (allowlisted Guest) DMing the bot must NOT receive Private or
2194        // other-channel facts — fall through to the privacy filter below, same as
2195        // a group channel. Without this gate, a guest's prompt would be injected
2196        // with the owner's private memory.
2197        if requester_is_owner
2198            && matches!(
2199                visibility,
2200                ChannelVisibility::Private | ChannelVisibility::Internal
2201            )
2202        {
2203            return self.get_relevant_facts(query, max).await;
2204        }
2205
2206        // PublicExternal: do NOT inject any stored facts (treat as untrusted).
2207        if matches!(visibility, ChannelVisibility::PublicExternal) {
2208            return Ok(vec![]);
2209        }
2210
2211        // Public/PrivateGroup: global + same-channel facts (no private, no other-channel)
2212        let rows = sqlx::query(
2213            "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
2214             FROM facts WHERE superseded_at IS NULL AND archived_at IS NULL ORDER BY updated_at DESC",
2215        )
2216        .fetch_all(&self.pool)
2217        .await?;
2218
2219        // One visibility rule for every surface that shows a fact
2220        // (`memory_visible`): what the prompt is given here is what a
2221        // memory search would show this audience.
2222        let all_facts: Vec<Fact> = rows.iter().map(Self::row_to_fact).collect();
2223        let filtered_indices: Vec<usize> = all_facts
2224            .iter()
2225            .enumerate()
2226            .filter(|(_, f)| {
2227                super::memory_visible(
2228                    self.channels.as_ref(),
2229                    f.privacy,
2230                    f.channel_id.as_deref(),
2231                    channel_id,
2232                    visibility,
2233                    requester_is_owner,
2234                )
2235            })
2236            .map(|(i, _)| i)
2237            .collect();
2238
2239        let filtered: Vec<Fact> = filtered_indices
2240            .iter()
2241            .map(|&i| all_facts[i].clone())
2242            .collect();
2243
2244        if filtered.is_empty() || query.trim().is_empty() {
2245            let mut facts = filtered;
2246            facts.truncate(max);
2247            return Ok(facts);
2248        }
2249
2250        // Apply semantic filtering using stored embeddings
2251        let query_vec = match self.embedding_service.embed(query.to_string()).await {
2252            Ok(v) => v,
2253            Err(_) => {
2254                let facts = lexical_relevant_facts(&filtered, query, max);
2255                return Ok(facts);
2256            }
2257        };
2258
2259        let now = Utc::now();
2260        let query_lower = query.to_lowercase();
2261        let tokens = query_tokens(&query_lower);
2262        let indexed_scores = self
2263            .fact_embedding_scores(&query_vec, rows.len())
2264            .await
2265            .unwrap_or_default();
2266        let fts_fact_ids: std::collections::HashSet<i64> = self
2267            .search_memory_claims(
2268                query,
2269                channel_id,
2270                visibility,
2271                requester_is_owner,
2272                max.saturating_mul(4).max(16),
2273            )
2274            .await
2275            .unwrap_or_default()
2276            .into_iter()
2277            .filter_map(|claim| claim.source_fact_id)
2278            .collect();
2279        let graph_fact_ids = self
2280            .graph_fact_ids_for_query(query)
2281            .await
2282            .unwrap_or_default();
2283
2284        let fallback_scores = self
2285            .unindexed_fact_scores(&query_vec, filtered.iter().map(|f| f.id), &indexed_scores)
2286            .await;
2287        let mut candidates: Vec<(usize, f32, f32, bool)> = Vec::with_capacity(filtered.len());
2288        for (fi, fact) in filtered.iter().enumerate() {
2289            let freshness = fact_freshness_boost(now, fact.updated_at);
2290
2291            let semantic = indexed_scores
2292                .get(&fact.id)
2293                .or_else(|| fallback_scores.get(&fact.id))
2294                .copied();
2295            let lexical = if fts_fact_ids.contains(&fact.id) {
2296                FACT_LEXICAL_MAX_SCORE
2297            } else {
2298                lexical_fallback_score(&query_lower, &tokens, fact)
2299            };
2300            if let Some(semantic) = semantic {
2301                if semantic > FACT_SEMANTIC_MIN_SCORE {
2302                    candidates.push((
2303                        fi,
2304                        semantic,
2305                        hybrid_fact_score(
2306                            fact,
2307                            semantic,
2308                            lexical,
2309                            graph_fact_ids.contains(&fact.id),
2310                            freshness,
2311                        ),
2312                        true,
2313                    ));
2314                    continue;
2315                }
2316                // Below semantic threshold — try lexical as fallback for keyword matches
2317                let best = semantic.max(lexical);
2318                let is_semantic = best == semantic;
2319                candidates.push((
2320                    fi,
2321                    best,
2322                    hybrid_fact_score(
2323                        fact,
2324                        semantic,
2325                        lexical,
2326                        graph_fact_ids.contains(&fact.id),
2327                        freshness,
2328                    ),
2329                    is_semantic,
2330                ));
2331                continue;
2332            }
2333
2334            candidates.push((
2335                fi,
2336                lexical,
2337                hybrid_fact_score(
2338                    fact,
2339                    0.0,
2340                    lexical,
2341                    graph_fact_ids.contains(&fact.id),
2342                    freshness,
2343                ),
2344                false,
2345            ));
2346        }
2347        candidates.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));
2348
2349        let overfetch = max.saturating_mul(RECALL_DIVERSITY_OVERFETCH);
2350        let mut relevant: Vec<Fact> = Vec::with_capacity(overfetch.min(filtered.len()));
2351        let mut seen_ids: std::collections::HashSet<i64> = std::collections::HashSet::new();
2352        for (fi, base_score, _sort_score, is_semantic) in candidates.into_iter() {
2353            if relevant.len() >= overfetch {
2354                break;
2355            }
2356            let min_score = if is_semantic {
2357                FACT_SEMANTIC_MIN_SCORE
2358            } else {
2359                FACT_LEXICAL_MIN_SCORE
2360            };
2361            if base_score > min_score {
2362                let fact = filtered[fi].clone();
2363                if seen_ids.insert(fact.id) {
2364                    relevant.push(fact);
2365                }
2366            }
2367        }
2368
2369        Ok(self.diverse_facts(relevant, max).await)
2370    }
2371
2372    async fn update_fact_privacy(&self, fact_id: i64, privacy: FactPrivacy) -> anyhow::Result<()> {
2373        sqlx::query("UPDATE facts SET privacy = ? WHERE id = ?")
2374            .bind(privacy.to_string())
2375            .bind(fact_id)
2376            .execute(&self.pool)
2377            .await?;
2378        if let Err(error) = self.project_fact_memory(fact_id).await {
2379            tracing::warn!(%error, fact_id, "Deferred fact privacy projection");
2380        }
2381        Ok(())
2382    }
2383
2384    async fn delete_fact(&self, fact_id: i64) -> anyhow::Result<()> {
2385        // A canonical personal-memory record reaches the model and UI under a
2386        // synthetic negative id; forgetting it retracts that record AND retires
2387        // any shadowed flat owner-profile rows for the same canonical key so
2388        // they cannot resurrect on the next snapshot or recall.
2389        if fact_id < 0 {
2390            let projected = self
2391                .canonical_personal_facts()
2392                .await
2393                .unwrap_or_default()
2394                .into_iter()
2395                .find(|fact| fact.id == fact_id);
2396            let retracted = self
2397                .retract_canonical_projection(fact_id, "owner_forget")
2398                .await?;
2399            if retracted
2400                && let Some(fact) = projected
2401                && fact.category == "user"
2402            {
2403                let now = Utc::now().to_rfc3339();
2404                let target_family = crate::text::owner_projection_family(&fact.key);
2405                let _ = self
2406                    .record_tombstone(
2407                        "user",
2408                        &target_family,
2409                        &fact.value,
2410                        SupersededReason::Deleted,
2411                        &now,
2412                    )
2413                    .await;
2414                let flat_rows: Vec<(i64, String, String, String)> = sqlx::query_as(
2415                    "SELECT id, LOWER(TRIM(category)), LOWER(TRIM(key)), value FROM facts
2416                     WHERE superseded_at IS NULL
2417                       AND LOWER(TRIM(category)) IN ('user', 'personal', 'profile', 'preference')",
2418                )
2419                .fetch_all(&self.pool)
2420                .await?;
2421                for (flat_id, flat_cat, flat_key, flat_val) in flat_rows {
2422                    let is_shadowed_cat = is_owner_profile_category(&flat_cat)
2423                        || (flat_cat == "preference"
2424                            && crate::text::is_owner_profile_key(&flat_key));
2425                    if is_shadowed_cat
2426                        && crate::text::owner_projection_family(&flat_key) == target_family
2427                    {
2428                        sqlx::query(
2429                            "UPDATE facts SET superseded_at = ?, superseded_reason = 'deleted', archived_at = NULL WHERE id = ?",
2430                        )
2431                        .bind(&now)
2432                        .bind(flat_id)
2433                        .execute(&self.pool)
2434                        .await?;
2435                        if let Err(error) = self.project_fact_memory(flat_id).await {
2436                            tracing::warn!(%error, fact_id = flat_id, "Deferred shadowed-fact deletion projection");
2437                        }
2438                        let _ = self
2439                            .record_tombstone(
2440                                &flat_cat,
2441                                &flat_key,
2442                                &flat_val,
2443                                SupersededReason::Deleted,
2444                                &now,
2445                            )
2446                            .await;
2447                    }
2448                }
2449            }
2450            return Ok(());
2451        }
2452        let now = Utc::now().to_rfc3339();
2453        let forgotten: Option<(String, String, String)> = sqlx::query_as(
2454            "SELECT LOWER(TRIM(category)), LOWER(TRIM(key)), value FROM facts
2455             WHERE id = ? AND superseded_at IS NULL",
2456        )
2457        .bind(fact_id)
2458        .fetch_optional(&self.pool)
2459        .await?;
2460        sqlx::query(
2461            "UPDATE facts SET superseded_at = ?, superseded_reason = 'deleted', archived_at = NULL WHERE id = ?",
2462        )
2463        .bind(&now)
2464        .bind(fact_id)
2465        .execute(&self.pool)
2466        .await?;
2467        if let Err(error) = self.project_fact_memory(fact_id).await {
2468            tracing::warn!(%error, fact_id, "Deferred deleted-fact projection");
2469        }
2470        if let Some((category, key, value)) = forgotten {
2471            let _ = self
2472                .record_tombstone(&category, &key, &value, SupersededReason::Deleted, &now)
2473                .await;
2474            self.supersede_copies(fact_id, &key, &value, SupersededReason::Deleted, 2)
2475                .await?;
2476            if is_owner_profile_category(&category)
2477                || (category == "preference" && crate::text::is_owner_profile_key(&key))
2478            {
2479                self.retract_owner_profile_key(&key, "owner_forget").await?;
2480            }
2481        }
2482        Ok(())
2483    }
2484
2485    async fn delete_fact_by_key(&self, category: &str, key: &str) -> anyhow::Result<bool> {
2486        let now = Utc::now().to_rfc3339();
2487        // Canonicalize: lowercase, trim, strip [brackets]
2488        let cat_clean = category.trim().to_lowercase();
2489        let key_clean = key.trim().to_lowercase();
2490        let deleted: Vec<(i64, String, String)> = sqlx::query_as(
2491            "SELECT id, key, value FROM facts WHERE LOWER(TRIM(category)) = ? AND LOWER(TRIM(key)) = ? AND superseded_at IS NULL",
2492        )
2493        .bind(&cat_clean)
2494        .bind(&key_clean)
2495        .fetch_all(&self.pool)
2496        .await?;
2497        let ids: Vec<i64> = deleted.iter().map(|(id, _, _)| *id).collect();
2498        let result = sqlx::query(
2499            "UPDATE facts SET superseded_at = ?, superseded_reason = 'deleted', archived_at = NULL WHERE LOWER(TRIM(category)) = ? AND LOWER(TRIM(key)) = ? AND superseded_at IS NULL",
2500        )
2501        .bind(&now)
2502        .bind(&cat_clean)
2503        .bind(&key_clean)
2504        .execute(&self.pool)
2505        .await?;
2506        for id in ids {
2507            if let Err(error) = self.project_fact_memory(id).await {
2508                tracing::warn!(%error, fact_id = id, "Deferred deleted-fact projection");
2509            }
2510        }
2511        // The owner's profile also lives in the canonical store, which the
2512        // prompt renders as its own block: forgetting the legacy row alone
2513        // left the old value in front of the model.
2514        for (id, key, value) in &deleted {
2515            let _ = self
2516                .record_tombstone(&cat_clean, key, value, SupersededReason::Deleted, &now)
2517                .await;
2518            self.supersede_copies(*id, key, value, SupersededReason::Deleted, 2)
2519                .await?;
2520        }
2521        let canonical = (is_owner_profile_category(&cat_clean)
2522            || (cat_clean == "preference" && crate::text::is_owner_profile_key(&key_clean)))
2523            && self
2524                .retract_owner_profile_key(&key_clean, "owner_forget")
2525                .await?;
2526        Ok(result.rows_affected() > 0 || canonical)
2527    }
2528
2529    async fn update_fact_value(&self, fact_id: i64, value: &str) -> anyhow::Result<Option<Fact>> {
2530        let trimmed = value.trim();
2531        if trimmed.is_empty() {
2532            return Ok(None);
2533        }
2534        if fact_id < 0 {
2535            return self
2536                .update_canonical_projection(fact_id, trimmed, "user_stated")
2537                .await;
2538        }
2539        let _upsert_guard = self.fact_upsert_lock.lock().await;
2540        let row = sqlx::query(
2541            "SELECT category, key FROM facts WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL",
2542        )
2543        .bind(fact_id)
2544        .fetch_optional(&self.pool)
2545        .await?;
2546        let Some(row) = row else {
2547            return Ok(None);
2548        };
2549        let category: String = row.get("category");
2550        let key: String = row.get("key");
2551        let now = Utc::now().to_rfc3339();
2552        let fact_text = build_fact_embedding_text(&category, &key, trimmed);
2553        let embedding_blob = self
2554            .embedding_service
2555            .embed(fact_text)
2556            .await
2557            .ok()
2558            .map(|v| encode_embedding(&v));
2559        sqlx::query(
2560            "UPDATE facts
2561             SET value = ?, source = 'user_stated', updated_at = ?,
2562                 embedding = COALESCE(?, embedding)
2563             WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL",
2564        )
2565        .bind(trimmed)
2566        .bind(&now)
2567        .bind(&embedding_blob)
2568        .bind(fact_id)
2569        .execute(&self.pool)
2570        .await?;
2571        if let Err(error) = self.project_fact_memory(fact_id).await {
2572            tracing::warn!(%error, fact_id, "Deferred edited-fact projection");
2573        }
2574        let updated = sqlx::query(
2575            "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
2576             FROM facts WHERE id = ?",
2577        )
2578        .bind(fact_id)
2579        .fetch_optional(&self.pool)
2580        .await?;
2581        Ok(updated.as_ref().map(Self::row_to_fact))
2582    }
2583
2584    async fn archive_fact(&self, fact_id: i64) -> anyhow::Result<bool> {
2585        if fact_id < 0 {
2586            return Ok(false);
2587        }
2588        let now = Utc::now().to_rfc3339();
2589        let res = sqlx::query(
2590            "UPDATE facts SET archived_at = ?
2591             WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL",
2592        )
2593        .bind(&now)
2594        .bind(fact_id)
2595        .execute(&self.pool)
2596        .await?;
2597        if res.rows_affected() > 0 {
2598            // Invalidate the archived fact's claim projection, embedding, and graph edges.
2599            if let Err(error) = self.project_fact_memory(fact_id).await {
2600                tracing::warn!(%error, fact_id, "Deferred archived-fact projection");
2601            }
2602            return Ok(true);
2603        }
2604        Ok(false)
2605    }
2606
2607    async fn restore_fact(&self, fact_id: i64) -> anyhow::Result<Option<Fact>> {
2608        if fact_id < 0 {
2609            return Ok(None);
2610        }
2611        let now = Utc::now().to_rfc3339();
2612        let res = sqlx::query(
2613            "UPDATE facts SET archived_at = NULL, expires_at = NULL, updated_at = ?
2614             WHERE id = ? AND superseded_at IS NULL AND archived_at IS NOT NULL",
2615        )
2616        .bind(&now)
2617        .bind(fact_id)
2618        .execute(&self.pool)
2619        .await?;
2620        if res.rows_affected() == 0 {
2621            return Ok(None);
2622        }
2623        if let Err(error) = self.project_fact_memory(fact_id).await {
2624            tracing::warn!(%error, fact_id, "Deferred restored-fact projection");
2625        }
2626        let restored = sqlx::query(
2627            "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
2628             FROM facts WHERE id = ?",
2629        )
2630        .bind(fact_id)
2631        .fetch_optional(&self.pool)
2632        .await?;
2633        Ok(restored.as_ref().map(Self::row_to_fact))
2634    }
2635
2636    async fn get_archived_facts(&self, limit: usize) -> anyhow::Result<Vec<Fact>> {
2637        let rows = sqlx::query(
2638            "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
2639             FROM facts
2640             WHERE superseded_at IS NULL AND archived_at IS NOT NULL
2641             ORDER BY archived_at DESC
2642             LIMIT ?",
2643        )
2644        .bind(limit.min(500) as i64)
2645        .fetch_all(&self.pool)
2646        .await?;
2647        Ok(rows.iter().map(Self::row_to_fact).collect())
2648    }
2649
2650    async fn archive_expired_facts(&self, now: DateTime<Utc>) -> anyhow::Result<u64> {
2651        let now_str = now.to_rfc3339();
2652        let expired: Vec<i64> = sqlx::query_scalar(
2653            "SELECT id FROM facts
2654             WHERE superseded_at IS NULL AND archived_at IS NULL
2655               AND expires_at IS NOT NULL AND expires_at <= ?",
2656        )
2657        .bind(&now_str)
2658        .fetch_all(&self.pool)
2659        .await?;
2660        if expired.is_empty() {
2661            return Ok(0);
2662        }
2663        let mut count = 0u64;
2664        for id in expired {
2665            if self.archive_fact(id).await? {
2666                count += 1;
2667            }
2668        }
2669        if count > 0 {
2670            tracing::info!(count, "Archived expired facts");
2671        }
2672        Ok(count)
2673    }
2674
2675    async fn detect_fact_overlaps(&self) -> anyhow::Result<std::collections::HashMap<i64, i64>> {
2676        let mut candidates = self.fold_candidates().await?;
2677        // Include canonical owner facts so flat duplicates (e.g. preference/address_as)
2678        // can be flagged against canonical user/preferred_name, and drop flat rows
2679        // already shadowed by canonical owner facts so overlap pointers always
2680        // reference visible items.
2681        let canonical = self.canonical_personal_facts().await.unwrap_or_default();
2682        let canonical_owner_keys: std::collections::HashSet<String> = canonical
2683            .iter()
2684            .filter(|f| f.category == "user")
2685            .map(|f| crate::text::owner_projection_family(&f.key))
2686            .collect();
2687        candidates.retain(|c| {
2688            let cat = c.category.trim().to_ascii_lowercase();
2689            let shadowed_owner = (is_owner_profile_category(&cat)
2690                || (cat == "preference" && crate::text::is_owner_profile_key(&c.key)))
2691                && canonical_owner_keys.contains(&crate::text::owner_projection_family(&c.key));
2692            !shadowed_owner
2693        });
2694        for fact in canonical.into_iter().filter(|f| f.category == "user") {
2695            candidates.push(super::fact_folds::FoldCandidate {
2696                id: fact.id,
2697                pinned: true,
2698                category: fact.category,
2699                key: fact.key,
2700                value: fact.value,
2701                source_rank: fact_source_rank(&fact.source),
2702                recall_count: fact.recall_count as i64,
2703                privacy: fact.privacy.to_string(),
2704                channel_id: fact.channel_id,
2705                vector: Vec::new(),
2706            });
2707        }
2708        let hashes: std::collections::HashMap<i64, String> = candidates
2709            .iter()
2710            .map(|c| (c.id, overlap_content_hash(&c.category, &c.key, &c.value)))
2711            .collect();
2712        let distinct = self
2713            .valid_distinct_pairs(&hashes)
2714            .await
2715            .unwrap_or_else(|error| {
2716                tracing::warn!(%error, "could not read overlap reviews");
2717                Default::default()
2718            });
2719        Ok(super::fact_folds::detect_overlaps_excluding(
2720            &mut candidates,
2721            &distinct,
2722        ))
2723    }
2724
2725    async fn resolve_numeric_fact_conflicts(&self) -> anyhow::Result<usize> {
2726        let _upsert_guard = self.fact_upsert_lock.lock().await;
2727        let candidates = self.conflict_candidates().await?;
2728        let conflicts = super::fact_folds::plan_numeric_conflicts(&candidates);
2729        let retirements = super::fact_folds::numeric_conflict_retirements(&conflicts);
2730        if retirements.is_empty() {
2731            return Ok(0);
2732        }
2733        let by_id: std::collections::HashMap<i64, &super::fact_folds::ConflictCandidate> =
2734            candidates.iter().map(|c| (c.id, c)).collect();
2735        let now = Utc::now().to_rfc3339();
2736        let mut retired = Vec::new();
2737        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
2738        for (loser, winner) in &retirements {
2739            // Both still active: a write since the read may have changed them.
2740            let done = sqlx::query(
2741                "UPDATE facts SET superseded_at = ?, superseded_reason = ?, folded_into = ?
2742                 WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL
2743                   AND EXISTS (SELECT 1 FROM facts w WHERE w.id = ?
2744                               AND w.superseded_at IS NULL AND w.archived_at IS NULL)",
2745            )
2746            .bind(&now)
2747            .bind(SupersededReason::Replaced.as_str())
2748            .bind(winner)
2749            .bind(loser)
2750            .bind(winner)
2751            .execute(&mut *tx)
2752            .await?
2753            .rows_affected()
2754                > 0;
2755            if !done {
2756                continue;
2757            }
2758            if let Some(row) = by_id.get(loser) {
2759                insert_tombstone(
2760                    &mut *tx,
2761                    &row.category,
2762                    &row.key,
2763                    &row.value,
2764                    SupersededReason::Replaced,
2765                    &now,
2766                )
2767                .await?;
2768            }
2769            retired.push(*loser);
2770        }
2771        tx.commit().await?;
2772        for id in &retired {
2773            if let Err(error) = self.project_fact_memory(*id).await {
2774                tracing::warn!(%error, fact_id = id, "Deferred conflict-retired projection");
2775            }
2776        }
2777        if !retired.is_empty() {
2778            tracing::info!(
2779                retired = retired.len(),
2780                unresolved = conflicts
2781                    .iter()
2782                    .filter(|c| !matches!(
2783                        c.verdict,
2784                        super::fact_folds::ConflictVerdict::Resolved { .. }
2785                    ))
2786                    .count(),
2787                "Retired superseded numeric fact values"
2788            );
2789        }
2790        Ok(retired.len())
2791    }
2792
2793    async fn archive_unused_automated_facts(
2794        &self,
2795        now: DateTime<Utc>,
2796        min_idle_days: i64,
2797    ) -> anyhow::Result<u64> {
2798        if min_idle_days <= 0 {
2799            return Ok(0);
2800        }
2801        let cutoff = (now - chrono::Duration::days(min_idle_days)).to_rfc3339();
2802        let identity = crate::full::recall::IDENTITY_CATEGORIES;
2803        let filter = format!(
2804            "superseded_at IS NULL AND archived_at IS NULL
2805               AND source IN ({sources})
2806               AND LOWER(TRIM(category)) NOT IN ({categories})
2807               AND COALESCE(recall_count, 0) = 0 AND last_recalled_at IS NULL
2808               AND updated_at < ?",
2809            sources = vec!["?"; UNUSED_ARCHIVABLE_SOURCES.len()].join(", "),
2810            categories = vec!["?"; identity.len()].join(", "),
2811        );
2812        let _upsert_guard = self.fact_upsert_lock.lock().await;
2813        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
2814        let select = format!("SELECT id FROM facts WHERE {filter}");
2815        let mut query = sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(select));
2816        for value in UNUSED_ARCHIVABLE_SOURCES.iter().chain(identity) {
2817            query = query.bind(*value);
2818        }
2819        let ids: Vec<i64> = query.bind(&cutoff).fetch_all(&mut *tx).await?;
2820        if ids.is_empty() {
2821            return Ok(0);
2822        }
2823        let update = format!("UPDATE facts SET archived_at = ? WHERE {filter}");
2824        let mut query = sqlx::query(sqlx::AssertSqlSafe(update)).bind(now.to_rfc3339());
2825        for value in UNUSED_ARCHIVABLE_SOURCES.iter().chain(identity) {
2826            query = query.bind(*value);
2827        }
2828        let archived = query.bind(&cutoff).execute(&mut *tx).await?.rows_affected();
2829        tx.commit().await?;
2830        for id in ids {
2831            if let Err(error) = self.project_fact_memory(id).await {
2832                tracing::warn!(%error, fact_id = id, "Deferred unused-fact archive projection");
2833            }
2834        }
2835        if archived > 0 {
2836            tracing::info!(archived, min_idle_days, "Archived unused automated facts");
2837        }
2838        Ok(archived)
2839    }
2840
2841    async fn fold_fact_into(&self, folded_id: i64, kept_id: i64) -> anyhow::Result<bool> {
2842        self.fold_fact_pair(folded_id, kept_id, true).await
2843    }
2844
2845    async fn owner_fold_fact_into(&self, folded_id: i64, kept_id: i64) -> anyhow::Result<bool> {
2846        self.fold_fact_pair(folded_id, kept_id, false).await
2847    }
2848
2849    async fn confirm_fact(&self, fact_id: i64) -> anyhow::Result<Option<Fact>> {
2850        if fact_id <= 0 {
2851            return Ok(None);
2852        }
2853        let _upsert_guard = self.fact_upsert_lock.lock().await;
2854        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
2855        let exists: Option<i64> = sqlx::query_scalar(
2856            "SELECT id FROM facts
2857             WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL",
2858        )
2859        .bind(fact_id)
2860        .fetch_optional(&mut *tx)
2861        .await?;
2862        if exists.is_none() {
2863            return Ok(None);
2864        }
2865        sqlx::query(
2866            "UPDATE facts SET source = 'user_stated', updated_at = ?
2867             WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL",
2868        )
2869        .bind(Utc::now().to_rfc3339())
2870        .bind(fact_id)
2871        .execute(&mut *tx)
2872        .await?;
2873        tx.commit().await?;
2874        if let Err(error) = self.project_fact_memory(fact_id).await {
2875            tracing::warn!(%error, fact_id, "Deferred confirmed-fact projection");
2876        }
2877        self.get_fact_by_id(fact_id).await
2878    }
2879
2880    async fn unfold_fact(&self, folded_id: i64) -> anyhow::Result<Option<Fact>> {
2881        if folded_id <= 0 {
2882            return Ok(None);
2883        }
2884        let _upsert_guard = self.fact_upsert_lock.lock().await;
2885        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
2886        let row: Option<(String, String, String)> = sqlx::query_as(
2887            "SELECT category, key, value FROM facts
2888             WHERE id = ? AND superseded_at IS NOT NULL AND superseded_reason = ?",
2889        )
2890        .bind(folded_id)
2891        .bind(SupersededReason::Folded.as_str())
2892        .fetch_optional(&mut *tx)
2893        .await?;
2894        let Some((category, key, value)) = row else {
2895            return Ok(None);
2896        };
2897        // Another active row holds the key: restoring would make two.
2898        let occupied: Option<i64> = sqlx::query_scalar(
2899            "SELECT id FROM facts
2900             WHERE LOWER(TRIM(category)) = LOWER(TRIM(?)) AND LOWER(TRIM(key)) = LOWER(TRIM(?))
2901               AND superseded_at IS NULL LIMIT 1",
2902        )
2903        .bind(&category)
2904        .bind(&key)
2905        .fetch_optional(&mut *tx)
2906        .await?;
2907        if occupied.is_some() {
2908            return Ok(None);
2909        }
2910        sqlx::query(
2911            "UPDATE facts SET superseded_at = NULL, superseded_reason = NULL, folded_into = NULL
2912             WHERE id = ?",
2913        )
2914        .bind(folded_id)
2915        .execute(&mut *tx)
2916        .await?;
2917        sqlx::query(
2918            "DELETE FROM memory_fact_tombstones
2919             WHERE category = ? AND canonical_key = ? AND normalized_value = ? AND reason = ?",
2920        )
2921        .bind(category.trim().to_ascii_lowercase())
2922        .bind(canonicalize_fact_key(&key))
2923        .bind(crate::text::normalize_fact_value(&value))
2924        .bind(SupersededReason::Folded.as_str())
2925        .execute(&mut *tx)
2926        .await?;
2927        tx.commit().await?;
2928        if let Err(error) = self.project_fact_memory(folded_id).await {
2929            tracing::warn!(%error, fact_id = folded_id, "Deferred unfolded-fact projection");
2930        }
2931        self.get_fact_by_id(folded_id).await
2932    }
2933
2934    async fn refine_automated_fact_value(
2935        &self,
2936        fact_id: i64,
2937        new_value: &str,
2938    ) -> anyhow::Result<Option<Fact>> {
2939        let new_value = new_value.trim();
2940        if fact_id <= 0 || new_value.is_empty() {
2941            return Ok(None);
2942        }
2943        // Read metadata and embed BEFORE acquiring the upsert lock so slow
2944        // embedding never blocks concurrent writes; rank is re-verified inside
2945        // the BEGIN IMMEDIATE transaction below.
2946        let row: Option<(String, String, String)> = sqlx::query_as(
2947            "SELECT category, key, source FROM facts
2948             WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL",
2949        )
2950        .bind(fact_id)
2951        .fetch_optional(&self.pool)
2952        .await?;
2953        let Some((category, key, source)) = row else {
2954            return Ok(None);
2955        };
2956        // Only rank-0 automated facts may be rewritten: rank-1 owner_quoted
2957        // facts keep their verbatim owner-quoted wording and rank-2 facts are
2958        // owner-authored.
2959        if fact_source_rank(&source) > 0 {
2960            return Ok(None);
2961        }
2962        let embedding = self
2963            .embedding_service
2964            .embed(build_fact_embedding_text(&category, &key, new_value))
2965            .await
2966            .ok()
2967            .map(|vector| encode_embedding(&vector));
2968        let _upsert_guard = self.fact_upsert_lock.lock().await;
2969        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
2970        // The source may have been raised since the initial read.
2971        let source: Option<String> = sqlx::query_scalar(
2972            "SELECT source FROM facts WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL",
2973        )
2974        .bind(fact_id)
2975        .fetch_optional(&mut *tx)
2976        .await?;
2977        if source.as_deref().is_none_or(|s| fact_source_rank(s) > 0) {
2978            return Ok(None);
2979        }
2980        // A vector of the old value would no longer match: none is better.
2981        sqlx::query("UPDATE facts SET value = ?, embedding = ?, updated_at = ? WHERE id = ?")
2982            .bind(new_value)
2983            .bind(&embedding)
2984            .bind(Utc::now().to_rfc3339())
2985            .bind(fact_id)
2986            .execute(&mut *tx)
2987            .await?;
2988        tx.commit().await?;
2989        if let Err(error) = self.project_fact_memory(fact_id).await {
2990            tracing::warn!(%error, fact_id, "Deferred refined-fact projection");
2991        }
2992        self.get_fact_by_id(fact_id).await
2993    }
2994
2995    async fn record_overlap_review(
2996        &self,
2997        fact_a_id: i64,
2998        fact_b_id: i64,
2999        verdict: crate::stores::OverlapReviewVerdict,
3000        reviewer: &str,
3001    ) -> anyhow::Result<()> {
3002        anyhow::ensure!(fact_a_id != fact_b_id, "an overlap review needs two facts");
3003        let (a, b) = super::fact_folds::overlap_pair(fact_a_id, fact_b_id);
3004        let (Some(hash_a), Some(hash_b)) = (
3005            self.fact_content_hash(a).await?,
3006            self.fact_content_hash(b).await?,
3007        ) else {
3008            anyhow::bail!("overlap review: fact {a} or {b} is not an active fact");
3009        };
3010        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
3011        sqlx::query(
3012            "INSERT INTO memory_overlap_reviews
3013                (fact_a_id, fact_b_id, hash_a, hash_b, verdict, reviewed_at, reviewer)
3014             VALUES (?, ?, ?, ?, ?, ?, ?)
3015             ON CONFLICT(fact_a_id, fact_b_id) DO UPDATE SET
3016                hash_a = excluded.hash_a, hash_b = excluded.hash_b,
3017                verdict = excluded.verdict, reviewed_at = excluded.reviewed_at,
3018                reviewer = excluded.reviewer",
3019        )
3020        .bind(a)
3021        .bind(b)
3022        .bind(&hash_a)
3023        .bind(&hash_b)
3024        .bind(verdict.as_str())
3025        .bind(Utc::now().to_rfc3339())
3026        .bind(reviewer)
3027        .execute(&mut *tx)
3028        .await?;
3029        tx.commit().await?;
3030        Ok(())
3031    }
3032
3033    async fn has_valid_overlap_review(
3034        &self,
3035        fact_a_id: i64,
3036        fact_b_id: i64,
3037    ) -> anyhow::Result<Option<crate::stores::OverlapReviewVerdict>> {
3038        let (a, b) = super::fact_folds::overlap_pair(fact_a_id, fact_b_id);
3039        let row: Option<(String, String, String)> = sqlx::query_as(
3040            "SELECT hash_a, hash_b, verdict FROM memory_overlap_reviews
3041             WHERE fact_a_id = ? AND fact_b_id = ?",
3042        )
3043        .bind(a)
3044        .bind(b)
3045        .fetch_optional(&self.pool)
3046        .await?;
3047        let Some((hash_a, hash_b, verdict)) = row else {
3048            return Ok(None);
3049        };
3050        let current_a = self.fact_content_hash(a).await?;
3051        let current_b = self.fact_content_hash(b).await?;
3052        if current_a.as_deref() != Some(hash_a.as_str())
3053            || current_b.as_deref() != Some(hash_b.as_str())
3054        {
3055            return Ok(None);
3056        }
3057        Ok(crate::stores::OverlapReviewVerdict::parse(&verdict))
3058    }
3059
3060    async fn fact_exists(&self, fact_id: i64) -> anyhow::Result<bool> {
3061        if fact_id < 0 {
3062            return Ok(self.get_fact_by_id(fact_id).await?.is_some());
3063        }
3064        Ok(sqlx::query_scalar::<_, i64>(
3065            "SELECT 1 FROM facts WHERE id = ? AND superseded_at IS NULL",
3066        )
3067        .bind(fact_id)
3068        .fetch_optional(&self.pool)
3069        .await?
3070        .is_some())
3071    }
3072
3073    async fn get_fact_by_id(&self, fact_id: i64) -> anyhow::Result<Option<Fact>> {
3074        if fact_id < 0 {
3075            return Ok(self
3076                .canonical_personal_facts()
3077                .await?
3078                .into_iter()
3079                .find(|fact| fact.id == fact_id));
3080        }
3081        let row = sqlx::query(sqlx::AssertSqlSafe(format!(
3082            "SELECT {FACT_COLUMNS} FROM facts WHERE id = ? AND superseded_at IS NULL"
3083        )))
3084        .bind(fact_id)
3085        .fetch_optional(&self.pool)
3086        .await?;
3087        Ok(row.as_ref().map(Self::row_to_fact))
3088    }
3089
3090    async fn job_last_run_at(&self, job_name: &str) -> anyhow::Result<Option<DateTime<Utc>>> {
3091        let at: Option<String> =
3092            sqlx::query_scalar("SELECT last_run_at FROM memory_job_watermarks WHERE job_name = ?")
3093                .bind(job_name)
3094                .fetch_optional(&self.pool)
3095                .await?;
3096        Ok(at.as_deref().and_then(crate::types::parse_ts))
3097    }
3098
3099    async fn record_job_run_at(&self, job_name: &str, at: DateTime<Utc>) -> anyhow::Result<()> {
3100        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
3101        sqlx::query(
3102            "INSERT INTO memory_job_watermarks (job_name, last_run_at) VALUES (?, ?)
3103             ON CONFLICT(job_name) DO UPDATE SET last_run_at = excluded.last_run_at",
3104        )
3105        .bind(job_name)
3106        .bind(at.to_rfc3339())
3107        .execute(&mut *tx)
3108        .await?;
3109        tx.commit().await?;
3110        Ok(())
3111    }
3112
3113    async fn get_all_facts_with_provenance(&self) -> anyhow::Result<Vec<Fact>> {
3114        let rows = sqlx::query(
3115            "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
3116             FROM facts WHERE superseded_at IS NULL AND archived_at IS NULL ORDER BY category, key"
3117        )
3118        .fetch_all(&self.pool)
3119        .await?;
3120
3121        Ok(rows.iter().map(Self::row_to_fact).collect())
3122    }
3123}
3124
3125/// SQL for [`super::fact_folds::FoldScope::OwnerPrivate`] rows: private, or
3126/// a channel fact from an owner app conversation (`app:` prefix, compared
3127/// case-sensitively like `fold_scope_key`).
3128const OWNER_PRIVATE_SCOPE_SQL: &str = "(LOWER(COALESCE(privacy, 'global')) = 'private'
3129      OR (LOWER(COALESCE(privacy, 'global')) = 'channel' AND substr(channel_id, 1, 4) = 'app:'))";
3130
3131/// Columns `SqliteMemory::row_to_fact` reads.
3132const FACT_COLUMNS: &str = "id, category, key, value, source, created_at, updated_at, superseded_at, recall_count, last_recalled_at, channel_id, privacy, first_seen_at, source_excerpt";
3133
3134/// Sources of background extractors, whose facts nobody stated: the only
3135/// facts maintenance may archive for disuse. Owner-stated (`agent`,
3136/// `user_stated`...) and quoted (`owner_quoted`) facts are never listed.
3137const UNUSED_ARCHIVABLE_SOURCES: &[&str] = &[
3138    "consolidation",
3139    "inferred",
3140    "derived",
3141    "progressive",
3142    "task_learning",
3143];
3144
3145/// Similarity at which a lower-ranked recall candidate in the same category
3146/// adds nothing beside a fact already picked: paraphrases of one preference
3147/// score alike and would otherwise fill neighbouring recall slots.
3148pub(crate) const RECALL_DIVERSITY_MAX_SIMILARITY: f32 = 0.88;
3149
3150/// How many ranked candidates per recall slot the diversity pass looks at.
3151const RECALL_DIVERSITY_OVERFETCH: usize = 3;
3152
3153/// Keep `ranked` items in order, skipping any whose vector is at least
3154/// [`RECALL_DIVERSITY_MAX_SIMILARITY`] similar to an item already kept in the
3155/// same category, until `max` are kept. Items without a vector are never
3156/// skipped. Each item is `(value, normalized category, vector)`.
3157pub(crate) fn select_diverse<T>(
3158    ranked: impl IntoIterator<Item = (T, String, Option<Vec<f32>>)>,
3159    max: usize,
3160) -> Vec<T> {
3161    let mut kept: Vec<(String, Option<Vec<f32>>)> = Vec::new();
3162    let mut out = Vec::new();
3163    for (item, category, vector) in ranked {
3164        if out.len() >= max {
3165            break;
3166        }
3167        let redundant = vector.as_ref().is_some_and(|vector| {
3168            kept.iter().any(|(other_category, other)| {
3169                *other_category == category
3170                    && other.as_ref().is_some_and(|other| {
3171                        other.len() == vector.len()
3172                            && cosine_similarity(vector, other) >= RECALL_DIVERSITY_MAX_SIMILARITY
3173                    })
3174            })
3175        });
3176        if redundant {
3177            continue;
3178        }
3179        kept.push((category, vector));
3180        out.push(item);
3181    }
3182    out
3183}
3184
3185/// The content an overlap verdict is bound to: category and key as the
3186/// fact is filed, and its exact value.
3187pub(crate) fn overlap_content_hash(category: &str, key: &str, value: &str) -> String {
3188    crate::embedding_index::content_hash(&format!(
3189        "{}\u{1f}{}\u{1f}{}",
3190        category.trim().to_ascii_lowercase(),
3191        key.trim().to_ascii_lowercase(),
3192        value.trim()
3193    ))
3194}
3195
3196impl SqliteMemory {
3197    /// Fold `folded_id` into `kept_id` inside `BEGIN IMMEDIATE`. When
3198    /// `enforce_automated_guards` is true, also enforces the background hygiene
3199    /// safety rails (never fold owner-stated facts, never fold higher rank into
3200    /// lower rank, never hide from an audience, never unpin identity facts).
3201    async fn fold_fact_pair(
3202        &self,
3203        folded_id: i64,
3204        kept_id: i64,
3205        enforce_rank_guards: bool,
3206    ) -> anyhow::Result<bool> {
3207        type FoldPairRow = (i64, String, String, String, String, String, Option<String>);
3208        if folded_id <= 0 || kept_id <= 0 || folded_id == kept_id {
3209            return Ok(false);
3210        }
3211        let _upsert_guard = self.fact_upsert_lock.lock().await;
3212        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
3213        let rows: Vec<FoldPairRow> = sqlx::query_as(
3214            "SELECT id, category, key, value, source, COALESCE(privacy, 'global'), channel_id
3215             FROM facts
3216             WHERE id IN (?, ?) AND superseded_at IS NULL AND archived_at IS NULL",
3217        )
3218        .bind(folded_id)
3219        .bind(kept_id)
3220        .fetch_all(&mut *tx)
3221        .await?;
3222        let (Some(folded), Some(kept)) = (
3223            rows.iter().find(|row| row.0 == folded_id),
3224            rows.iter().find(|row| row.0 == kept_id),
3225        ) else {
3226            return Ok(false);
3227        };
3228        let (folded_rank, kept_rank) = (fact_source_rank(&folded.4), fact_source_rank(&kept.4));
3229        if enforce_rank_guards && (folded_rank >= 2 || folded_rank > kept_rank) {
3230            return Ok(false);
3231        }
3232        // Scope and identity-pin guards apply to both automated and owner
3233        // merges so folding never silently hides a group-channel fact or
3234        // unpins an identity fact.
3235        let folded_scope = super::fact_folds::fold_scope_key(&folded.5, folded.6.as_deref());
3236        let kept_scope = super::fact_folds::fold_scope_key(&kept.5, kept.6.as_deref());
3237        if !kept_scope.can_keep(&folded_scope) {
3238            return Ok(false);
3239        }
3240        let pinned = |category: &str| {
3241            crate::full::recall::IDENTITY_CATEGORIES
3242                .contains(&category.trim().to_ascii_lowercase().as_str())
3243        };
3244        if pinned(&folded.1) && !pinned(&kept.1) {
3245            return Ok(false);
3246        }
3247        let now = Utc::now().to_rfc3339();
3248        sqlx::query(
3249            "UPDATE facts SET superseded_at = ?, superseded_reason = ?, folded_into = ?
3250             WHERE id = ? AND superseded_at IS NULL",
3251        )
3252        .bind(&now)
3253        .bind(SupersededReason::Folded.as_str())
3254        .bind(kept_id)
3255        .bind(folded_id)
3256        .execute(&mut *tx)
3257        .await?;
3258        // An explicit owner merge confirms the surviving row as owner-verified
3259        // when it was automated, so owner-reviewed knowledge isn't archived
3260        // later by the unused-automated rule.
3261        if !enforce_rank_guards && kept_rank < 2 {
3262            sqlx::query(
3263                "UPDATE facts
3264                 SET recall_count = MAX(COALESCE(recall_count, 0),
3265                         (SELECT COALESCE(recall_count, 0) FROM facts WHERE id = ?)),
3266                     source = 'user_stated',
3267                     updated_at = ?
3268                 WHERE id = ?",
3269            )
3270            .bind(folded_id)
3271            .bind(&now)
3272            .bind(kept_id)
3273            .execute(&mut *tx)
3274            .await?;
3275        } else {
3276            sqlx::query(
3277                "UPDATE facts SET recall_count = MAX(COALESCE(recall_count, 0),
3278                     (SELECT COALESCE(recall_count, 0) FROM facts WHERE id = ?))
3279                 WHERE id = ?",
3280            )
3281            .bind(folded_id)
3282            .bind(kept_id)
3283            .execute(&mut *tx)
3284            .await?;
3285        }
3286        insert_tombstone(
3287            &mut *tx,
3288            &folded.1,
3289            &folded.2,
3290            &folded.3,
3291            SupersededReason::Folded,
3292            &now,
3293        )
3294        .await?;
3295        sqlx::query("DELETE FROM memory_overlap_reviews WHERE fact_a_id = ? OR fact_b_id = ?")
3296            .bind(folded_id)
3297            .bind(folded_id)
3298            .execute(&mut *tx)
3299            .await?;
3300        tx.commit().await?;
3301        if let Err(error) = self.project_fact_memory(folded_id).await {
3302            tracing::warn!(%error, fact_id = folded_id, "Deferred folded-fact projection");
3303        }
3304        Ok(true)
3305    }
3306
3307    /// Stored full-fact vectors of `ids`, read in chunks.
3308    async fn fact_vectors(&self, ids: &[i64]) -> std::collections::HashMap<i64, Vec<f32>> {
3309        let mut vectors = std::collections::HashMap::new();
3310        let ids: Vec<i64> = ids.iter().copied().filter(|id| *id > 0).collect();
3311        for chunk in ids.chunks(500) {
3312            let mut builder = sqlx::QueryBuilder::<sqlx::Sqlite>::new(
3313                "SELECT id, embedding FROM facts WHERE embedding IS NOT NULL AND id IN (",
3314            );
3315            let mut separated = builder.separated(", ");
3316            for id in chunk {
3317                separated.push_bind(*id);
3318            }
3319            separated.push_unseparated(")");
3320            let rows = match builder.build().fetch_all(&self.pool).await {
3321                Ok(rows) => rows,
3322                Err(error) => {
3323                    tracing::warn!(%error, "could not read fact vectors for recall diversity");
3324                    return vectors;
3325                }
3326            };
3327            for row in rows {
3328                let blob: Vec<u8> = row.get("embedding");
3329                if let Ok(vector) = self.embedding_service.decode(&blob) {
3330                    vectors.insert(row.get("id"), vector);
3331                }
3332            }
3333        }
3334        vectors
3335    }
3336
3337    /// The first `max` of `ranked` (best first) that are not paraphrases of
3338    /// a fact ranked above them ([`select_diverse`]).
3339    async fn diverse_facts(&self, ranked: Vec<Fact>, max: usize) -> Vec<Fact> {
3340        if ranked.len() <= 1 {
3341            return ranked.into_iter().take(max).collect();
3342        }
3343        let ids: Vec<i64> = ranked.iter().map(|fact| fact.id).collect();
3344        let mut vectors = self.fact_vectors(&ids).await;
3345        select_diverse(
3346            ranked.into_iter().map(|fact| {
3347                let category = fact.category.trim().to_ascii_lowercase();
3348                let vector = vectors.remove(&fact.id);
3349                (fact, category, vector)
3350            }),
3351            max,
3352        )
3353    }
3354
3355    /// Every active fact with a vector, as the numeric-conflict planner
3356    /// reads it.
3357    pub async fn conflict_candidates(
3358        &self,
3359    ) -> anyhow::Result<Vec<super::fact_folds::ConflictCandidate>> {
3360        let rows = sqlx::query(
3361            "SELECT id, category, key, value, source, COALESCE(first_seen_at, updated_at) AS seen,
3362                    COALESCE(privacy, 'global') AS privacy, channel_id, embedding
3363             FROM facts
3364             WHERE superseded_at IS NULL AND archived_at IS NULL AND embedding IS NOT NULL
3365             ORDER BY id ASC",
3366        )
3367        .fetch_all(&self.pool)
3368        .await?;
3369        Ok(rows
3370            .into_iter()
3371            .filter_map(|row| {
3372                let blob: Vec<u8> = row.get("embedding");
3373                let vector = self.embedding_service.decode(&blob).ok()?;
3374                let source: String = row.get("source");
3375                let seen: Option<String> = row.get("seen");
3376                Some(super::fact_folds::ConflictCandidate {
3377                    id: row.get("id"),
3378                    category: row.get("category"),
3379                    key: row.get("key"),
3380                    value: row.get("value"),
3381                    source_rank: fact_source_rank(&source),
3382                    seen: seen
3383                        .as_deref()
3384                        .and_then(super::fact_folds::parse_fact_timestamp),
3385                    privacy: row.get("privacy"),
3386                    channel_id: row.get("channel_id"),
3387                    vector,
3388                })
3389            })
3390            .collect())
3391    }
3392
3393    /// The overlap-review content hash of a fact that is not retired: a
3394    /// flat row by positive id, a canonical projection by negative id.
3395    async fn fact_content_hash(&self, fact_id: i64) -> anyhow::Result<Option<String>> {
3396        Ok(self
3397            .get_fact_by_id(fact_id)
3398            .await?
3399            .map(|fact| overlap_content_hash(&fact.category, &fact.key, &fact.value)))
3400    }
3401
3402    /// Pairs a reviewer judged distinct whose facts still hold the content
3403    /// they were judged on. `hashes` maps fact id to its current content
3404    /// hash; a pair with a side missing from it is not returned.
3405    async fn valid_distinct_pairs(
3406        &self,
3407        hashes: &std::collections::HashMap<i64, String>,
3408    ) -> anyhow::Result<std::collections::HashSet<(i64, i64)>> {
3409        let rows: Vec<(i64, i64, String, String)> = sqlx::query_as(
3410            "SELECT fact_a_id, fact_b_id, hash_a, hash_b FROM memory_overlap_reviews
3411             WHERE verdict = ?",
3412        )
3413        .bind(crate::stores::OverlapReviewVerdict::Distinct.as_str())
3414        .fetch_all(&self.pool)
3415        .await?;
3416        Ok(rows
3417            .into_iter()
3418            .filter(|(a, b, hash_a, hash_b)| {
3419                hashes.get(a) == Some(hash_a) && hashes.get(b) == Some(hash_b)
3420            })
3421            .map(|(a, b, _, _)| super::fact_folds::overlap_pair(a, b))
3422            .collect())
3423    }
3424}
3425
3426/// Legacy categories whose keys describe the owner, as the canonical store
3427/// projects them (`user`) and as writers name them.
3428fn is_owner_profile_category(category: &str) -> bool {
3429    matches!(category, "user" | "personal" | "profile")
3430}
3431
3432#[cfg(test)]
3433mod hygiene_tests {
3434    use std::sync::Arc;
3435
3436    use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
3437
3438    use super::super::{EMBEDDING_DIM, migrate};
3439    use super::*;
3440    use crate::HashEmbedder;
3441    use crate::stores::{DecayPolicy, OverlapReviewVerdict};
3442
3443    async fn open() -> (SqliteMemory, tempfile::NamedTempFile) {
3444        let file = tempfile::NamedTempFile::new().unwrap();
3445        let options = SqliteConnectOptions::new()
3446            .filename(file.path())
3447            .synchronous(sqlx::sqlite::SqliteSynchronous::Off);
3448        let pool = SqlitePoolOptions::new()
3449            .max_connections(2)
3450            .connect_with(options)
3451            .await
3452            .unwrap();
3453        migrate(&pool).await.unwrap();
3454        let memory = SqliteMemory::new(pool, Arc::new(HashEmbedder::new(EMBEDDING_DIM)));
3455        (memory, file)
3456    }
3457
3458    /// Unit vector along `axis`, tilted toward `axis + 1` so that its
3459    /// cosine with the plain axis is `cos`.
3460    fn tilted(axis: usize, cos: f32) -> Vec<f32> {
3461        let mut v = vec![0.0; EMBEDDING_DIM];
3462        v[axis] = cos;
3463        v[axis + 1] = (1.0 - cos * cos).sqrt();
3464        v
3465    }
3466
3467    struct Row<'a> {
3468        category: &'a str,
3469        key: &'a str,
3470        value: &'a str,
3471        source: &'a str,
3472        privacy: &'a str,
3473        channel: Option<&'a str>,
3474        vector: Vec<f32>,
3475        recall: i64,
3476        age_days: i64,
3477    }
3478
3479    impl<'a> Row<'a> {
3480        fn new(category: &'a str, key: &'a str, value: &'a str, vector: Vec<f32>) -> Self {
3481            Self {
3482                category,
3483                key,
3484                value,
3485                source: "consolidation",
3486                privacy: "private",
3487                channel: None,
3488                vector,
3489                recall: 0,
3490                age_days: 0,
3491            }
3492        }
3493    }
3494
3495    /// A fact row written directly, with exactly the vector given.
3496    async fn insert(memory: &SqliteMemory, row: Row<'_>) -> i64 {
3497        let at = (Utc::now() - chrono::Duration::days(row.age_days)).to_rfc3339();
3498        sqlx::query(
3499            "INSERT INTO facts (category, key, value, source, created_at, updated_at, recall_count,
3500                                channel_id, privacy, embedding, first_seen_at)
3501             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
3502        )
3503        .bind(row.category)
3504        .bind(row.key)
3505        .bind(row.value)
3506        .bind(row.source)
3507        .bind(&at)
3508        .bind(&at)
3509        .bind(row.recall)
3510        .bind(row.channel)
3511        .bind(row.privacy)
3512        .bind(encode_embedding(&row.vector))
3513        .bind(&at)
3514        .execute(memory.pool())
3515        .await
3516        .unwrap()
3517        .last_insert_rowid()
3518    }
3519
3520    async fn status(memory: &SqliteMemory, id: i64) -> (Option<String>, Option<i64>) {
3521        sqlx::query_as("SELECT superseded_reason, folded_into FROM facts WHERE id = ?")
3522            .bind(id)
3523            .fetch_one(memory.pool())
3524            .await
3525            .unwrap()
3526    }
3527
3528    async fn tombstones(memory: &SqliteMemory, reason: &str) -> i64 {
3529        sqlx::query_scalar("SELECT COUNT(*) FROM memory_fact_tombstones WHERE reason = ?")
3530            .bind(reason)
3531            .fetch_one(memory.pool())
3532            .await
3533            .unwrap()
3534    }
3535
3536    async fn active_count(memory: &SqliteMemory) -> usize {
3537        memory.get_facts(None).await.unwrap().len()
3538    }
3539
3540    #[tokio::test]
3541    async fn app_conversation_facts_and_private_facts_fold_as_one_audience() {
3542        let (memory, _file) = open().await;
3543        let v = tilted(0, 1.0);
3544        let value = "short answers with code first";
3545        let a = insert(
3546            &memory,
3547            Row {
3548                privacy: "channel",
3549                channel: Some("app:synthetic-conv-1"),
3550                ..Row::new("preference", "reply_style", value, v.clone())
3551            },
3552        )
3553        .await;
3554        let b = insert(
3555            &memory,
3556            Row {
3557                privacy: "channel",
3558                channel: Some("app:synthetic-conv-2"),
3559                ..Row::new("preference", "answer_style", value, v.clone())
3560            },
3561        )
3562        .await;
3563        let c = insert(
3564            &memory,
3565            Row::new("preference", "response_format", value, v.clone()),
3566        )
3567        .await;
3568        // A group channel and a global copy never merge with the owner's.
3569        let group = insert(
3570            &memory,
3571            Row {
3572                privacy: "channel",
3573                channel: Some("slack:synthetic-team"),
3574                ..Row::new("preference", "team_reply_style", value, v.clone())
3575            },
3576        )
3577        .await;
3578        let global = insert(
3579            &memory,
3580            Row {
3581                privacy: "global",
3582                ..Row::new("preference", "global_reply_style", value, v.clone())
3583            },
3584        )
3585        .await;
3586        assert_eq!(memory.fold_restated_facts().await.unwrap(), 2);
3587        assert_eq!(status(&memory, a).await, (None, None));
3588        assert_eq!(status(&memory, b).await, (Some("folded".into()), Some(a)));
3589        assert_eq!(status(&memory, c).await, (Some("folded".into()), Some(a)));
3590        assert_eq!(status(&memory, group).await, (None, None));
3591        assert_eq!(status(&memory, global).await, (None, None));
3592    }
3593
3594    #[tokio::test]
3595    async fn write_time_dedup_treats_app_conversations_as_the_owners_scope() {
3596        let (memory, _file) = open().await;
3597        let value = "prefers concise replies with the code first";
3598        memory
3599            .upsert_fact(
3600                "preference",
3601                "reply_style",
3602                value,
3603                "consolidation",
3604                Some("app:synthetic-conv-1"),
3605                FactPrivacy::Channel,
3606            )
3607            .await
3608            .unwrap();
3609        // The same value under a reworded key, from another app
3610        // conversation and from an owner DM: one fact.
3611        for (key, channel, privacy) in [
3612            (
3613                "reply_style_preference",
3614                Some("app:synthetic-conv-2"),
3615                FactPrivacy::Channel,
3616            ),
3617            ("preferred_reply_style", None, FactPrivacy::Private),
3618        ] {
3619            memory
3620                .upsert_fact("preference", key, value, "consolidation", channel, privacy)
3621                .await
3622                .unwrap();
3623        }
3624        assert_eq!(active_count(&memory).await, 1);
3625        // A group channel keeps its own copy.
3626        memory
3627            .upsert_fact(
3628                "preference",
3629                "reply_style_preference",
3630                value,
3631                "consolidation",
3632                Some("slack:synthetic-team"),
3633                FactPrivacy::Channel,
3634            )
3635            .await
3636            .unwrap();
3637        assert_eq!(active_count(&memory).await, 2);
3638    }
3639
3640    #[tokio::test]
3641    async fn numeric_conflicts_retire_only_what_a_closer_or_newer_source_replaced() {
3642        let (memory, _file) = open().await;
3643        // Owner-stated beats inferred.
3644        let owner = insert(
3645            &memory,
3646            Row {
3647                source: "user_stated",
3648                ..Row::new("project", "api_port", "port 8080", tilted(0, 1.0))
3649            },
3650        )
3651        .await;
3652        let inferred = insert(
3653            &memory,
3654            Row::new("project", "default_api_port", "port 9090", tilted(0, 0.95)),
3655        )
3656        .await;
3657        // Two automated values of one attribute: the one seen later wins.
3658        let older = insert(
3659            &memory,
3660            Row {
3661                age_days: 30,
3662                ..Row::new("technical", "node_version", "Node 18", tilted(4, 1.0))
3663            },
3664        )
3665        .await;
3666        let newer = insert(
3667            &memory,
3668            Row::new(
3669                "technical",
3670                "current_node_version",
3671                "Node 20",
3672                tilted(4, 0.95),
3673            ),
3674        )
3675        .await;
3676        // Keys that may name two attributes: kept.
3677        let release = insert(
3678            &memory,
3679            Row::new("project", "release_version", "1.2", tilted(8, 1.0)),
3680        )
3681        .await;
3682        let build = insert(
3683            &memory,
3684            Row::new("project", "build_version", "3.4", tilted(8, 0.95)),
3685        )
3686        .await;
3687        // Two owner-stated values: only the owner can say.
3688        let stated_a = insert(
3689            &memory,
3690            Row {
3691                source: "user_stated",
3692                ..Row::new("project", "deadline_day", "day 12", tilted(12, 1.0))
3693            },
3694        )
3695        .await;
3696        let stated_b = insert(
3697            &memory,
3698            Row {
3699                source: "agent",
3700                ..Row::new("project", "deadline", "day 14", tilted(12, 0.95))
3701            },
3702        )
3703        .await;
3704        // Another scope never conflicts.
3705        let group = insert(
3706            &memory,
3707            Row {
3708                privacy: "channel",
3709                channel: Some("slack:synthetic-team"),
3710                ..Row::new("project", "api_port_value", "port 7070", tilted(0, 0.97))
3711            },
3712        )
3713        .await;
3714
3715        assert_eq!(memory.resolve_numeric_fact_conflicts().await.unwrap(), 2);
3716        assert_eq!(
3717            status(&memory, inferred).await,
3718            (Some("replaced".into()), Some(owner))
3719        );
3720        assert_eq!(
3721            status(&memory, older).await,
3722            (Some("replaced".into()), Some(newer))
3723        );
3724        for id in [owner, newer, release, build, stated_a, stated_b, group] {
3725            assert_eq!(status(&memory, id).await, (None, None), "#{id}");
3726        }
3727        assert_eq!(tombstones(&memory, "replaced").await, 2);
3728        // Idempotent.
3729        assert_eq!(memory.resolve_numeric_fact_conflicts().await.unwrap(), 0);
3730    }
3731
3732    #[tokio::test]
3733    async fn fold_and_unfold_round_trip() {
3734        let (memory, _file) = open().await;
3735        let kept = insert(
3736            &memory,
3737            Row {
3738                recall: 1,
3739                ..Row::new(
3740                    "preference",
3741                    "editor",
3742                    "Helix with relative line numbers",
3743                    tilted(0, 1.0),
3744                )
3745            },
3746        )
3747        .await;
3748        let folded = insert(
3749            &memory,
3750            Row {
3751                recall: 7,
3752                ..Row::new(
3753                    "preference",
3754                    "editor_setup",
3755                    "Uses Helix, relative numbers on",
3756                    tilted(0, 0.9),
3757                )
3758            },
3759        )
3760        .await;
3761        memory.project_fact_memory(folded).await.unwrap();
3762        let claim_open = |memory: &SqliteMemory| {
3763            let pool = memory.pool().clone();
3764            async move {
3765                sqlx::query_scalar::<_, Option<String>>(
3766                    "SELECT valid_to FROM memory_claims WHERE source_fact_id = ?",
3767                )
3768                .bind(folded)
3769                .fetch_one(&pool)
3770                .await
3771                .unwrap()
3772                .is_none()
3773            }
3774        };
3775        assert!(claim_open(&memory).await);
3776
3777        assert!(memory.fold_fact_into(folded, kept).await.unwrap());
3778        assert_eq!(
3779            status(&memory, folded).await,
3780            (Some("folded".into()), Some(kept))
3781        );
3782        assert_eq!(
3783            memory
3784                .get_fact_by_id(kept)
3785                .await
3786                .unwrap()
3787                .unwrap()
3788                .recall_count,
3789            7
3790        );
3791        assert!(memory.get_fact_by_id(folded).await.unwrap().is_none());
3792        assert!(!memory.fact_exists(folded).await.unwrap());
3793        assert_eq!(tombstones(&memory, "folded").await, 1);
3794        assert!(!claim_open(&memory).await);
3795        // Folding twice does nothing.
3796        assert!(!memory.fold_fact_into(folded, kept).await.unwrap());
3797
3798        let restored = memory.unfold_fact(folded).await.unwrap().unwrap();
3799        assert_eq!(restored.value, "Uses Helix, relative numbers on");
3800        assert_eq!(status(&memory, folded).await, (None, None));
3801        assert_eq!(tombstones(&memory, "folded").await, 0);
3802        assert!(claim_open(&memory).await);
3803        assert!(memory.fact_exists(folded).await.unwrap());
3804        // Unfolding an active fact does nothing.
3805        assert!(memory.unfold_fact(folded).await.unwrap().is_none());
3806
3807        // A fact that took the key since blocks the unfold.
3808        assert!(memory.fold_fact_into(folded, kept).await.unwrap());
3809        insert(
3810            &memory,
3811            Row::new("preference", "editor_setup", "Zed", tilted(20, 1.0)),
3812        )
3813        .await;
3814        assert!(memory.unfold_fact(folded).await.unwrap().is_none());
3815    }
3816
3817    #[tokio::test]
3818    async fn fold_refuses_owner_words_farther_sources_and_narrower_scopes() {
3819        let (memory, _file) = open().await;
3820        let v = tilted(0, 1.0);
3821        let inferred = insert(&memory, Row::new("preference", "a", "x one", v.clone())).await;
3822        let owner = insert(
3823            &memory,
3824            Row {
3825                source: "user_stated",
3826                ..Row::new("preference", "b", "x two", v.clone())
3827            },
3828        )
3829        .await;
3830        let quoted = insert(
3831            &memory,
3832            Row {
3833                source: OWNER_QUOTED_SOURCE,
3834                ..Row::new("preference", "c", "x three", v.clone())
3835            },
3836        )
3837        .await;
3838        let global = insert(
3839            &memory,
3840            Row {
3841                privacy: "global",
3842                ..Row::new("preference", "d", "x four", v.clone())
3843            },
3844        )
3845        .await;
3846        let identity = insert(&memory, Row::new("user", "e", "x five", v.clone())).await;
3847        // Owner-stated is never folded away.
3848        assert!(!memory.fold_fact_into(owner, inferred).await.unwrap());
3849        // A quote is not folded into an inference.
3850        assert!(!memory.fold_fact_into(quoted, inferred).await.unwrap());
3851        // A global fact folded into a private one would hide it.
3852        assert!(!memory.fold_fact_into(global, inferred).await.unwrap());
3853        // An identity fact is not unpinned.
3854        assert!(!memory.fold_fact_into(identity, inferred).await.unwrap());
3855        assert!(!memory.fold_fact_into(inferred, inferred).await.unwrap());
3856        assert!(!memory.fold_fact_into(inferred, 999_999).await.unwrap());
3857        // A private inference folds into a global, owner-stated fact.
3858        assert!(memory.fold_fact_into(inferred, owner).await.unwrap());
3859        assert!(memory.fold_fact_into(quoted, owner).await.unwrap());
3860        assert!(!memory.fold_fact_into(global, owner).await.unwrap());
3861    }
3862
3863    #[tokio::test]
3864    async fn refine_rewrites_automated_facts_only() {
3865        let (memory, _file) = open().await;
3866        let inferred = insert(
3867            &memory,
3868            Row::new("preference", "tone", "casual", tilted(0, 1.0)),
3869        )
3870        .await;
3871        let owner = insert(
3872            &memory,
3873            Row {
3874                source: "user_stated",
3875                ..Row::new("preference", "greeting", "hi", tilted(2, 1.0))
3876            },
3877        )
3878        .await;
3879        let blob = |id: i64| {
3880            let pool = memory.pool().clone();
3881            async move {
3882                sqlx::query_scalar::<_, Option<Vec<u8>>>("SELECT embedding FROM facts WHERE id = ?")
3883                    .bind(id)
3884                    .fetch_one(&pool)
3885                    .await
3886                    .unwrap()
3887            }
3888        };
3889        let before = blob(inferred).await;
3890        let refined = memory
3891            .refine_automated_fact_value(inferred, "  casual and brief  ")
3892            .await
3893            .unwrap()
3894            .unwrap();
3895        assert_eq!(refined.value, "casual and brief");
3896        assert_eq!(refined.source, "consolidation");
3897        let after = blob(inferred).await;
3898        assert!(after.is_some() && after != before);
3899        let expected = HashEmbedder::new(EMBEDDING_DIM).embed_one(&build_fact_embedding_text(
3900            "preference",
3901            "tone",
3902            "casual and brief",
3903        ));
3904        assert_eq!(after, Some(encode_embedding(&expected)));
3905
3906        assert!(
3907            memory
3908                .refine_automated_fact_value(owner, "hello")
3909                .await
3910                .unwrap()
3911                .is_none()
3912        );
3913        assert_eq!(
3914            memory.get_fact_by_id(owner).await.unwrap().unwrap().value,
3915            "hi"
3916        );
3917        assert!(
3918            memory
3919                .refine_automated_fact_value(inferred, "   ")
3920                .await
3921                .unwrap()
3922                .is_none()
3923        );
3924    }
3925
3926    #[tokio::test]
3927    async fn a_distinct_verdict_hides_the_pair_until_either_fact_changes() {
3928        let (memory, _file) = open().await;
3929        let value = "dark theme in every editor";
3930        let a = insert(
3931            &memory,
3932            Row::new("preference", "theme", value, tilted(0, 1.0)),
3933        )
3934        .await;
3935        let b = insert(
3936            &memory,
3937            Row {
3938                privacy: "global",
3939                ..Row::new("technical", "editor_theme", value, tilted(0, 0.97))
3940            },
3941        )
3942        .await;
3943        let paired = |overlaps: &std::collections::HashMap<i64, i64>| {
3944            overlaps.get(&a) == Some(&b) || overlaps.get(&b) == Some(&a)
3945        };
3946        assert!(paired(&memory.detect_fact_overlaps().await.unwrap()));
3947        assert_eq!(memory.has_valid_overlap_review(a, b).await.unwrap(), None);
3948
3949        memory
3950            .record_overlap_review(b, a, OverlapReviewVerdict::Conflict, "test")
3951            .await
3952            .unwrap();
3953        // A conflict is still shown.
3954        assert!(paired(&memory.detect_fact_overlaps().await.unwrap()));
3955        memory
3956            .record_overlap_review(b, a, OverlapReviewVerdict::Distinct, "test")
3957            .await
3958            .unwrap();
3959        assert_eq!(
3960            memory.has_valid_overlap_review(a, b).await.unwrap(),
3961            Some(OverlapReviewVerdict::Distinct)
3962        );
3963        assert!(!paired(&memory.detect_fact_overlaps().await.unwrap()));
3964
3965        // An edit voids the verdict and the pair is flagged again.
3966        sqlx::query("UPDATE facts SET value = value || '!' WHERE id = ?")
3967            .bind(b)
3968            .execute(memory.pool())
3969            .await
3970            .unwrap();
3971        assert_eq!(memory.has_valid_overlap_review(a, b).await.unwrap(), None);
3972        assert!(paired(&memory.detect_fact_overlaps().await.unwrap()));
3973        assert!(
3974            memory
3975                .record_overlap_review(a, 999_999, OverlapReviewVerdict::Distinct, "test")
3976                .await
3977                .is_err()
3978        );
3979    }
3980
3981    #[tokio::test]
3982    async fn unused_automated_facts_are_archived_and_nothing_else() {
3983        let (memory, _file) = open().await;
3984        let v = || tilted(0, 1.0);
3985        let idle = insert(
3986            &memory,
3987            Row {
3988                age_days: 90,
3989                ..Row::new("preference", "idle", "idle value", v())
3990            },
3991        )
3992        .await;
3993        let progressive = insert(
3994            &memory,
3995            Row {
3996                age_days: 90,
3997                source: "progressive",
3998                ..Row::new("technical", "idle_tool", "idle tool", v())
3999            },
4000        )
4001        .await;
4002        let mut kept = Vec::new();
4003        for row in [
4004            Row {
4005                age_days: 90,
4006                recall: 1,
4007                ..Row::new("preference", "recalled", "r", v())
4008            },
4009            Row {
4010                age_days: 90,
4011                source: "user_stated",
4012                ..Row::new("preference", "stated", "s", v())
4013            },
4014            Row {
4015                age_days: 90,
4016                source: OWNER_QUOTED_SOURCE,
4017                ..Row::new("preference", "quoted", "q", v())
4018            },
4019            Row {
4020                age_days: 90,
4021                ..Row::new("user", "hometown", "h", v())
4022            },
4023            Row {
4024                age_days: 10,
4025                ..Row::new("preference", "recent", "n", v())
4026            },
4027        ] {
4028            kept.push(insert(&memory, row).await);
4029        }
4030        let recalled_once = insert(
4031            &memory,
4032            Row {
4033                age_days: 90,
4034                ..Row::new("preference", "recalled_once", "o", v())
4035            },
4036        )
4037        .await;
4038        sqlx::query("UPDATE facts SET last_recalled_at = ? WHERE id = ?")
4039            .bind(Utc::now().to_rfc3339())
4040            .bind(recalled_once)
4041            .execute(memory.pool())
4042            .await
4043            .unwrap();
4044        kept.push(recalled_once);
4045
4046        let now = Utc::now();
4047        assert_eq!(
4048            memory.archive_unused_automated_facts(now, 0).await.unwrap(),
4049            0
4050        );
4051        assert_eq!(
4052            memory
4053                .archive_unused_automated_facts(now, 60)
4054                .await
4055                .unwrap(),
4056            2
4057        );
4058        let archived: Vec<i64> = memory
4059            .get_archived_facts(10)
4060            .await
4061            .unwrap()
4062            .into_iter()
4063            .map(|f| f.id)
4064            .collect();
4065        assert!(archived.contains(&idle) && archived.contains(&progressive));
4066        for id in &kept {
4067            assert!(!archived.contains(id), "#{id} archived");
4068        }
4069        // Reversible.
4070        assert!(memory.restore_fact(idle).await.unwrap().is_some());
4071    }
4072
4073    #[tokio::test]
4074    async fn decay_memory_runs_the_hygiene_steps() {
4075        let (memory, _file) = open().await;
4076        insert(
4077            &memory,
4078            Row {
4079                age_days: 90,
4080                ..Row::new("preference", "idle", "idle value", tilted(0, 1.0))
4081            },
4082        )
4083        .await;
4084        let old = insert(
4085            &memory,
4086            Row::new("technical", "node_version", "Node 18", tilted(4, 1.0)),
4087        )
4088        .await;
4089        insert(
4090            &memory,
4091            Row::new(
4092                "technical",
4093                "current_node_version",
4094                "Node 20",
4095                tilted(4, 0.95),
4096            ),
4097        )
4098        .await;
4099        crate::stores::decay_memory(&memory, &DecayPolicy::default())
4100            .await
4101            .unwrap();
4102        assert_eq!(memory.get_archived_facts(10).await.unwrap().len(), 1);
4103        assert_eq!(status(&memory, old).await.0.as_deref(), Some("replaced"));
4104    }
4105
4106    #[tokio::test]
4107    async fn job_watermarks_round_trip() {
4108        let (memory, _file) = open().await;
4109        assert_eq!(memory.job_last_run_at("memory_decay").await.unwrap(), None);
4110        let first = Utc::now() - chrono::Duration::hours(30);
4111        memory
4112            .record_job_run_at("memory_decay", first)
4113            .await
4114            .unwrap();
4115        let read = memory
4116            .job_last_run_at("memory_decay")
4117            .await
4118            .unwrap()
4119            .unwrap();
4120        assert_eq!(read.timestamp(), first.timestamp());
4121        let second = Utc::now();
4122        memory
4123            .record_job_run_at("memory_decay", second)
4124            .await
4125            .unwrap();
4126        let read = memory
4127            .job_last_run_at("memory_decay")
4128            .await
4129            .unwrap()
4130            .unwrap();
4131        assert_eq!(read.timestamp(), second.timestamp());
4132        assert_eq!(memory.job_last_run_at("other_job").await.unwrap(), None);
4133    }
4134
4135    #[tokio::test]
4136    async fn fact_lookup_by_id_sees_archived_but_not_retired_facts() {
4137        let (memory, _file) = open().await;
4138        let id = insert(&memory, Row::new("project", "p", "v", tilted(0, 1.0))).await;
4139        assert!(memory.fact_exists(id).await.unwrap());
4140        assert!(memory.archive_fact(id).await.unwrap());
4141        assert!(memory.fact_exists(id).await.unwrap());
4142        assert_eq!(memory.get_fact_by_id(id).await.unwrap().unwrap().value, "v");
4143        memory.delete_fact(id).await.unwrap();
4144        assert!(!memory.fact_exists(id).await.unwrap());
4145        assert!(!memory.fact_exists(424_242).await.unwrap());
4146        assert!(!memory.fact_exists(-424_242).await.unwrap());
4147    }
4148
4149    #[test]
4150    fn select_diverse_skips_paraphrases_within_a_category() {
4151        let ranked = vec![
4152            ("a", "preference".to_string(), Some(tilted(0, 1.0))),
4153            (
4154                "a-paraphrase",
4155                "preference".to_string(),
4156                Some(tilted(0, 0.95)),
4157            ),
4158            (
4159                "same-vector-other-category",
4160                "project".to_string(),
4161                Some(tilted(0, 1.0)),
4162            ),
4163            ("no-vector", "preference".to_string(), None),
4164            ("b", "preference".to_string(), Some(tilted(0, 0.6))),
4165        ];
4166        assert_eq!(
4167            select_diverse(ranked.clone(), 10),
4168            vec!["a", "same-vector-other-category", "no-vector", "b"]
4169        );
4170        assert_eq!(
4171            select_diverse(ranked, 2),
4172            vec!["a", "same-vector-other-category"]
4173        );
4174    }
4175
4176    #[tokio::test]
4177    async fn a_paraphrase_does_not_crowd_a_distinct_fact_out_of_recall() {
4178        let (memory, _file) = open().await;
4179        let query = "what tone should replies use";
4180        let q = HashEmbedder::new(EMBEDDING_DIM).embed_one(query);
4181        // Two unit vectors orthogonal to q and to each other.
4182        let orthogonal = |seed: usize, against: &[&[f32]]| {
4183            let mut v = vec![0.0f32; EMBEDDING_DIM];
4184            v[seed] = 1.0;
4185            for other in against {
4186                let dot: f32 = v.iter().zip(other.iter()).map(|(x, y)| x * y).sum();
4187                v.iter_mut()
4188                    .zip(other.iter())
4189                    .for_each(|(x, y)| *x -= dot * y);
4190            }
4191            let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
4192            v.iter_mut().for_each(|x| *x /= norm);
4193            v
4194        };
4195        let u = orthogonal(3, &[&q]);
4196        let w = orthogonal(7, &[&q, &u]);
4197        let mix = |a: f32, x: &[f32], b: f32, y: &[f32]| -> Vec<f32> {
4198            x.iter().zip(y).map(|(x, y)| a * x + b * y).collect()
4199        };
4200        let top = insert(
4201            &memory,
4202            Row {
4203                source: "user_stated",
4204                ..Row::new("preference", "voice", "warm and direct", q.clone())
4205            },
4206        )
4207        .await;
4208        let paraphrase = insert(
4209            &memory,
4210            Row {
4211                source: "user_stated",
4212                ..Row::new(
4213                    "preference",
4214                    "voice_style",
4215                    "direct, warm voice",
4216                    mix(0.95, &q, 0.3122, &u),
4217                )
4218            },
4219        )
4220        .await;
4221        let distinct = insert(
4222            &memory,
4223            Row {
4224                source: "user_stated",
4225                ..Row::new(
4226                    "preference",
4227                    "length",
4228                    "under five sentences",
4229                    mix(0.6, &q, 0.8, &w),
4230                )
4231            },
4232        )
4233        .await;
4234        let ids: Vec<i64> = memory
4235            .get_relevant_facts(query, 2)
4236            .await
4237            .unwrap()
4238            .into_iter()
4239            .map(|f| f.id)
4240            .collect();
4241        assert!(ids.contains(&top) && ids.contains(&distinct), "{ids:?}");
4242        assert!(!ids.contains(&paraphrase));
4243        // With room for all three, the paraphrase is still left out: it
4244        // adds nothing beside the fact it restates.
4245        let ids: Vec<i64> = memory
4246            .get_relevant_facts_for_channel(query, 5, None, ChannelVisibility::Private, true)
4247            .await
4248            .unwrap()
4249            .into_iter()
4250            .map(|f| f.id)
4251            .collect();
4252        assert_eq!(ids.len(), 2, "{ids:?}");
4253    }
4254
4255    #[tokio::test]
4256    async fn owner_fold_and_confirm_fact_work_for_explicit_triage() {
4257        let (memory, _file) = open().await;
4258        let kept = insert(
4259            &memory,
4260            Row {
4261                source: "user_stated",
4262                recall: 2,
4263                ..Row::new(
4264                    "preference",
4265                    "design_pref",
4266                    "Polished sites",
4267                    tilted(0, 1.0),
4268                )
4269            },
4270        )
4271        .await;
4272        let owner_dup = insert(
4273            &memory,
4274            Row {
4275                source: "user_stated",
4276                recall: 5,
4277                ..Row::new(
4278                    "preference",
4279                    "design_quality",
4280                    "Nice polished sites",
4281                    tilted(0, 0.88),
4282                )
4283            },
4284        )
4285        .await;
4286        // Automated fold refuses rank-2 owner facts, while explicit owner fold succeeds.
4287        assert!(!memory.fold_fact_into(owner_dup, kept).await.unwrap());
4288        assert!(memory.owner_fold_fact_into(owner_dup, kept).await.unwrap());
4289        assert_eq!(
4290            status(&memory, owner_dup).await,
4291            (Some("folded".into()), Some(kept))
4292        );
4293        // Owner fold still refuses narrowing a group-channel fact into private.
4294        let group_dup = insert(
4295            &memory,
4296            Row {
4297                privacy: "channel",
4298                channel: Some("slack:synthetic-team"),
4299                ..Row::new(
4300                    "preference",
4301                    "design_team",
4302                    "Team polished sites",
4303                    tilted(0, 0.88),
4304                )
4305            },
4306        )
4307        .await;
4308        assert!(!memory.owner_fold_fact_into(group_dup, kept).await.unwrap());
4309
4310        let inferred = insert(
4311            &memory,
4312            Row {
4313                source: "inferred",
4314                ..Row::new("preference", "editor", "Uses Helix", tilted(4, 1.0))
4315            },
4316        )
4317        .await;
4318        let confirmed = memory
4319            .confirm_fact(inferred)
4320            .await
4321            .unwrap()
4322            .expect("confirmed fact");
4323        assert_eq!(confirmed.source, "user_stated");
4324        assert_eq!(confirmed.value, "Uses Helix");
4325        assert!(memory.confirm_fact(-10).await.unwrap().is_none());
4326    }
4327}