Skip to main content

second_brain_api/
associate.rs

1use second_brain_core::redact::redact_for_store;
2use second_brain_core::schema::{Relation, RelationType};
3use second_brain_core::sqlite_store::SqliteStore;
4use second_brain_core::store::Store;
5use uuid::Uuid;
6
7use crate::routes::retry_write;
8
9/// The relations a caller may create by hand. The others (`mentions`,
10/// `derived_from`, `distilled_from`) are written by ingest and consolidation.
11const USER_RELATIONS: [(&str, RelationType); 4] = [
12    ("relates_to", RelationType::RelatesTo),
13    ("contradicts", RelationType::Contradicts),
14    ("reinforces", RelationType::Reinforces),
15    ("supersedes", RelationType::Supersedes),
16];
17
18#[derive(Debug)]
19pub enum LinkError {
20    BadRequest(String),
21    NotFound(String),
22    Conflict(String),
23    Store(anyhow::Error),
24}
25
26impl From<anyhow::Error> for LinkError {
27    fn from(e: anyhow::Error) -> Self {
28        LinkError::Store(e)
29    }
30}
31
32#[derive(Debug, PartialEq, Eq)]
33pub struct Linked {
34    pub from_id: Uuid,
35    pub to_id: Uuid,
36    /// True when the link retired its target from recall.
37    pub superseded: bool,
38}
39
40#[derive(Clone, Copy)]
41enum Node {
42    Memory(Uuid),
43    Entity(Uuid),
44}
45
46impl Node {
47    fn id(self) -> Uuid {
48        match self {
49            Node::Memory(id) | Node::Entity(id) => id,
50        }
51    }
52}
53
54pub fn parse_relation(name: &str) -> Result<RelationType, LinkError> {
55    USER_RELATIONS
56        .iter()
57        .find(|(n, _)| *n == name)
58        .map(|(_, t)| *t)
59        .ok_or_else(|| {
60            let valid: Vec<&str> = USER_RELATIONS.iter().map(|(n, _)| *n).collect();
61            LinkError::BadRequest(format!(
62                "unknown relation '{name}'; valid values: {}",
63                valid.join(", ")
64            ))
65        })
66}
67
68/// A reference is the id of a stored memory or entity, or an entity name.
69fn resolve(store: &SqliteStore, reference: &str) -> Result<Node, LinkError> {
70    if let Ok(id) = Uuid::parse_str(reference) {
71        if store.get_memory(id)?.is_some() {
72            return Ok(Node::Memory(id));
73        }
74        if store.get_entity(id)?.is_some() {
75            return Ok(Node::Entity(id));
76        }
77        return Err(LinkError::NotFound(format!(
78            "no memory or entity with id {id}"
79        )));
80    }
81    match store.find_entity_by_name(reference)? {
82        Some(entity) => Ok(Node::Entity(entity.id)),
83        None => Err(LinkError::NotFound(format!(
84            "no entity named '{reference}' (pass a memory id, an entity id, or an existing entity name)"
85        ))),
86    }
87}
88
89pub fn link(
90    store: &SqliteStore,
91    from: &str,
92    to: &str,
93    relation: &str,
94    context: Option<String>,
95) -> Result<Linked, LinkError> {
96    let relation_type = parse_relation(relation)?;
97    let from = resolve(store, from)?;
98    let to = resolve(store, to)?;
99
100    let stored_type = stored_relation(from, to, relation_type)?;
101
102    let mut superseded = false;
103    if relation_type == RelationType::Supersedes {
104        superseded = supersede(store, from, to)?;
105    }
106
107    let edge = Relation {
108        from_id: from.id(),
109        to_id: to.id(),
110        relation_type: stored_type,
111        strength: 1.0,
112        context: context.as_deref().map(redact_for_store),
113    };
114    retry_write(|| store.store_relation(&edge))?;
115    Ok(Linked {
116        from_id: edge.from_id,
117        to_id: edge.to_id,
118        superseded,
119    })
120}
121
122/// The relation actually written. Every edge starts at a memory, and the
123/// only memory-to-entity edge the store keeps is `mentions`: sync refuses
124/// any other kind and the scheduled repair prunes it as dangling. So a
125/// `relates_to` aimed at an entity is written as `mentions`, and the other
126/// relations, which only make sense between two memories, are refused
127/// rather than accepted and silently lost.
128fn stored_relation(
129    from: Node,
130    to: Node,
131    relation_type: RelationType,
132) -> Result<RelationType, LinkError> {
133    match (from, to) {
134        (Node::Entity(_), _) => Err(LinkError::BadRequest(
135            "a link must start at a memory; pass the memory as from and the entity as to".into(),
136        )),
137        (Node::Memory(_), Node::Memory(_)) => Ok(relation_type),
138        (Node::Memory(_), Node::Entity(_)) if relation_type == RelationType::RelatesTo => {
139            Ok(RelationType::Mentions)
140        }
141        (Node::Memory(_), Node::Entity(_)) => Err(LinkError::BadRequest(
142            "only relates_to can link a memory to an entity; the other relations link two memories"
143                .into(),
144        )),
145    }
146}
147
148/// Marks `older` as superseded by `newer`. Repeating the same link is a
149/// no-op; a second successor for the same memory, or a superseded memory
150/// acting as a successor, is refused so the chain cannot fork or cycle.
151fn supersede(store: &SqliteStore, newer: Node, older: Node) -> Result<bool, LinkError> {
152    let (Node::Memory(newer), Node::Memory(older)) = (newer, older) else {
153        return Err(LinkError::BadRequest(
154            "supersedes links two memories; an entity cannot supersede or be superseded".into(),
155        ));
156    };
157    if newer == older {
158        return Err(LinkError::BadRequest(
159            "a memory cannot supersede itself".into(),
160        ));
161    }
162    let newer_row = store
163        .get_memory(newer)?
164        .ok_or_else(|| LinkError::NotFound(format!("no memory with id {newer}")))?;
165    if let Some(by) = newer_row.superseded_by {
166        return Err(LinkError::Conflict(format!(
167            "memory {newer} is itself superseded by {by} and cannot supersede another"
168        )));
169    }
170    let older_row = store
171        .get_memory(older)?
172        .ok_or_else(|| LinkError::NotFound(format!("no memory with id {older}")))?;
173    match older_row.superseded_by {
174        Some(by) if by == newer => Ok(false),
175        Some(by) => Err(LinkError::Conflict(format!(
176            "memory {older} is already superseded by {by}"
177        ))),
178        None => {
179            retry_write(|| store.supersede_memory(older, newer))?;
180            Ok(true)
181        }
182    }
183}