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, archived_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        let archived_at: Option<String> = row.get("archived_at");
285        if let Some(valid_to) = superseded_at.or(archived_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    pub async fn backfill_missing_memory_projections(
450        &self,
451    ) -> anyhow::Result<(usize, usize, usize, usize, usize)> {
452        const BATCH_SIZE: i64 = 500;
453        let selected_event_spans_before: i64 = sqlx::query_scalar(
454            "SELECT COUNT(*) FROM memory_spans WHERE source_event_id IS NOT NULL",
455        )
456        .fetch_one(&self.pool)
457        .await?;
458        let mut fact_count = 0usize;
459        loop {
460            let ids: Vec<i64> = sqlx::query_scalar(
461                "SELECT f.id FROM facts f
462                 LEFT JOIN memory_claims c ON c.source_fact_id = f.id
463                 WHERE (f.superseded_at IS NULL AND f.archived_at IS NULL AND c.id IS NULL)
464                    OR ((f.superseded_at IS NOT NULL OR f.archived_at IS NOT NULL)
465                        AND c.id IS NOT NULL
466                        AND c.valid_to IS NULL)
467                 ORDER BY f.id LIMIT ?",
468            )
469            .bind(BATCH_SIZE)
470            .fetch_all(&self.pool)
471            .await?;
472            if ids.is_empty() {
473                break;
474            }
475            fact_count += ids.len();
476            for id in ids {
477                self.project_fact_memory(id).await?;
478            }
479        }
480
481        let mut episode_count = 0usize;
482        loop {
483            let ids: Vec<i64> = sqlx::query_scalar(
484                "SELECT e.id FROM episodes e
485                 LEFT JOIN memory_spans s ON s.source_episode_id = e.id
486                 WHERE s.id IS NULL ORDER BY e.id LIMIT ?",
487            )
488            .bind(BATCH_SIZE)
489            .fetch_all(&self.pool)
490            .await?;
491            if ids.is_empty() {
492                break;
493            }
494            episode_count += ids.len();
495            for id in ids {
496                self.project_episode_memory(id).await?;
497            }
498        }
499
500        // Raw user messages remain canonical events and exact-history rows.
501        // They enter the durable memory graph only when a selected fact/claim
502        // needs that exact event as provenance; an allowed memory policy is a
503        // capability boundary, not a decision to remember every control turn.
504        let evidence_fact_ids: Vec<i64> = sqlx::query_scalar(
505            "SELECT f.id
506             FROM facts f
507             JOIN memory_claims c ON c.source_fact_id = f.id
508             WHERE c.source_span_id IS NULL
509               AND f.source_excerpt IS NOT NULL
510               AND trim(f.source_excerpt) != ''
511             ORDER BY f.id",
512        )
513        .fetch_all(&self.pool)
514        .await?;
515        for id in evidence_fact_ids {
516            self.project_fact_memory(id).await?;
517        }
518        let selected_event_spans_after: i64 = sqlx::query_scalar(
519            "SELECT COUNT(*) FROM memory_spans WHERE source_event_id IS NOT NULL",
520        )
521        .fetch_one(&self.pool)
522        .await?;
523        let event_count =
524            selected_event_spans_after.saturating_sub(selected_event_spans_before) as usize;
525
526        let mut procedure_count = 0usize;
527        let mut after_id = 0i64;
528        loop {
529            let rows = sqlx::query(
530                "SELECT p.id, p.trigger_pattern, p.trigger_embedding
531                 FROM procedures p
532                 WHERE p.id > ? AND p.trigger_embedding IS NOT NULL
533                   AND NOT EXISTS (
534                       SELECT 1 FROM memory_embeddings me
535                       WHERE me.owner_type = 'procedure' AND me.owner_id = CAST(p.id AS TEXT)
536                         AND me.embedding_purpose = 'trigger' AND me.embedding_model = ?
537                         AND me.stale_at IS NULL
538                   )
539                 ORDER BY p.id LIMIT ?",
540            )
541            .bind(after_id)
542            .bind(self.embedding_service.model_id())
543            .bind(BATCH_SIZE)
544            .fetch_all(&self.pool)
545            .await?;
546            if rows.is_empty() {
547                break;
548            }
549            for row in rows {
550                let id: i64 = row.get("id");
551                after_id = id;
552                let content: String = row.get("trigger_pattern");
553                let blob: Vec<u8> = row.get("trigger_embedding");
554                if let Ok(embedding) = self.embedding_service.decode(&blob) {
555                    self.upsert_owner_embedding("procedure", id, "trigger", &content, embedding)
556                        .await?;
557                    procedure_count += 1;
558                }
559            }
560        }
561
562        let mut error_count = 0usize;
563        after_id = 0;
564        loop {
565            let rows = sqlx::query(
566                "SELECT e.id, e.error_pattern, e.error_embedding
567                 FROM error_solutions e
568                 WHERE e.id > ? AND e.error_embedding IS NOT NULL
569                   AND NOT EXISTS (
570                       SELECT 1 FROM memory_embeddings me
571                       WHERE me.owner_type = 'error_solution' AND me.owner_id = CAST(e.id AS TEXT)
572                         AND me.embedding_purpose = 'error' AND me.embedding_model = ?
573                         AND me.stale_at IS NULL
574                   )
575                 ORDER BY e.id LIMIT ?",
576            )
577            .bind(after_id)
578            .bind(self.embedding_service.model_id())
579            .bind(BATCH_SIZE)
580            .fetch_all(&self.pool)
581            .await?;
582            if rows.is_empty() {
583                break;
584            }
585            for row in rows {
586                let id: i64 = row.get("id");
587                after_id = id;
588                let content: String = row.get("error_pattern");
589                let blob: Vec<u8> = row.get("error_embedding");
590                if let Ok(embedding) = self.embedding_service.decode(&blob) {
591                    self.upsert_owner_embedding("error_solution", id, "error", &content, embedding)
592                        .await?;
593                    error_count += 1;
594                }
595            }
596        }
597
598        Ok((
599            fact_count,
600            episode_count,
601            event_count,
602            procedure_count,
603            error_count,
604        ))
605    }
606
607    /// Project the facts one write changed: the rows of `category` whose
608    /// `updated_at` or `superseded_at` is that write's timestamp. Every row
609    /// a fact upsert touches carries its timestamp, and re-projecting the
610    /// whole category on each write took seconds in a large one.
611    pub(crate) async fn sync_fact_memory_written_at(
612        &self,
613        category: &str,
614        written_at: &str,
615    ) -> anyhow::Result<()> {
616        let ids: Vec<i64> = sqlx::query_scalar(
617            "SELECT id FROM facts
618             WHERE category = ? AND (updated_at = ? OR superseded_at = ?)",
619        )
620        .bind(category)
621        .bind(written_at)
622        .bind(written_at)
623        .fetch_all(&self.pool)
624        .await?;
625        self.sync_fact_memory_rows(category, &ids).await
626    }
627
628    async fn sync_fact_memory_rows(&self, category: &str, ids: &[i64]) -> anyhow::Result<()> {
629        for id in ids {
630            self.project_fact_memory(*id).await?;
631        }
632        sqlx::query(
633            "UPDATE memory_claims AS old
634             SET superseded_by_claim_id = (
635                SELECT replacement.id
636                FROM memory_claims replacement
637                JOIN facts new_fact ON new_fact.id = replacement.source_fact_id
638                JOIN facts old_fact ON old_fact.id = old.source_fact_id
639                WHERE new_fact.category = old_fact.category
640                  AND new_fact.key = old_fact.key
641                  AND new_fact.superseded_at IS NULL
642                LIMIT 1
643             )
644             WHERE old.source_fact_id IN (SELECT id FROM facts WHERE category = ?)
645               AND old.valid_to IS NOT NULL",
646        )
647        .bind(category)
648        .execute(&self.pool)
649        .await?;
650        Ok(())
651    }
652
653    /// FTS5 claim search with visibility and temporal filtering at the owner row.
654    pub async fn search_memory_claims(
655        &self,
656        query: &str,
657        channel_id: Option<&str>,
658        visibility: ChannelVisibility,
659        requester_is_owner: bool,
660        limit: usize,
661    ) -> anyhow::Result<Vec<MemoryClaimRecord>> {
662        let Some(fts_query) = sanitize_fts_query(query) else {
663            return Ok(Vec::new());
664        };
665        if matches!(visibility, ChannelVisibility::PublicExternal) || limit == 0 {
666            return Ok(Vec::new());
667        }
668
669        let rows = match sqlx::query(
670            "SELECT c.id, c.claim_text, c.source_fact_id, c.channel_id, c.privacy
671             FROM memory_claims_fts f
672             JOIN memory_claims c ON c.id = f.rowid
673             WHERE memory_claims_fts MATCH ?
674               AND c.deleted_at IS NULL AND c.valid_to IS NULL
675             ORDER BY bm25(memory_claims_fts) LIMIT ?",
676        )
677        .bind(&fts_query)
678        .bind((limit.saturating_mul(8).max(limit)) as i64)
679        .fetch_all(&self.pool)
680        .await
681        {
682            // `migrate` always creates memory_claims_fts, so a failure here
683            // is a real error for the caller, never a missing table.
684            Ok(rows) => rows,
685            Err(error) => return Err(error.into()),
686        };
687
688        let mut claims = Vec::new();
689        for row in rows {
690            let privacy = FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy"));
691            let claim_channel: Option<String> = row.get("channel_id");
692            if memory_visible(
693                self.channels.as_ref(),
694                privacy,
695                claim_channel.as_deref(),
696                channel_id,
697                visibility,
698                requester_is_owner,
699            ) {
700                claims.push(MemoryClaimRecord {
701                    id: row.get("id"),
702                    claim_text: row.get("claim_text"),
703                    source_fact_id: row.get("source_fact_id"),
704                    channel_id: claim_channel,
705                    privacy,
706                });
707                if claims.len() == limit {
708                    break;
709                }
710            }
711        }
712        Ok(claims)
713    }
714
715    /// Traverse active graph edges to at most `max_depth` (clamped to two).
716    pub async fn memory_graph_neighbors(
717        &self,
718        start_entity_id: i64,
719        max_depth: usize,
720        channel_id: Option<&str>,
721        visibility: ChannelVisibility,
722        requester_is_owner: bool,
723    ) -> anyhow::Result<Vec<GraphNeighbor>> {
724        let max_depth = max_depth.min(2);
725        let mut queue = VecDeque::from([(start_entity_id, 0usize)]);
726        let mut visited = HashSet::from([start_entity_id]);
727        let mut output = Vec::new();
728        while let Some((entity_id, depth)) = queue.pop_front() {
729            if depth >= max_depth {
730                continue;
731            }
732            let rows = sqlx::query(
733                "SELECT e.source_entity_id, e.target_entity_id, e.relation, e.channel_id,
734                        e.privacy, target.display_name
735                 FROM memory_edges e
736                 JOIN memory_entities target ON target.id = CASE
737                    WHEN e.source_entity_id = ? THEN e.target_entity_id ELSE e.source_entity_id END
738                 WHERE (e.source_entity_id = ? OR e.target_entity_id = ?)
739                   AND e.deleted_at IS NULL AND e.valid_to IS NULL
740                   AND target.deleted_at IS NULL
741                 LIMIT 100",
742            )
743            .bind(entity_id)
744            .bind(entity_id)
745            .bind(entity_id)
746            .fetch_all(&self.pool)
747            .await?;
748            for row in rows {
749                let privacy = FactPrivacy::from_str_lossy(&row.get::<String, _>("privacy"));
750                let edge_channel: Option<String> = row.get("channel_id");
751                if !memory_visible(
752                    self.channels.as_ref(),
753                    privacy,
754                    edge_channel.as_deref(),
755                    channel_id,
756                    visibility,
757                    requester_is_owner,
758                ) {
759                    continue;
760                }
761                let source: i64 = row.get("source_entity_id");
762                let target: i64 = row.get("target_entity_id");
763                let neighbor_id = if source == entity_id { target } else { source };
764                if visited.insert(neighbor_id) {
765                    output.push(GraphNeighbor {
766                        entity_id: neighbor_id,
767                        display_name: row.get("display_name"),
768                        relation: row.get("relation"),
769                        depth: depth + 1,
770                    });
771                    queue.push_back((neighbor_id, depth + 1));
772                }
773            }
774        }
775        Ok(output)
776    }
777
778    async fn project_claim_graph(
779        &self,
780        claim_id: i64,
781        category: &str,
782        key: &str,
783        privacy: &str,
784        channel_id: Option<&str>,
785    ) -> anyhow::Result<()> {
786        let privacy_level = FactPrivacy::from_str_lossy(privacy);
787        let owner_id = MemoryGraphStore::upsert_entity(
788            self,
789            GraphEntityUpsert {
790                entity_type: "person".to_string(),
791                canonical_name: "owner".to_string(),
792                display_name: "Owner".to_string(),
793                aliases: Vec::new(),
794                channel_id: channel_id.map(str::to_owned),
795                privacy: privacy_level,
796            },
797        )
798        .await?;
799        let canonical = format!("{}:{}", category.to_lowercase(), key.to_lowercase());
800        let concept_id = MemoryGraphStore::upsert_entity(
801            self,
802            GraphEntityUpsert {
803                entity_type: "concept".to_string(),
804                canonical_name: canonical,
805                display_name: key.to_string(),
806                aliases: Vec::new(),
807                channel_id: channel_id.map(str::to_owned),
808                privacy: privacy_level,
809            },
810        )
811        .await?;
812        MemoryGraphStore::upsert_edge(
813            self,
814            GraphEdgeUpsert {
815                source_entity_id: owner_id,
816                target_entity_id: concept_id,
817                relation: "has_attribute".to_string(),
818                source_claim_id: claim_id,
819                confidence: 1.0,
820                channel_id: channel_id.map(str::to_owned),
821                privacy: privacy_level,
822            },
823        )
824        .await?;
825
826        Ok(())
827    }
828
829    pub async fn persist_extracted_fact_graph(
830        &self,
831        category: &str,
832        key: &str,
833        source_excerpt: &str,
834        graph: &crate::records::ExtractedMemoryGraph,
835    ) -> anyhow::Result<()> {
836        use std::collections::HashMap;
837
838        const MIN_CONFIDENCE: f32 = 0.65;
839        let claim = sqlx::query(
840            "SELECT c.id, c.channel_id, c.privacy
841             FROM memory_claims c
842             JOIN facts f ON f.id = c.source_fact_id
843             WHERE lower(f.category) = lower(?) AND lower(f.key) = lower(?)
844               AND f.superseded_at IS NULL AND c.deleted_at IS NULL AND c.valid_to IS NULL
845             ORDER BY f.updated_at DESC LIMIT 1",
846        )
847        .bind(category)
848        .bind(key)
849        .fetch_optional(&self.pool)
850        .await?;
851        let Some(claim) = claim else {
852            return Ok(());
853        };
854        let claim_id: i64 = claim.get("id");
855        let channel_id: Option<String> = claim.get("channel_id");
856        let privacy = FactPrivacy::from_str_lossy(&claim.get::<String, _>("privacy"));
857        let evidence = source_excerpt.to_lowercase();
858        let mut resolved = HashMap::new();
859
860        for entity in graph.entities.iter().take(32) {
861            let name = entity.name.trim();
862            let entity_type = normalize_graph_token(&entity.entity_type, 48);
863            let local_id = entity.local_id.trim();
864            if entity.confidence < MIN_CONFIDENCE
865                || name.is_empty()
866                || name.len() > 200
867                || entity_type.is_empty()
868                || local_id.is_empty()
869                || resolved.contains_key(local_id)
870                || !entity_is_grounded(name, &entity.aliases, &evidence)
871            {
872                continue;
873            }
874            let canonical_name = normalize_graph_name(name);
875            if canonical_name.is_empty() {
876                continue;
877            }
878            let (canonical_name, aliases) = resolve_entity_identity(
879                &self.pool,
880                &entity_type,
881                &canonical_name,
882                name,
883                &entity.aliases,
884            )
885            .await?;
886            let entity_id = MemoryGraphStore::upsert_entity(
887                self,
888                GraphEntityUpsert {
889                    entity_type,
890                    canonical_name,
891                    display_name: name.to_string(),
892                    aliases,
893                    channel_id: channel_id.clone(),
894                    privacy,
895                },
896            )
897            .await?;
898            resolved.insert(local_id.to_string(), entity_id);
899        }
900
901        for relationship in graph.relationships.iter().take(64) {
902            let relation = normalize_graph_token(&relationship.relation, 80);
903            let (Some(&source_entity_id), Some(&target_entity_id)) = (
904                resolved.get(relationship.source_id.trim()),
905                resolved.get(relationship.target_id.trim()),
906            ) else {
907                continue;
908            };
909            if relationship.confidence < MIN_CONFIDENCE
910                || relation.is_empty()
911                || source_entity_id == target_entity_id
912            {
913                continue;
914            }
915            MemoryGraphStore::upsert_edge(
916                self,
917                GraphEdgeUpsert {
918                    source_entity_id,
919                    target_entity_id,
920                    relation,
921                    source_claim_id: claim_id,
922                    confidence: relationship.confidence.clamp(0.0, 1.0),
923                    channel_id: channel_id.clone(),
924                    privacy,
925                },
926            )
927            .await?;
928        }
929        Ok(())
930    }
931}
932
933fn normalize_graph_token(value: &str, max_len: usize) -> String {
934    value
935        .trim()
936        .to_lowercase()
937        .chars()
938        .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
939        .collect::<String>()
940        .trim_matches('_')
941        .chars()
942        .take(max_len)
943        .collect()
944}
945
946use crate::text::normalize_fact_value as normalize_graph_name;
947
948/// Whether an extracted entity is named in its evidence: its name or an
949/// alias (two characters or more) occurs there as whole words, in order
950/// ("Al" is grounded by "Al said", never by "also"). The graph extractor
951/// gives no span offsets, so this checks the citation on word boundaries.
952fn entity_is_grounded(name: &str, aliases: &[String], evidence: &str) -> bool {
953    let evidence = word_tokens(evidence);
954    let named = |text: &str| {
955        let words = word_tokens(text);
956        !words.is_empty()
957            && evidence
958                .windows(words.len())
959                .any(|window| window == words.as_slice())
960    };
961    name.eq_ignore_ascii_case("owner")
962        || named(name)
963        || aliases
964            .iter()
965            .filter(|alias| alias.trim().chars().count() >= 2)
966            .any(|alias| named(alias))
967}
968
969/// Lowercase alphanumeric words of `text`, in order.
970fn word_tokens(text: &str) -> Vec<String> {
971    crate::text::words(text).collect()
972}
973
974async fn resolve_entity_identity(
975    pool: &SqlitePool,
976    entity_type: &str,
977    proposed_canonical: &str,
978    display_name: &str,
979    proposed_aliases: &[String],
980) -> anyhow::Result<(String, Vec<String>)> {
981    let mut proposed_names = HashSet::from([proposed_canonical.to_string()]);
982    proposed_names.extend(
983        proposed_aliases
984            .iter()
985            .map(|alias| normalize_graph_name(alias))
986            .filter(|alias| !alias.is_empty()),
987    );
988    let rows = sqlx::query(
989        "SELECT canonical_name, display_name, aliases_json
990         FROM memory_entities
991         WHERE entity_type = ? AND deleted_at IS NULL
992         ORDER BY updated_at DESC LIMIT 500",
993    )
994    .bind(entity_type)
995    .fetch_all(pool)
996    .await?;
997    for row in rows {
998        let canonical: String = row.get("canonical_name");
999        let existing_display: String = row.get("display_name");
1000        let mut aliases: Vec<String> =
1001            serde_json::from_str(&row.get::<String, _>("aliases_json")).unwrap_or_default();
1002        let existing_names: HashSet<String> = std::iter::once(canonical.clone())
1003            .chain(std::iter::once(normalize_graph_name(&existing_display)))
1004            .chain(aliases.iter().map(|alias| normalize_graph_name(alias)))
1005            .collect();
1006        if proposed_names.is_disjoint(&existing_names) {
1007            continue;
1008        }
1009        aliases.push(display_name.to_string());
1010        aliases.extend(proposed_aliases.iter().cloned());
1011        aliases.sort_by_key(|alias| alias.to_lowercase());
1012        aliases.dedup_by(|left, right| left.eq_ignore_ascii_case(right));
1013        aliases.retain(|alias| !alias.eq_ignore_ascii_case(&existing_display));
1014        aliases.truncate(12);
1015        return Ok((canonical, aliases));
1016    }
1017    let mut aliases: Vec<String> = proposed_aliases.iter().take(12).cloned().collect();
1018    aliases.sort_by_key(|alias| alias.to_lowercase());
1019    aliases.dedup_by(|left, right| left.eq_ignore_ascii_case(right));
1020    Ok((proposed_canonical.to_string(), aliases))
1021}
1022
1023async fn find_evidence_span(
1024    pool: &SqlitePool,
1025    source_excerpt: Option<&str>,
1026    channel_id: Option<&str>,
1027    first_seen_at: Option<&str>,
1028) -> anyhow::Result<Option<(i64, Option<i64>)>> {
1029    let Some(excerpt) = source_excerpt
1030        .map(str::trim)
1031        .filter(|text| !text.is_empty())
1032    else {
1033        return Ok(None);
1034    };
1035    let row = sqlx::query(
1036        "SELECT id, source_event_id FROM memory_spans
1037         WHERE span_kind = 'message' AND deleted_at IS NULL
1038           AND (instr(content, ?) > 0 OR instr(?, content) > 0)
1039           AND (? IS NULL OR channel_id = ? OR channel_id IS NULL)
1040         ORDER BY CASE WHEN ? IS NULL THEN 0
1041                       ELSE ABS(julianday(observed_from) - julianday(?)) END ASC,
1042                  id DESC
1043         LIMIT 1",
1044    )
1045    .bind(excerpt)
1046    .bind(excerpt)
1047    .bind(channel_id)
1048    .bind(channel_id)
1049    .bind(first_seen_at)
1050    .bind(first_seen_at)
1051    .fetch_optional(pool)
1052    .await?;
1053    Ok(row.map(|row| (row.get("id"), row.get("source_event_id"))))
1054}
1055
1056/// Index a user message from the host's log as a searchable span. The host
1057/// passes only messages memory may learn from. `channels` derives the span's
1058/// channel from its session.
1059pub async fn project_message_span(
1060    pool: &SqlitePool,
1061    channels: &dyn ChannelIds,
1062    message: &crate::history::LoggedMessage,
1063) -> anyhow::Result<()> {
1064    let event_id = message.id;
1065    let content = &message.content;
1066    if content.trim().is_empty() {
1067        return Ok(());
1068    }
1069    let session_id = &message.session_id;
1070    let channel_id = channels.channel_of_session(session_id);
1071    let created_at = &message.created_at;
1072    sqlx::query(
1073        "INSERT INTO memory_spans
1074            (span_kind, source_event_id, session_id, channel_id, role, content,
1075             content_hash, privacy, observed_from, valid_from)
1076         VALUES ('message', ?, ?, ?, 'user', ?, ?, 'channel', ?, ?)
1077         ON CONFLICT(source_event_id) WHERE source_event_id IS NOT NULL DO UPDATE SET
1078            content = excluded.content,
1079            content_hash = excluded.content_hash,
1080            channel_id = excluded.channel_id,
1081            deleted_at = NULL",
1082    )
1083    .bind(event_id)
1084    .bind(session_id)
1085    .bind(channel_id.as_deref())
1086    .bind(content)
1087    .bind(content_hash(content))
1088    .bind(created_at)
1089    .bind(created_at)
1090    .execute(pool)
1091    .await?;
1092    Ok(())
1093}
1094
1095async fn upsert_entity(
1096    pool: &SqlitePool,
1097    entity_type: &str,
1098    canonical_name: &str,
1099    display_name: &str,
1100    aliases: &[String],
1101    privacy: &str,
1102    channel_id: Option<&str>,
1103) -> anyhow::Result<i64> {
1104    sqlx::query(
1105        "INSERT INTO memory_entities
1106            (entity_type, canonical_name, display_name, aliases_json, channel_id, privacy)
1107         VALUES (?, ?, ?, ?, ?, ?)
1108         ON CONFLICT(entity_type, canonical_name) DO UPDATE SET
1109            display_name = excluded.display_name,
1110            aliases_json = excluded.aliases_json,
1111            channel_id = COALESCE(memory_entities.channel_id, excluded.channel_id),
1112            privacy = CASE WHEN memory_entities.privacy = 'private' OR excluded.privacy = 'private'
1113                           THEN 'private' ELSE excluded.privacy END,
1114            deleted_at = NULL,
1115            updated_at = datetime('now')",
1116    )
1117    .bind(entity_type)
1118    .bind(canonical_name)
1119    .bind(display_name)
1120    .bind(serde_json::to_string(aliases)?)
1121    .bind(channel_id)
1122    .bind(privacy)
1123    .execute(pool)
1124    .await?;
1125    Ok(sqlx::query_scalar(
1126        "SELECT id FROM memory_entities WHERE entity_type = ? AND canonical_name = ?",
1127    )
1128    .bind(entity_type)
1129    .bind(canonical_name)
1130    .fetch_one(pool)
1131    .await?)
1132}
1133
1134#[async_trait]
1135impl MemoryGraphStore for SqliteMemory {
1136    async fn upsert_entity(&self, entity: GraphEntityUpsert) -> anyhow::Result<i64> {
1137        upsert_entity(
1138            &self.pool,
1139            &entity.entity_type,
1140            &entity.canonical_name,
1141            &entity.display_name,
1142            &entity.aliases,
1143            &entity.privacy.to_string(),
1144            entity.channel_id.as_deref(),
1145        )
1146        .await
1147    }
1148
1149    async fn upsert_edge(&self, edge: GraphEdgeUpsert) -> anyhow::Result<()> {
1150        sqlx::query(
1151            "INSERT INTO memory_edges
1152                (source_entity_id, target_entity_id, relation, source_claim_id,
1153                 confidence, channel_id, privacy, valid_from)
1154             VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'))
1155             ON CONFLICT(source_entity_id, target_entity_id, relation, source_claim_id)
1156             DO UPDATE SET confidence = excluded.confidence,
1157                           channel_id = excluded.channel_id,
1158                           privacy = excluded.privacy,
1159                           valid_to = NULL, deleted_at = NULL",
1160        )
1161        .bind(edge.source_entity_id)
1162        .bind(edge.target_entity_id)
1163        .bind(&edge.relation)
1164        .bind(edge.source_claim_id)
1165        .bind(edge.confidence)
1166        .bind(edge.channel_id.as_deref())
1167        .bind(edge.privacy.to_string())
1168        .execute(&self.pool)
1169        .await?;
1170        Ok(())
1171    }
1172
1173    async fn invalidate_claim(&self, claim_id: i64, valid_to: &str) -> anyhow::Result<()> {
1174        sqlx::query(
1175            "UPDATE memory_edges SET valid_to = COALESCE(valid_to, ?)
1176             WHERE source_claim_id = ? AND deleted_at IS NULL",
1177        )
1178        .bind(valid_to)
1179        .bind(claim_id)
1180        .execute(&self.pool)
1181        .await?;
1182        Ok(())
1183    }
1184
1185    async fn neighbors(
1186        &self,
1187        start_entity_id: i64,
1188        max_depth: usize,
1189        scope: &GraphSearchScope,
1190    ) -> anyhow::Result<Vec<GraphNeighbor>> {
1191        self.memory_graph_neighbors(
1192            start_entity_id,
1193            max_depth,
1194            scope.channel_id.as_deref(),
1195            scope.visibility,
1196            scope.requester_is_owner,
1197        )
1198        .await
1199    }
1200}
1201
1202fn sanitize_fts_query(query: &str) -> Option<String> {
1203    let tokens: Vec<String> = query
1204        .split(|c: char| !c.is_alphanumeric() && c != '_')
1205        .map(str::to_lowercase)
1206        .filter(|token| token.len() >= 3 && !super::facts::is_stopword(token))
1207        .take(16)
1208        .map(|token| format!("\"{}\"", token.replace('"', "")))
1209        .collect();
1210    (!tokens.is_empty()).then(|| tokens.join(" OR "))
1211}
1212
1213pub(crate) fn memory_visible(
1214    channels: &dyn ChannelIds,
1215    privacy: FactPrivacy,
1216    stored_channel: Option<&str>,
1217    current_channel: Option<&str>,
1218    visibility: ChannelVisibility,
1219    requester_is_owner: bool,
1220) -> bool {
1221    if matches!(visibility, ChannelVisibility::PublicExternal) {
1222        return false;
1223    }
1224    if requester_is_owner
1225        && matches!(
1226            visibility,
1227            ChannelVisibility::Private | ChannelVisibility::Internal
1228        )
1229    {
1230        return true;
1231    }
1232    match privacy {
1233        FactPrivacy::Private => false,
1234        // The owner's general facts reach the owner's own turns in a small
1235        // group, never a guest's or a stranger's turn (whose reply goes to
1236        // them), and never a public channel.
1237        FactPrivacy::Global => {
1238            requester_is_owner && !matches!(visibility, ChannelVisibility::Public)
1239        }
1240        FactPrivacy::Channel => stored_channel
1241            .zip(current_channel)
1242            .is_some_and(|(stored, current)| channels.same_channel(stored, current)),
1243    }
1244}
1245
1246#[cfg(test)]
1247mod tests {
1248    use super::*;
1249
1250    #[test]
1251    fn fts_query_does_not_expose_operators() {
1252        assert_eq!(
1253            sanitize_fts_query("editor OR secret:*"),
1254            Some("\"editor\" OR \"secret\"".to_string())
1255        );
1256    }
1257
1258    #[test]
1259    fn visibility_is_fail_closed() {
1260        assert!(!memory_visible(
1261            &ExactChannelIds,
1262            FactPrivacy::Private,
1263            None,
1264            None,
1265            ChannelVisibility::Public,
1266            false
1267        ));
1268        assert!(!memory_visible(
1269            &ExactChannelIds,
1270            FactPrivacy::Global,
1271            None,
1272            None,
1273            ChannelVisibility::PublicExternal,
1274            true
1275        ));
1276    }
1277
1278    #[test]
1279    fn global_facts_reach_only_the_owner() {
1280        for visibility in [ChannelVisibility::Private, ChannelVisibility::PrivateGroup] {
1281            assert!(!memory_visible(
1282                &ExactChannelIds,
1283                FactPrivacy::Global,
1284                None,
1285                Some("telegram:synthetic-chat-1"),
1286                visibility,
1287                false
1288            ));
1289        }
1290        assert!(memory_visible(
1291            &ExactChannelIds,
1292            FactPrivacy::Global,
1293            None,
1294            Some("telegram:synthetic-chat-1"),
1295            ChannelVisibility::PrivateGroup,
1296            true
1297        ));
1298        assert!(memory_visible(
1299            &ExactChannelIds,
1300            FactPrivacy::Channel,
1301            Some("telegram:synthetic-chat-1"),
1302            Some("telegram:synthetic-chat-1"),
1303            ChannelVisibility::PrivateGroup,
1304            false
1305        ));
1306    }
1307
1308    #[test]
1309    fn an_entity_is_grounded_only_by_whole_words() {
1310        let aliases = vec!["Al".to_string()];
1311        assert!(!entity_is_grounded(
1312            "Alice Rivera",
1313            &aliases,
1314            "I also moved to Lisbon"
1315        ));
1316        assert!(entity_is_grounded("Alice Rivera", &aliases, "Al said hi"));
1317        assert!(entity_is_grounded(
1318            "Alice Rivera",
1319            &[],
1320            "my sister alice rivera, again"
1321        ));
1322        assert!(!entity_is_grounded("Alice Rivera", &[], "Alice moved"));
1323        assert!(!entity_is_grounded("Jordan", &[], "Jordanna called"));
1324    }
1325}
1326
1327/// Facts whose edge names a token in an entity's name or the relation, at
1328/// most 500 per token (as the per-token query had). `lower()` in SQLite
1329/// folds ASCII only, so the tokens are matched as they come.
1330fn graph_matches(
1331    tokens: &[String],
1332    rows: &[(i64, String, String, String, String, String)],
1333) -> HashSet<i64> {
1334    let mut ids = HashSet::new();
1335    for token in tokens {
1336        let mut per_token = HashSet::new();
1337        for (fact, a, b, c, d, relation) in rows {
1338            if per_token.len() >= 500 {
1339                break;
1340            }
1341            if [a, b, c, d, relation]
1342                .iter()
1343                .any(|field| field.contains(token.as_str()))
1344            {
1345                per_token.insert(*fact);
1346            }
1347        }
1348        ids.extend(per_token);
1349    }
1350    ids
1351}
1352
1353#[cfg(test)]
1354mod graph_match_tests {
1355    use super::graph_matches;
1356
1357    #[test]
1358    fn a_token_in_any_name_or_relation_finds_the_fact() {
1359        let row = |fact: i64, source: &str, target: &str, relation: &str| {
1360            (
1361                fact,
1362                source.to_string(),
1363                source.to_string(),
1364                target.to_string(),
1365                target.to_string(),
1366                relation.to_string(),
1367            )
1368        };
1369        let rows = vec![
1370            row(1, "alice rivera", "acme corp", "works_at"),
1371            row(2, "mia", "piano", "plays"),
1372            row(3, "jordan lee", "acme corp", "manages"),
1373        ];
1374        let tokens = vec!["acme".to_string(), "plays".to_string()];
1375        let found = graph_matches(&tokens, &rows);
1376        assert_eq!(found, [1, 2, 3].into_iter().collect());
1377        assert!(graph_matches(&["zzz".to_string()], &rows).is_empty());
1378    }
1379}