Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
M1-A: store schema + migrations + single-writer SQLite actor
AkitaOnRails2b9f3ba24156
diff --git a/Cargo.lock b/Cargo.lockindex 33adf7eb..308fdeda 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2,6 +2,18 @@# It is not intended for manual editing.version = 4+[[package]]+name = "ahash"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"+dependencies = [+ "cfg-if",+ "once_cell",+ "version_check",+ "zerocopy",+]+[[package]]name = "aho-corasick"version = "1.1.4"@@ -73,6 +85,19 @@ name = "ai-memory-store"version = "0.1.0"dependencies = ["ai-memory-core",+ "anyhow",+ "jiff",+ "parking_lot",+ "refinery",+ "rusqlite",+ "serde",+ "serde_json",+ "sha2",+ "tempfile",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "uuid",][[package]]@@ -138,6 +163,17 @@ version = "1.0.102"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"+[[package]]+name = "async-trait"+version = "0.1.89"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "atomic"version = "0.6.1"@@ -153,6 +189,15 @@ version = "2.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"+[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]+[[package]]name = "bumpalo"version = "3.20.2"@@ -171,6 +216,16 @@ version = "1.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"+[[package]]+name = "cc"+version = "1.2.62"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98"+dependencies = [+ "find-msvc-tools",+ "shlex",+]+[[package]]name = "cfg-if"version = "1.0.4"@@ -223,6 +278,15 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"+[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]+[[package]]name = "crossbeam-channel"version = "0.5.15"@@ -238,6 +302,16 @@ version = "0.8.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"+[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]+[[package]]name = "deranged"version = "0.5.8"@@ -247,6 +321,16 @@ dependencies = ["powerfmt",]+[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+]+[[package]]name = "dirs"version = "5.0.1"@@ -268,6 +352,17 @@ dependencies = ["windows-sys 0.48.0",]+[[package]]+name = "displaydoc"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "equivalent"version = "1.0.2"@@ -284,6 +379,18 @@ dependencies = ["windows-sys 0.61.2",]+[[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.4.1"@@ -304,12 +411,27 @@ dependencies = ["version_check",]+[[package]]+name = "find-msvc-tools"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"+[[package]]name = "foldhash"version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"+[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]+[[package]]name = "futures-core"version = "0.3.32"@@ -334,6 +456,16 @@ dependencies = ["slab",]+[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]+[[package]]name = "getrandom"version = "0.2.17"@@ -358,6 +490,15 @@ dependencies = ["wasip3",]+[[package]]+name = "hashbrown"+version = "0.14.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"+dependencies = [+ "ahash",+]+[[package]]name = "hashbrown"version = "0.15.5"@@ -373,18 +514,130 @@ version = "0.17.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+[[package]]+name = "hashlink"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"+dependencies = [+ "hashbrown 0.14.5",+]+[[package]]name = "heck"version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"+[[package]]+name = "icu_collections"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"+dependencies = [+ "displaydoc",+ "potential_utf",+ "utf8_iter",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"++[[package]]+name = "icu_properties"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"+dependencies = [+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"++[[package]]+name = "icu_provider"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]+[[package]]name = "id-arena"version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"+[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]+[[package]]name = "indexmap"version = "2.14.0"@@ -495,12 +748,29 @@ dependencies = ["libc",]+[[package]]+name = "libsqlite3-sys"+version = "0.30.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"+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 = "litemap"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"+[[package]]name = "lock_api"version = "0.4.14"@@ -621,12 +891,24 @@ dependencies = ["syn",]+[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"+[[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.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"+[[package]]name = "portable-atomic"version = "1.13.1"@@ -642,6 +924,15 @@ dependencies = ["portable-atomic",]+[[package]]+name = "potential_utf"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"+dependencies = [+ "zerovec",+]+[[package]]name = "powerfmt"version = "0.2.0"@@ -715,6 +1006,62 @@ dependencies = ["thiserror 1.0.69",]+[[package]]+name = "refinery"+version = "0.8.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ba5d693abf62492c37268512ff35b77655d2e957ca53dab85bf993fe9172d15"+dependencies = [+ "refinery-core",+ "refinery-macros",+]++[[package]]+name = "refinery-core"+version = "0.8.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a83581f18c1a4c3a6ebd7a174bdc665f17f618d79f7edccb6a0ac67e660b319"+dependencies = [+ "async-trait",+ "cfg-if",+ "log",+ "regex",+ "rusqlite",+ "serde",+ "siphasher",+ "thiserror 1.0.69",+ "time",+ "toml",+ "url",+ "walkdir",+]++[[package]]+name = "refinery-macros"+version = "0.8.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72c225407d8e52ef8cf094393781ecda9a99d6544ec28d90a6915751de259264"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "refinery-core",+ "regex",+ "syn",+]++[[package]]+name = "regex"+version = "1.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]+[[package]]name = "regex-automata"version = "0.4.14"@@ -732,6 +1079,20 @@ version = "0.8.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"+[[package]]+name = "rusqlite"+version = "0.32.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"+dependencies = [+ "bitflags",+ "fallible-iterator",+ "fallible-streaming-iterator",+ "hashlink",+ "libsqlite3-sys",+ "smallvec",+]+[[package]]name = "rustix"version = "1.1.4"@@ -751,6 +1112,15 @@ version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"+[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]+[[package]]name = "scopeguard"version = "1.2.0"@@ -815,6 +1185,17 @@ dependencies = ["serde",]+[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]+[[package]]name = "sharded-slab"version = "0.1.7"@@ -824,6 +1205,12 @@ dependencies = ["lazy_static",]+[[package]]+name = "shlex"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"+[[package]]name = "signal-hook-registry"version = "1.4.8"@@ -834,6 +1221,12 @@ dependencies = ["libc",]+[[package]]+name = "siphasher"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"+[[package]]name = "slab"version = "0.4.12"@@ -856,6 +1249,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"+[[package]]name = "strsim"version = "0.11.1"@@ -879,6 +1278,17 @@ dependencies = ["unicode-ident",]+[[package]]+name = "synstructure"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "tempfile"version = "3.27.0"@@ -972,6 +1382,16 @@ dependencies = ["time-core",]+[[package]]+name = "tinystr"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"+dependencies = [+ "displaydoc",+ "zerovec",+]+[[package]]name = "tokio"version = "1.52.3"@@ -1128,6 +1548,12 @@ dependencies = ["tracing-serde",]+[[package]]+name = "typenum"+version = "1.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"+[[package]]name = "uncased"version = "0.9.10"@@ -1149,6 +1575,24 @@ version = "0.2.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"+[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+]++[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"+[[package]]name = "utf8parse"version = "0.2.2"@@ -1173,12 +1617,28 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"+[[package]]+name = "vcpkg"+version = "0.2.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"+[[package]]name = "version_check"version = "0.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"+[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]+[[package]]name = "wasi"version = "0.11.1+wasi-snapshot-preview1"@@ -1282,6 +1742,15 @@ dependencies = ["semver",]+[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]+[[package]]name = "windows-link"version = "0.2.1"@@ -1466,12 +1935,115 @@ dependencies = ["wasmparser",]+[[package]]+name = "writeable"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"+[[package]]name = "yansi"version = "1.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"+[[package]]+name = "yoke"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zerocopy"+version = "0.8.48"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.48"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zerotrie"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "zmij"version = "1.0.21"diff --git a/Cargo.toml b/Cargo.tomlindex b2edac1f..1bfcb4b1 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -58,6 +58,12 @@ dirs = "5"# Secrets.secrecy = { version = "0.10", features = ["serde"] }+# Storage.+rusqlite = { version = "0.32", features = ["bundled"] }+refinery = { version = "0.8", features = ["rusqlite"] }+sha2 = "0.10"+parking_lot = "0.12"+# Testing.tempfile = "3"diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex 0f6b1510..183fe425 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -27,6 +27,24 @@ macro_rules! id_newtype {pub fn new() -> Self {Self(Uuid::now_v7())}++ /// Borrow the raw 16-byte big-endian representation.+ #[must_use]+ pub fn as_bytes(&self) -> &[u8; 16] {+ self.0.as_bytes()+ }++ /// Reconstruct from a 16-byte slice (typically read from+ /// SQLite as a `BLOB`).+ ///+ /// # Errors+ /// Returns [`MemoryError::MalformedRecord`] if the slice is+ /// not exactly 16 bytes.+ pub fn from_slice(bytes: &[u8]) -> Result<Self, MemoryError> {+ Uuid::from_slice(bytes)+ .map(Self)+ .map_err(|e| MemoryError::MalformedRecord(format!("invalid uuid bytes: {e}")))+ }}impl Default for $name {@@ -62,6 +80,7 @@ id_newtype!(pub WorkspaceId, "Workspace identifier (top of the 3-tuple).");id_newtype!(pub ProjectId, "Project identifier (middle of the 3-tuple).");id_newtype!(pub SessionId, "Identifier for a single agent run.");id_newtype!(pub ObservationId, "Identifier for a single observation captured during a session.");+id_newtype!(pub PageId, "Identifier for a single wiki page version.");/// Relative path of a page within the wiki tree.///diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex 9a208631..e3816153 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -6,6 +6,8 @@pub mod error;pub mod ids;+pub mod page;pub use error::{MemoryError, MemoryResult};-pub use ids::{AgentKind, ObservationId, PagePath, ProjectId, SessionId, WorkspaceId};+pub use ids::{AgentKind, ObservationId, PageId, PagePath, ProjectId, SessionId, WorkspaceId};+pub use page::{NewPage, Page, Tier};diff --git a/crates/ai-memory-core/src/page.rs b/crates/ai-memory-core/src/page.rsnew file mode 100644index 00000000..64c98665--- /dev/null+++ b/crates/ai-memory-core/src/page.rs@@ -0,0 +1,145 @@+//! Page-level domain types.+//!+//! A *page* is the unit of long-term memory — one markdown file under+//! `<data_dir>/wiki/`. Pages live in tiers (working/episodic/semantic/+//! procedural) and are versioned in place via supersession (an old+//! `is_latest=false` row links to the new `is_latest=true` row through+//! [`Page::supersedes`]).++use std::str::FromStr;++use jiff::Timestamp;+use serde::{Deserialize, Serialize};++use crate::ids::{PageId, PagePath, ProjectId, WorkspaceId};++/// Lifetime classification for a page.+///+/// Adopted from agentmemory's four-tier model, simplified. See+/// [`docs/design-decisions.md`](../../docs/design-decisions.md) §7.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Tier {+ /// Current session: last N observations, current files.+ Working,+ /// Per-session summaries with concept tags and files touched.+ Episodic,+ /// Distilled facts/preferences/architecture notes — wiki pages proper.+ Semantic,+ /// Repeated patterns extracted from episodic clusters.+ Procedural,+}++/// Input for upserting a page. Generated by the wiki layer, consumed by+/// the store's writer actor.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct NewPage {+ /// Owning workspace.+ pub workspace_id: WorkspaceId,+ /// Owning project.+ pub project_id: ProjectId,+ /// Relative path within the wiki tree.+ pub path: PagePath,+ /// Page title (rendered from frontmatter or the first H1).+ pub title: String,+ /// Markdown body excluding the YAML frontmatter.+ pub body: String,+ /// Tier classification.+ pub tier: Tier,+ /// Frontmatter, stored as JSON for cheap querying.+ pub frontmatter_json: serde_json::Value,+ /// `true` to mark the page as user-pinned (never decay).+ pub pinned: bool,+}++/// Materialised view of a page row.+#[derive(Clone, Debug)]+pub struct Page {+ /// Stable identifier for this page *version*.+ pub id: PageId,+ /// Owning workspace.+ pub workspace_id: WorkspaceId,+ /// Owning project.+ pub project_id: ProjectId,+ /// Relative path within the wiki tree.+ pub path: PagePath,+ /// Page title.+ pub title: String,+ /// Markdown body.+ pub body: String,+ /// SHA-256 of [`Self::body`].+ pub body_sha256: [u8; 32],+ /// Tier classification.+ pub tier: Tier,+ /// Frontmatter as JSON.+ pub frontmatter: serde_json::Value,+ /// `true` if this row is the current visible version.+ pub is_latest: bool,+ /// Previous version of this page, if any.+ pub supersedes: Option<PageId>,+ /// `true` if the user has pinned this page (decay sweep skips it).+ pub pinned: bool,+ /// Wall-clock creation time of *this version*.+ pub created_at: Timestamp,+ /// Wall-clock last-update time of *this version*.+ pub updated_at: Timestamp,+}++impl Tier {+ /// Canonical short string for storage and serialisation.+ #[must_use]+ pub const fn as_str(&self) -> &'static str {+ match self {+ Self::Working => "working",+ Self::Episodic => "episodic",+ Self::Semantic => "semantic",+ Self::Procedural => "procedural",+ }+ }+}++impl FromStr for Tier {+ type Err = crate::MemoryError;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s {+ "working" => Ok(Self::Working),+ "episodic" => Ok(Self::Episodic),+ "semantic" => Ok(Self::Semantic),+ "procedural" => Ok(Self::Procedural),+ other => Err(crate::MemoryError::MalformedRecord(format!(+ "unknown tier: {other}"+ ))),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn tier_round_trips() {+ for t in [+ Tier::Working,+ Tier::Episodic,+ Tier::Semantic,+ Tier::Procedural,+ ] {+ assert_eq!(t.as_str().parse::<Tier>().unwrap(), t);+ }+ }++ #[test]+ fn tier_rejects_unknown() {+ assert!("nope".parse::<Tier>().is_err());+ }++ #[test]+ fn tier_serde() {+ assert_eq!(+ serde_json::to_string(&Tier::Procedural).unwrap(),+ "\"procedural\""+ );+ }+}diff --git a/crates/ai-memory-store/Cargo.toml b/crates/ai-memory-store/Cargo.tomlindex b2731013..adddedd9 100644--- a/crates/ai-memory-store/Cargo.toml+++ b/crates/ai-memory-store/Cargo.toml@@ -10,6 +10,21 @@ description = "SQLite storage layer with single-writer actor and FTS5/sqlite-vec[dependencies]ai-memory-core.workspace = true+anyhow.workspace = true+thiserror.workspace = true+serde.workspace = true+serde_json.workspace = true+tokio.workspace = true+tracing.workspace = true+jiff.workspace = true+uuid.workspace = true+sha2.workspace = true+rusqlite.workspace = true+refinery.workspace = true+parking_lot.workspace = true++[dev-dependencies]+tempfile.workspace = true[lints]workspace = truediff --git a/crates/ai-memory-store/migrations/V01__init.sql b/crates/ai-memory-store/migrations/V01__init.sqlnew file mode 100644index 00000000..d3c546eb--- /dev/null+++ b/crates/ai-memory-store/migrations/V01__init.sql@@ -0,0 +1,126 @@+-- Initial ai-memory schema.+-- Identity is the 3-tuple (workspace_id, project_id, path) on every domain+-- table, baked in from M1 so we never inherit basic-memory's v0.20 retrofit+-- pain (issues #783, #834 and friends).++CREATE TABLE workspaces (+ id BLOB PRIMARY KEY NOT NULL,+ name TEXT NOT NULL UNIQUE,+ created_at INTEGER NOT NULL -- microseconds since epoch+);++CREATE TABLE projects (+ id BLOB PRIMARY KEY NOT NULL,+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ repo_path TEXT, -- absolute filesystem path, for cwd matching+ created_at INTEGER NOT NULL,+ UNIQUE (workspace_id, name)+);++CREATE INDEX idx_projects_workspace ON projects(workspace_id);++CREATE TABLE pages (+ id BLOB PRIMARY KEY NOT NULL,+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,+ path TEXT NOT NULL, -- POSIX path relative to wiki/+ title TEXT NOT NULL,+ tier TEXT NOT NULL CHECK (tier IN ('working','episodic','semantic','procedural')),+ body TEXT NOT NULL,+ body_sha256 BLOB NOT NULL, -- 32 bytes+ frontmatter_json TEXT NOT NULL DEFAULT '{}',+ is_latest INTEGER NOT NULL DEFAULT 1 CHECK (is_latest IN (0,1)),+ supersedes BLOB REFERENCES pages(id) ON DELETE SET NULL,+ pinned INTEGER NOT NULL DEFAULT 0 CHECK (pinned IN (0,1)),+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ -- Embedding columns are NULL through v1 (M9 fills them in).+ embedding_provider TEXT,+ embedding_model TEXT,+ embedding_dim INTEGER+);++-- One latest version per (workspace, project, path). Older versions stay in+-- the table with is_latest=0, linked via supersedes.+CREATE UNIQUE INDEX idx_pages_latest_path+ ON pages(workspace_id, project_id, path)+ WHERE is_latest = 1;++CREATE INDEX idx_pages_updated ON pages(updated_at DESC);+CREATE INDEX idx_pages_supersedes ON pages(supersedes) WHERE supersedes IS NOT NULL;++-- FTS5 over title + body. `content='pages'` keeps the FTS table contentless+-- (the source row owns the text); the triggers below propagate changes.+CREATE VIRTUAL TABLE pages_fts USING fts5(+ title, body,+ content='pages',+ content_rowid='rowid',+ tokenize="unicode61 tokenchars '/_-'"+);++CREATE TRIGGER pages_fts_ai AFTER INSERT ON pages BEGIN+ INSERT INTO pages_fts(rowid, title, body)+ VALUES (new.rowid, new.title, new.body);+END;++CREATE TRIGGER pages_fts_ad AFTER DELETE ON pages BEGIN+ INSERT INTO pages_fts(pages_fts, rowid, title, body)+ VALUES ('delete', old.rowid, old.title, old.body);+END;++CREATE TRIGGER pages_fts_au AFTER UPDATE ON pages BEGIN+ INSERT INTO pages_fts(pages_fts, rowid, title, body)+ VALUES ('delete', old.rowid, old.title, old.body);+ INSERT INTO pages_fts(rowid, title, body)+ VALUES (new.rowid, new.title, new.body);+END;++CREATE TABLE sessions (+ id BLOB PRIMARY KEY NOT NULL,+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,+ agent_kind TEXT NOT NULL CHECK (agent_kind IN ('claude-code','codex','open-code','other')),+ cwd TEXT,+ started_at INTEGER NOT NULL,+ ended_at INTEGER,+ summary_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL+);++CREATE INDEX idx_sessions_recent ON sessions(workspace_id, project_id, started_at DESC);++CREATE TABLE observations (+ id BLOB PRIMARY KEY NOT NULL,+ session_id BLOB NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,+ kind TEXT NOT NULL,+ title TEXT NOT NULL,+ body TEXT NOT NULL,+ importance INTEGER NOT NULL DEFAULT 5 CHECK (importance BETWEEN 1 AND 10),+ created_at INTEGER NOT NULL+);++CREATE INDEX idx_observations_session ON observations(session_id, created_at);++CREATE TABLE links (+ from_page_id BLOB NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ to_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL,+ to_path TEXT NOT NULL, -- raw target, may be unresolved+ link_type TEXT NOT NULL DEFAULT 'references',+ PRIMARY KEY (from_page_id, to_path, link_type)+);++CREATE INDEX idx_links_to ON links(to_page_id) WHERE to_page_id IS NOT NULL;++CREATE TABLE audit_log (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ at INTEGER NOT NULL,+ op TEXT NOT NULL,+ workspace_id BLOB,+ project_id BLOB,+ page_id BLOB,+ detail TEXT NOT NULL DEFAULT '{}'+);++CREATE INDEX idx_audit_recent ON audit_log(at DESC);diff --git a/crates/ai-memory-store/src/error.rs b/crates/ai-memory-store/src/error.rsnew file mode 100644index 00000000..f2806ad3--- /dev/null+++ b/crates/ai-memory-store/src/error.rs@@ -0,0 +1,37 @@+//! Store-level error type.++use thiserror::Error;++use ai_memory_core::MemoryError;++/// Result alias used throughout the store crate.+pub type StoreResult<T> = Result<T, StoreError>;++/// Errors raised by the store layer.+#[derive(Debug, Error)]+#[non_exhaustive]+pub enum StoreError {+ /// Underlying SQLite error.+ #[error("sqlite: {0}")]+ Sqlite(#[from] rusqlite::Error),++ /// Migration runner failed.+ #[error("migration: {0}")]+ Migration(#[from] refinery::Error),++ /// I/O failed (e.g. opening the DB file).+ #[error(transparent)]+ Io(#[from] std::io::Error),++ /// JSON serialisation failure (frontmatter).+ #[error("serde: {0}")]+ Serde(#[from] serde_json::Error),++ /// Writer actor has shut down.+ #[error("writer actor is no longer running")]+ WriterClosed,++ /// Re-export of [`MemoryError`] for cross-crate propagation.+ #[error(transparent)]+ Memory(#[from] MemoryError),+}diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex ff07721e..9881b230 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -1,5 +1,146 @@//! SQLite storage layer for ai-memory.//!-//! Hosts the single-writer actor and the read-only connection pool. Schema-//! migrations land via `refinery`. Implementation lands in milestone M1; this-//! crate is intentionally empty in M0.+//! The crate owns a single SQLite file under `<data_dir>/db/memory.sqlite`,+//! opens it in WAL mode with foreign keys on, runs all pending migrations+//! at startup, and exposes a [`WriterHandle`] that serialises every mutation+//! through a dedicated OS thread.+//!+//! Reader-side APIs land in milestone M1-B; the writer + migrations are+//! sufficient for M1-A's "drop a page in, see it persisted" demo.++use std::path::{Path, PathBuf};++use rusqlite::Connection;++mod error;+mod migrations;+mod ops;+mod writer;++pub use error::{StoreError, StoreResult};+pub use writer::WriterHandle;++/// Filename used inside the data dir's `db/` subdirectory.+pub const DB_FILENAME: &str = "memory.sqlite";++/// Open (and migrate) a [`Store`] rooted at the given data directory.+pub struct Store {+ /// Cloneable handle to submit mutations.+ pub writer: WriterHandle,+ db_path: PathBuf,+}++impl Store {+ /// Open the SQLite file at `<data_dir>/db/memory.sqlite`, applying any+ /// outstanding migrations, then spawn the writer thread.+ ///+ /// # Errors+ /// Returns [`StoreError`] if the file cannot be opened, migrations+ /// cannot be applied, or the writer thread fails to start.+ pub fn open(data_dir: &Path) -> StoreResult<Self> {+ let db_dir = data_dir.join("db");+ std::fs::create_dir_all(&db_dir)?;+ let db_path = db_dir.join(DB_FILENAME);++ let mut conn = Connection::open(&db_path)?;+ conn.pragma_update(None, "journal_mode", "WAL")?;+ conn.pragma_update(None, "synchronous", "NORMAL")?;+ conn.pragma_update(None, "foreign_keys", "ON")?;+ conn.pragma_update(None, "busy_timeout", 5_000)?; // ms++ migrations::run(&mut conn)?;++ let writer = WriterHandle::spawn(conn);+ Ok(Self { writer, db_path })+ }++ /// Path of the SQLite file on disk.+ #[must_use]+ pub fn db_path(&self) -> &Path {+ &self.db_path+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use ai_memory_core::{NewPage, PagePath, ProjectId, Tier, WorkspaceId};+ use tempfile::TempDir;++ fn sample_page(ws: WorkspaceId, proj: ProjectId, path: &str, body: &str) -> NewPage {+ NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(path).unwrap(),+ title: "test".into(),+ body: body.into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ }+ }++ #[tokio::test]+ async fn open_and_upsert_page() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = WorkspaceId::new();+ let proj = ProjectId::new();+ store.writer.ensure_workspace(ws, "default").await.unwrap();+ store+ .writer+ .ensure_project(proj, ws, "ai-memory", None)+ .await+ .unwrap();+ let id_a = store+ .writer+ .upsert_page(sample_page(ws, proj, "foo.md", "hello"))+ .await+ .unwrap();+ // Same body again: returns the same id, no supersession.+ let id_b = store+ .writer+ .upsert_page(sample_page(ws, proj, "foo.md", "hello"))+ .await+ .unwrap();+ assert_eq!(id_a, id_b);+ // Different body: supersession produces a new id.+ let id_c = store+ .writer+ .upsert_page(sample_page(ws, proj, "foo.md", "hello world"))+ .await+ .unwrap();+ assert_ne!(id_b, id_c);+ }++ #[tokio::test]+ async fn serialises_parallel_writes() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = WorkspaceId::new();+ let proj = ProjectId::new();+ store.writer.ensure_workspace(ws, "default").await.unwrap();+ store+ .writer+ .ensure_project(proj, ws, "ai-memory", None)+ .await+ .unwrap();+ // Spawn 16 concurrent writes; the writer must serialise them.+ let mut handles = Vec::new();+ for i in 0..16 {+ let w = store.writer.clone();+ handles.push(tokio::spawn(async move {+ w.upsert_page(sample_page(+ ws,+ proj,+ &format!("p{i}.md"),+ &format!("body-{i}"),+ ))+ .await+ }));+ }+ for h in handles {+ h.await.unwrap().unwrap();+ }+ }+}diff --git a/crates/ai-memory-store/src/migrations.rs b/crates/ai-memory-store/src/migrations.rsnew file mode 100644index 00000000..b21c6083--- /dev/null+++ b/crates/ai-memory-store/src/migrations.rs@@ -0,0 +1,12 @@+//! refinery-driven schema migrations.++refinery::embed_migrations!("migrations");++/// Run all pending migrations against an open connection.+///+/// # Errors+/// Propagates the underlying refinery error if a migration fails.+pub fn run(conn: &mut rusqlite::Connection) -> Result<(), refinery::Error> {+ migrations::runner().run(conn)?;+ Ok(())+}diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsnew file mode 100644index 00000000..b3c43629--- /dev/null+++ b/crates/ai-memory-store/src/ops.rs@@ -0,0 +1,180 @@+//! Mutating SQL operations executed on the writer thread.+//!+//! Each operation is one transaction. Calling them from anywhere other than+//! the writer thread would violate the single-writer invariant (see+//! [`crate::writer`]).++use ai_memory_core::{NewPage, PageId};+use jiff::Timestamp;+use rusqlite::{Connection, OptionalExtension, params};+use sha2::{Digest, Sha256};++use crate::error::StoreResult;++/// Upsert a page by path, superseding any existing latest version when the+/// content (sha256 of body) has changed.+///+/// Returns the id of the page row that should now be considered current.+pub fn upsert_page(conn: &mut Connection, page: &NewPage) -> StoreResult<PageId> {+ let body_sha256: [u8; 32] = {+ let mut hasher = Sha256::new();+ hasher.update(page.body.as_bytes());+ hasher.finalize().into()+ };+ let frontmatter_str = serde_json::to_string(&page.frontmatter_json)?;+ let now = Timestamp::now().as_microsecond();+ let tier_str = page.tier.as_str();++ let tx = conn.transaction()?;++ let existing: Option<(Vec<u8>, Vec<u8>)> = tx+ .query_row(+ "SELECT id, body_sha256 FROM pages \+ WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3 AND is_latest = 1",+ params![+ page.workspace_id.as_bytes(),+ page.project_id.as_bytes(),+ page.path.as_str(),+ ],+ |row| Ok((row.get(0)?, row.get(1)?)),+ )+ .optional()?;++ let result_id = if let Some((existing_id, existing_sha)) = existing {+ if existing_sha == body_sha256 {+ // Content unchanged; touch updated_at only and return existing id.+ tx.execute(+ "UPDATE pages SET updated_at = ?1 WHERE id = ?2",+ params![now, existing_id],+ )?;+ PageId::from_slice(&existing_id)?+ } else {+ let new_id = PageId::new();+ tx.execute(+ "UPDATE pages SET is_latest = 0 WHERE id = ?1",+ params![existing_id],+ )?;+ tx.execute(+ "INSERT INTO pages \+ (id, workspace_id, project_id, path, title, tier, body, body_sha256, \+ frontmatter_json, is_latest, supersedes, pinned, created_at, updated_at) \+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 1, ?10, ?11, ?12, ?12)",+ params![+ new_id.as_bytes(),+ page.workspace_id.as_bytes(),+ page.project_id.as_bytes(),+ page.path.as_str(),+ page.title,+ tier_str,+ page.body,+ body_sha256.as_slice(),+ frontmatter_str,+ existing_id,+ i64::from(page.pinned),+ now,+ ],+ )?;+ audit(+ &tx,+ "supersede_page",+ Some(page.workspace_id.as_bytes()),+ Some(page.project_id.as_bytes()),+ Some(new_id.as_bytes()),+ now,+ )?;+ new_id+ }+ } else {+ let new_id = PageId::new();+ tx.execute(+ "INSERT INTO pages \+ (id, workspace_id, project_id, path, title, tier, body, body_sha256, \+ frontmatter_json, is_latest, pinned, created_at, updated_at) \+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 1, ?10, ?11, ?11)",+ params![+ new_id.as_bytes(),+ page.workspace_id.as_bytes(),+ page.project_id.as_bytes(),+ page.path.as_str(),+ page.title,+ tier_str,+ page.body,+ body_sha256.as_slice(),+ frontmatter_str,+ i64::from(page.pinned),+ now,+ ],+ )?;+ audit(+ &tx,+ "create_page",+ Some(page.workspace_id.as_bytes()),+ Some(page.project_id.as_bytes()),+ Some(new_id.as_bytes()),+ now,+ )?;+ new_id+ };++ tx.commit()?;+ Ok(result_id)+}++/// Ensure a workspace exists; insert a stub row keyed on `name` otherwise.+pub fn ensure_workspace(+ conn: &mut Connection,+ id: &ai_memory_core::WorkspaceId,+ name: &str,+) -> StoreResult<()> {+ conn.execute(+ "INSERT INTO workspaces (id, name, created_at) VALUES (?1, ?2, ?3) \+ ON CONFLICT(name) DO NOTHING",+ params![id.as_bytes(), name, Timestamp::now().as_microsecond()],+ )?;+ Ok(())+}++/// Ensure a project exists under the given workspace.+pub fn ensure_project(+ conn: &mut Connection,+ id: &ai_memory_core::ProjectId,+ workspace_id: &ai_memory_core::WorkspaceId,+ name: &str,+ repo_path: Option<&str>,+) -> StoreResult<()> {+ conn.execute(+ "INSERT INTO projects (id, workspace_id, name, repo_path, created_at) \+ VALUES (?1, ?2, ?3, ?4, ?5) \+ ON CONFLICT(workspace_id, name) DO NOTHING",+ params![+ id.as_bytes(),+ workspace_id.as_bytes(),+ name,+ repo_path,+ Timestamp::now().as_microsecond()+ ],+ )?;+ Ok(())+}++fn audit(+ tx: &rusqlite::Transaction<'_>,+ op: &str,+ workspace_id: Option<&[u8; 16]>,+ project_id: Option<&[u8; 16]>,+ page_id: Option<&[u8; 16]>,+ at: i64,+) -> StoreResult<()> {+ tx.execute(+ "INSERT INTO audit_log (at, op, workspace_id, project_id, page_id, detail) \+ VALUES (?1, ?2, ?3, ?4, ?5, '{}')",+ params![+ at,+ op,+ workspace_id.map(|b| &b[..]),+ project_id.map(|b| &b[..]),+ page_id.map(|b| &b[..])+ ],+ )?;+ Ok(())+}diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsnew file mode 100644index 00000000..7e9ddaa8--- /dev/null+++ b/crates/ai-memory-store/src/writer.rs@@ -0,0 +1,169 @@+//! Single-writer SQLite actor.+//!+//! Every mutating SQL statement flows through one dedicated OS thread that+//! owns the writer [`rusqlite::Connection`]. Callers send [`WriteCmd`]+//! variants over an mpsc channel and receive results back through a+//! `oneshot`. This pattern eliminates the `database is locked` failure+//! mode that bit cognee (#2717) — there is exactly one writer at all+//! times, by construction.++use std::sync::{Arc, Mutex};+use std::thread::{self, JoinHandle};++use ai_memory_core::{NewPage, PageId, ProjectId, WorkspaceId};+use rusqlite::Connection;+use tokio::sync::{mpsc, oneshot};++use crate::error::{StoreError, StoreResult};+use crate::ops;++/// Commands accepted by the writer thread.+pub(crate) enum WriteCmd {+ EnsureWorkspace {+ id: WorkspaceId,+ name: String,+ reply: oneshot::Sender<StoreResult<()>>,+ },+ EnsureProject {+ id: ProjectId,+ workspace_id: WorkspaceId,+ name: String,+ repo_path: Option<String>,+ reply: oneshot::Sender<StoreResult<()>>,+ },+ UpsertPage {+ page: NewPage,+ reply: oneshot::Sender<StoreResult<PageId>>,+ },+ Shutdown,+}++/// Cheap, cloneable handle that submits commands to the writer.+#[derive(Clone)]+pub struct WriterHandle {+ inner: Arc<WriterInner>,+}++struct WriterInner {+ tx: mpsc::Sender<WriteCmd>,+ join: Mutex<Option<JoinHandle<()>>>,+}++impl WriterHandle {+ /// Take ownership of `conn` and spawn the writer thread.+ pub(crate) fn spawn(conn: Connection) -> Self {+ let (tx, rx) = mpsc::channel(1024);+ let handle = thread::Builder::new()+ .name("ai-memory-writer".into())+ .spawn(move || worker_loop(conn, rx))+ .expect("spawn writer thread");++ Self {+ inner: Arc::new(WriterInner {+ tx,+ join: Mutex::new(Some(handle)),+ }),+ }+ }++ /// Ensure a workspace row exists.+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or+ /// propagates the SQL error from [`ops::ensure_workspace`].+ pub async fn ensure_workspace(+ &self,+ id: WorkspaceId,+ name: impl Into<String>,+ ) -> StoreResult<()> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::EnsureWorkspace {+ id,+ name: name.into(),+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Ensure a project row exists under the given workspace.+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or+ /// propagates the SQL error from [`ops::ensure_project`].+ pub async fn ensure_project(+ &self,+ id: ProjectId,+ workspace_id: WorkspaceId,+ name: impl Into<String>,+ repo_path: Option<String>,+ ) -> StoreResult<()> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::EnsureProject {+ id,+ workspace_id,+ name: name.into(),+ repo_path,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Upsert a page (creating it or superseding the existing latest+ /// version when the body has changed).+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or+ /// propagates the SQL error from [`ops::upsert_page`].+ pub async fn upsert_page(&self, page: NewPage) -> StoreResult<PageId> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::UpsertPage { page, reply: tx }).await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ async fn send(&self, cmd: WriteCmd) -> StoreResult<()> {+ self.inner+ .tx+ .send(cmd)+ .await+ .map_err(|_| StoreError::WriterClosed)+ }+}++impl Drop for WriterInner {+ fn drop(&mut self) {+ let _ = self.tx.try_send(WriteCmd::Shutdown);+ if let Some(handle) = self.join.lock().expect("writer join mutex poisoned").take() {+ let _ = handle.join();+ }+ }+}++fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {+ while let Some(cmd) = rx.blocking_recv() {+ match cmd {+ WriteCmd::Shutdown => break,+ WriteCmd::EnsureWorkspace { id, name, reply } => {+ let result = ops::ensure_workspace(&mut conn, &id, &name);+ let _ = reply.send(result);+ }+ WriteCmd::EnsureProject {+ id,+ workspace_id,+ name,+ repo_path,+ reply,+ } => {+ let result =+ ops::ensure_project(&mut conn, &id, &workspace_id, &name, repo_path.as_deref());+ let _ = reply.send(result);+ }+ WriteCmd::UpsertPage { page, reply } => {+ let result = ops::upsert_page(&mut conn, &page);+ let _ = reply.send(result);+ }+ }+ }+ tracing::debug!("writer thread exiting cleanly");+}