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