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