mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 15:26:17 +00:00
feat(core): workspace and synapse-core foundation
Domain model, SQLite graph store, link parser, journals chained in time, page origin/activity anchors, weighted synapses with spreading activation, content-addressed blob store and HLC op log with LWW remote apply. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7f5c7738e5
commit
fbcfcf678f
18 files changed
+3094
-1
No files matched your search
@@ -0,0 +1,85 @@
|
||||
//! Content-addressed blob store for assets (images, PDFs, videos...). Files are streamed and
|
||||
//! hashed with blake3; identical content is stored once at `blobs/<2 hex>/<rest>`.
|
||||
|
||||
use crate::Result;
|
||||
use std::fs;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BlobStore {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
impl BlobStore {
|
||||
pub fn open(root: impl Into<PathBuf>) -> Result<Self> {
|
||||
let root = root.into();
|
||||
fs::create_dir_all(root.join("tmp"))?;
|
||||
Ok(Self { root })
|
||||
}
|
||||
|
||||
pub fn path_of(&self, hash: &str) -> PathBuf {
|
||||
self.root.join(&hash[..2]).join(&hash[2..])
|
||||
}
|
||||
|
||||
pub fn contains(&self, hash: &str) -> bool {
|
||||
hash.len() > 2 && self.path_of(hash).exists()
|
||||
}
|
||||
|
||||
/// Streams `reader` into the store. Returns `(hash, size)`.
|
||||
pub fn put_reader(&self, mut reader: impl Read) -> Result<(String, u64)> {
|
||||
let tmp = self
|
||||
.root
|
||||
.join("tmp")
|
||||
.join(crate::model::new_id().to_string());
|
||||
let mut out = io::BufWriter::new(fs::File::create(&tmp)?);
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
let mut buf = vec![0u8; 256 * 1024];
|
||||
let mut size = 0u64;
|
||||
loop {
|
||||
let n = reader.read(&mut buf)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buf[..n]);
|
||||
out.write_all(&buf[..n])?;
|
||||
size += n as u64;
|
||||
}
|
||||
out.flush()?;
|
||||
drop(out);
|
||||
let hash = hasher.finalize().to_hex().to_string();
|
||||
let dest = self.path_of(&hash);
|
||||
if dest.exists() {
|
||||
fs::remove_file(&tmp)?;
|
||||
} else {
|
||||
fs::create_dir_all(dest.parent().unwrap())?;
|
||||
fs::rename(&tmp, &dest)?;
|
||||
}
|
||||
Ok((hash, size))
|
||||
}
|
||||
|
||||
pub fn put_file(&self, path: &Path) -> Result<(String, u64)> {
|
||||
self.put_reader(fs::File::open(path)?)
|
||||
}
|
||||
|
||||
pub fn open_blob(&self, hash: &str) -> Result<fs::File> {
|
||||
Ok(fs::File::open(self.path_of(hash))?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn dedups_by_content() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let s = BlobStore::open(dir.path()).unwrap();
|
||||
let (h1, n) = s.put_reader(&b"hello"[..]).unwrap();
|
||||
let (h2, _) = s.put_reader(&b"hello"[..]).unwrap();
|
||||
assert_eq!((h1.clone(), n), (h2, 5));
|
||||
let mut out = String::new();
|
||||
s.open_blob(&h1).unwrap().read_to_string(&mut out).unwrap();
|
||||
assert_eq!(out, "hello");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
//! Embedding abstraction shared by `synapse-search` (consumer) and `synapse-ai` (providers).
|
||||
|
||||
pub type EmbedError = Box<dyn std::error::Error + Send + Sync>;
|
||||
|
||||
/// Turns texts into dense vectors. Implementations may block (network or local model).
|
||||
pub trait Embedder: Send + Sync {
|
||||
/// Stable identifier, e.g. `openai/text-embedding-3-small`. Indexes are keyed by it.
|
||||
fn model_id(&self) -> String;
|
||||
fn dims(&self) -> usize;
|
||||
fn embed(&self, texts: &[String]) -> std::result::Result<Vec<Vec<f32>>, EmbedError>;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
#[error("sqlite: {0}")]
|
||||
Sqlite(#[from] rusqlite::Error),
|
||||
#[error("io: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("json: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error("not found: {0}")]
|
||||
NotFound(String),
|
||||
#[error("conflict: {0}")]
|
||||
Conflict(String),
|
||||
#[error("invalid: {0}")]
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Hybrid logical clock. Encoded as a lexicographically sortable string
|
||||
//! `{millis:013}-{counter:05}-{actor}` so ordering is plain string comparison.
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct HlcClock {
|
||||
actor: String,
|
||||
state: Mutex<(i64, u32)>,
|
||||
}
|
||||
|
||||
impl HlcClock {
|
||||
pub fn new(actor: impl Into<String>) -> Self {
|
||||
Self {
|
||||
actor: actor.into(),
|
||||
state: Mutex::new((0, 0)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn actor(&self) -> &str {
|
||||
&self.actor
|
||||
}
|
||||
|
||||
/// Next timestamp for a local event at wall-clock `now_ms`.
|
||||
pub fn tick(&self, now_ms: i64) -> String {
|
||||
let mut s = self.state.lock().unwrap();
|
||||
if now_ms > s.0 {
|
||||
*s = (now_ms, 0);
|
||||
} else {
|
||||
s.1 += 1;
|
||||
}
|
||||
encode(s.0, s.1, &self.actor)
|
||||
}
|
||||
|
||||
/// Merge a remote timestamp so later local ticks sort after it.
|
||||
pub fn observe(&self, remote: &str) {
|
||||
if let Some((ms, c)) = decode(remote) {
|
||||
let mut s = self.state.lock().unwrap();
|
||||
if (ms, c) > *s {
|
||||
*s = (ms, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode(ms: i64, counter: u32, actor: &str) -> String {
|
||||
format!("{ms:013}-{counter:05}-{actor}")
|
||||
}
|
||||
|
||||
pub fn decode(h: &str) -> Option<(i64, u32)> {
|
||||
let mut it = h.splitn(3, '-');
|
||||
Some((it.next()?.parse().ok()?, it.next()?.parse().ok()?))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn monotonic_and_sortable() {
|
||||
let c = HlcClock::new("a");
|
||||
let t1 = c.tick(1000);
|
||||
let t2 = c.tick(1000);
|
||||
let t3 = c.tick(999);
|
||||
assert!(t1 < t2 && t2 < t3);
|
||||
c.observe(&encode(5000, 7, "b"));
|
||||
assert!(c.tick(10) > encode(5000, 7, "b"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Synapse core: domain model, SQLite-backed graph store, link parsing, temporal (journal)
|
||||
//! links, weighted synapses and a content-addressed blob store.
|
||||
//!
|
||||
//! Every mutation is appended to an op log (`Graph::ops_since`), which is the single change
|
||||
//! feed used by indexers (search), backup (history) and sync.
|
||||
|
||||
pub mod blob;
|
||||
pub mod embed;
|
||||
pub mod error;
|
||||
pub mod hlc;
|
||||
pub mod model;
|
||||
pub mod parse;
|
||||
pub mod position;
|
||||
mod schema;
|
||||
pub mod store;
|
||||
pub mod synapse;
|
||||
|
||||
pub use error::{Error, Result};
|
||||
pub use model::*;
|
||||
pub use store::Graph;
|
||||
@@ -0,0 +1,172 @@
|
||||
use chrono::NaiveDate;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub type PageId = Uuid;
|
||||
pub type BlockId = Uuid;
|
||||
/// Free-form properties (`key:: value` in Logseq).
|
||||
pub type Properties = serde_json::Map<String, serde_json::Value>;
|
||||
|
||||
pub fn new_id() -> Uuid {
|
||||
Uuid::now_v7()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Page {
|
||||
pub id: PageId,
|
||||
pub title: String,
|
||||
/// Set for journal pages: the day they represent.
|
||||
pub journal_date: Option<NaiveDate>,
|
||||
/// Journal day in which this page was born (episodic anchor).
|
||||
pub origin_journal: Option<NaiveDate>,
|
||||
pub properties: Properties,
|
||||
pub created_at: i64,
|
||||
pub updated_at: i64,
|
||||
}
|
||||
|
||||
impl Page {
|
||||
pub fn is_journal(&self) -> bool {
|
||||
self.journal_date.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Block {
|
||||
pub id: BlockId,
|
||||
pub page_id: PageId,
|
||||
pub parent_id: Option<BlockId>,
|
||||
/// Fractional index among siblings (see [`crate::position`]).
|
||||
pub position: String,
|
||||
/// Logseq-flavoured Markdown (rich text source of truth).
|
||||
pub content: String,
|
||||
pub properties: Properties,
|
||||
pub collapsed: bool,
|
||||
pub created_at: i64,
|
||||
pub updated_at: i64,
|
||||
}
|
||||
|
||||
/// Kind of a link from a block to a page.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum RefKind {
|
||||
/// `[[Page]]`
|
||||
Link,
|
||||
/// `#tag` / `#[[tag]]`
|
||||
Tag,
|
||||
/// `key:: [[Page]]` inside properties
|
||||
Property,
|
||||
}
|
||||
|
||||
impl RefKind {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
RefKind::Link => "link",
|
||||
RefKind::Tag => "tag",
|
||||
RefKind::Property => "property",
|
||||
}
|
||||
}
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
Some(match s {
|
||||
"link" => RefKind::Link,
|
||||
"tag" => RefKind::Tag,
|
||||
"property" => RefKind::Property,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A backlink: `block` (on `page`) references the queried page.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Backlink {
|
||||
pub block: Block,
|
||||
pub page_title: String,
|
||||
pub kind: RefKind,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Asset {
|
||||
/// blake3 hex of the content.
|
||||
pub hash: String,
|
||||
pub size: u64,
|
||||
pub mime: Option<String>,
|
||||
pub original_name: Option<String>,
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
/// One day on the timeline view.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct TimelineDay {
|
||||
pub date: NaiveDate,
|
||||
pub journal: Option<PageId>,
|
||||
/// Pages born on this day.
|
||||
pub created: Vec<PageId>,
|
||||
/// Pages edited on this day (excluding the journal itself), with edit counts.
|
||||
pub edited: Vec<(PageId, u32)>,
|
||||
}
|
||||
|
||||
/// Journal neighbours (episodic chain).
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct JournalNeighbors {
|
||||
pub prev: Option<NaiveDate>,
|
||||
pub next: Option<NaiveDate>,
|
||||
}
|
||||
|
||||
/// Entry of the op log, the change feed for indexing, backup and sync.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct OpRecord {
|
||||
pub seq: i64,
|
||||
pub hlc: String,
|
||||
pub op: Op,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum Op {
|
||||
UpsertPage { page: Page },
|
||||
DeletePage { id: PageId },
|
||||
UpsertBlock { block: Block },
|
||||
DeleteBlock { id: BlockId },
|
||||
PutAsset { asset: Asset },
|
||||
SetAlias { alias: String, page: Option<PageId> },
|
||||
}
|
||||
|
||||
/// Fields for creating a page; defaults come from the graph clock.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct NewPage {
|
||||
pub title: String,
|
||||
pub origin_journal: Option<NaiveDate>,
|
||||
pub properties: Properties,
|
||||
/// Override timestamps (importer). Millis since epoch.
|
||||
pub created_at: Option<i64>,
|
||||
pub updated_at: Option<i64>,
|
||||
}
|
||||
|
||||
impl NewPage {
|
||||
pub fn titled(title: impl Into<String>) -> Self {
|
||||
Self {
|
||||
title: title.into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where to insert a new block.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Placement {
|
||||
/// Last child of `parent` (or last root block when `None`).
|
||||
LastChildOf(Option<BlockId>),
|
||||
/// Right after a sibling.
|
||||
After(BlockId),
|
||||
/// Right before a sibling.
|
||||
Before(BlockId),
|
||||
}
|
||||
|
||||
/// Journal page title for a date (ISO; the UI formats it for display).
|
||||
pub fn journal_title(date: NaiveDate) -> String {
|
||||
date.format("%Y-%m-%d").to_string()
|
||||
}
|
||||
|
||||
/// Normalised key used for title/alias lookups.
|
||||
pub fn title_key(title: &str) -> String {
|
||||
title.trim().to_lowercase()
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
//! Extracts references from Logseq-flavoured Markdown block content.
|
||||
|
||||
use crate::model::RefKind;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct Refs {
|
||||
/// Referenced page titles with their kind (deduplicated, original casing).
|
||||
pub pages: Vec<(String, RefKind)>,
|
||||
/// `((uuid))` block references.
|
||||
pub blocks: Vec<Uuid>,
|
||||
/// `{{embed ((uuid))}}` block embeds.
|
||||
pub embeds: Vec<Uuid>,
|
||||
}
|
||||
|
||||
impl Refs {
|
||||
fn push_page(&mut self, title: &str, kind: RefKind) {
|
||||
let t = title.trim();
|
||||
if t.is_empty() {
|
||||
return;
|
||||
}
|
||||
let key = crate::model::title_key(t);
|
||||
if !self
|
||||
.pages
|
||||
.iter()
|
||||
.any(|(p, k)| *k == kind && crate::model::title_key(p) == key)
|
||||
{
|
||||
self.pages.push((t.to_string(), kind));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses refs, skipping inline code and fenced code blocks.
|
||||
pub fn extract_refs(content: &str) -> Refs {
|
||||
let mut refs = Refs::default();
|
||||
let mut in_fence = false;
|
||||
for line in content.lines() {
|
||||
if line.trim_start().starts_with("```") {
|
||||
in_fence = !in_fence;
|
||||
continue;
|
||||
}
|
||||
if in_fence {
|
||||
continue;
|
||||
}
|
||||
let prop_line = property_split(line);
|
||||
scan_line(
|
||||
prop_line.map(|(_, v)| v).unwrap_or(line),
|
||||
prop_line.is_some(),
|
||||
&mut refs,
|
||||
);
|
||||
}
|
||||
refs
|
||||
}
|
||||
|
||||
/// `key:: value` → `(key, value)`.
|
||||
pub fn property_split(line: &str) -> Option<(&str, &str)> {
|
||||
let (k, v) = line.split_once("::")?;
|
||||
let k = k.trim();
|
||||
(!k.is_empty()
|
||||
&& k.chars()
|
||||
.all(|c| c.is_alphanumeric() || c == '-' || c == '_'))
|
||||
.then_some((k, v.trim()))
|
||||
}
|
||||
|
||||
fn scan_line(line: &str, is_prop: bool, refs: &mut Refs) {
|
||||
let link_kind = if is_prop {
|
||||
RefKind::Property
|
||||
} else {
|
||||
RefKind::Link
|
||||
};
|
||||
let b = line.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
match b[i] {
|
||||
b'`' => {
|
||||
i = line[i + 1..]
|
||||
.find('`')
|
||||
.map(|j| i + 1 + j + 1)
|
||||
.unwrap_or(b.len());
|
||||
}
|
||||
b'[' if line[i..].starts_with("[[") => match find_close(line, i + 2) {
|
||||
Some(end) => {
|
||||
refs.push_page(&line[i + 2..end], link_kind);
|
||||
i = end + 2;
|
||||
}
|
||||
None => i += 2,
|
||||
},
|
||||
b'(' if line[i..].starts_with("((") => match line[i + 2..].find("))") {
|
||||
Some(j) => {
|
||||
if let Ok(id) = Uuid::parse_str(line[i + 2..i + 2 + j].trim()) {
|
||||
let embed = line[..i].trim_end().ends_with("{{embed");
|
||||
let list = if embed {
|
||||
&mut refs.embeds
|
||||
} else {
|
||||
&mut refs.blocks
|
||||
};
|
||||
if !list.contains(&id) {
|
||||
list.push(id);
|
||||
}
|
||||
}
|
||||
i += 2 + j + 2;
|
||||
}
|
||||
None => i += 2,
|
||||
},
|
||||
b'#' if i == 0 || b[i - 1].is_ascii_whitespace() => {
|
||||
if line[i + 1..].starts_with("[[")
|
||||
&& let Some(end) = find_close(line, i + 3)
|
||||
{
|
||||
refs.push_page(&line[i + 3..end], RefKind::Tag);
|
||||
i = end + 2;
|
||||
continue;
|
||||
}
|
||||
let rest = &line[i + 1..];
|
||||
let len = rest
|
||||
.find(|c: char| c.is_whitespace() || ",.;:!?()[]{}\"'".contains(c))
|
||||
.unwrap_or(rest.len());
|
||||
// `#` alone or a Markdown heading (`# `, `## `) is not a tag.
|
||||
if len > 0 && !rest.starts_with('#') {
|
||||
refs.push_page(&rest[..len], RefKind::Tag);
|
||||
}
|
||||
i += 1 + len;
|
||||
}
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds the `]]` closing a `[[` that opened before `from`, allowing nested `[[..]]`.
|
||||
fn find_close(s: &str, from: usize) -> Option<usize> {
|
||||
let mut depth = 0;
|
||||
let mut i = from;
|
||||
while i + 1 < s.len() {
|
||||
if s[i..].starts_with("[[") {
|
||||
depth += 1;
|
||||
i += 2;
|
||||
} else if s[i..].starts_with("]]") {
|
||||
if depth == 0 {
|
||||
return Some(i);
|
||||
}
|
||||
depth -= 1;
|
||||
i += 2;
|
||||
} else {
|
||||
i += s[i..].chars().next().map_or(1, char::len_utf8);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn links_tags_props_and_block_refs() {
|
||||
let id = Uuid::now_v7();
|
||||
let c = format!(
|
||||
"Met [[Ana López]] about #rust and #[[Second Brain]] see (({id}))\n\
|
||||
type:: [[Meeting]]\n`[[not a link]]` # heading-ish\n{{{{embed (({id}))}}}}"
|
||||
);
|
||||
let r = extract_refs(&c);
|
||||
assert_eq!(
|
||||
r.pages,
|
||||
vec![
|
||||
("Ana López".into(), RefKind::Link),
|
||||
("rust".into(), RefKind::Tag),
|
||||
("Second Brain".into(), RefKind::Tag),
|
||||
("Meeting".into(), RefKind::Property),
|
||||
]
|
||||
);
|
||||
assert_eq!(r.blocks, vec![id]);
|
||||
assert_eq!(r.embeds, vec![id]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_code_fences_and_headings() {
|
||||
let r = extract_refs("## Title\n```\n[[inside]]\n```\nok [[outside]]");
|
||||
assert_eq!(r.pages, vec![("outside".into(), RefKind::Link)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_links() {
|
||||
let r = extract_refs("[[a [[b]] c]]");
|
||||
assert_eq!(r.pages[0].0, "a [[b]] c");
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrites references to the page whose normalised title is `old_key` so they point at
|
||||
/// `new_title`: `[[old]]`, `#[[old]]` and `#old`.
|
||||
pub fn rewrite_refs(content: &str, old_key: &str, new_title: &str) -> String {
|
||||
let tag = if new_title.contains(char::is_whitespace) {
|
||||
format!("#[[{new_title}]]")
|
||||
} else {
|
||||
format!("#{new_title}")
|
||||
};
|
||||
let mut out = String::with_capacity(content.len());
|
||||
let mut i = 0;
|
||||
while i < content.len() {
|
||||
let rest = &content[i..];
|
||||
if rest.starts_with("[[")
|
||||
&& let Some(end) = find_close(content, i + 2)
|
||||
{
|
||||
if crate::model::title_key(&content[i + 2..end]) == old_key {
|
||||
out.push_str(&format!("[[{new_title}]]"));
|
||||
} else {
|
||||
out.push_str(&content[i..end + 2]);
|
||||
}
|
||||
i = end + 2;
|
||||
continue;
|
||||
}
|
||||
if rest.starts_with('#') && !rest.starts_with("#[[") {
|
||||
let prev_ok = i == 0 || content[..i].ends_with(char::is_whitespace);
|
||||
let body = &rest[1..];
|
||||
let len = body
|
||||
.find(|c: char| c.is_whitespace() || ",.;:!?()[]{}\"'".contains(c))
|
||||
.unwrap_or(body.len());
|
||||
if prev_ok && len > 0 && crate::model::title_key(&body[..len]) == old_key {
|
||||
out.push_str(&tag);
|
||||
i += 1 + len;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let c = rest.chars().next().unwrap();
|
||||
out.push(c);
|
||||
i += c.len_utf8();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod rewrite_tests {
|
||||
use super::rewrite_refs;
|
||||
|
||||
#[test]
|
||||
fn rewrites_links_and_tags() {
|
||||
assert_eq!(
|
||||
rewrite_refs(
|
||||
"see [[Foo]], #foo and #[[foo]] not #foobar",
|
||||
"foo",
|
||||
"Big Bar"
|
||||
),
|
||||
"see [[Big Bar]], #[[Big Bar]] and #[[Big Bar]] not #foobar"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! Fractional indexing for sibling order: keys are strings over `[0-9a-z]` with no trailing
|
||||
//! `0`, so a key strictly between any two keys always exists and moves touch one row.
|
||||
|
||||
const DIGITS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
|
||||
const BASE: usize = DIGITS.len();
|
||||
|
||||
fn digit(c: u8) -> usize {
|
||||
DIGITS
|
||||
.iter()
|
||||
.position(|&d| d == c)
|
||||
.expect("invalid position digit")
|
||||
}
|
||||
|
||||
/// Returns a key strictly between `lo` and `hi` (`None` = open bound).
|
||||
pub fn between(lo: Option<&str>, hi: Option<&str>) -> String {
|
||||
let lo = lo.unwrap_or("");
|
||||
if let Some(h) = hi {
|
||||
assert!(lo < h, "position bounds out of order: {lo:?} >= {h:?}");
|
||||
}
|
||||
midpoint(lo.as_bytes(), hi.map(str::as_bytes))
|
||||
}
|
||||
|
||||
fn midpoint(a: &[u8], b: Option<&[u8]>) -> String {
|
||||
if let Some(b) = b {
|
||||
let mut n = 0;
|
||||
while n < b.len() && a.get(n).copied().unwrap_or(b'0') == b[n] {
|
||||
n += 1;
|
||||
}
|
||||
if n > 0 {
|
||||
let rest = midpoint(a.get(n..).unwrap_or(&[]), Some(&b[n..]));
|
||||
return String::from_utf8(b[..n].to_vec()).unwrap() + &rest;
|
||||
}
|
||||
}
|
||||
let da = a.first().map(|&c| digit(c)).unwrap_or(0);
|
||||
let db = b.and_then(|b| b.first()).map(|&c| digit(c)).unwrap_or(BASE);
|
||||
if db - da > 1 {
|
||||
return (DIGITS[(da + db) / 2] as char).to_string();
|
||||
}
|
||||
match b {
|
||||
Some(b) if b.len() > 1 => (b[0] as char).to_string(),
|
||||
_ => (DIGITS[da] as char).to_string() + &midpoint(a.get(1..).unwrap_or(&[]), None),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ordering_holds_under_repeated_inserts() {
|
||||
let mut keys = vec![between(None, None)];
|
||||
for i in 0..200 {
|
||||
let k = match i % 3 {
|
||||
0 => between(None, Some(&keys[0])),
|
||||
1 => between(Some(keys.last().unwrap()), None),
|
||||
_ => between(Some(&keys[0]), Some(&keys[1])),
|
||||
};
|
||||
keys.push(k);
|
||||
keys.sort();
|
||||
keys.dedup();
|
||||
assert_eq!(keys.len(), i + 2);
|
||||
}
|
||||
assert!(keys.iter().all(|k| !k.ends_with('0')));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
pub const VERSION: i64 = 1;
|
||||
|
||||
pub const SCHEMA: &str = r#"
|
||||
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS pages (
|
||||
id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
title_key TEXT NOT NULL UNIQUE,
|
||||
journal_date TEXT UNIQUE,
|
||||
origin_journal TEXT,
|
||||
properties TEXT NOT NULL DEFAULT '{}',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
hlc TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS pages_updated ON pages(updated_at);
|
||||
CREATE INDEX IF NOT EXISTS pages_origin ON pages(origin_journal);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS aliases (
|
||||
alias_key TEXT PRIMARY KEY,
|
||||
alias TEXT NOT NULL,
|
||||
page_id TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS aliases_page ON aliases(page_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS blocks (
|
||||
id TEXT PRIMARY KEY,
|
||||
page_id TEXT NOT NULL,
|
||||
parent_id TEXT,
|
||||
position TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
properties TEXT NOT NULL DEFAULT '{}',
|
||||
collapsed INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
hlc TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS blocks_tree ON blocks(page_id, parent_id, position);
|
||||
|
||||
-- Page refs are stored by normalised title so they never dangle and survive sync.
|
||||
CREATE TABLE IF NOT EXISTS refs (
|
||||
block_id TEXT NOT NULL,
|
||||
target_key TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
PRIMARY KEY (block_id, target_key, kind)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS refs_target ON refs(target_key);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS block_refs (
|
||||
block_id TEXT NOT NULL,
|
||||
target_block TEXT NOT NULL,
|
||||
embed INTEGER NOT NULL,
|
||||
PRIMARY KEY (block_id, target_block, embed)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS block_refs_target ON block_refs(target_block);
|
||||
|
||||
-- Days on which a page was edited (links pages to journals of those days).
|
||||
CREATE TABLE IF NOT EXISTS page_activity (
|
||||
page_id TEXT NOT NULL,
|
||||
day TEXT NOT NULL,
|
||||
edits INTEGER NOT NULL,
|
||||
PRIMARY KEY (page_id, day)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS page_activity_day ON page_activity(day);
|
||||
|
||||
-- Weighted, undirected associations between pages (a < b). Local to the device.
|
||||
CREATE TABLE IF NOT EXISTS synapses (
|
||||
a TEXT NOT NULL,
|
||||
b TEXT NOT NULL,
|
||||
weight REAL NOT NULL,
|
||||
last_fired INTEGER NOT NULL,
|
||||
PRIMARY KEY (a, b)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS synapses_b ON synapses(b);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS assets (
|
||||
hash TEXT PRIMARY KEY,
|
||||
size INTEGER NOT NULL,
|
||||
mime TEXT,
|
||||
original_name TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tombstones (id TEXT PRIMARY KEY, hlc TEXT NOT NULL);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ops (
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
hlc TEXT NOT NULL,
|
||||
payload TEXT NOT NULL
|
||||
);
|
||||
"#;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,144 @@
|
||||
//! Weighted associations between pages ("synapses") and spreading activation.
|
||||
//!
|
||||
//! Weights grow when two pages are linked, co-visited or co-edited (Hebbian) and decay with a
|
||||
//! half-life unless reinforced. `spread` ranks related notes by propagating activation over
|
||||
//! explicit refs, synapses and the temporal journal structure.
|
||||
|
||||
use crate::model::PageId;
|
||||
use crate::store::{Graph, parse_id};
|
||||
use crate::{Result, journal_title};
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub const HALF_LIFE_MS: f64 = 30.0 * 24.0 * 3600.0 * 1000.0;
|
||||
pub const LINK_STRENGTH: f32 = 0.5;
|
||||
pub const VISIT_STRENGTH: f32 = 0.2;
|
||||
pub const MAX_WEIGHT: f32 = 10.0;
|
||||
|
||||
fn ordered(a: PageId, b: PageId) -> (String, String) {
|
||||
if a < b {
|
||||
(a.to_string(), b.to_string())
|
||||
} else {
|
||||
(b.to_string(), a.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn decayed(w: f32, last: i64, now: i64) -> f32 {
|
||||
let dt = (now - last).max(0) as f64;
|
||||
(w as f64 * 0.5f64.powf(dt / HALF_LIFE_MS)) as f32
|
||||
}
|
||||
|
||||
/// Strengthens the a–b synapse by `amount` (negative to weaken, e.g. rejected suggestion).
|
||||
pub fn fire(conn: &Connection, a: PageId, b: PageId, amount: f32, now: i64) -> Result<()> {
|
||||
if a == b {
|
||||
return Ok(());
|
||||
}
|
||||
let w = (weight(conn, a, b, now)? + amount).clamp(0.0, MAX_WEIGHT);
|
||||
let (x, y) = ordered(a, b);
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO synapses(a, b, weight, last_fired) VALUES (?1, ?2, ?3, ?4)",
|
||||
params![x, y, w, now],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn weight(conn: &Connection, a: PageId, b: PageId, now: i64) -> Result<f32> {
|
||||
let (x, y) = ordered(a, b);
|
||||
let row: Option<(f32, i64)> = conn
|
||||
.query_row(
|
||||
"SELECT weight, last_fired FROM synapses WHERE a=?1 AND b=?2",
|
||||
params![x, y],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)
|
||||
.optional()?;
|
||||
Ok(row.map(|(w, l)| decayed(w, l, now)).unwrap_or(0.0))
|
||||
}
|
||||
|
||||
/// Weighted neighbours of a page: refs both ways, synapses, journal chain and anchors.
|
||||
pub fn neighbors(g: &Graph, page: PageId) -> Result<Vec<(PageId, f32)>> {
|
||||
let conn = g.conn();
|
||||
let now = g.now_ms();
|
||||
let mut out: HashMap<PageId, f32> = HashMap::new();
|
||||
let mut add = |id: PageId, w: f32| *out.entry(id).or_default() += w;
|
||||
|
||||
for p in g.outgoing_pages(page)? {
|
||||
add(p, 1.0);
|
||||
}
|
||||
for bl in g.backlinks(page)? {
|
||||
add(bl.block.page_id, 1.0);
|
||||
}
|
||||
let pid = page.to_string();
|
||||
let mut st = conn.prepare_cached(
|
||||
"SELECT b, weight, last_fired FROM synapses WHERE a=?1
|
||||
UNION ALL SELECT a, weight, last_fired FROM synapses WHERE b=?1",
|
||||
)?;
|
||||
for r in st.query_map([&pid], |r| {
|
||||
Ok((
|
||||
r.get::<_, String>(0)?,
|
||||
r.get::<_, f32>(1)?,
|
||||
r.get::<_, i64>(2)?,
|
||||
))
|
||||
})? {
|
||||
let (other, w, last) = r?;
|
||||
add(parse_id(&other)?, decayed(w, last, now) / 2.0);
|
||||
}
|
||||
if let Some(p) = g.get_page(page)? {
|
||||
if let Some(d) = p.journal_date {
|
||||
let n = g.journal_neighbors(d)?;
|
||||
for j in [n.prev, n.next].into_iter().flatten() {
|
||||
add(crate::store::journal_id(j), 0.5);
|
||||
}
|
||||
let day = journal_title(d);
|
||||
let mut st = conn.prepare_cached(
|
||||
"SELECT id FROM pages WHERE origin_journal=?1
|
||||
UNION SELECT page_id FROM page_activity WHERE day=?1",
|
||||
)?;
|
||||
for r in st.query_map([&day], |r| r.get::<_, String>(0))? {
|
||||
add(parse_id(&r?)?, 0.4);
|
||||
}
|
||||
} else {
|
||||
if let Some(o) = p.origin_journal {
|
||||
add(crate::store::journal_id(o), 0.4);
|
||||
}
|
||||
for (d, _) in g.edit_days(page)? {
|
||||
add(crate::store::journal_id(d), 0.3);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.remove(&page);
|
||||
Ok(out.into_iter().collect())
|
||||
}
|
||||
|
||||
/// Spreading activation from `seed`, three hops, normalised by fan-out.
|
||||
pub fn spread(g: &Graph, seed: PageId, limit: usize) -> Result<Vec<(PageId, f32)>> {
|
||||
const DECAY: f32 = 0.5;
|
||||
let mut activation: HashMap<PageId, f32> = HashMap::new();
|
||||
let mut frontier = vec![(seed, 1.0f32)];
|
||||
let mut cache: HashMap<PageId, Vec<(PageId, f32)>> = HashMap::new();
|
||||
for _ in 0..3 {
|
||||
let mut next: HashMap<PageId, f32> = HashMap::new();
|
||||
for (node, a) in frontier {
|
||||
if a < 0.01 {
|
||||
continue;
|
||||
}
|
||||
if let std::collections::hash_map::Entry::Vacant(e) = cache.entry(node) {
|
||||
e.insert(neighbors(g, node)?);
|
||||
}
|
||||
let nbrs = &cache[&node];
|
||||
let fan = (nbrs.len().max(1) as f32).sqrt();
|
||||
for &(m, w) in nbrs {
|
||||
if m != seed {
|
||||
*next.entry(m).or_default() += a * w * DECAY / fan;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (m, a) in &next {
|
||||
*activation.entry(*m).or_default() += a;
|
||||
}
|
||||
frontier = next.into_iter().collect();
|
||||
}
|
||||
let mut ranked: Vec<_> = activation.into_iter().collect();
|
||||
ranked.sort_by(|a, b| b.1.total_cmp(&a.1));
|
||||
ranked.truncate(limit);
|
||||
Ok(ranked)
|
||||
}
|
||||
Reference in new issue
Block a user