From fbcfcf678ff6dc11632ebb85f24ac25ce769cd1e Mon Sep 17 00:00:00 2001 From: Dasemu Date: Wed, 21 Oct 2026 03:24:22 +0200 Subject: [PATCH] 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 --- .claude/hooks/format.sh | 2 +- Cargo.lock | 631 ++++++++++++++ Cargo.toml | 18 + crates/synapse-core/Cargo.toml | 18 + crates/synapse-core/src/blob.rs | 85 ++ crates/synapse-core/src/embed.rs | 11 + crates/synapse-core/src/error.rs | 19 + crates/synapse-core/src/hlc.rs | 69 ++ crates/synapse-core/src/lib.rs | 20 + crates/synapse-core/src/model.rs | 172 ++++ crates/synapse-core/src/parse.rs | 244 ++++++ crates/synapse-core/src/position.rs | 65 ++ crates/synapse-core/src/schema.rs | 92 +++ crates/synapse-core/src/store.rs | 1192 +++++++++++++++++++++++++++ crates/synapse-core/src/synapse.rs | 144 ++++ crates/synapse-core/tests/graph.rs | 188 +++++ docs/architecture.md | 47 ++ docs/plan.md | 78 ++ 18 files changed, 3094 insertions(+), 1 deletion(-) create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 crates/synapse-core/Cargo.toml create mode 100644 crates/synapse-core/src/blob.rs create mode 100644 crates/synapse-core/src/embed.rs create mode 100644 crates/synapse-core/src/error.rs create mode 100644 crates/synapse-core/src/hlc.rs create mode 100644 crates/synapse-core/src/lib.rs create mode 100644 crates/synapse-core/src/model.rs create mode 100644 crates/synapse-core/src/parse.rs create mode 100644 crates/synapse-core/src/position.rs create mode 100644 crates/synapse-core/src/schema.rs create mode 100644 crates/synapse-core/src/store.rs create mode 100644 crates/synapse-core/src/synapse.rs create mode 100644 crates/synapse-core/tests/graph.rs create mode 100644 docs/architecture.md create mode 100644 docs/plan.md diff --git a/.claude/hooks/format.sh b/.claude/hooks/format.sh index 4618fe9..18bbfdd 100755 --- a/.claude/hooks/format.sh +++ b/.claude/hooks/format.sh @@ -3,7 +3,7 @@ f=$(jq -r '.tool_input.file_path // empty' 2>/dev/null) [ -n "$f" ] && [ -f "$f" ] || exit 0 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 ;; esac exit 0 diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..4da5ab4 --- /dev/null +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..3cfcde3 --- /dev/null +++ b/Cargo.toml @@ -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"] } diff --git a/crates/synapse-core/Cargo.toml b/crates/synapse-core/Cargo.toml new file mode 100644 index 0000000..4eb4ab4 --- /dev/null +++ b/crates/synapse-core/Cargo.toml @@ -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" diff --git a/crates/synapse-core/src/blob.rs b/crates/synapse-core/src/blob.rs new file mode 100644 index 0000000..6fea2b2 --- /dev/null +++ b/crates/synapse-core/src/blob.rs @@ -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>/`. + +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) -> Result { + 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 { + 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"); + } +} diff --git a/crates/synapse-core/src/embed.rs b/crates/synapse-core/src/embed.rs new file mode 100644 index 0000000..88bb134 --- /dev/null +++ b/crates/synapse-core/src/embed.rs @@ -0,0 +1,11 @@ +//! Embedding abstraction shared by `synapse-search` (consumer) and `synapse-ai` (providers). + +pub type EmbedError = Box; + +/// 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>, EmbedError>; +} diff --git a/crates/synapse-core/src/error.rs b/crates/synapse-core/src/error.rs new file mode 100644 index 0000000..df6bca1 --- /dev/null +++ b/crates/synapse-core/src/error.rs @@ -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 = std::result::Result; diff --git a/crates/synapse-core/src/hlc.rs b/crates/synapse-core/src/hlc.rs new file mode 100644 index 0000000..11d423e --- /dev/null +++ b/crates/synapse-core/src/hlc.rs @@ -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) -> 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")); + } +} diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs new file mode 100644 index 0000000..f4b3383 --- /dev/null +++ b/crates/synapse-core/src/lib.rs @@ -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; diff --git a/crates/synapse-core/src/model.rs b/crates/synapse-core/src/model.rs new file mode 100644 index 0000000..d5792b1 --- /dev/null +++ b/crates/synapse-core/src/model.rs @@ -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; + +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, + /// Journal day in which this page was born (episodic anchor). + pub origin_journal: Option, + 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, + /// 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 { + 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, + pub original_name: Option, + 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, + /// Pages born on this day. + pub created: Vec, + /// 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, + pub next: Option, +} + +/// 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 }, +} + +/// 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, + pub properties: Properties, + /// Override timestamps (importer). Millis since epoch. + pub created_at: Option, + pub updated_at: Option, +} + +impl NewPage { + pub fn titled(title: impl Into) -> 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), + /// 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() +} diff --git a/crates/synapse-core/src/parse.rs b/crates/synapse-core/src/parse.rs new file mode 100644 index 0000000..01fd94f --- /dev/null +++ b/crates/synapse-core/src/parse.rs @@ -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, + /// `{{embed ((uuid))}}` block embeds. + pub embeds: Vec, +} + +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 { + 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" + ); + } +} diff --git a/crates/synapse-core/src/position.rs b/crates/synapse-core/src/position.rs new file mode 100644 index 0000000..4da1aa5 --- /dev/null +++ b/crates/synapse-core/src/position.rs @@ -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'))); + } +} diff --git a/crates/synapse-core/src/schema.rs b/crates/synapse-core/src/schema.rs new file mode 100644 index 0000000..d8f56a7 --- /dev/null +++ b/crates/synapse-core/src/schema.rs @@ -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 +); +"#; diff --git a/crates/synapse-core/src/store.rs b/crates/synapse-core/src/store.rs new file mode 100644 index 0000000..ab9e133 --- /dev/null +++ b/crates/synapse-core/src/store.rs @@ -0,0 +1,1192 @@ +//! The graph store: pages, blocks, refs, journals, assets and the op log on SQLite. + +use crate::blob::BlobStore; +use crate::hlc::HlcClock; +use crate::model::*; +use crate::parse::{self, extract_refs}; +use crate::position::between; +use crate::{Error, Result, schema, synapse}; +use chrono::{Local, NaiveDate, TimeZone}; +use rusqlite::{Connection, OptionalExtension, Row, params}; +use std::cell::Cell; +use std::collections::HashMap; +use std::io::Read; +use std::path::{Path, PathBuf}; +use uuid::Uuid; + +/// Namespace for deterministic journal ids (same day ⇒ same id on every device). +const JOURNAL_NS: Uuid = Uuid::from_u128(0x5f1e_7a2c_93b4_4d61_a0c8_6e2f_1b3d_9c47); + +pub fn journal_id(date: NaiveDate) -> PageId { + Uuid::new_v5(&JOURNAL_NS, journal_title(date).as_bytes()) +} + +const PAGE_COLS: &str = + "id, title, journal_date, origin_journal, properties, created_at, updated_at"; +const BLOCK_COLS: &str = + "id, page_id, parent_id, position, content, properties, collapsed, created_at, updated_at"; + +pub struct Graph { + conn: Connection, + blobs: BlobStore, + clock: HlcClock, + dir: PathBuf, + now_override: Cell>, +} + +impl Graph { + /// Opens (or creates) a graph stored in `dir` (`synapse.db` + `blobs/`). + pub fn open(dir: impl AsRef) -> Result { + let dir = dir.as_ref().to_path_buf(); + std::fs::create_dir_all(&dir)?; + let conn = Connection::open(dir.join("synapse.db"))?; + conn.pragma_update(None, "journal_mode", "WAL")?; + conn.pragma_update(None, "synchronous", "NORMAL")?; + conn.pragma_update(None, "foreign_keys", "OFF")?; + conn.execute_batch(schema::SCHEMA)?; + let actor: String = match conn + .query_row("SELECT value FROM meta WHERE key='actor'", [], |r| r.get(0)) + .optional()? + { + Some(a) => a, + None => { + let a = new_id().simple().to_string()[..12].to_string(); + conn.execute("INSERT INTO meta(key, value) VALUES ('actor', ?1)", [&a])?; + conn.execute( + "INSERT OR REPLACE INTO meta(key, value) VALUES ('schema', ?1)", + [schema::VERSION.to_string()], + )?; + a + } + }; + let clock = HlcClock::new(actor); + if let Some(last) = conn + .query_row("SELECT hlc FROM ops ORDER BY seq DESC LIMIT 1", [], |r| { + r.get::<_, String>(0) + }) + .optional()? + { + clock.observe(&last); + } + let blobs = BlobStore::open(dir.join("blobs"))?; + Ok(Self { + conn, + blobs, + clock, + dir, + now_override: Cell::new(None), + }) + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + pub fn blobs(&self) -> &BlobStore { + &self.blobs + } + + /// Device/actor id used in HLC timestamps. + pub fn actor(&self) -> &str { + self.clock.actor() + } + + /// Raw connection for sibling crates that keep their own tables (read-mostly). + pub fn conn(&self) -> &Connection { + &self.conn + } + + /// Fixes "now" (millis since epoch). Used by tests and importers. + pub fn set_now(&self, ms: Option) { + self.now_override.set(ms); + } + + pub fn now_ms(&self) -> i64 { + self.now_override + .get() + .unwrap_or_else(|| Local::now().timestamp_millis()) + } + + pub fn today(&self) -> NaiveDate { + day_of(self.now_ms()) + } + + // ---------------------------------------------------------------- pages + + pub fn get_page(&self, id: PageId) -> Result> { + Ok(self + .conn + .query_row( + &format!("SELECT {PAGE_COLS} FROM pages WHERE id=?1"), + [id.to_string()], + page_row, + ) + .optional()?) + } + + /// Looks a page up by title or alias (case-insensitive). + pub fn page_by_title(&self, title: &str) -> Result> { + let key = title_key(title); + let page = self + .conn + .query_row( + &format!("SELECT {PAGE_COLS} FROM pages WHERE title_key=?1"), + [&key], + page_row, + ) + .optional()?; + if page.is_some() { + return Ok(page); + } + let id: Option = self + .conn + .query_row( + "SELECT page_id FROM aliases WHERE alias_key=?1", + [&key], + |r| r.get(0), + ) + .optional()?; + match id { + Some(id) => self.get_page(parse_id(&id)?), + None => Ok(None), + } + } + + /// Creates a page. Its origin defaults to today's journal (pages are born in journals). + pub fn create_page(&self, new: NewPage) -> Result { + let tx = self.conn.unchecked_transaction()?; + let page = self.create_page_tx(new)?; + tx.commit()?; + Ok(page) + } + + fn create_page_tx(&self, new: NewPage) -> Result { + let title = new.title.trim().to_string(); + if title.is_empty() { + return Err(Error::Invalid("empty page title".into())); + } + if self.page_by_title(&title)?.is_some() { + return Err(Error::Conflict(format!("page {title:?} already exists"))); + } + let now = self.now_ms(); + let origin = new.origin_journal.unwrap_or_else(|| self.today()); + self.ensure_journal_tx(origin)?; + let page = Page { + id: new_id(), + title, + journal_date: None, + origin_journal: Some(origin), + properties: new.properties, + created_at: new.created_at.unwrap_or(now), + updated_at: new.updated_at.unwrap_or(now), + }; + self.write_page(&page, &self.tick())?; + Ok(page) + } + + /// Returns the page with this title, creating it (born in `origin`) if missing. + pub fn ensure_page(&self, title: &str, origin: Option) -> Result { + if let Some(p) = self.page_by_title(title)? { + return Ok(p); + } + self.create_page(NewPage { + title: title.into(), + origin_journal: origin, + ..Default::default() + }) + } + + /// Pages ordered by last update (most recent first). + pub fn list_pages(&self, include_journals: bool, limit: u32, offset: u32) -> Result> { + let filter = if include_journals { + "" + } else { + "WHERE journal_date IS NULL" + }; + let mut st = self.conn.prepare_cached(&format!( + "SELECT {PAGE_COLS} FROM pages {filter} ORDER BY updated_at DESC LIMIT ?1 OFFSET ?2" + ))?; + let rows = st.query_map(params![limit, offset], page_row)?; + Ok(rows.collect::>()?) + } + + /// All page titles and aliases with their page id (for auto-link matching). + pub fn all_titles(&self) -> Result> { + let mut st = self + .conn + .prepare("SELECT title, id FROM pages UNION ALL SELECT alias, page_id FROM aliases")?; + let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; + rows.map(|r| { + let (t, id) = r?; + Ok((t, parse_id(&id)?)) + }) + .collect() + } + + pub fn set_page_properties(&self, id: PageId, properties: Properties) -> Result { + let mut page = self + .get_page(id)? + .ok_or_else(|| Error::NotFound(id.to_string()))?; + page.properties = properties; + page.updated_at = self.now_ms(); + self.write_page(&page, &self.tick())?; + Ok(page) + } + + /// Renames a page and rewrites `[[Old]]` / `#Old` in every referencing block. + pub fn rename_page(&self, id: PageId, new_title: &str) -> Result { + let tx = self.conn.unchecked_transaction()?; + let mut page = self + .get_page(id)? + .ok_or_else(|| Error::NotFound(id.to_string()))?; + if page.is_journal() { + return Err(Error::Invalid("journal pages cannot be renamed".into())); + } + let new_title = new_title.trim(); + if let Some(other) = self.page_by_title(new_title)? + && other.id != id + { + return Err(Error::Conflict(format!( + "page {new_title:?} already exists" + ))); + } + let old_key = title_key(&page.title); + let referencing: Vec = { + let mut st = self + .conn + .prepare("SELECT DISTINCT block_id FROM refs WHERE target_key=?1")?; + st.query_map([&old_key], |r| r.get(0))? + .collect::>()? + }; + page.title = new_title.to_string(); + page.updated_at = self.now_ms(); + self.write_page(&page, &self.tick())?; + for bid in referencing { + if let Some(mut b) = self.get_block(parse_id(&bid)?)? { + let rewritten = parse::rewrite_refs(&b.content, &old_key, new_title); + if rewritten != b.content { + b.content = rewritten; + b.updated_at = self.now_ms(); + self.write_block(&b, &self.tick())?; + } + } + } + tx.commit()?; + Ok(page) + } + + /// Deletes a page and all its blocks. + pub fn delete_page(&self, id: PageId) -> Result<()> { + let tx = self.conn.unchecked_transaction()?; + let ids: Vec = { + let mut st = self + .conn + .prepare("SELECT id FROM blocks WHERE page_id=?1")?; + st.query_map([id.to_string()], |r| r.get(0))? + .collect::>()? + }; + for b in ids { + self.remove_block_row(parse_id(&b)?, &self.tick())?; + } + self.remove_page_row(id, &self.tick())?; + tx.commit()?; + Ok(()) + } + + /// Points `alias` at `page` (or removes it with `None`). + pub fn set_alias(&self, alias: &str, page: Option) -> Result<()> { + let hlc = self.tick(); + self.write_alias(alias, page)?; + self.log( + &hlc, + &Op::SetAlias { + alias: alias.to_string(), + page, + }, + ) + } + + pub fn aliases_of(&self, page: PageId) -> Result> { + let mut st = self + .conn + .prepare("SELECT alias FROM aliases WHERE page_id=?1 ORDER BY alias")?; + let rows = st.query_map([page.to_string()], |r| r.get(0))?; + Ok(rows.collect::>()?) + } + + // ------------------------------------------------------------- journals + + /// The journal page for `date`, created if missing. + pub fn journal(&self, date: NaiveDate) -> Result { + let tx = self.conn.unchecked_transaction()?; + let p = self.ensure_journal_tx(date)?; + tx.commit()?; + Ok(p) + } + + pub fn today_journal(&self) -> Result { + self.journal(self.today()) + } + + fn ensure_journal_tx(&self, date: NaiveDate) -> Result { + if let Some(p) = self.get_page(journal_id(date))? { + return Ok(p); + } + let ms = Local + .from_local_datetime(&date.and_hms_opt(0, 0, 0).unwrap()) + .earliest() + .map(|d| d.timestamp_millis()) + .unwrap_or_else(|| self.now_ms()); + let page = Page { + id: journal_id(date), + title: journal_title(date), + journal_date: Some(date), + origin_journal: None, + properties: Properties::new(), + created_at: ms, + updated_at: ms, + }; + self.write_page(&page, &self.tick())?; + Ok(page) + } + + /// Previous and next existing journals around `date` (the episodic chain). + pub fn journal_neighbors(&self, date: NaiveDate) -> Result { + let d = journal_title(date); + let prev: Option = self.conn.query_row( + "SELECT max(journal_date) FROM pages WHERE journal_date < ?1", + [&d], + |r| r.get(0), + )?; + let next: Option = self.conn.query_row( + "SELECT min(journal_date) FROM pages WHERE journal_date > ?1", + [&d], + |r| r.get(0), + )?; + Ok(JournalNeighbors { + prev: prev.and_then(|s| parse_day(&s)), + next: next.and_then(|s| parse_day(&s)), + }) + } + + /// Journals in `[from, to]`, newest first. + pub fn journals_between(&self, from: NaiveDate, to: NaiveDate) -> Result> { + let mut st = self.conn.prepare_cached(&format!( + "SELECT {PAGE_COLS} FROM pages WHERE journal_date BETWEEN ?1 AND ?2 ORDER BY journal_date DESC" + ))?; + let rows = st.query_map(params![journal_title(from), journal_title(to)], page_row)?; + Ok(rows.collect::>()?) + } + + /// Timeline view data for `[from, to]`, oldest first. + pub fn timeline(&self, from: NaiveDate, to: NaiveDate) -> Result> { + let (f, t) = (journal_title(from), journal_title(to)); + let mut days: std::collections::BTreeMap = Default::default(); + let mut st = self + .conn + .prepare("SELECT journal_date, id FROM pages WHERE journal_date BETWEEN ?1 AND ?2")?; + for r in st.query_map(params![f, t], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)) + })? { + let (d, id) = r?; + entry(&mut days, &d)?.journal = Some(parse_id(&id)?); + } + let mut st = self.conn.prepare( + "SELECT origin_journal, id FROM pages WHERE origin_journal BETWEEN ?1 AND ?2 ORDER BY created_at", + )?; + for r in st.query_map(params![f, t], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)) + })? { + let (d, id) = r?; + entry(&mut days, &d)?.created.push(parse_id(&id)?); + } + let mut st = self.conn.prepare( + "SELECT a.day, a.page_id, a.edits FROM page_activity a JOIN pages p ON p.id = a.page_id + WHERE a.day BETWEEN ?1 AND ?2 AND p.journal_date IS NULL ORDER BY a.edits DESC", + )?; + for r in st.query_map(params![f, t], |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, String>(1)?, + r.get::<_, u32>(2)?, + )) + })? { + let (d, id, n) = r?; + entry(&mut days, &d)?.edited.push((parse_id(&id)?, n)); + } + Ok(days.into_values().collect()) + } + + /// Days on which `page` was edited, with edit counts (oldest first). + pub fn edit_days(&self, page: PageId) -> Result> { + let mut st = self + .conn + .prepare_cached("SELECT day, edits FROM page_activity WHERE page_id=?1 ORDER BY day")?; + let rows = st.query_map([page.to_string()], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, u32>(1)?)) + })?; + rows.map(|r| { + let (d, n) = r?; + Ok((parse_day(&d).ok_or_else(|| Error::Invalid(d))?, n)) + }) + .collect() + } + + // --------------------------------------------------------------- blocks + + pub fn get_block(&self, id: BlockId) -> Result> { + Ok(self + .conn + .query_row( + &format!("SELECT {BLOCK_COLS} FROM blocks WHERE id=?1"), + [id.to_string()], + block_row, + ) + .optional()?) + } + + /// Blocks of a page in outline (pre-order) order, with their depth. + pub fn page_tree(&self, page: PageId) -> Result> { + let mut st = self.conn.prepare_cached(&format!( + "SELECT {BLOCK_COLS} FROM blocks WHERE page_id=?1 ORDER BY position" + ))?; + let all: Vec = st + .query_map([page.to_string()], block_row)? + .collect::>()?; + let mut children: HashMap, Vec> = HashMap::new(); + for b in all { + children.entry(b.parent_id).or_default().push(b); + } + let mut out = Vec::new(); + let mut stack: Vec<(usize, Block)> = children + .remove(&None) + .unwrap_or_default() + .into_iter() + .rev() + .map(|b| (0, b)) + .collect(); + while let Some((d, b)) = stack.pop() { + if let Some(kids) = children.remove(&Some(b.id)) { + stack.extend(kids.into_iter().rev().map(|k| (d + 1, k))); + } + out.push((d, b)); + } + Ok(out) + } + + /// Inserts a new block with `content` and indexes its refs. + pub fn insert_block(&self, page: PageId, at: Placement, content: &str) -> Result { + let tx = self.conn.unchecked_transaction()?; + let (parent_id, position) = self.resolve_placement(page, at)?; + let now = self.now_ms(); + let block = Block { + id: new_id(), + page_id: page, + parent_id, + position, + content: content.to_string(), + properties: Properties::new(), + collapsed: false, + created_at: now, + updated_at: now, + }; + self.local_block_write(&block)?; + tx.commit()?; + Ok(block) + } + + /// Writes a fully specified block (importer). Pages referenced by it are created, born in + /// the block's journal when it lives in one. Does not record edit activity. + pub fn put_block(&self, block: &Block) -> Result<()> { + let tx = self.conn.unchecked_transaction()?; + self.write_block(block, &self.tick())?; + self.ensure_ref_pages(block)?; + tx.commit()?; + Ok(()) + } + + pub fn update_block(&self, id: BlockId, content: &str) -> Result { + let tx = self.conn.unchecked_transaction()?; + let mut b = self + .get_block(id)? + .ok_or_else(|| Error::NotFound(id.to_string()))?; + if b.content != content { + b.content = content.to_string(); + b.updated_at = self.now_ms(); + self.local_block_write(&b)?; + } + tx.commit()?; + Ok(b) + } + + pub fn set_block_properties(&self, id: BlockId, properties: Properties) -> Result { + let tx = self.conn.unchecked_transaction()?; + let mut b = self + .get_block(id)? + .ok_or_else(|| Error::NotFound(id.to_string()))?; + b.properties = properties; + b.updated_at = self.now_ms(); + self.local_block_write(&b)?; + tx.commit()?; + Ok(b) + } + + pub fn set_collapsed(&self, id: BlockId, collapsed: bool) -> Result<()> { + let mut b = self + .get_block(id)? + .ok_or_else(|| Error::NotFound(id.to_string()))?; + b.collapsed = collapsed; + self.write_block(&b, &self.tick()) + } + + /// Moves a block (with its subtree) to a new place, possibly on another page. + pub fn move_block(&self, id: BlockId, page: PageId, at: Placement) -> Result { + let tx = self.conn.unchecked_transaction()?; + let mut b = self + .get_block(id)? + .ok_or_else(|| Error::NotFound(id.to_string()))?; + let (parent_id, position) = self.resolve_placement(page, at)?; + let mut p = parent_id; + while let Some(pid) = p { + if pid == id { + return Err(Error::Invalid( + "cannot move a block into its own subtree".into(), + )); + } + p = self.get_block(pid)?.and_then(|x| x.parent_id); + } + let old_page = b.page_id; + b.parent_id = parent_id; + b.position = position; + b.page_id = page; + b.updated_at = self.now_ms(); + self.local_block_write(&b)?; + if old_page != page { + for d in self.descendants(id)? { + let mut c = self.get_block(d)?.unwrap(); + c.page_id = page; + self.write_block(&c, &self.tick())?; + } + self.touch_page(old_page)?; + } + tx.commit()?; + Ok(b) + } + + /// Deletes a block and its subtree. + pub fn delete_block(&self, id: BlockId) -> Result<()> { + let tx = self.conn.unchecked_transaction()?; + let b = self + .get_block(id)? + .ok_or_else(|| Error::NotFound(id.to_string()))?; + let mut ids = self.descendants(id)?; + ids.push(id); + for d in ids { + self.remove_block_row(d, &self.tick())?; + } + self.touch_page(b.page_id)?; + tx.commit()?; + Ok(()) + } + + fn descendants(&self, id: BlockId) -> Result> { + let mut st = self.conn.prepare_cached( + "WITH RECURSIVE d(id) AS (SELECT id FROM blocks WHERE parent_id=?1 + UNION ALL SELECT b.id FROM blocks b JOIN d ON b.parent_id = d.id) + SELECT id FROM d", + )?; + let rows = st.query_map([id.to_string()], |r| r.get::<_, String>(0))?; + rows.map(|r| parse_id(&r?)).collect() + } + + /// Blocks referencing `page` (by title or alias), newest first. + pub fn backlinks(&self, page: PageId) -> Result> { + let mut st = self.conn.prepare_cached(&format!( + "SELECT {}, p.title, r.kind FROM refs r + JOIN blocks b ON b.id = r.block_id JOIN pages p ON p.id = b.page_id + WHERE r.target_key IN (SELECT title_key FROM pages WHERE id=?1 + UNION SELECT alias_key FROM aliases WHERE page_id=?1) + AND b.page_id != ?1 + ORDER BY b.updated_at DESC", + BLOCK_COLS + .split(", ") + .map(|c| format!("b.{c}")) + .collect::>() + .join(", ") + ))?; + let rows = st.query_map([page.to_string()], |r| { + Ok(Backlink { + block: block_row(r)?, + page_title: r.get(9)?, + kind: RefKind::parse(&r.get::<_, String>(10)?).unwrap_or(RefKind::Link), + }) + })?; + Ok(rows.collect::>()?) + } + + /// Blocks that reference or embed block `id`. + pub fn block_backrefs(&self, id: BlockId) -> Result> { + let mut st = self.conn.prepare_cached(&format!( + "SELECT {} FROM block_refs r JOIN blocks b ON b.id = r.block_id WHERE r.target_block=?1", + BLOCK_COLS.split(", ").map(|c| format!("b.{c}")).collect::>().join(", ") + ))?; + let rows = st.query_map([id.to_string()], block_row)?; + Ok(rows.collect::>()?) + } + + /// Pages that blocks of `page` link to. + pub fn outgoing_pages(&self, page: PageId) -> Result> { + let mut st = self.conn.prepare_cached( + "SELECT DISTINCT p.id FROM refs r JOIN blocks b ON b.id = r.block_id + JOIN pages p ON p.title_key = r.target_key WHERE b.page_id=?1", + )?; + let rows = st.query_map([page.to_string()], |r| r.get::<_, String>(0))?; + rows.map(|r| parse_id(&r?)).collect() + } + + fn resolve_placement(&self, page: PageId, at: Placement) -> Result<(Option, String)> { + let sib = |id: BlockId| -> Result { + let b = self + .get_block(id)? + .ok_or_else(|| Error::NotFound(id.to_string()))?; + if b.page_id != page { + return Err(Error::Invalid("sibling is on another page".into())); + } + Ok(b) + }; + let parent_sql = "page_id=?1 AND parent_id IS ?2"; + Ok(match at { + Placement::LastChildOf(parent) => { + let max: Option = self.conn.query_row( + &format!("SELECT max(position) FROM blocks WHERE {parent_sql}"), + params![page.to_string(), parent.map(|p| p.to_string())], + |r| r.get(0), + )?; + (parent, between(max.as_deref(), None)) + } + Placement::After(s) => { + let s = sib(s)?; + let next: Option = self.conn.query_row( + &format!( + "SELECT min(position) FROM blocks WHERE {parent_sql} AND position > ?3" + ), + params![ + page.to_string(), + s.parent_id.map(|p| p.to_string()), + s.position + ], + |r| r.get(0), + )?; + (s.parent_id, between(Some(&s.position), next.as_deref())) + } + Placement::Before(s) => { + let s = sib(s)?; + let prev: Option = self.conn.query_row( + &format!( + "SELECT max(position) FROM blocks WHERE {parent_sql} AND position < ?3" + ), + params![ + page.to_string(), + s.parent_id.map(|p| p.to_string()), + s.position + ], + |r| r.get(0), + )?; + (s.parent_id, between(prev.as_deref(), Some(&s.position))) + } + }) + } + + /// A local edit: write, create referenced pages, record activity and fire synapses. + fn local_block_write(&self, block: &Block) -> Result<()> { + let before: Vec = self.ref_keys(block.id)?; + self.write_block(block, &self.tick())?; + self.ensure_ref_pages(block)?; + let after = self.ref_keys(block.id)?; + for key in after.iter().filter(|k| !before.contains(k)) { + if let Some(target) = self.page_by_title(key)? { + synapse::fire( + &self.conn, + block.page_id, + target.id, + synapse::LINK_STRENGTH, + self.now_ms(), + )?; + } + } + self.touch_page(block.page_id) + } + + fn ref_keys(&self, block: BlockId) -> Result> { + let mut st = self + .conn + .prepare_cached("SELECT target_key FROM refs WHERE block_id=?1")?; + let rows = st.query_map([block.to_string()], |r| r.get(0))?; + Ok(rows.collect::>()?) + } + + /// Creates pages referenced by `block` that do not exist yet. Returns how many. + fn ensure_ref_pages(&self, block: &Block) -> Result { + let origin = match self.get_page(block.page_id)? { + Some(p) if p.is_journal() => p.journal_date, + _ => Some(day_of(block.created_at)), + }; + let mut n = 0; + for (title, _) in extract_refs(&block.content).pages { + if self.page_by_title(&title)?.is_none() { + if let Some(date) = parse_day(&title) { + self.ensure_journal_tx(date)?; + } else { + self.create_page_tx(NewPage { + title, + origin_journal: origin, + created_at: Some(block.created_at), + updated_at: Some(block.created_at), + ..Default::default() + })?; + } + n += 1; + } + } + Ok(n) + } + + /// Bumps `updated_at` and records today's activity for a page. + fn touch_page(&self, page: PageId) -> Result<()> { + let now = self.now_ms(); + let day = journal_title(day_of(now)); + self.conn.execute( + "UPDATE pages SET updated_at=?2 WHERE id=?1", + params![page.to_string(), now], + )?; + let is_journal: bool = self + .conn + .query_row( + "SELECT journal_date IS NOT NULL FROM pages WHERE id=?1", + [page.to_string()], + |r| r.get(0), + ) + .optional()? + .unwrap_or(true); + if !is_journal { + self.ensure_journal_tx(day_of(now))?; + self.conn.execute( + "INSERT INTO page_activity(page_id, day, edits) VALUES (?1, ?2, 1) + ON CONFLICT(page_id, day) DO UPDATE SET edits = edits + 1", + params![page.to_string(), day], + )?; + } + Ok(()) + } + + // --------------------------------------------------------------- assets + + /// Streams a file into the blob store and registers it. + pub fn put_asset_file(&self, path: &Path, mime: Option<&str>) -> Result { + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()); + self.put_asset_reader(std::fs::File::open(path)?, name.as_deref(), mime) + } + + pub fn put_asset_reader( + &self, + reader: impl Read, + name: Option<&str>, + mime: Option<&str>, + ) -> Result { + let (hash, size) = self.blobs.put_reader(reader)?; + if let Some(a) = self.asset(&hash)? { + return Ok(a); + } + let asset = Asset { + hash, + size, + mime: mime.map(str::to_string), + original_name: name.map(str::to_string), + created_at: self.now_ms(), + }; + let hlc = self.tick(); + self.write_asset(&asset)?; + self.log( + &hlc, + &Op::PutAsset { + asset: asset.clone(), + }, + )?; + Ok(asset) + } + + pub fn asset(&self, hash: &str) -> Result> { + Ok(self + .conn + .query_row( + "SELECT hash, size, mime, original_name, created_at FROM assets WHERE hash=?1", + [hash], + |r| { + Ok(Asset { + hash: r.get(0)?, + size: r.get::<_, i64>(1)? as u64, + mime: r.get(2)?, + original_name: r.get(3)?, + created_at: r.get(4)?, + }) + }, + ) + .optional()?) + } + + // ------------------------------------------------------- synapses/brain + + /// Records navigation `from` → `to`; co-visits strengthen the pair (Hebbian). + pub fn record_visit(&self, from: Option, to: PageId) -> Result<()> { + if let Some(f) = from + && f != to + { + synapse::fire(&self.conn, f, to, synapse::VISIT_STRENGTH, self.now_ms())?; + } + Ok(()) + } + + /// Notes related to `page` by spreading activation over refs, synapses and time. + pub fn related(&self, page: PageId, limit: usize) -> Result> { + synapse::spread(self, page, limit) + } + + /// Current (decayed) synapse weight between two pages. + pub fn synapse_weight(&self, a: PageId, b: PageId) -> Result { + synapse::weight(&self.conn, a, b, self.now_ms()) + } + + // ------------------------------------------------------------------ ops + + /// Op log entries with `seq > after`, oldest first. + pub fn ops_since(&self, after: i64, limit: u32) -> Result> { + let mut st = self.conn.prepare_cached( + "SELECT seq, hlc, payload FROM ops WHERE seq > ?1 ORDER BY seq LIMIT ?2", + )?; + let rows = st.query_map(params![after, limit], |r| { + Ok(( + r.get::<_, i64>(0)?, + r.get::<_, String>(1)?, + r.get::<_, String>(2)?, + )) + })?; + rows.map(|r| { + let (seq, hlc, payload) = r?; + Ok(OpRecord { + seq, + hlc, + op: serde_json::from_str(&payload)?, + }) + }) + .collect() + } + + pub fn last_seq(&self) -> Result { + Ok(self + .conn + .query_row("SELECT coalesce(max(seq), 0) FROM ops", [], |r| r.get(0))?) + } + + /// Applies an op from another replica with last-writer-wins per entity. + /// Returns whether it changed local state. Applied ops are re-logged locally. + pub fn apply_remote(&self, hlc: &str, op: &Op) -> Result { + self.clock.observe(hlc); + let tx = self.conn.unchecked_transaction()?; + let newer = |table: &str, id: &str| -> Result { + let local: Option = self + .conn + .query_row(&format!("SELECT hlc FROM {table} WHERE id=?1"), [id], |r| { + r.get(0) + }) + .optional()?; + let tomb: Option = self + .conn + .query_row("SELECT hlc FROM tombstones WHERE id=?1", [id], |r| r.get(0)) + .optional()?; + Ok(local.is_none_or(|l| hlc > l.as_str()) && tomb.is_none_or(|t| hlc > t.as_str())) + }; + let applied = match op { + Op::UpsertPage { page } => { + if !newer("pages", &page.id.to_string())? { + false + } else { + let mut page = page.clone(); + // Two replicas created the same title offline: the smaller id keeps it. + if let Some(other) = self.page_by_title(&page.title)? { + if other.id != page.id && other.id < page.id { + page.title = + format!("{} ~{}", page.title, &page.id.simple().to_string()[..6]); + } else if other.id != page.id { + let mut o = other.clone(); + o.title = format!("{} ~{}", o.title, &o.id.simple().to_string()[..6]); + self.write_page(&o, &self.tick())?; + } + } + self.write_page_row(&page, hlc)?; + true + } + } + Op::DeletePage { id } => { + newer("pages", &id.to_string())? && { + self.remove_page_row_raw(*id, hlc)?; + true + } + } + Op::UpsertBlock { block } => { + newer("blocks", &block.id.to_string())? && { + self.write_block_row(block, hlc)?; + true + } + } + Op::DeleteBlock { id } => { + newer("blocks", &id.to_string())? && { + self.remove_block_row_raw(*id, hlc)?; + true + } + } + Op::PutAsset { asset } => { + self.asset(&asset.hash)?.is_none() && { + self.write_asset(asset)?; + true + } + } + Op::SetAlias { alias, page } => { + self.write_alias(alias, *page)?; + true + } + }; + if applied { + self.log(hlc, op)?; + } + tx.commit()?; + Ok(applied) + } + + // ----------------------------------------------------------- raw writes + + fn tick(&self) -> String { + self.clock.tick(self.now_ms()) + } + + fn log(&self, hlc: &str, op: &Op) -> Result<()> { + self.conn.execute( + "INSERT INTO ops(hlc, payload) VALUES (?1, ?2)", + params![hlc, serde_json::to_string(op)?], + )?; + Ok(()) + } + + fn write_page(&self, page: &Page, hlc: &str) -> Result<()> { + self.write_page_row(page, hlc)?; + self.log(hlc, &Op::UpsertPage { page: page.clone() }) + } + + fn write_page_row(&self, p: &Page, hlc: &str) -> Result<()> { + self.conn.execute( + "INSERT INTO pages(id, title, title_key, journal_date, origin_journal, properties, created_at, updated_at, hlc) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) + ON CONFLICT(id) DO UPDATE SET title=?2, title_key=?3, journal_date=?4, origin_journal=?5, + properties=?6, created_at=?7, updated_at=?8, hlc=?9", + params![ + p.id.to_string(), + p.title, + title_key(&p.title), + p.journal_date.map(journal_title), + p.origin_journal.map(journal_title), + serde_json::to_string(&p.properties)?, + p.created_at, + p.updated_at, + hlc + ], + )?; + Ok(()) + } + + fn remove_page_row(&self, id: PageId, hlc: &str) -> Result<()> { + self.remove_page_row_raw(id, hlc)?; + self.log(hlc, &Op::DeletePage { id }) + } + + fn remove_page_row_raw(&self, id: PageId, hlc: &str) -> Result<()> { + let s = id.to_string(); + self.conn.execute("DELETE FROM pages WHERE id=?1", [&s])?; + self.conn + .execute("DELETE FROM aliases WHERE page_id=?1", [&s])?; + self.conn + .execute("DELETE FROM page_activity WHERE page_id=?1", [&s])?; + self.conn + .execute("DELETE FROM synapses WHERE a=?1 OR b=?1", [&s])?; + self.conn.execute( + "INSERT OR REPLACE INTO tombstones(id, hlc) VALUES (?1, ?2)", + params![s, hlc], + )?; + Ok(()) + } + + fn write_block(&self, block: &Block, hlc: &str) -> Result<()> { + self.write_block_row(block, hlc)?; + self.log( + hlc, + &Op::UpsertBlock { + block: block.clone(), + }, + ) + } + + fn write_block_row(&self, b: &Block, hlc: &str) -> Result<()> { + let id = b.id.to_string(); + self.conn.execute( + "INSERT INTO blocks(id, page_id, parent_id, position, content, properties, collapsed, created_at, updated_at, hlc) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) + ON CONFLICT(id) DO UPDATE SET page_id=?2, parent_id=?3, position=?4, content=?5, + properties=?6, collapsed=?7, created_at=?8, updated_at=?9, hlc=?10", + params![ + id, + b.page_id.to_string(), + b.parent_id.map(|p| p.to_string()), + b.position, + b.content, + serde_json::to_string(&b.properties)?, + b.collapsed, + b.created_at, + b.updated_at, + hlc + ], + )?; + self.conn + .execute("DELETE FROM refs WHERE block_id=?1", [&id])?; + self.conn + .execute("DELETE FROM block_refs WHERE block_id=?1", [&id])?; + let refs = extract_refs(&b.content); + for (title, kind) in &refs.pages { + self.conn.execute( + "INSERT OR IGNORE INTO refs(block_id, target_key, kind) VALUES (?1, ?2, ?3)", + params![id, title_key(title), kind.as_str()], + )?; + } + for v in b.properties.values() { + for (title, _) in extract_refs( + &v.as_str() + .map(str::to_string) + .unwrap_or_else(|| v.to_string()), + ) + .pages + { + self.conn.execute( + "INSERT OR IGNORE INTO refs(block_id, target_key, kind) VALUES (?1, ?2, 'property')", + params![id, title_key(&title)], + )?; + } + } + for (list, embed) in [(&refs.blocks, false), (&refs.embeds, true)] { + for t in list { + self.conn.execute( + "INSERT OR IGNORE INTO block_refs(block_id, target_block, embed) VALUES (?1, ?2, ?3)", + params![id, t.to_string(), embed], + )?; + } + } + Ok(()) + } + + fn remove_block_row(&self, id: BlockId, hlc: &str) -> Result<()> { + self.remove_block_row_raw(id, hlc)?; + self.log(hlc, &Op::DeleteBlock { id }) + } + + fn remove_block_row_raw(&self, id: BlockId, hlc: &str) -> Result<()> { + let s = id.to_string(); + self.conn.execute("DELETE FROM blocks WHERE id=?1", [&s])?; + self.conn + .execute("DELETE FROM refs WHERE block_id=?1", [&s])?; + self.conn + .execute("DELETE FROM block_refs WHERE block_id=?1", [&s])?; + self.conn.execute( + "INSERT OR REPLACE INTO tombstones(id, hlc) VALUES (?1, ?2)", + params![s, hlc], + )?; + Ok(()) + } + + fn write_asset(&self, a: &Asset) -> Result<()> { + self.conn.execute( + "INSERT OR IGNORE INTO assets(hash, size, mime, original_name, created_at) VALUES (?1, ?2, ?3, ?4, ?5)", + params![a.hash, a.size as i64, a.mime, a.original_name, a.created_at], + )?; + Ok(()) + } + + fn write_alias(&self, alias: &str, page: Option) -> Result<()> { + match page { + Some(p) => self.conn.execute( + "INSERT OR REPLACE INTO aliases(alias_key, alias, page_id) VALUES (?1, ?2, ?3)", + params![title_key(alias), alias.trim(), p.to_string()], + )?, + None => self + .conn + .execute("DELETE FROM aliases WHERE alias_key=?1", [title_key(alias)])?, + }; + Ok(()) + } +} + +fn entry<'a>( + days: &'a mut std::collections::BTreeMap, + d: &str, +) -> Result<&'a mut TimelineDay> { + let date = parse_day(d).ok_or_else(|| Error::Invalid(d.into()))?; + Ok(days.entry(d.to_string()).or_insert_with(|| TimelineDay { + date, + journal: None, + created: vec![], + edited: vec![], + })) +} + +pub(crate) fn day_of(ms: i64) -> NaiveDate { + Local + .timestamp_millis_opt(ms) + .single() + .map(|d| d.date_naive()) + .unwrap_or_default() +} + +pub(crate) fn parse_day(s: &str) -> Option { + NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok() +} + +pub(crate) fn parse_id(s: &str) -> Result { + Uuid::parse_str(s).map_err(|e| Error::Invalid(format!("bad id {s}: {e}"))) +} + +fn props(s: String) -> Properties { + serde_json::from_str(&s).unwrap_or_default() +} + +fn page_row(r: &Row) -> rusqlite::Result { + let id: String = r.get(0)?; + Ok(Page { + id: Uuid::parse_str(&id).unwrap_or_default(), + title: r.get(1)?, + journal_date: r.get::<_, Option>(2)?.and_then(|s| parse_day(&s)), + origin_journal: r.get::<_, Option>(3)?.and_then(|s| parse_day(&s)), + properties: props(r.get(4)?), + created_at: r.get(5)?, + updated_at: r.get(6)?, + }) +} + +fn block_row(r: &Row) -> rusqlite::Result { + let id = |s: String| Uuid::parse_str(&s).unwrap_or_default(); + Ok(Block { + id: id(r.get(0)?), + page_id: id(r.get(1)?), + parent_id: r.get::<_, Option>(2)?.map(id), + position: r.get(3)?, + content: r.get(4)?, + properties: props(r.get(5)?), + collapsed: r.get(6)?, + created_at: r.get(7)?, + updated_at: r.get(8)?, + }) +} diff --git a/crates/synapse-core/src/synapse.rs b/crates/synapse-core/src/synapse.rs new file mode 100644 index 0000000..30f7f65 --- /dev/null +++ b/crates/synapse-core/src/synapse.rs @@ -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 { + 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> { + let conn = g.conn(); + let now = g.now_ms(); + let mut out: HashMap = 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> { + const DECAY: f32 = 0.5; + let mut activation: HashMap = HashMap::new(); + let mut frontier = vec![(seed, 1.0f32)]; + let mut cache: HashMap> = HashMap::new(); + for _ in 0..3 { + let mut next: HashMap = 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) +} diff --git a/crates/synapse-core/tests/graph.rs b/crates/synapse-core/tests/graph.rs new file mode 100644 index 0000000..c853c99 --- /dev/null +++ b/crates/synapse-core/tests/graph.rs @@ -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::>() + }; + 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)); +} diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..cfa3f82 --- /dev/null +++ b/docs/architecture.md @@ -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 +`/synapse.db` (SQLite, WAL) + `/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 `/` (e.g. `/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. diff --git a/docs/plan.md b/docs/plan.md new file mode 100644 index 0000000..f515c8f --- /dev/null +++ b/docs/plan.md @@ -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).