Skip to main content

second_brain_api/
associate.rs

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