Skip to main content

aidaemon_memory/sqlite/
claims.rs

1use std::collections::HashSet;
2
3use sqlx::Row;
4
5use super::*;
6use crate::embedding_index::{
7    EmbeddingHit, EmbeddingIndex, EmbeddingItem, EmbeddingSearchFilter, MemoryOwner, content_hash,
8};
9use crate::stores::{
10    GraphEdgeUpsert, GraphEntityUpsert, GraphNeighbor, GraphSearchScope, MemoryGraphStore,
11};
12
13/// Ids per lookup query, well under SQLite's bound-parameter limit.
14const LOOKUP_CHUNK: usize = 500;
15
16/// Hit scores by numeric owner id; ids that are not numbers are skipped.
17fn owner_scores(hits: &[EmbeddingHit]) -> std::collections::HashMap<i64, f32> {
18    let mut scores = std::collections::HashMap::new();
19    for hit in hits {
20        if let Ok(id) = hit.owner.owner_id.parse::<i64>() {
21            scores
22                .entry(id)
23                .and_modify(|existing: &mut f32| *existing = existing.max(hit.score))
24                .or_insert(hit.score);
25        }
26    }
27    scores
28}
29
30#[derive(Debug, Clone)]
31#[allow(dead_code)]
32pub struct MemoryClaimRecord {
33    pub id: i64,
34    pub claim_text: String,
35    pub source_fact_id: Option<i64>,
36    pub channel_id: Option<String>,
37    pub privacy: FactPrivacy,
38}
39
40impl SqliteMemory {
41    pub async fn canonical_memory_health(
42        &self,
43    ) -> anyhow::Result<crate::records::MemoryHealthReport> {
44        async fn count(pool: &SqlitePool, sql: &str) -> anyhow::Result<i64> {
45            Ok(sqlx::query_scalar(sqlx::AssertSqlSafe(sql))
46                .fetch_one(pool)
47                .await?)
48        }
49        Ok(crate::records::MemoryHealthReport {
50            spans: count(&self.pool, "SELECT COUNT(*) FROM memory_spans WHERE deleted_at IS NULL")
51                .await?,
52            active_claims: count(
53                &self.pool,
54                "SELECT COUNT(*) FROM memory_claims WHERE deleted_at IS NULL AND valid_to IS NULL",
55            )
56            .await?,
57            entities: count(
58                &self.pool,
59                "SELECT COUNT(*) FROM memory_entities WHERE deleted_at IS NULL",
60            )
61            .await?,
62            active_edges: count(
63                &self.pool,
64                "SELECT COUNT(*) FROM memory_edges WHERE deleted_at IS NULL AND valid_to IS NULL",
65            )
66            .await?,
67            active_embeddings: count(
68                &self.pool,
69                "SELECT COUNT(*) FROM memory_embeddings WHERE stale_at IS NULL",
70            )
71            .await?,
72            stale_embeddings: count(
73                &self.pool,
74                "SELECT COUNT(*) FROM memory_embeddings WHERE stale_at IS NOT NULL",
75            )
76            .await?,
77            facts_missing_claims: count(
78                &self.pool,
79                "SELECT COUNT(*) FROM facts f LEFT JOIN memory_claims c ON c.source_fact_id = f.id
80                 WHERE f.superseded_at IS NULL AND c.id IS NULL",
81            )
82            .await?,
83            episodes_missing_spans: count(
84                &self.pool,
85                "SELECT COUNT(*) FROM episodes e LEFT JOIN memory_spans s ON s.source_episode_id = e.id
86                 WHERE s.id IS NULL",
87            )
88            .await?,
89            orphan_edges: count(
90                &self.pool,
91                "SELECT COUNT(*) FROM memory_edges edge
92                 WHERE NOT EXISTS (SELECT 1 FROM memory_entities e WHERE e.id = edge.source_entity_id)
93                    OR NOT EXISTS (SELECT 1 FROM memory_entities e WHERE e.id = edge.target_entity_id)
94                    OR (edge.source_claim_id IS NOT NULL AND NOT EXISTS (
95                        SELECT 1 FROM memory_claims c WHERE c.id = edge.source_claim_id))",
96            )
97            .await?,
98            embedding_dimension_mismatches: count(
99                &self.pool,
100                "SELECT COUNT(*) FROM memory_embeddings
101                 WHERE embedding_dim <= 0 OR length(embedding) != embedding_dim * 4",
102            )
103            .await?,
104        })
105    }
106
107    pub async fn graph_fact_ids_for_query(&self, query: &str) -> anyhow::Result<HashSet<i64>> {
108        let tokens: Vec<String> = query
109            .split(|ch: char| !ch.is_alphanumeric())
110            .map(str::trim)
111            .filter(|token| token.len() >= 3)
112            .take(12)
113            .map(str::to_lowercase)
114            .collect();
115        let mut ids = HashSet::new();
116        for token in tokens {
117            let pattern = format!("%{token}%");
118            let rows: Vec<i64> = sqlx::query_scalar(
119                "SELECT DISTINCT c.source_fact_id
120                 FROM memory_edges edge
121                 JOIN memory_entities source ON source.id = edge.source_entity_id
122                 JOIN memory_entities target ON target.id = edge.target_entity_id
123                 JOIN memory_claims c ON c.id = edge.source_claim_id
124                 WHERE edge.deleted_at IS NULL AND edge.valid_to IS NULL
125                   AND c.deleted_at IS NULL AND c.valid_to IS NULL
126                   AND c.source_fact_id IS NOT NULL
127                   AND (lower(source.display_name) LIKE ? OR lower(source.canonical_name) LIKE ?
128                        OR lower(target.display_name) LIKE ? OR lower(target.canonical_name) LIKE ?
129                        OR lower(edge.relation) LIKE ?)
130                 LIMIT 500",
131            )
132            .bind(&pattern)
133            .bind(&pattern)
134            .bind(&pattern)
135            .bind(&pattern)
136            .bind(&pattern)
137            .fetch_all(&self.pool)
138            .await?;
139            ids.extend(rows);
140        }
141        Ok(ids)
142    }
143
144    pub async fn search_embedding_owners(
145        &self,
146        query: &[f32],
147        owner_type: &str,
148        purpose: &str,
149        limit: usize,
150    ) -> anyhow::Result<Vec<EmbeddingHit>> {
151        self.embedding_index
152            .search(
153                query,
154                &EmbeddingSearchFilter {
155                    owner_types: vec![owner_type.to_string()],
156                    purpose: Some(purpose.to_string()),
157                    model: Some(self.embedding_service.model_id()),
158                },
159                limit,
160            )
161            .await
162    }
163
164    pub async fn fact_embedding_scores(
165        &self,
166        query: &[f32],
167        limit: usize,
168    ) -> anyhow::Result<std::collections::HashMap<i64, f32>> {
169        let hits = self
170            .search_embedding_owners(query, "claim", "recall", limit)
171            .await?;
172        let claim_scores = owner_scores(&hits);
173        let mut scores = std::collections::HashMap::new();
174        // One query per chunk of hits, not one per hit: recall asks for as
175        // many hits as there are facts.
176        let ids: Vec<i64> = claim_scores.keys().copied().collect();
177        for chunk in ids.chunks(LOOKUP_CHUNK) {
178            let mut builder = sqlx::QueryBuilder::<sqlx::Sqlite>::new(
179                "SELECT c.id AS claim_id, c.source_fact_id AS fact_id
180                 FROM memory_claims c
181                 JOIN facts f ON f.id = c.source_fact_id
182                 JOIN memory_embeddings me
183                   ON me.owner_type = 'claim' AND me.owner_id = CAST(c.id AS TEXT)
184                  AND me.embedding_purpose = 'recall' AND me.embedding_model = ",
185            );
186            builder.push_bind(self.embedding_service.model_id());
187            builder.push(
188                " AND me.stale_at IS NULL
189                 WHERE c.deleted_at IS NULL AND c.valid_to IS NULL
190                   AND ((f.embedding IS NOT NULL AND me.embedding = f.embedding)
191                     OR (f.embedding IS NULL
192                         AND julianday(me.updated_at) >= julianday(f.updated_at)))
193                   AND c.id IN (",
194            );
195            let mut separated = builder.separated(", ");
196            for id in chunk {
197                separated.push_bind(*id);
198            }
199            separated.push_unseparated(")");
200            for row in builder.build().fetch_all(&self.pool).await? {
201                let claim_id: i64 = row.get("claim_id");
202                let Some(fact_id) = row.get::<Option<i64>, _>("fact_id") else {
203                    continue;
204                };
205                let Some(score) = claim_scores.get(&claim_id).copied() else {
206                    continue;
207                };
208                scores
209                    .entry(fact_id)
210                    .and_modify(|existing: &mut f32| *existing = existing.max(score))
211                    .or_insert(score);
212            }
213        }
214        Ok(scores)
215    }
216
217    pub async fn episode_embedding_scores(
218        &self,
219        query: &[f32],
220        limit: usize,
221    ) -> anyhow::Result<std::collections::HashMap<i64, f32>> {
222        let hits = self
223            .search_embedding_owners(query, "span", "recall", limit)
224            .await?;
225        let span_scores = owner_scores(&hits);
226        let mut scores = std::collections::HashMap::new();
227        let ids: Vec<i64> = span_scores.keys().copied().collect();
228        for chunk in ids.chunks(LOOKUP_CHUNK) {
229            let mut builder = sqlx::QueryBuilder::<sqlx::Sqlite>::new(
230                "SELECT id, source_episode_id FROM memory_spans
231                 WHERE deleted_at IS NULL AND valid_to IS NULL AND id IN (",
232            );
233            let mut separated = builder.separated(", ");
234            for id in chunk {
235                separated.push_bind(*id);
236            }
237            separated.push_unseparated(")");
238            for row in builder.build().fetch_all(&self.pool).await? {
239                let span_id: i64 = row.get("id");
240                let Some(episode_id) = row.get::<Option<i64>, _>("source_episode_id") else {
241                    continue;
242                };
243                let Some(score) = span_scores.get(&span_id).copied() else {
244                    continue;
245                };
246                // Several spans can come from one episode: keep the best.
247                scores
248                    .entry(episode_id)
249                    .and_modify(|existing: &mut f32| *existing = existing.max(score))
250                    .or_insert(score);
251            }
252        }
253        Ok(scores)
254    }
255
256    pub async fn upsert_owner_embedding(
257        &self,
258        owner_type: &str,
259        owner_id: i64,
260        purpose: &str,
261        content: &str,
262        embedding: Vec<f32>,
263    ) -> anyhow::Result<()> {
264        self.embedding_index
265            .upsert(EmbeddingItem {
266                owner: MemoryOwner::new(owner_type, owner_id),
267                purpose: purpose.to_string(),
268                model: self.embedding_service.model_id(),
269                content_hash: content_hash(content),
270                embedding,
271            })
272            .await
273    }
274
275    pub async fn project_fact_memory(&self, fact_id: i64) -> anyhow::Result<()> {
276        let Some(row) = sqlx::query(
277            "SELECT id, category, key, value, source, channel_id, privacy, embedding,
278                    created_at, updated_at, superseded_at, first_seen_at, source_excerpt
279             FROM facts WHERE id = ?",
280        )
281        .bind(fact_id)
282        .fetch_optional(&self.pool)
283        .await?
284        else {
285            return Ok(());
286        };
287
288        let superseded_at: Option<String> = row.get("superseded_at");
289        if let Some(valid_to) = superseded_at {
290            sqlx::query(
291                "UPDATE memory_claims SET valid_to = COALESCE(valid_to, ?), updated_at = datetime('now')
292                 WHERE source_fact_id = ?",
293            )
294            .bind(&valid_to)
295            .bind(fact_id)
296            .execute(&self.pool)
297            .await?;
298            if let Some(claim_id) = sqlx::query_scalar::<_, i64>(
299                "SELECT id FROM memory_claims WHERE source_fact_id = ?",
300            )
301            .bind(fact_id)
302            .fetch_optional(&self.pool)
303            .await?
304            {
305                self.embedding_index
306                    .mark_stale(&MemoryOwner::new("claim", claim_id))
307                    .await?;
308                MemoryGraphStore::invalidate_claim(self, claim_id, &valid_to).await?;
309            }
310            return Ok(());
311        }
312
313        let category: String = row.get("category");
314        let key: String = row.get("key");
315        let value: String = row.get("value");
316        let source: String = row.get("source");
317        let channel_id: Option<String> = row.get("channel_id");
318        let privacy: String = row.get("privacy");
319        let valid_from: String = row.get("created_at");
320        let first_seen_at: Option<String> = row.get("first_seen_at");
321        let source_excerpt: Option<String> = row.get("source_excerpt");
322        let evidence = find_evidence_span(
323            &self.pool,
324            source_excerpt.as_deref(),
325            channel_id.as_deref(),
326            first_seen_at.as_deref(),
327        )
328        .await?;
329        let claim_text = super::facts::build_fact_embedding_text(&category, &key, &value);
330
331        sqlx::query(
332            "INSERT INTO memory_claims
333                (subject, predicate, object, claim_text, source_fact_id, source_span_id,
334                 source_event_id, provenance,
335                 confidence, channel_id, privacy, valid_from, updated_at)
336             VALUES ('owner', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
337             ON CONFLICT(source_fact_id) DO UPDATE SET
338                predicate = excluded.predicate,
339                object = excluded.object,
340                claim_text = excluded.claim_text,
341                source_span_id = COALESCE(excluded.source_span_id, memory_claims.source_span_id),
342                source_event_id = COALESCE(excluded.source_event_id, memory_claims.source_event_id),
343                provenance = excluded.provenance,
344                confidence = excluded.confidence,
345                channel_id = excluded.channel_id,
346                privacy = excluded.privacy,
347                valid_to = NULL,
348                deleted_at = NULL,
349                updated_at = datetime('now')",
350        )
351        .bind(&key)
352        .bind(&value)
353        .bind(&claim_text)
354        .bind(fact_id)
355        .bind(evidence.map(|(span_id, _)| span_id))
356        .bind(evidence.and_then(|(_, event_id)| event_id))
357        .bind(&source)
358        .bind(if source == "consolidation" { 0.7 } else { 1.0 })
359        .bind(channel_id.as_deref())
360        .bind(&privacy)
361        .bind(&valid_from)
362        .execute(&self.pool)
363        .await?;
364
365        let claim_id: i64 =
366            sqlx::query_scalar("SELECT id FROM memory_claims WHERE source_fact_id = ?")
367                .bind(fact_id)
368                .fetch_one(&self.pool)
369                .await?;
370
371        if let Some(blob) = row.get::<Option<Vec<u8>>, _>("embedding")
372            && let Ok(embedding) = self.embedding_service.decode(&blob)
373        {
374            self.embedding_index
375                .upsert(EmbeddingItem {
376                    owner: MemoryOwner::new("claim", claim_id),
377                    purpose: "recall".to_string(),
378                    model: self.embedding_service.model_id(),
379                    content_hash: content_hash(&claim_text),
380                    embedding,
381                })
382                .await?;
383        }
384
385        self.project_claim_graph(claim_id, &category, &key, &privacy, channel_id.as_deref())
386            .await?;
387        Ok(())
388    }
389
390    pub async fn project_episode_memory(&self, episode_id: i64) -> anyhow::Result<()> {
391        let Some(row) = sqlx::query(
392            "SELECT id, session_id, summary, channel_id, embedding, start_time, end_time
393             FROM episodes WHERE id = ?",
394        )
395        .bind(episode_id)
396        .fetch_optional(&self.pool)
397        .await?
398        else {
399            return Ok(());
400        };
401        let summary: String = row.get("summary");
402        let session_id: String = row.get("session_id");
403        let channel_id: Option<String> = row.get("channel_id");
404        let start_time: String = row.get("start_time");
405        let end_time: String = row.get("end_time");
406        sqlx::query(
407            "INSERT INTO memory_spans
408                (span_kind, source_episode_id, session_id, channel_id, role, content,
409                content_hash, privacy, observed_from, observed_to, valid_from)
410             VALUES ('episode', ?, ?, ?, 'summary', ?, ?, 'channel', ?, ?, ?)
411             ON CONFLICT(source_episode_id) DO UPDATE SET
412                session_id = excluded.session_id,
413                channel_id = excluded.channel_id,
414                content = excluded.content,
415                content_hash = excluded.content_hash,
416                observed_from = excluded.observed_from,
417                observed_to = excluded.observed_to,
418                valid_from = excluded.valid_from,
419                valid_to = NULL,
420                deleted_at = NULL",
421        )
422        .bind(episode_id)
423        .bind(&session_id)
424        .bind(channel_id.as_deref())
425        .bind(&summary)
426        .bind(content_hash(&summary))
427        .bind(&start_time)
428        .bind(&end_time)
429        .bind(&start_time)
430        .execute(&self.pool)
431        .await?;
432        let span_id: i64 =
433            sqlx::query_scalar("SELECT id FROM memory_spans WHERE source_episode_id = ?")
434                .bind(episode_id)
435                .fetch_one(&self.pool)
436                .await?;
437        if let Some(blob) = row.get::<Option<Vec<u8>>, _>("embedding")
438            && let Ok(embedding) = self.embedding_service.decode(&blob)
439        {
440            self.embedding_index
441                .upsert(EmbeddingItem {
442                    owner: MemoryOwner::new("span", span_id),
443                    purpose: "recall".to_string(),
444                    model: self.embedding_service.model_id(),
445                    content_hash: content_hash(&summary),
446                    embedding,
447                })
448                .await?;
449        }
450        Ok(())
451    }
452
453    #[allow(dead_code)]
454    pub async fn rebuild_memory_projections(&self) -> anyhow::Result<(usize, usize)> {
455        let fact_ids: Vec<i64> = sqlx::query_scalar("SELECT id FROM facts ORDER BY id")
456            .fetch_all(&self.pool)
457            .await?;
458        for id in &fact_ids {
459            self.project_fact_memory(*id).await?;
460        }
461        let episode_ids: Vec<i64> = sqlx::query_scalar("SELECT id FROM episodes ORDER BY id")
462            .fetch_all(&self.pool)
463            .await?;
464        for id in &episode_ids {
465            self.project_episode_memory(*id).await?;
466        }
467        Ok((fact_ids.len(), episode_ids.len()))
468    }
469
470    pub async fn backfill_missing_memory_projections(
471        &self,
472    ) -> anyhow::Result<(usize, usize, usize, usize, usize)> {
473        const BATCH_SIZE: i64 = 500;
474        let selected_event_spans_before: i64 = sqlx::query_scalar(
475            "SELECT COUNT(*) FROM memory_spans WHERE source_event_id IS NOT NULL",
476        )
477        .fetch_one(&self.pool)
478        .await?;
479        let mut fact_count = 0usize;
480        loop {
481            let ids: Vec<i64> = sqlx::query_scalar(
482                "SELECT f.id FROM facts f
483                 LEFT JOIN memory_claims c ON c.source_fact_id = f.id
484                 WHERE (f.superseded_at IS NULL AND c.id IS NULL)
485                    OR (f.superseded_at IS NOT NULL
486                        AND c.id IS NOT NULL
487                        AND c.valid_to IS NULL)
488                 ORDER BY f.id LIMIT ?",
489            )
490            .bind(BATCH_SIZE)
491            .fetch_all(&self.pool)
492            .await?;
493            if ids.is_empty() {
494                break;
495            }
496            fact_count += ids.len();
497            for id in ids {
498                self.project_fact_memory(id).await?;
499            }
500        }
501
502        let mut episode_count = 0usize;
503        loop {
504            let ids: Vec<i64> = sqlx::query_scalar(
505                "SELECT e.id FROM episodes e
506                 LEFT JOIN memory_spans s ON s.source_episode_id = e.id
507                 WHERE s.id IS NULL ORDER BY e.id LIMIT ?",
508            )
509            .bind(BATCH_SIZE)
510            .fetch_all(&self.pool)
511            .await?;
512            if ids.is_empty() {
513                break;
514            }
515            episode_count += ids.len();
516            for id in ids {
517                self.project_episode_memory(id).await?;
518            }
519        }
520
521        // Raw user messages remain canonical events and exact-history rows.
522        // They enter the durable memory graph only when a selected fact/claim
523        // needs that exact event as provenance; an allowed memory policy is a
524        // capability boundary, not a decision to remember every control turn.
525        let evidence_fact_ids: Vec<i64> = sqlx::query_scalar(
526            "SELECT f.id
527             FROM facts f
528             JOIN memory_claims c ON c.source_fact_id = f.id
529             WHERE c.source_span_id IS NULL
530               AND f.source_excerpt IS NOT NULL
531               AND trim(f.source_excerpt) != ''
532             ORDER BY f.id",
533        )
534        .fetch_all(&self.pool)
535        .await?;
536        for id in evidence_fact_ids {
537            self.project_fact_memory(id).await?;
538        }
539        let selected_event_spans_after: i64 = sqlx::query_scalar(
540            "SELECT COUNT(*) FROM memory_spans WHERE source_event_id IS NOT NULL",
541        )
542        .fetch_one(&self.pool)
543        .await?;
544        let event_count =
545            selected_event_spans_after.saturating_sub(selected_event_spans_before) as usize;
546
547        let mut procedure_count = 0usize;
548        let mut after_id = 0i64;
549        loop {
550            let rows = sqlx::query(
551                "SELECT p.id, p.trigger_pattern, p.trigger_embedding
552                 FROM procedures p
553                 WHERE p.id > ? AND p.trigger_embedding IS NOT NULL
554                   AND NOT EXISTS (
555                       SELECT 1 FROM memory_embeddings me
556                       WHERE me.owner_type = 'procedure' AND me.owner_id = CAST(p.id AS TEXT)
557                         AND me.embedding_purpose = 'trigger' AND me.embedding_model = ?
558                         AND me.stale_at IS NULL
559                   )
560                 ORDER BY p.id LIMIT ?",
561            )
562            .bind(after_id)
563            .bind(self.embedding_service.model_id())
564            .bind(BATCH_SIZE)
565            .fetch_all(&self.pool)
566            .await?;
567            if rows.is_empty() {
568                break;
569            }
570            for row in rows {
571                let id: i64 = row.get("id");
572                after_id = id;
573                let content: String = row.get("trigger_pattern");
574                let blob: Vec<u8> = row.get("trigger_embedding");
575                if let Ok(embedding) = self.embedding_service.decode(&blob) {
576                    self.upsert_owner_embedding("procedure", id, "trigger", &content, embedding)
577                        .await?;
578                    procedure_count += 1;
579                }
580            }
581        }
582
583        let mut error_count = 0usize;
584        after_id = 0;
585        loop {
586            let rows = sqlx::query(
587                "SELECT e.id, e.error_pattern, e.error_embedding
588                 FROM error_solutions e
589                 WHERE e.id > ? AND e.error_embedding IS NOT NULL
590                   AND NOT EXISTS (
591                       SELECT 1 FROM memory_embeddings me
592                       WHERE me.owner_type = 'error_solution' AND me.owner_id = CAST(e.id AS TEXT)
593                         AND me.embedding_purpose = 'error' AND me.embedding_model = ?
594                         AND me.stale_at IS NULL
595                   )
596                 ORDER BY e.id LIMIT ?",
597            )
598            .bind(after_id)
599            .bind(self.embedding_service.model_id())
600            .bind(BATCH_SIZE)
601            .fetch_all(&self.pool)
602            .await?;
603            if rows.is_empty() {
604                break;
605            }
606            for row in rows {
607                let id: i64 = row.get("id");
608                after_id = id;
609                let content: String = row.get("error_pattern");
610                let blob: Vec<u8> = row.get("error_embedding");
611                if let Ok(embedding) = self.embedding_service.decode(&blob) {
612                    self.upsert_owner_embedding("error_solution", id, "error", &content, embedding)
613                        .await?;
614                    error_count += 1;
615                }
616            }
617        }
618
619        Ok((
620            fact_count,
621            episode_count,
622            event_count,
623            procedure_count,
624            error_count,
625        ))
626    }
627
628    pub async fn sync_fact_memory_category(&self, category: &str) -> anyhow::Result<()> {
629        let ids: Vec<i64> = sqlx::query_scalar("SELECT id FROM facts WHERE category = ?")
630            .bind(category)
631            .fetch_all(&self.pool)
632            .await?;
633        self.sync_fact_memory_rows(category, &ids).await
634    }
635
636    /// Project the facts one write changed: the rows of `category` whose
637    /// `updated_at` or `superseded_at` is that write's timestamp. Every row
638    /// a fact upsert touches carries its timestamp, and re-projecting the
639    /// whole category on each write took seconds in a large one.
640    pub(crate) async fn sync_fact_memory_written_at(
641        &self,
642        category: &str,
643        written_at: &str,
644    ) -> anyhow::Result<()> {
645        let ids: Vec<i64> = sqlx::query_scalar(
646            "SELECT id FROM facts
647             WHERE category = ? AND (updated_at = ? OR superseded_at = ?)",
648        )
649        .bind(category)
650        .bind(written_at)
651        .bind(written_at)
652        .fetch_all(&self.pool)
653        .await?;
654        self.sync_fact_memory_rows(category, &ids).await
655    }
656
657    async fn sync_fact_memory_rows(&self, category: &str, ids: &[i64]) -> anyhow::Result<()> {
658        for id in ids {
659            self.project_fact_memory(*id).await?;
660        }
661        sqlx::query(
662            "UPDATE memory_claims AS old
663             SET superseded_by_claim_id = (
664                SELECT replacement.id
665                FROM memory_claims replacement
666                JOIN facts new_fact ON new_fact.id = replacement.source_fact_id
667                JOIN facts old_fact ON old_fact.id = old.source_fact_id
668                WHERE new_fact.category = old_fact.category
669                  AND new_fact.key = old_fact.key
670                  AND new_fact.superseded_at IS NULL
671                LIMIT 1
672             )
673             WHERE old.source_fact_id IN (SELECT id FROM facts WHERE category = ?)
674               AND old.valid_to IS NOT NULL",
675        )
676        .bind(category)
677        .execute(&self.pool)
678        .await?;
679        Ok(())
680    }
681
682    /// FTS5 claim search with visibility and temporal filtering at the owner row.
683    pub async fn search_memory_claims(
684        &self,
685        query: &str,
686        channel_id: Option<&str>,
687        visibility: ChannelVisibility,
688        requester_is_owner: bool,
689        limit: usize,
690    ) -> anyhow::Result<Vec<MemoryClaimRecord>> {
691        let Some(fts_query) = sanitize_fts_query(query) else {
692            return Ok(Vec::new());
693        };
694        if matches!(visibility, ChannelVisibility::PublicExternal) || limit == 0 {
695            return Ok(Vec::new());
696        }
697
698        let rows = match sqlx::query(
699            "SELECT c.id, c.claim_text, c.source_fact_id, c.channel_id, c.privacy
700             FROM memory_claims_fts f
701             JOIN memory_claims c ON c.id = f.rowid
702             WHERE memory_claims_fts MATCH ?
703               AND c.deleted_at IS NULL AND c.valid_to IS NULL
704             ORDER BY bm25(memory_claims_fts) LIMIT ?",
705        )
706        .bind(&fts_query)
707        .bind((limit.saturating_mul(8).max(limit)) as i64)
708        .fetch_all(&self.pool)
709        .await
710        {
711            // `migrate` always creates memory_claims_fts, so a failure here
712            // is a real error for the caller, never a missing table.
713            Ok(rows) => rows,
714            Err(error) => return Err(error.into()),
715        };
716
717        let mut claims = Vec::new();
718        for row in rows {
719            let privacy = FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy"));
720            let claim_channel: Option<String> = row.get("channel_id");
721            if memory_visible(
722                self.channels.as_ref(),
723                privacy,
724                claim_channel.as_deref(),
725                channel_id,
726                visibility,
727                requester_is_owner,
728            ) {
729                claims.push(MemoryClaimRecord {
730                    id: row.get("id"),
731                    claim_text: row.get("claim_text"),
732                    source_fact_id: row.get("source_fact_id"),
733                    channel_id: claim_channel,
734                    privacy,
735                });
736                if claims.len() == limit {
737                    break;
738                }
739            }
740        }
741        Ok(claims)
742    }
743
744    /// Traverse active graph edges to at most `max_depth` (clamped to two).
745    #[allow(dead_code)]
746    pub async fn memory_graph_neighbors(
747        &self,
748        start_entity_id: i64,
749        max_depth: usize,
750        channel_id: Option<&str>,
751        visibility: ChannelVisibility,
752        requester_is_owner: bool,
753    ) -> anyhow::Result<Vec<GraphNeighbor>> {
754        let max_depth = max_depth.min(2);
755        let mut queue = VecDeque::from([(start_entity_id, 0usize)]);
756        let mut visited = HashSet::from([start_entity_id]);
757        let mut output = Vec::new();
758        while let Some((entity_id, depth)) = queue.pop_front() {
759            if depth >= max_depth {
760                continue;
761            }
762            let rows = sqlx::query(
763                "SELECT e.source_entity_id, e.target_entity_id, e.relation, e.channel_id,
764                        e.privacy, target.display_name
765                 FROM memory_edges e
766                 JOIN memory_entities target ON target.id = CASE
767                    WHEN e.source_entity_id = ? THEN e.target_entity_id ELSE e.source_entity_id END
768                 WHERE (e.source_entity_id = ? OR e.target_entity_id = ?)
769                   AND e.deleted_at IS NULL AND e.valid_to IS NULL
770                   AND target.deleted_at IS NULL
771                 LIMIT 100",
772            )
773            .bind(entity_id)
774            .bind(entity_id)
775            .bind(entity_id)
776            .fetch_all(&self.pool)
777            .await?;
778            for row in rows {
779                let privacy = FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy"));
780                let edge_channel: Option<String> = row.get("channel_id");
781                if !memory_visible(
782                    self.channels.as_ref(),
783                    privacy,
784                    edge_channel.as_deref(),
785                    channel_id,
786                    visibility,
787                    requester_is_owner,
788                ) {
789                    continue;
790                }
791                let source: i64 = row.get("source_entity_id");
792                let target: i64 = row.get("target_entity_id");
793                let neighbor_id = if source == entity_id { target } else { source };
794                if visited.insert(neighbor_id) {
795                    output.push(GraphNeighbor {
796                        entity_id: neighbor_id,
797                        display_name: row.get("display_name"),
798                        relation: row.get("relation"),
799                        depth: depth + 1,
800                    });
801                    queue.push_back((neighbor_id, depth + 1));
802                }
803            }
804        }
805        Ok(output)
806    }
807
808    async fn project_claim_graph(
809        &self,
810        claim_id: i64,
811        category: &str,
812        key: &str,
813        privacy: &str,
814        channel_id: Option<&str>,
815    ) -> anyhow::Result<()> {
816        let privacy_level = FactPrivacy::from_str_lossy(privacy);
817        let owner_id = MemoryGraphStore::upsert_entity(
818            self,
819            GraphEntityUpsert {
820                entity_type: "person".to_string(),
821                canonical_name: "owner".to_string(),
822                display_name: "Owner".to_string(),
823                aliases: Vec::new(),
824                channel_id: channel_id.map(str::to_owned),
825                privacy: privacy_level,
826            },
827        )
828        .await?;
829        let canonical = format!("{}:{}", category.to_lowercase(), key.to_lowercase());
830        let concept_id = MemoryGraphStore::upsert_entity(
831            self,
832            GraphEntityUpsert {
833                entity_type: "concept".to_string(),
834                canonical_name: canonical,
835                display_name: key.to_string(),
836                aliases: Vec::new(),
837                channel_id: channel_id.map(str::to_owned),
838                privacy: privacy_level,
839            },
840        )
841        .await?;
842        MemoryGraphStore::upsert_edge(
843            self,
844            GraphEdgeUpsert {
845                source_entity_id: owner_id,
846                target_entity_id: concept_id,
847                relation: "has_attribute".to_string(),
848                source_claim_id: claim_id,
849                confidence: 1.0,
850                channel_id: channel_id.map(str::to_owned),
851                privacy: privacy_level,
852            },
853        )
854        .await?;
855
856        Ok(())
857    }
858
859    pub async fn persist_extracted_fact_graph(
860        &self,
861        category: &str,
862        key: &str,
863        source_excerpt: &str,
864        graph: &crate::records::ExtractedMemoryGraph,
865    ) -> anyhow::Result<()> {
866        use std::collections::HashMap;
867
868        const MIN_CONFIDENCE: f32 = 0.65;
869        let claim = sqlx::query(
870            "SELECT c.id, c.channel_id, c.privacy
871             FROM memory_claims c
872             JOIN facts f ON f.id = c.source_fact_id
873             WHERE lower(f.category) = lower(?) AND lower(f.key) = lower(?)
874               AND f.superseded_at IS NULL AND c.deleted_at IS NULL AND c.valid_to IS NULL
875             ORDER BY f.updated_at DESC LIMIT 1",
876        )
877        .bind(category)
878        .bind(key)
879        .fetch_optional(&self.pool)
880        .await?;
881        let Some(claim) = claim else {
882            return Ok(());
883        };
884        let claim_id: i64 = claim.get("id");
885        let channel_id: Option<String> = claim.get("channel_id");
886        let privacy = FactPrivacy::from_str_lossy(&claim.get::<String, _>("privacy"));
887        let evidence = source_excerpt.to_lowercase();
888        let mut resolved = HashMap::new();
889
890        for entity in graph.entities.iter().take(32) {
891            let name = entity.name.trim();
892            let entity_type = normalize_graph_token(&entity.entity_type, 48);
893            let local_id = entity.local_id.trim();
894            if entity.confidence < MIN_CONFIDENCE
895                || name.is_empty()
896                || name.len() > 200
897                || entity_type.is_empty()
898                || local_id.is_empty()
899                || resolved.contains_key(local_id)
900                || !entity_is_grounded(name, &entity.aliases, &evidence)
901            {
902                continue;
903            }
904            let canonical_name = normalize_graph_name(name);
905            if canonical_name.is_empty() {
906                continue;
907            }
908            let (canonical_name, aliases) = resolve_entity_identity(
909                &self.pool,
910                &entity_type,
911                &canonical_name,
912                name,
913                &entity.aliases,
914            )
915            .await?;
916            let entity_id = MemoryGraphStore::upsert_entity(
917                self,
918                GraphEntityUpsert {
919                    entity_type,
920                    canonical_name,
921                    display_name: name.to_string(),
922                    aliases,
923                    channel_id: channel_id.clone(),
924                    privacy,
925                },
926            )
927            .await?;
928            resolved.insert(local_id.to_string(), entity_id);
929        }
930
931        for relationship in graph.relationships.iter().take(64) {
932            let relation = normalize_graph_token(&relationship.relation, 80);
933            let (Some(&source_entity_id), Some(&target_entity_id)) = (
934                resolved.get(relationship.source_id.trim()),
935                resolved.get(relationship.target_id.trim()),
936            ) else {
937                continue;
938            };
939            if relationship.confidence < MIN_CONFIDENCE
940                || relation.is_empty()
941                || source_entity_id == target_entity_id
942            {
943                continue;
944            }
945            MemoryGraphStore::upsert_edge(
946                self,
947                GraphEdgeUpsert {
948                    source_entity_id,
949                    target_entity_id,
950                    relation,
951                    source_claim_id: claim_id,
952                    confidence: relationship.confidence.clamp(0.0, 1.0),
953                    channel_id: channel_id.clone(),
954                    privacy,
955                },
956            )
957            .await?;
958        }
959        Ok(())
960    }
961}
962
963fn normalize_graph_token(value: &str, max_len: usize) -> String {
964    value
965        .trim()
966        .to_lowercase()
967        .chars()
968        .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
969        .collect::<String>()
970        .trim_matches('_')
971        .chars()
972        .take(max_len)
973        .collect()
974}
975
976fn normalize_graph_name(value: &str) -> String {
977    value
978        .split(|ch: char| !ch.is_alphanumeric())
979        .filter(|part| !part.is_empty())
980        .map(str::to_lowercase)
981        .collect::<Vec<_>>()
982        .join(" ")
983}
984
985/// Whether an extracted entity is named in its evidence: its name or an
986/// alias (two characters or more) occurs there as whole words, in order
987/// ("Al" is grounded by "Al said", never by "also"). The graph extractor
988/// gives no span offsets, so this checks the citation on word boundaries.
989fn entity_is_grounded(name: &str, aliases: &[String], evidence: &str) -> bool {
990    let evidence = word_tokens(evidence);
991    let named = |text: &str| {
992        let words = word_tokens(text);
993        !words.is_empty()
994            && evidence
995                .windows(words.len())
996                .any(|window| window == words.as_slice())
997    };
998    name.eq_ignore_ascii_case("owner")
999        || named(name)
1000        || aliases
1001            .iter()
1002            .filter(|alias| alias.trim().chars().count() >= 2)
1003            .any(|alias| named(alias))
1004}
1005
1006/// Lowercase alphanumeric words of `text`, in order.
1007fn word_tokens(text: &str) -> Vec<String> {
1008    text.split(|c: char| !c.is_alphanumeric())
1009        .filter(|word| !word.is_empty())
1010        .map(str::to_lowercase)
1011        .collect()
1012}
1013
1014async fn resolve_entity_identity(
1015    pool: &SqlitePool,
1016    entity_type: &str,
1017    proposed_canonical: &str,
1018    display_name: &str,
1019    proposed_aliases: &[String],
1020) -> anyhow::Result<(String, Vec<String>)> {
1021    let mut proposed_names = HashSet::from([proposed_canonical.to_string()]);
1022    proposed_names.extend(
1023        proposed_aliases
1024            .iter()
1025            .map(|alias| normalize_graph_name(alias))
1026            .filter(|alias| !alias.is_empty()),
1027    );
1028    let rows = sqlx::query(
1029        "SELECT canonical_name, display_name, aliases_json
1030         FROM memory_entities
1031         WHERE entity_type = ? AND deleted_at IS NULL
1032         ORDER BY updated_at DESC LIMIT 500",
1033    )
1034    .bind(entity_type)
1035    .fetch_all(pool)
1036    .await?;
1037    for row in rows {
1038        let canonical: String = row.get("canonical_name");
1039        let existing_display: String = row.get("display_name");
1040        let mut aliases: Vec<String> =
1041            serde_json::from_str(&row.get::<String, _>("aliases_json")).unwrap_or_default();
1042        let existing_names: HashSet<String> = std::iter::once(canonical.clone())
1043            .chain(std::iter::once(normalize_graph_name(&existing_display)))
1044            .chain(aliases.iter().map(|alias| normalize_graph_name(alias)))
1045            .collect();
1046        if proposed_names.is_disjoint(&existing_names) {
1047            continue;
1048        }
1049        aliases.push(display_name.to_string());
1050        aliases.extend(proposed_aliases.iter().cloned());
1051        aliases.sort_by_key(|alias| alias.to_lowercase());
1052        aliases.dedup_by(|left, right| left.eq_ignore_ascii_case(right));
1053        aliases.retain(|alias| !alias.eq_ignore_ascii_case(&existing_display));
1054        aliases.truncate(12);
1055        return Ok((canonical, aliases));
1056    }
1057    let mut aliases: Vec<String> = proposed_aliases.iter().take(12).cloned().collect();
1058    aliases.sort_by_key(|alias| alias.to_lowercase());
1059    aliases.dedup_by(|left, right| left.eq_ignore_ascii_case(right));
1060    Ok((proposed_canonical.to_string(), aliases))
1061}
1062
1063async fn find_evidence_span(
1064    pool: &SqlitePool,
1065    source_excerpt: Option<&str>,
1066    channel_id: Option<&str>,
1067    first_seen_at: Option<&str>,
1068) -> anyhow::Result<Option<(i64, Option<i64>)>> {
1069    let Some(excerpt) = source_excerpt
1070        .map(str::trim)
1071        .filter(|text| !text.is_empty())
1072    else {
1073        return Ok(None);
1074    };
1075    let row = sqlx::query(
1076        "SELECT id, source_event_id FROM memory_spans
1077         WHERE span_kind = 'message' AND deleted_at IS NULL
1078           AND (instr(content, ?) > 0 OR instr(?, content) > 0)
1079           AND (? IS NULL OR channel_id = ? OR channel_id IS NULL)
1080         ORDER BY CASE WHEN ? IS NULL THEN 0
1081                       ELSE ABS(julianday(observed_from) - julianday(?)) END ASC,
1082                  id DESC
1083         LIMIT 1",
1084    )
1085    .bind(excerpt)
1086    .bind(excerpt)
1087    .bind(channel_id)
1088    .bind(channel_id)
1089    .bind(first_seen_at)
1090    .bind(first_seen_at)
1091    .fetch_optional(pool)
1092    .await?;
1093    Ok(row.map(|row| (row.get("id"), row.get("source_event_id"))))
1094}
1095
1096/// Index a user message from the host's log as a searchable span. The host
1097/// passes only messages memory may learn from. `channels` derives the span's
1098/// channel from its session.
1099pub async fn project_message_span(
1100    pool: &SqlitePool,
1101    channels: &dyn ChannelIds,
1102    message: &crate::history::LoggedMessage,
1103) -> anyhow::Result<()> {
1104    let event_id = message.id;
1105    let content = &message.content;
1106    if content.trim().is_empty() {
1107        return Ok(());
1108    }
1109    let session_id = &message.session_id;
1110    let channel_id = channels.channel_of_session(session_id);
1111    let created_at = &message.created_at;
1112    sqlx::query(
1113        "INSERT INTO memory_spans
1114            (span_kind, source_event_id, session_id, channel_id, role, content,
1115             content_hash, privacy, observed_from, valid_from)
1116         VALUES ('message', ?, ?, ?, 'user', ?, ?, 'channel', ?, ?)
1117         ON CONFLICT(source_event_id) WHERE source_event_id IS NOT NULL DO UPDATE SET
1118            content = excluded.content,
1119            content_hash = excluded.content_hash,
1120            channel_id = excluded.channel_id,
1121            deleted_at = NULL",
1122    )
1123    .bind(event_id)
1124    .bind(session_id)
1125    .bind(channel_id.as_deref())
1126    .bind(content)
1127    .bind(content_hash(content))
1128    .bind(created_at)
1129    .bind(created_at)
1130    .execute(pool)
1131    .await?;
1132    Ok(())
1133}
1134
1135async fn upsert_entity(
1136    pool: &SqlitePool,
1137    entity_type: &str,
1138    canonical_name: &str,
1139    display_name: &str,
1140    aliases: &[String],
1141    privacy: &str,
1142    channel_id: Option<&str>,
1143) -> anyhow::Result<i64> {
1144    sqlx::query(
1145        "INSERT INTO memory_entities
1146            (entity_type, canonical_name, display_name, aliases_json, channel_id, privacy)
1147         VALUES (?, ?, ?, ?, ?, ?)
1148         ON CONFLICT(entity_type, canonical_name) DO UPDATE SET
1149            display_name = excluded.display_name,
1150            aliases_json = excluded.aliases_json,
1151            channel_id = COALESCE(memory_entities.channel_id, excluded.channel_id),
1152            privacy = CASE WHEN memory_entities.privacy = 'private' OR excluded.privacy = 'private'
1153                           THEN 'private' ELSE excluded.privacy END,
1154            deleted_at = NULL,
1155            updated_at = datetime('now')",
1156    )
1157    .bind(entity_type)
1158    .bind(canonical_name)
1159    .bind(display_name)
1160    .bind(serde_json::to_string(aliases)?)
1161    .bind(channel_id)
1162    .bind(privacy)
1163    .execute(pool)
1164    .await?;
1165    Ok(sqlx::query_scalar(
1166        "SELECT id FROM memory_entities WHERE entity_type = ? AND canonical_name = ?",
1167    )
1168    .bind(entity_type)
1169    .bind(canonical_name)
1170    .fetch_one(pool)
1171    .await?)
1172}
1173
1174#[async_trait]
1175impl MemoryGraphStore for SqliteMemory {
1176    async fn upsert_entity(&self, entity: GraphEntityUpsert) -> anyhow::Result<i64> {
1177        upsert_entity(
1178            &self.pool,
1179            &entity.entity_type,
1180            &entity.canonical_name,
1181            &entity.display_name,
1182            &entity.aliases,
1183            &entity.privacy.to_string(),
1184            entity.channel_id.as_deref(),
1185        )
1186        .await
1187    }
1188
1189    async fn upsert_edge(&self, edge: GraphEdgeUpsert) -> anyhow::Result<()> {
1190        sqlx::query(
1191            "INSERT INTO memory_edges
1192                (source_entity_id, target_entity_id, relation, source_claim_id,
1193                 confidence, channel_id, privacy, valid_from)
1194             VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'))
1195             ON CONFLICT(source_entity_id, target_entity_id, relation, source_claim_id)
1196             DO UPDATE SET confidence = excluded.confidence,
1197                           channel_id = excluded.channel_id,
1198                           privacy = excluded.privacy,
1199                           valid_to = NULL, deleted_at = NULL",
1200        )
1201        .bind(edge.source_entity_id)
1202        .bind(edge.target_entity_id)
1203        .bind(&edge.relation)
1204        .bind(edge.source_claim_id)
1205        .bind(edge.confidence)
1206        .bind(edge.channel_id.as_deref())
1207        .bind(edge.privacy.to_string())
1208        .execute(&self.pool)
1209        .await?;
1210        Ok(())
1211    }
1212
1213    async fn invalidate_claim(&self, claim_id: i64, valid_to: &str) -> anyhow::Result<()> {
1214        sqlx::query(
1215            "UPDATE memory_edges SET valid_to = COALESCE(valid_to, ?)
1216             WHERE source_claim_id = ? AND deleted_at IS NULL",
1217        )
1218        .bind(valid_to)
1219        .bind(claim_id)
1220        .execute(&self.pool)
1221        .await?;
1222        Ok(())
1223    }
1224
1225    async fn neighbors(
1226        &self,
1227        start_entity_id: i64,
1228        max_depth: usize,
1229        scope: &GraphSearchScope,
1230    ) -> anyhow::Result<Vec<GraphNeighbor>> {
1231        self.memory_graph_neighbors(
1232            start_entity_id,
1233            max_depth,
1234            scope.channel_id.as_deref(),
1235            scope.visibility,
1236            scope.requester_is_owner,
1237        )
1238        .await
1239    }
1240}
1241
1242fn sanitize_fts_query(query: &str) -> Option<String> {
1243    let tokens: Vec<String> = query
1244        .split(|c: char| !c.is_alphanumeric() && c != '_')
1245        .map(str::to_lowercase)
1246        .filter(|token| token.len() >= 3 && !super::facts::is_stopword(token))
1247        .take(16)
1248        .map(|token| format!("\"{}\"", token.replace('"', "")))
1249        .collect();
1250    (!tokens.is_empty()).then(|| tokens.join(" OR "))
1251}
1252
1253pub(crate) fn memory_visible(
1254    channels: &dyn ChannelIds,
1255    privacy: FactPrivacy,
1256    stored_channel: Option<&str>,
1257    current_channel: Option<&str>,
1258    visibility: ChannelVisibility,
1259    requester_is_owner: bool,
1260) -> bool {
1261    if matches!(visibility, ChannelVisibility::PublicExternal) {
1262        return false;
1263    }
1264    if requester_is_owner
1265        && matches!(
1266            visibility,
1267            ChannelVisibility::Private | ChannelVisibility::Internal
1268        )
1269    {
1270        return true;
1271    }
1272    match privacy {
1273        FactPrivacy::Private => false,
1274        FactPrivacy::Global => !matches!(visibility, ChannelVisibility::Public),
1275        FactPrivacy::Channel => stored_channel
1276            .zip(current_channel)
1277            .is_some_and(|(stored, current)| channels.same_channel(stored, current)),
1278    }
1279}
1280
1281#[cfg(test)]
1282mod tests {
1283    use super::*;
1284
1285    #[test]
1286    fn fts_query_does_not_expose_operators() {
1287        assert_eq!(
1288            sanitize_fts_query("editor OR secret:*"),
1289            Some("\"editor\" OR \"secret\"".to_string())
1290        );
1291    }
1292
1293    #[test]
1294    fn visibility_is_fail_closed() {
1295        assert!(!memory_visible(
1296            &ExactChannelIds,
1297            FactPrivacy::Private,
1298            None,
1299            None,
1300            ChannelVisibility::Public,
1301            false
1302        ));
1303        assert!(!memory_visible(
1304            &ExactChannelIds,
1305            FactPrivacy::Global,
1306            None,
1307            None,
1308            ChannelVisibility::PublicExternal,
1309            true
1310        ));
1311    }
1312
1313    #[test]
1314    fn an_entity_is_grounded_only_by_whole_words() {
1315        let aliases = vec!["Al".to_string()];
1316        assert!(!entity_is_grounded(
1317            "Alice Rivera",
1318            &aliases,
1319            "I also moved to Lisbon"
1320        ));
1321        assert!(entity_is_grounded("Alice Rivera", &aliases, "Al said hi"));
1322        assert!(entity_is_grounded(
1323            "Alice Rivera",
1324            &[],
1325            "my sister alice rivera, again"
1326        ));
1327        assert!(!entity_is_grounded("Alice Rivera", &[], "Alice moved"));
1328        assert!(!entity_is_grounded("Jordan", &[], "Jordanna called"));
1329    }
1330}