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:
dasemuandClaude Opus 5.5 committed 2026-10-21 03:24:22 +02:00
1 parent 7f5c7738e5
commit fbcfcf678f
18 files changed
+3094 -1

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@
f=$(jq -r '.tool_input.file_path // empty' 2>/dev/null) f=$(jq -r '.tool_input.file_path // empty' 2>/dev/null)
[ -n "$f" ] && [ -f "$f" ] || exit 0 [ -n "$f" ] && [ -f "$f" ] || exit 0
case "$f" in case "$f" in
*.rs) command -v rustfmt >/dev/null && rustfmt --edition 2021 -q "$f" 2>/dev/null ;; *.rs) command -v rustfmt >/dev/null && rustfmt --edition 2024 -q "$f" 2>/dev/null ;;
*.dart) command -v dart >/dev/null && dart format -o write "$f" >/dev/null 2>&1 ;; *.dart) command -v dart >/dev/null && dart format -o write "$f" >/dev/null 2>&1 ;;
esac esac
exit 0 exit 0
Generated
+631
View File
@@ -0,0 +1,631 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "android_system_properties"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
dependencies = [
"libc",
]
[[package]]
name = "arrayvec"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "blake3"
version = "1.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae"
dependencies = [
"arrayvec",
"cc",
"cfg-if",
"constant_time_eq",
"cpufeatures",
]
[[package]]
name = "bumpalo"
version = "3.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
name = "cc"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "chrono"
version = "0.4.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
dependencies = [
"iana-time-zone",
"num-traits",
"serde",
"windows-link",
]
[[package]]
name = "constant_time_eq"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fallible-iterator"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
[[package]]
name = "fallible-streaming-iterator"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "futures-core"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
[[package]]
name = "futures-task"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
[[package]]
name = "futures-util"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"slab",
]
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
]
[[package]]
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"foldhash",
]
[[package]]
name = "hashlink"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1"
dependencies = [
"hashbrown",
]
[[package]]
name = "iana-time-zone"
version = "0.1.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"log",
"wasm-bindgen",
"windows-core",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
dependencies = [
"cc",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "js-sys"
version = "0.3.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
dependencies = [
"cfg-if",
"futures-util",
"wasm-bindgen",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libsqlite3-sys"
version = "0.35.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f"
dependencies = [
"cc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "log"
version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rusqlite"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f"
dependencies = [
"bitflags",
"fallible-iterator",
"fallible-streaming-iterator",
"hashlink",
"libsqlite3-sys",
"smallvec",
]
[[package]]
name = "rustix"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "rustversion"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "sha1_smol"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "smallvec"
version = "1.16.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "synapse-core"
version = "0.1.0"
dependencies = [
"blake3",
"chrono",
"rusqlite",
"serde",
"serde_json",
"tempfile",
"thiserror",
"uuid",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom",
"once_cell",
"rustix",
"windows-sys",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "uuid"
version = "1.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606"
dependencies = [
"getrandom",
"js-sys",
"serde_core",
"sha1_smol",
"wasm-bindgen",
]
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "wasm-bindgen"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn 3.0.9",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
dependencies = [
"unicode-ident",
]
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+18
View File
@@ -0,0 +1,18 @@
[workspace]
resolver = "3"
members = ["crates/*"]
[workspace.package]
edition = "2024"
license = "AGPL-3.0-or-later"
rust-version = "1.85"
# Only deps shared by several crates go here. Crate-specific deps live in each crate.
[workspace.dependencies]
synapse-core = { path = "crates/synapse-core" }
chrono = { version = "0.4", default-features = false, features = ["clock", "std", "serde"] }
rusqlite = { version = "0.37", features = ["bundled"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
uuid = { version = "1", features = ["v5", "v7", "serde"] }
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "synapse-core"
version = "0.1.0"
edition.workspace = true
license.workspace = true
description = "Synapse domain model, storage, link parsing and temporal graph"
[dependencies]
blake3 = "1"
chrono.workspace = true
rusqlite.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
uuid.workspace = true
[dev-dependencies]
tempfile = "3"
+85
View File
@@ -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");
}
}
+11
View File
@@ -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>;
}
+19
View File
@@ -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>;
+69
View File
@@ -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"));
}
}
+20
View File
@@ -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;
+172
View File
@@ -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()
}
+244
View File
@@ -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"
);
}
}
+65
View File
@@ -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')));
}
}
+92
View File
@@ -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
+144
View File
@@ -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)
}
+188
View File
@@ -0,0 +1,188 @@
use chrono::{Local, NaiveDate, TimeZone};
use synapse_core::{Graph, NewPage, Op, Placement};
fn ms(y: i32, m: u32, d: u32) -> i64 {
Local
.with_ymd_and_hms(y, m, d, 12, 0, 0)
.unwrap()
.timestamp_millis()
}
fn day(y: i32, m: u32, d: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(y, m, d).unwrap()
}
fn graph() -> (tempfile::TempDir, Graph) {
let dir = tempfile::tempdir().unwrap();
let g = Graph::open(dir.path()).unwrap();
(dir, g)
}
#[test]
fn journals_chain_and_pages_are_anchored() {
let (_d, g) = graph();
g.set_now(Some(ms(2026, 10, 1)));
let j1 = g.today_journal().unwrap();
g.insert_block(
j1.id,
Placement::LastChildOf(None),
"Idea about [[Rust FFI]]",
)
.unwrap();
let page = g.page_by_title("rust ffi").unwrap().unwrap();
assert_eq!(page.origin_journal, Some(day(2026, 10, 1)));
g.set_now(Some(ms(2026, 10, 5)));
g.journal(day(2026, 10, 5)).unwrap();
g.insert_block(page.id, Placement::LastChildOf(None), "more notes")
.unwrap();
let n = g.journal_neighbors(day(2026, 10, 3)).unwrap();
assert_eq!(
(n.prev, n.next),
(Some(day(2026, 10, 1)), Some(day(2026, 10, 5)))
);
assert_eq!(g.edit_days(page.id).unwrap(), vec![(day(2026, 10, 5), 1)]);
let tl = g.timeline(day(2026, 9, 30), day(2026, 10, 6)).unwrap();
assert_eq!(tl.len(), 2);
assert_eq!(tl[0].created, vec![page.id]);
assert_eq!(tl[1].edited, vec![(page.id, 1)]);
}
#[test]
fn outline_order_moves_and_deletes() {
let (_d, g) = graph();
let p = g.create_page(NewPage::titled("Outline")).unwrap();
let a = g
.insert_block(p.id, Placement::LastChildOf(None), "a")
.unwrap();
let c = g.insert_block(p.id, Placement::After(a.id), "c").unwrap();
let b = g.insert_block(p.id, Placement::Before(c.id), "b").unwrap();
let b1 = g
.insert_block(p.id, Placement::LastChildOf(Some(b.id)), "b1")
.unwrap();
let order = |g: &Graph| {
g.page_tree(p.id)
.unwrap()
.into_iter()
.map(|(d, b)| format!("{d}{}", b.content))
.collect::<Vec<_>>()
};
assert_eq!(order(&g), ["0a", "0b", "1b1", "0c"]);
assert!(
g.move_block(b.id, p.id, Placement::LastChildOf(Some(b1.id)))
.is_err()
);
g.move_block(c.id, p.id, Placement::Before(a.id)).unwrap();
assert_eq!(order(&g), ["0c", "0a", "0b", "1b1"]);
g.delete_block(b.id).unwrap();
assert_eq!(order(&g), ["0c", "0a"]);
assert!(g.get_block(b1.id).unwrap().is_none());
}
#[test]
fn backlinks_aliases_and_rename() {
let (_d, g) = graph();
let p = g.create_page(NewPage::titled("Notes")).unwrap();
g.insert_block(
p.id,
Placement::LastChildOf(None),
"about [[Brain]] and #brain",
)
.unwrap();
let brain = g.page_by_title("Brain").unwrap().unwrap();
g.set_alias("Cerebro", Some(brain.id)).unwrap();
g.insert_block(p.id, Placement::LastChildOf(None), "en [[cerebro]]")
.unwrap();
assert_eq!(g.backlinks(brain.id).unwrap().len(), 3);
assert_eq!(g.page_by_title("CEREBRO").unwrap().unwrap().id, brain.id);
g.rename_page(brain.id, "Second Brain").unwrap();
let contents: Vec<_> = g
.page_tree(p.id)
.unwrap()
.into_iter()
.map(|(_, b)| b.content)
.collect();
assert_eq!(contents[0], "about [[Second Brain]] and #[[Second Brain]]");
assert_eq!(g.backlinks(brain.id).unwrap().len(), 3);
assert!(g.synapse_weight(p.id, brain.id).unwrap() > 0.0);
}
#[test]
fn replicas_converge_through_op_log() {
let (_a, a) = graph();
let (_b, b) = graph();
let p = a.create_page(NewPage::titled("Shared")).unwrap();
let blk = a
.insert_block(p.id, Placement::LastChildOf(None), "v1")
.unwrap();
for r in a.ops_since(0, 1000).unwrap() {
b.apply_remote(&r.hlc, &r.op).unwrap();
}
assert_eq!(b.get_block(blk.id).unwrap().unwrap().content, "v1");
let seq_a = a.last_seq().unwrap();
let seq_b = b.last_seq().unwrap();
b.update_block(blk.id, "v2 from b").unwrap();
std::thread::sleep(std::time::Duration::from_millis(2));
a.update_block(blk.id, "v3 from a").unwrap();
let from_b = b.ops_since(seq_b, 1000).unwrap();
let from_a = a.ops_since(seq_a, 1000).unwrap();
for r in &from_b {
a.apply_remote(&r.hlc, &r.op).unwrap();
}
for r in &from_a {
b.apply_remote(&r.hlc, &r.op).unwrap();
}
let ca = a.get_block(blk.id).unwrap().unwrap().content;
let cb = b.get_block(blk.id).unwrap().unwrap().content;
assert_eq!(ca, cb);
assert_eq!(ca, "v3 from a");
let del = a.last_seq().unwrap();
a.delete_block(blk.id).unwrap();
for r in a.ops_since(del, 100).unwrap() {
assert!(matches!(
r.op,
Op::DeleteBlock { .. } | Op::UpsertPage { .. }
));
b.apply_remote(&r.hlc, &r.op).unwrap();
}
assert!(b.get_block(blk.id).unwrap().is_none());
}
#[test]
fn related_prefers_connected_notes() {
let (_d, g) = graph();
let hub = g.create_page(NewPage::titled("Hub")).unwrap();
g.insert_block(
hub.id,
Placement::LastChildOf(None),
"[[Near]] [[Also Near]]",
)
.unwrap();
let near = g.page_by_title("Near").unwrap().unwrap();
g.insert_block(near.id, Placement::LastChildOf(None), "[[Far]]")
.unwrap();
let related = g.related(hub.id, 10).unwrap();
let pos = |t: &str| {
let id = g.page_by_title(t).unwrap().unwrap().id;
related.iter().position(|(p, _)| *p == id).unwrap()
};
assert!(pos("Near") < pos("Far"));
}
#[test]
fn assets_are_deduplicated() {
let (_d, g) = graph();
let a = g
.put_asset_reader(&b"big file"[..], Some("x.pdf"), Some("application/pdf"))
.unwrap();
let b = g
.put_asset_reader(&b"big file"[..], Some("y.pdf"), None)
.unwrap();
assert_eq!(a, b);
assert!(g.blobs().contains(&a.hash));
}
+47
View File
@@ -0,0 +1,47 @@
# Architecture
```
app/ (Flutter, Dart) ──FFI──▶ synapse-ffi ──▶ synapse-core ◀── synapse-search
│ ▲ ▲ synapse-import
│ │ └─────── synapse-history
├──▶ synapse-ai ──┘ (Embedder) synapse-caldav
└──▶ synapse-sync ──HTTP──▶ synapse-server (axum)
```
## Graph on disk
`<graph>/synapse.db` (SQLite, WAL) + `<graph>/blobs/` (content-addressed, blake3). Sibling
crates may add their own tables to the same database (prefix them: `search_*`, `history_*`,
`caldav_*`, `sync_*`) or their own files under `<graph>/` (e.g. `<graph>/index/` for tantivy).
## Data model (`synapse-core`)
- **Page**: title (unique, case-insensitive), optional `journal_date`, `origin_journal`
(the day it was born), properties. Journal ids are UUIDv5 of the date, so the same day has
the same id on every replica; other ids are UUIDv7.
- **Block**: outliner node (`parent_id`, fractional `position`), Markdown `content`,
properties, collapsed flag.
- **Refs**: extracted on every write from `[[Page]]`, `#tag`, `#[[tag]]`, `key:: [[Page]]`,
`((block))`, `{{embed ((block))}}`. Page refs are stored by normalised title, so they
never dangle and survive sync/renames (rename rewrites the text).
- **Aliases**: alternative titles resolving to a page.
- **page_activity**: (page, day, edits) — links pages to the journals of days they were edited.
- **Synapses**: local weighted associations between pages (Hebbian, 30-day half-life).
- **Assets**: metadata rows; bytes in the blob store.
## Temporal model
- `journal_neighbors(date)` gives the previous/next existing journal (episodic chain).
- Pages created from a journal block are born there; other new pages are born in today's
journal. `timeline(from, to)` returns, per day: journal, pages born, pages edited.
## Change feed and sync
Every mutation appends an `Op` to the `ops` table with a hybrid logical clock timestamp.
`ops_since(seq)` is the single feed for indexers, backups and sync. `apply_remote(hlc, op)`
merges another replica's ops with last-writer-wins per entity and tombstones for deletes;
applied ops are re-logged locally so they propagate further.
## Threading
`Graph` owns a `rusqlite::Connection` and is `Send` but not `Sync`. The FFI layer keeps it
behind a mutex (or one graph per worker thread opening the same directory; WAL allows it).
## Brain-like queries
`related(page)` runs spreading activation (3 hops, fan-out normalised) over refs in both
directions, synapses, the journal chain and origin/activity anchors.
+78
View File
@@ -0,0 +1,78 @@
# Synapse plan
## Goals
A Logseq-like outliner that fixes what Logseq/Obsidian lack: native performance on Android,
Linux and Windows, a real database instead of re-parsing Markdown on every start, heavy assets
handled properly, built-in sync (self-hosted) and backup, semantic search and AI, and a
"brain-like" model where connections have strength, memory is episodic (journals) and
knowledge resurfaces on its own.
## Gaps we fix (vs Logseq / Obsidian / Notion)
| Pain | Synapse answer |
|---|---|
| Electron apps: slow start, RAM hungry, poor mobile | Rust core + Flutter AOT native UI |
| Logseq re-indexes huge graphs, chokes on big assets | SQLite store + content-addressed blob store, incremental index |
| Sync is paid or fragile (iCloud/Syncthing conflicts) | Own op-log sync with HLC clocks, self-hosted server |
| Only keyword search | Full-text (tantivy) + vector search, hybrid ranking |
| Links are manual | Auto-link suggestions (title/alias matching + embeddings) |
| Journals are isolated files | Journals chained in time; pages anchored to their journals |
| No history beyond file history | Automatic git-like snapshots, restore any version |
| Calendar/tasks live elsewhere | CalDAV events + VTODO tasks inside journals |
## Brain-like model
- **Episodic memory**: every journal links to the previous and next journal that exists.
- **Origin**: a page created inside a journal block remembers that journal (`origin_journal`).
- **Activity trail**: each edit of a page records the day; the page links to those journals.
- **Synapses**: every link is an edge with a *weight*. Co-visiting or co-editing two notes
strengthens their edge (Hebbian); weights decay over time unless reinforced.
- **Spreading activation**: "related" panel = activate the current note, propagate through
weighted edges with decay, rank by activation (plus vector similarity).
- **Resurfacing**: spaced-repetition-style review of notes/blocks flagged as cards, and
"on this day" + "forgotten but strongly connected" suggestions in the daily journal.
- **Consolidation** (AI): nightly/weekly summaries of journals into evergreen notes, proposed
links and tags; the user accepts or rejects (rejections lower the edge weight).
## Features (scope)
1. Logseq importer: pages, journals, properties, block refs, embeds, tags, aliases, assets
(large files streamed into the blob store), `logseq/config.edn` basics.
2. Efficient storage: SQLite (WAL) + blob store, op log for sync and undo.
3. Native GUI with rich text (block outliner, inline formatting, images, code, tables).
4. Auto-link suggestions.
5. Vector search (embeddings via AI provider or local model), hybrid with full-text.
6. Standalone (local graph) and client-server (online graph) modes, same API.
7. Semi-integrated AI: Anthropic, OpenAI, Gemini, Ollama/OpenAI-compatible; user API keys
stored in the OS keystore. Ask-your-graph (RAG), summarize, rewrite, extract tasks.
8. Modules: WASM plugins (sandboxed, capability-based API) for commands, block renderers,
importers. Phase 3.
9. Performance: lazy loading, virtualized lists, incremental indexing, background workers.
10. Temporal journals and page anchoring (see brain-like model).
11. Automatic backup: periodic git snapshots of a Markdown export of the graph.
12. Rich text.
13. CalDAV calendars and task lists (VTODO), shown in journals, two-way sync.
14. Graph views: force graph, **timeline** (journals on a line, pages hanging from their
journals), local neighborhood, heat map of activity.
15. Extras: queries (Datalog-lite filters), templates, flashcards (SRS), quick capture
(Android share target, global hotkey on desktop), web clipper via share, encryption at
rest for the server, PDF/image annotation as blocks (later).
## Phases
- **Phase 0 – Foundation** (this branch): workspace, `synapse-core` (model, SQLite store,
link parser, temporal links, synapses, blob store, op log), docs.
- **Phase 1 – Parallel build** (one session per piece, each in its own worktree/branch):
1. `synapse-import` – Logseq importer.
2. `synapse-search` – tantivy full-text, vector index, hybrid search, auto-link suggestions.
3. `synapse-ai` – providers, chat + embeddings, `Embedder` impls, RAG helpers.
4. `synapse-history` – automatic git snapshots of a Markdown export, restore.
5. `synapse-caldav` – CalDAV events and VTODO tasks client + mapping to blocks.
6. `synapse-sync` + `synapse-server` – op-log sync protocol, axum server, auth.
7. `synapse-ffi` + `app/` – Flutter app: outliner editor, journals, search, timeline view.
- **Phase 2 – Integration**: wire search/AI/history/caldav/sync into FFI and the app;
spreading-activation "related" panel; graph and timeline views polished; Android build.
- **Phase 3 – Modules & extras**: WASM plugin host, flashcards, queries, templates,
consolidation, encryption.
## Dependencies (core)
- `rusqlite` (bundled SQLite: portable to Android/Windows, no system lib).
- `uuid` v7 (time-ordered ids, good index locality), `chrono` (dates/journals).
- `serde`/`serde_json` (properties, op payloads), `thiserror` (errors),
`blake3` (fast content hashing for the blob store).