second-brain-core 0.13.5

Core library for second-brain: SQLite storage with vector and lexical indexes, BGE embeddings, and hybrid retrieval
Documentation
use std::borrow::Cow;
use std::fmt;

use anyhow::Result;
use chrono::Utc;
use rusqlite::{Connection, OptionalExtension, params};
use uuid::Uuid;

use super::{MEMORY_COLS, SqliteStore, conversion_err, row_to_memory};
use crate::keys::identity_tag_of;
use crate::schema::{Memory, Scope};

/// Who is asking. The self-hosted daemon serves one user and acts as
/// `Owner`; a store shared by several users (a kiln tenant) names each
/// caller as a `User`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Principal {
    Owner,
    User(String),
}

/// A user asked to change a memory it may not change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AccessDenied {
    pub memory_id: Uuid,
}

impl fmt::Display for AccessDenied {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "memory {} belongs to another user", self.memory_id)
    }
}

impl std::error::Error for AccessDenied {}

/// A user reads its own memories and every shared one. A memory with no
/// author predates attribution and belongs to no user.
pub fn can_read(principal: &Principal, memory: &Memory) -> bool {
    match principal {
        Principal::Owner => true,
        Principal::User(_) => memory.scope == Scope::Shared || owns(principal, memory),
    }
}

/// Only a memory's author changes it, shared or not.
pub fn can_change(principal: &Principal, memory: &Memory) -> bool {
    match principal {
        Principal::Owner => true,
        Principal::User(_) => owns(principal, memory),
    }
}

fn owns(principal: &Principal, memory: &Memory) -> bool {
    matches!(principal, Principal::User(id) if memory.author.as_deref() == Some(id.as_str()))
}

impl SqliteStore {
    /// The author a write records when its writer names none: this store's
    /// identity, or its device until it joins one.
    pub fn local_author(&self) -> Result<String> {
        local_author_on(&self.reader(), self.machine_id())
    }

    /// None when no such memory exists or `principal` may not read it, so
    /// a caller cannot tell another user's private memory from a missing
    /// one.
    pub fn get_memory_for(&self, id: Uuid, principal: &Principal) -> Result<Option<Memory>> {
        Ok(crate::store::Store::get_memory(self, id)?.filter(|m| can_read(principal, m)))
    }

    /// Fails with `AccessDenied` when the memory exists and `principal` may
    /// not change it; an absent memory passes, leaving the change itself to
    /// report it missing.
    pub fn check_change(&self, id: Uuid, principal: &Principal) -> Result<()> {
        match crate::store::Store::get_memory(self, id)? {
            Some(memory) if !can_change(principal, &memory) => {
                Err(AccessDenied { memory_id: id }.into())
            }
            _ => Ok(()),
        }
    }

    /// Sets who may read the memory, logged as an Update so every peer
    /// converges on it. False when no such memory exists.
    pub fn set_memory_scope(&self, id: Uuid, scope: Scope, principal: &Principal) -> Result<bool> {
        self.with_txn(|tx| {
            let Some(memory) = Self::memory_on_tx(tx, id)? else {
                return Ok(false);
            };
            if !can_change(principal, &memory) {
                return Err(AccessDenied { memory_id: id }.into());
            }
            if memory.scope == scope {
                return Ok(true);
            }
            tx.execute(
                "UPDATE memories SET scope = ?2, updated_at = ?3 WHERE id = ?1",
                params![id.to_string(), scope_to_str(scope), Utc::now().to_rfc3339()],
            )?;
            if let Some(memory) = Self::memory_on_tx(tx, id)? {
                self.log_memory_update(tx, &memory)?;
            }
            Ok(true)
        })
    }

    /// Streams every memory `principal` may read, without embeddings; a cold
    /// memory carries its full text read back from its segment.
    pub fn export_memories_for(
        &self,
        principal: &Principal,
        sink: &mut dyn FnMut(Memory) -> Result<()>,
    ) -> Result<()> {
        let conn = self.reader();
        let mut stmt = conn.prepare(&format!("SELECT {MEMORY_COLS} FROM memories ORDER BY id"))?;
        let mut rows = stmt.query([])?;
        while let Some(row) = rows.next()? {
            let memory = row_to_memory(row, false)?;
            if can_read(principal, &memory) {
                let mut full = self.full_text_form(&conn, &memory)?.into_owned();
                full.embedding = Vec::new();
                sink(full)?;
            }
        }
        Ok(())
    }

    /// `memory` as a local write stores it: a row that already exists keeps
    /// its author and scope, and a new row without an author gets this
    /// store's.
    pub(crate) fn attributed<'m>(
        &self,
        conn: &Connection,
        memory: &'m Memory,
    ) -> Result<Cow<'m, Memory>> {
        match attribution(conn, memory.id)? {
            Some(row) => Ok(overlay(Cow::Borrowed(memory), row)),
            None if memory.author.is_some() => Ok(Cow::Borrowed(memory)),
            None => Ok(Cow::Owned(Memory {
                author: Some(local_author_on(conn, self.machine_id())?),
                ..memory.clone()
            })),
        }
    }

    /// `memory` carrying its row's author and scope, which a caller's copy
    /// may lack: every logged form of a memory carries the row's.
    pub(crate) fn with_row_attribution<'m>(
        conn: &Connection,
        memory: Cow<'m, Memory>,
    ) -> Result<Cow<'m, Memory>> {
        Ok(match attribution(conn, memory.id)? {
            Some(row) => overlay(memory, row),
            None => memory,
        })
    }
}

fn overlay(memory: Cow<'_, Memory>, (author, scope): (Option<String>, Scope)) -> Cow<'_, Memory> {
    if memory.author == author && memory.scope == scope {
        return memory;
    }
    let mut owned = memory.into_owned();
    owned.author = author;
    owned.scope = scope;
    Cow::Owned(owned)
}

fn attribution(conn: &Connection, id: Uuid) -> Result<Option<(Option<String>, Scope)>> {
    conn.query_row(
        "SELECT author, scope FROM memories WHERE id = ?1",
        params![id.to_string()],
        |r| Ok((r.get(0)?, parse_scope(&r.get::<_, String>(1)?)?)),
    )
    .optional()
    .map_err(Into::into)
}

fn local_author_on(conn: &Connection, machine_id: &str) -> Result<String> {
    Ok(identity_tag_of(conn, machine_id)?.unwrap_or_else(|| format!("device:{machine_id}")))
}

pub(crate) fn scope_to_str(scope: Scope) -> &'static str {
    match scope {
        Scope::Private => "private",
        Scope::Shared => "shared",
    }
}

pub(crate) fn parse_scope(s: &str) -> rusqlite::Result<Scope> {
    match s {
        "private" => Ok(Scope::Private),
        "shared" => Ok(Scope::Shared),
        other => Err(conversion_err(std::io::Error::other(format!(
            "unknown scope: {other}"
        )))),
    }
}