Skip to main content

second_brain_api/
mentions.rs

1use anyhow::Result;
2use second_brain_adapters::claude_code::extract_entities;
3use second_brain_core::schema::{Relation, RelationType};
4use second_brain_core::store::StoreAdmin;
5use uuid::Uuid;
6
7/// The type given to an entity a caller names in `related_to` that the
8/// gazetteer does not recognise.
9const NAMED_ENTITY_TYPE: &str = "concept";
10
11/// Links `memory_id` to every entity the ingest gazetteer finds in `content`
12/// and to every name in `related_to`, creating entities that do not exist
13/// yet. The edges are `mentions` because that is the one memory-to-entity
14/// relation sync and the dangling-relation prune accept, and the one the
15/// recall graph term reads. Returns how many distinct entities were linked.
16pub fn link_mentions(
17    store: &dyn StoreAdmin,
18    memory_id: Uuid,
19    content: &str,
20    related_to: &[String],
21) -> Result<usize> {
22    let mut wanted: Vec<(String, String)> = extract_entities(content)
23        .into_iter()
24        .map(|e| (e.name, e.entity_type))
25        .collect();
26    for name in related_to
27        .iter()
28        .map(|n| n.trim())
29        .filter(|n| !n.is_empty())
30    {
31        if !wanted.iter().any(|(w, _)| w.eq_ignore_ascii_case(name)) {
32            wanted.push((name.to_string(), NAMED_ENTITY_TYPE.to_string()));
33        }
34    }
35
36    for (name, entity_type) in &wanted {
37        let entity = store.find_or_create_entity(name, entity_type)?;
38        store.store_relation(&Relation {
39            from_id: memory_id,
40            to_id: entity.id,
41            relation_type: RelationType::Mentions,
42            strength: 1.0,
43            context: None,
44        })?;
45    }
46    Ok(wanted.len())
47}