second-brain-api 0.12.0

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
Documentation
use second_brain_core::redact::redact_for_store;
use second_brain_core::schema::{Relation, RelationType};
use second_brain_core::sqlite_store::SqliteStore;
use second_brain_core::store::Store;
use uuid::Uuid;

use crate::routes::retry_write;

/// The relations a caller may create by hand. The others (`mentions`,
/// `derived_from`, `distilled_from`) are written by ingest and consolidation.
const USER_RELATIONS: [(&str, RelationType); 4] = [
    ("relates_to", RelationType::RelatesTo),
    ("contradicts", RelationType::Contradicts),
    ("reinforces", RelationType::Reinforces),
    ("supersedes", RelationType::Supersedes),
];

#[derive(Debug)]
pub enum LinkError {
    BadRequest(String),
    NotFound(String),
    Conflict(String),
    Store(anyhow::Error),
}

impl From<anyhow::Error> for LinkError {
    fn from(e: anyhow::Error) -> Self {
        LinkError::Store(e)
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct Linked {
    pub from_id: Uuid,
    pub to_id: Uuid,
    /// True when the link retired its target from recall.
    pub superseded: bool,
}

#[derive(Clone, Copy)]
enum Node {
    Memory(Uuid),
    Entity(Uuid),
}

impl Node {
    fn id(self) -> Uuid {
        match self {
            Node::Memory(id) | Node::Entity(id) => id,
        }
    }
}

pub fn parse_relation(name: &str) -> Result<RelationType, LinkError> {
    USER_RELATIONS
        .iter()
        .find(|(n, _)| *n == name)
        .map(|(_, t)| *t)
        .ok_or_else(|| {
            let valid: Vec<&str> = USER_RELATIONS.iter().map(|(n, _)| *n).collect();
            LinkError::BadRequest(format!(
                "unknown relation '{name}'; valid values: {}",
                valid.join(", ")
            ))
        })
}

/// A reference is the id of a stored memory or entity, or an entity name.
fn resolve(store: &SqliteStore, reference: &str) -> Result<Node, LinkError> {
    if let Ok(id) = Uuid::parse_str(reference) {
        if store.get_memory(id)?.is_some() {
            return Ok(Node::Memory(id));
        }
        if store.get_entity(id)?.is_some() {
            return Ok(Node::Entity(id));
        }
        return Err(LinkError::NotFound(format!(
            "no memory or entity with id {id}"
        )));
    }
    match store.find_entity_by_name(reference)? {
        Some(entity) => Ok(Node::Entity(entity.id)),
        None => Err(LinkError::NotFound(format!(
            "no entity named '{reference}' (pass a memory id, an entity id, or an existing entity name)"
        ))),
    }
}

pub fn link(
    store: &SqliteStore,
    from: &str,
    to: &str,
    relation: &str,
    context: Option<String>,
) -> Result<Linked, LinkError> {
    let relation_type = parse_relation(relation)?;
    let from = resolve(store, from)?;
    let to = resolve(store, to)?;

    let stored_type = stored_relation(from, to, relation_type)?;

    let mut superseded = false;
    if relation_type == RelationType::Supersedes {
        superseded = supersede(store, from, to)?;
    }

    let edge = Relation {
        from_id: from.id(),
        to_id: to.id(),
        relation_type: stored_type,
        strength: 1.0,
        context: context.as_deref().map(redact_for_store),
    };
    retry_write(|| store.store_relation(&edge))?;
    Ok(Linked {
        from_id: edge.from_id,
        to_id: edge.to_id,
        superseded,
    })
}

/// The relation actually written. Every edge starts at a memory, and the
/// only memory-to-entity edge the store keeps is `mentions`: sync refuses
/// any other kind and the scheduled repair prunes it as dangling. So a
/// `relates_to` aimed at an entity is written as `mentions`, and the other
/// relations, which only make sense between two memories, are refused
/// rather than accepted and silently lost.
fn stored_relation(
    from: Node,
    to: Node,
    relation_type: RelationType,
) -> Result<RelationType, LinkError> {
    match (from, to) {
        (Node::Entity(_), _) => Err(LinkError::BadRequest(
            "a link must start at a memory; pass the memory as from and the entity as to".into(),
        )),
        (Node::Memory(_), Node::Memory(_)) => Ok(relation_type),
        (Node::Memory(_), Node::Entity(_)) if relation_type == RelationType::RelatesTo => {
            Ok(RelationType::Mentions)
        }
        (Node::Memory(_), Node::Entity(_)) => Err(LinkError::BadRequest(
            "only relates_to can link a memory to an entity; the other relations link two memories"
                .into(),
        )),
    }
}

/// Marks `older` as superseded by `newer`. Repeating the same link is a
/// no-op; a second successor for the same memory, or a superseded memory
/// acting as a successor, is refused so the chain cannot fork or cycle.
fn supersede(store: &SqliteStore, newer: Node, older: Node) -> Result<bool, LinkError> {
    let (Node::Memory(newer), Node::Memory(older)) = (newer, older) else {
        return Err(LinkError::BadRequest(
            "supersedes links two memories; an entity cannot supersede or be superseded".into(),
        ));
    };
    if newer == older {
        return Err(LinkError::BadRequest(
            "a memory cannot supersede itself".into(),
        ));
    }
    let newer_row = store
        .get_memory(newer)?
        .ok_or_else(|| LinkError::NotFound(format!("no memory with id {newer}")))?;
    if let Some(by) = newer_row.superseded_by {
        return Err(LinkError::Conflict(format!(
            "memory {newer} is itself superseded by {by} and cannot supersede another"
        )));
    }
    let older_row = store
        .get_memory(older)?
        .ok_or_else(|| LinkError::NotFound(format!("no memory with id {older}")))?;
    match older_row.superseded_by {
        Some(by) if by == newer => Ok(false),
        Some(by) => Err(LinkError::Conflict(format!(
            "memory {older} is already superseded by {by}"
        ))),
        None => {
            retry_write(|| store.supersede_memory(older, newer))?;
            Ok(true)
        }
    }
}