From f74d53e446b07ef1249a4c193b03ac30361f2a67 Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Mon, 30 Nov 2026 11:37:48 +0100 Subject: [PATCH] memory: per-session semantic memory (strata-memory crate, Qdrant Edge + BGE-M3) remember/recall/forget agent tools, one-way opt-in latch with embedder gate, fail-open Store-authoritative design, keyword fallback, model-id rebuild, GUI toggle + i18n; docs updated; split-debuginfo=unpacked --- .gitignore | 1 + Cargo.lock | 1943 +++++++++++++++++++++++++++++++- Cargo.toml | 21 + README.md | 110 +- locales/en.json | 2 + locales/it.json | 2 + src/agent/memory.rs | 400 +++++++ src/agent/mod.rs | 41 +- src/api/routes.rs | 6 + src/api/sessions.rs | 55 +- src/config.rs | 34 + src/lib.rs | 1 + src/main.rs | 24 +- src/memory.rs | 454 ++++++++ src/store.rs | 167 +++ strata-memory/Cargo.toml | 20 + strata-memory/src/index.rs | 501 ++++++++ strata-memory/src/lib.rs | 281 +++++ strata-memory/src/workspace.rs | 804 +++++++++++++ tests/api_sessions.rs | 21 +- web/assets/app.js | 15 + web/assets/locales/en.json | 4 + web/assets/locales/it.json | 4 + web/index.html | 9 + 24 files changed, 4853 insertions(+), 67 deletions(-) create mode 100644 src/agent/memory.rs create mode 100644 src/memory.rs create mode 100644 strata-memory/Cargo.toml create mode 100644 strata-memory/src/index.rs create mode 100644 strata-memory/src/lib.rs create mode 100644 strata-memory/src/workspace.rs diff --git a/.gitignore b/.gitignore index c403c34..79c9efb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target .idea/ +/upstream diff --git a/Cargo.lock b/Cargo.lock index 172911c..9120ea1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,12 +2,27 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "addr2line" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e567177890eb1617b1f774005b66b26b2377afd138a2ca37aae7d8f0c81429d4" +dependencies = [ + "gimli", +] + [[package]] name = "adler2" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "adler32" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234" + [[package]] name = "ahash" version = "0.8.13" @@ -49,18 +64,107 @@ dependencies = [ "equator", ] +[[package]] +name = "allocator-api2" +version = "0.2.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" + +[[package]] +name = "allocator-api2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c880a97d28a3681c0267bd29cff89621202715b065127cd445fa0f0fe0aa2880" + +[[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 = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "anyhow" version = "1.0.105" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + [[package]] name = "arbitrary" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +[[package]] +name = "arc-swap" +version = "1.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" +dependencies = [ + "rustversion", +] + [[package]] name = "arg_enum_proc_macro" version = "0.3.4" @@ -93,6 +197,23 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "atomic_refcell" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21e4227379beff4205943696e6c3e0cd809bacdf3f0edd6e3dd153e2269571a4" + +[[package]] +name = "atomicwrites" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ef1bb8d1b645fe38d51dfc331d720fb5fc2c94b440c76cc79c80ff265ca33e3" +dependencies = [ + "rustix 0.38.44", + "tempfile", + "windows-sys 0.52.0", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -217,6 +338,21 @@ dependencies = [ "tracing", ] +[[package]] +name = "backtrace" +version = "0.3.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f4220217f3288537b83684130f42fad43320b1c3b805f1910d683d52ded24f" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide 0.9.1", + "object", + "rustc-demangle", + "windows-link", +] + [[package]] name = "base64" version = "0.13.1" @@ -229,6 +365,41 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + +[[package]] +name = "bincode" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740" +dependencies = [ + "bincode_derive", + "serde", + "unty", +] + +[[package]] +name = "bincode_derive" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf95709a440f45e986983918d0e8a1f30a9b1df04918fc828670606804ac3c09" +dependencies = [ + "virtue", +] + +[[package]] +name = "binout" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff5fa7be63dbf62cca511b0e64e4b869ebc68f2b99d65fb1aa127771c5b7cd0d" + [[package]] name = "bit_field" version = "0.10.4" @@ -241,6 +412,24 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "bitm" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7edec3daafc233e78a219c85a77bcf535ee267b0fae7a1aad96bd1a67add5d3" +dependencies = [ + "dyn_size_of", +] + +[[package]] +name = "bitpacking" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96a7139abd3d9cebf8cd6f920a389cf3dc9576172e32f4563f188cae3c3eb019" +dependencies = [ + "crunchy", +] + [[package]] name = "bitstream-io" version = "4.10.0" @@ -250,6 +439,27 @@ dependencies = [ "no_std_io2", ] +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "blink-alloc" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce4c15bad517bc0fb4a44523adf470e2c3eb3a365769327acdba849948ea3705" +dependencies = [ + "allocator-api2 0.4.0", +] + [[package]] name = "block-buffer" version = "0.12.1" @@ -271,11 +481,37 @@ version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" +[[package]] +name = "bytecount" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" + [[package]] name = "bytemuck" version = "1.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "byteorder-lite" @@ -310,6 +546,15 @@ dependencies = [ "shlex", ] +[[package]] +name = "cedarwood" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0524a528a6a0288df1863c3c20fe92c301875b4941e7b6c4b394ab08c5a4c55" +dependencies = [ + "smallvec", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -333,6 +578,38 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "charabia" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27d98f4c66de52108210ee491c9c991513021dfd259bf65e4bbd889687b488d7" +dependencies = [ + "aho-corasick", + "csv", + "either", + "fst", + "irg-kvariants", + "jieba-rs", + "serde", + "slice-group-by", + "unicode-normalization", + "whatlang", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + [[package]] name = "cmake" version = "0.1.58" @@ -348,6 +625,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "combine" version = "4.6.9" @@ -391,6 +674,35 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "cookie" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "indexmap 2.14.2", + "log", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -407,6 +719,17 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core_affinity" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a034b3a7b624016c6e13f5df875747cc25f884156aad2abd12b6c46797971342" +dependencies = [ + "libc", + "num_cpus", + "winapi", +] + [[package]] name = "cpufeatures" version = "0.3.1" @@ -416,6 +739,15 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32c" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f132a176423ee852e8f0a35d43088d1850966b50745be818a88b76f64b1c6cb" +dependencies = [ + "rustc_version", +] + [[package]] name = "crc32fast" version = "1.5.5" @@ -465,6 +797,33 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "csv" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938" +dependencies = [ + "csv-core", + "itoa", + "ryu", + "serde_core", +] + +[[package]] +name = "csv-core" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782" +dependencies = [ + "memchr", +] + +[[package]] +name = "daachorse" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f55d7153ba3b507595872a3874803f07a8a81d1e888abed8e5db7da0597d6e2" + [[package]] name = "daachorse" version = "3.0.3" @@ -477,8 +836,18 @@ version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" dependencies = [ - "darling_core", - "darling_macro", + "darling_core 0.20.11", + "darling_macro 0.20.11", +] + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core 0.23.0", + "darling_macro 0.23.0", ] [[package]] @@ -491,7 +860,20 @@ dependencies = [ "ident_case", "proc-macro2", "quote", - "strsim", + "strsim 0.11.1", + "syn 2.0.119", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim 0.11.1", "syn 2.0.119", ] @@ -501,7 +883,18 @@ version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ - "darling_core", + "darling_core 0.20.11", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core 0.23.0", "quote", "syn 2.0.119", ] @@ -515,6 +908,18 @@ dependencies = [ "serde", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "derive_builder" version = "0.20.2" @@ -530,7 +935,7 @@ version = "0.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" dependencies = [ - "darling", + "darling 0.20.11", "proc-macro2", "quote", "syn 2.0.119", @@ -568,12 +973,60 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "docopt" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f3f119846c823f9eafcf953a8f6ffb6ed69bf6240883261a7f13b634579a51f" +dependencies = [ + "lazy_static", + "regex", + "serde", + "strsim 0.10.0", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + [[package]] name = "dunce" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "duplicate" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e92f10a49176cbffacaedabfaa11d51db1ea0f80a83c26e1873b43cd1742c24" + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "dyn_size_of" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a742b95783b1f45b900129082cbc47717b6a77ee8d17eea70a8ea62462f5de3" + +[[package]] +name = "ecow" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dca6141d10838e13f9b166c190254a3f9b5d8379521f9b7510810061cef17a4" +dependencies = [ + "serde", +] + [[package]] name = "either" version = "1.19.0" @@ -586,6 +1039,29 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" +[[package]] +name = "env_filter" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "288efae2d67fb0418d01f837feb55c7a9cdc4c5db38d3dee91324a1c7ec6fd31" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82bdfc6e01c305a3ea46ed815b06ac0b379d7c5eac588fa4464048d731c4dcdf" +dependencies = [ + "anstream", + "anstyle", + "env_filter", + "jiff", + "log", +] + [[package]] name = "equator" version = "0.4.2" @@ -612,6 +1088,17 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "erased-serde" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + [[package]] name = "errno" version = "0.3.15" @@ -638,7 +1125,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" dependencies = [ "bit_field", - "half", + "half 2.7.1", "lebe", "miniz_oxide 0.8.9", "multiversion", @@ -659,6 +1146,12 @@ 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 = "fax" version = "0.2.7" @@ -674,12 +1167,28 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "filetime" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "fixedbitset" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" + [[package]] name = "flate2" version = "1.1.11" @@ -691,12 +1200,30 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "float_next_after" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37007738a80ea34f969af54a3390dd72cacdef654974cfd449c9f6f72dbaac10" + [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "form_urlencoded" version = "1.2.3" @@ -706,12 +1233,44 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs-err" +version = "3.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29" +dependencies = [ + "autocfg", + "tokio", +] + +[[package]] +name = "fs4" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5" +dependencies = [ + "rustix 1.1.6", + "windows-sys 0.61.2", +] + [[package]] name = "fs_extra" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" +[[package]] +name = "fst" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ab85b9b05e3978cc9a9cf8fea7f01b494e1a09ed3037e16ba39edc7a29eb61a" + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + [[package]] name = "futures" version = "0.3.34" @@ -800,6 +1359,57 @@ dependencies = [ "slab", ] +[[package]] +name = "geo" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30eb1fdc57c1e5cfd11826fe0caec4b9dc7901f3758263bb506228d88c8d9e9a" +dependencies = [ + "float_next_after", + "geo-types", + "geographiclib-rs", + "i_overlay", + "log", + "num-traits", + "rand 0.10.4", + "rand_pcg", + "robust", + "rstar", + "sif-itree", +] + +[[package]] +name = "geo-types" +version = "0.7.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c180387602f8ab649c98dd5e9540e42cdb40a62455fc4790f4d80e15d31daac5" +dependencies = [ + "approx", + "num-traits", + "rstar", + "serde", + "thiserror", +] + +[[package]] +name = "geographiclib-rs" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5a7f08910fd98737a6eda7568e7c5e645093e073328eeef49758cfe8b0489c7" +dependencies = [ + "libm", +] + +[[package]] +name = "geohash" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f58890382f70caccc5fa388981f7ac80c913795042afce9f3e065695d8f7464" +dependencies = [ + "geo-types", + "libm", +] + [[package]] name = "getopts" version = "0.2.24" @@ -858,17 +1468,47 @@ dependencies = [ "weezl", ] +[[package]] +name = "gimli" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1033caf0b349c518623b5396bfb2cf0bddf44f0306d543a250e5743297aafd10" + +[[package]] +name = "half" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b43ede17f21864e81be2fa654110bf1e793774238d86ef8555c37e6519c0403" + [[package]] name = "half" version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ + "bytemuck", "cfg-if", "crunchy", + "num-traits", + "serde", "zerocopy", ] +[[package]] +name = "hash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" +dependencies = [ + "byteorder", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + [[package]] name = "hashbrown" version = "0.14.5" @@ -878,6 +1518,28 @@ dependencies = [ "ahash", ] +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2 0.2.22", + "equivalent", + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2 0.2.22", + "equivalent", + "foldhash 0.2.0", +] + [[package]] name = "hashbrown" version = "0.17.2" @@ -893,6 +1555,34 @@ dependencies = [ "hashbrown 0.14.5", ] +[[package]] +name = "heapless" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" +dependencies = [ + "hash32", + "stable_deref_trait", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "http" version = "1.5.0" @@ -938,6 +1628,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "humantime" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" + [[package]] name = "hybrid-array" version = "0.4.15" @@ -1006,6 +1702,72 @@ dependencies = [ "tracing", ] +[[package]] +name = "i_float" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "813145bb0ad5b60f55cbbf3c74cdceda1c0a9d253b35c4cc36ae0df7887cb78f" +dependencies = [ + "libm", +] + +[[package]] +name = "i_key_sort" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d73d122b937fca067feb0ad74f62388920272b27c356d4df2d0cfdd59e044cf0" + +[[package]] +name = "i_overlay" +version = "4.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dd314b4668e2b3a12508f2e125558c82a6c0a8636fa5107a900f79ce414e450" +dependencies = [ + "i_float", + "i_key_sort", + "i_shape", + "i_tree", +] + +[[package]] +name = "i_shape" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa9eac533d7509a8ab87672b60ac610c17240f9ea4851d26227689fdfe349c8" +dependencies = [ + "i_float", +] + +[[package]] +name = "i_tree" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4804bdc1dc124eb7e1aa9e144ecc04096bcf787a10a15fa44af682b51f0f6cce" + +[[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 = "icu_collections" version = "2.4.0" @@ -1156,6 +1918,50 @@ version = "1.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" +[[package]] +name = "include-flate" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f677e494e19ac4aa62375916f64b496f6b2655964c7313231c959858608cd9eb" +dependencies = [ + "include-flate-codegen", + "include-flate-compress", +] + +[[package]] +name = "include-flate-codegen" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d3749676b6129ea4cf1e75adfb280a2148f03113806cb68cd7775fdfc65edf" +dependencies = [ + "include-flate-compress", + "proc-macro-error3", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "include-flate-compress" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "476a7e4feb3325e85ca85565893517e283a1e59d3c9b695c162791dead7f004d" +dependencies = [ + "libflate", + "zstd", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -1181,6 +1987,12 @@ dependencies = [ "web-time", ] +[[package]] +name = "integer-encoding" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c00403deb17c3221a1fe4fb571b9ed0370b3dcd116553c77fa294a3d918699" + [[package]] name = "interpolate_name" version = "0.2.4" @@ -1192,12 +2004,40 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "io-uring" +version = "0.7.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "878c26bc5e45fe089ce2ca25689260c152a87ce1d7de2ca86101efeea6973932" +dependencies = [ + "bitflags", + "cfg-if", + "libc", +] + [[package]] name = "ipnet" version = "2.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "007d6e6b91097094791302ccc6cd0588e0700ddac5c6829035bcd71eff4dc433" +[[package]] +name = "irg-kvariants" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2af7c331f2536964a32b78a7d2e0963d78b42f4a76323b16cc7d94b1ddce26" +dependencies = [ + "csv", + "once_cell", + "serde", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.14.0" @@ -1207,12 +2047,44 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "jieba-macros" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "455f837e9d0255b68a712200db247c68fdad4941b72471b76bfa61c3b0c1f79f" +dependencies = [ + "phf_codegen", +] + +[[package]] +name = "jieba-rs" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6a8bbb0f77ee810f0689a30b7cec56b875751ef4ec2e74fd995613dc52b3ae1" +dependencies = [ + "bytecount", + "cedarwood", + "include-flate", + "jieba-macros", + "phf", + "rustc-hash", +] + [[package]] name = "jiff" version = "1.0.3" @@ -1336,6 +2208,30 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libflate" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "561a8da1a50e1428d3c51321dafeca849df992a5bb67720c386131234caba82e" +dependencies = [ + "adler32", + "crc32fast", + "dary_heap", + "libflate_lz77", + "no_std_io2", +] + +[[package]] +name = "libflate_lz77" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff7a10e427698aef6eef269482776debfef63384d30f13aad39a1a95e0e098fd" +dependencies = [ + "hashbrown 0.16.1", + "no_std_io2", + "rle-decode-fast", +] + [[package]] name = "libfuzzer-sys" version = "0.4.13" @@ -1346,6 +2242,12 @@ dependencies = [ "cc", ] +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "libsqlite3-sys" version = "0.30.1" @@ -1357,12 +2259,30 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[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.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + [[package]] name = "lock_api" version = "0.4.14" @@ -1370,6 +2290,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" dependencies = [ "scopeguard", + "serde", ] [[package]] @@ -1393,6 +2314,12 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "lz4_flex" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f56455fff36934a9500d69062aec1c77037179b6f0669e4d5d6b72b84722d6a3" + [[package]] name = "macro_rules_attribute" version = "0.2.3" @@ -1440,6 +2367,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + [[package]] name = "mime" version = "0.3.18" @@ -1556,12 +2492,30 @@ dependencies = [ "target-features", ] +[[package]] +name = "murmur3_32" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e7c60ee0b5e809b81d443bab6a735f9c80fe2138ebc5d758cda7b4faa2cdbd" + [[package]] name = "new_debug_unreachable" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "nix" +version = "0.31.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bc81ce8148d3b4f3274da811f11cdd824ae661ee4ef732cdb229825cf5be7f7" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "no_std_io2" version = "0.9.4" @@ -1596,6 +2550,15 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -1615,6 +2578,18 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-cmp" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63335b2e2c34fae2fb0aa2cecfd9f0832a1e24b3b32ecec612c3426d46dc8aaa" + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-derive" version = "0.4.2" @@ -1626,6 +2601,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "num-derive" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e98dc3b890f6c23a0f9d3d491a2823d0dea0fa656302a13dd225fa924112a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "num-integer" version = "0.1.47" @@ -1653,6 +2639,45 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", +] + +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + +[[package]] +name = "object" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" +dependencies = [ + "memchr", ] [[package]] @@ -1661,6 +2686,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "onig" version = "6.5.3" @@ -1689,6 +2720,28 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" +[[package]] +name = "ordered-float" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ordered-float" +version = "5.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" +dependencies = [ + "bytemuck", + "num-traits", + "rand 0.8.8", + "schemars", + "serde", +] + [[package]] name = "parking_lot" version = "0.12.5" @@ -1705,8 +2758,10 @@ version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ + "backtrace", "cfg-if", "libc", + "petgraph", "redox_syscall", "smallvec", "windows-link", @@ -1736,6 +2791,69 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "petgraph" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" +dependencies = [ + "fixedbitset", + "indexmap 2.14.2", +] + +[[package]] +name = "ph" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2fbaf8da280599aae4047ea0659a1e79cf61739bce5bdc50ca88dc7e6357060" +dependencies = [ + "aligned-vec", + "binout", + "bitm", + "dyn_size_of", + "rayon", + "seedable_hash", +] + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_shared", + "serde", +] + +[[package]] +name = "phf_codegen" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project-lite" version = "0.2.18" @@ -1785,6 +2903,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1794,6 +2918,28 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "proc-macro-error-attr3" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e564d14133360e1ae169ffde5da25881b5fa47261665b8e5713c212c27799da" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error3" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f0d4471b3436c22106b21913b1dda531558918ae9b7ec55d58aa84b43552233" +dependencies = [ + "proc-macro-error-attr3", + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -1803,6 +2949,27 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "procfs" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25485360a54d6861439d60facef26de713b1e126bf015ec8f98239467a2b82f7" +dependencies = [ + "bitflags", + "procfs-core", + "rustix 1.1.6", +] + +[[package]] +name = "procfs-core" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6401bf7b6af22f78b563665d15a22e9aef27775b79b149a66ca022468a4e405" +dependencies = [ + "bitflags", + "hex", +] + [[package]] name = "profiling" version = "1.0.18" @@ -1856,6 +3023,113 @@ version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "qdrant-edge" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf059f7c7f5145aea9b8ccfea3e6f9bcf7d0fd2440132a1489c02124473468c" +dependencies = [ + "ahash", + "aligned-vec", + "arc-swap", + "arrayvec", + "atomic_refcell", + "atomicwrites", + "bincode 1.3.3", + "bitpacking", + "bitvec", + "blink-alloc", + "bytemuck", + "byteorder", + "cc", + "charabia", + "chrono", + "core_affinity", + "crc32c", + "data-encoding", + "docopt", + "duplicate", + "ecow", + "env_logger", + "fnv", + "fs-err", + "fs4", + "fs_extra", + "futures", + "geo", + "geohash", + "half 2.7.1", + "humantime", + "indexmap 2.14.2", + "integer-encoding", + "io-uring", + "itertools 0.15.0", + "log", + "lz4_flex", + "macro_rules_attribute", + "memchr", + "memmap2", + "murmur3_32", + "nix", + "nom 8.0.0", + "num-cmp", + "num-derive 0.5.1", + "num-traits", + "num_cpus", + "once_cell", + "ordered-float 5.5.1", + "parking_lot", + "ph", + "pin-project-lite", + "procfs", + "qdrant-rust-stemmers", + "quick_cache", + "rand 0.10.4", + "rand_distr", + "rayon", + "roaring", + "rustix 1.1.6", + "schemars", + "self_cell", + "semver", + "serde", + "serde-untagged", + "serde-value", + "serde_cbor", + "serde_json", + "serde_variant", + "sha2", + "siphasher", + "slab", + "smallvec", + "strum", + "stumpalo", + "sysinfo", + "tap", + "tar", + "tempfile", + "thiserror", + "thread-priority", + "tinyvec", + "tokio", + "uuid", + "validator", + "vaporetto", + "walkdir", + "zerocopy", + "zstd", +] + +[[package]] +name = "qdrant-rust-stemmers" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69360f6ae1f89d8ec3df92a04b223b5cbfd6308bfc8f28317c8c4ac6d15658a1" +dependencies = [ + "serde", + "serde_derive", +] + [[package]] name = "qoi" version = "0.4.1" @@ -1871,6 +3145,18 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" +[[package]] +name = "quick_cache" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "403c1a912fec895cafb223201e368234842acb9220aaf08ab042ae89ba5f135c" +dependencies = [ + "equivalent", + "foldhash 0.2.0", + "hashbrown 0.17.2", + "parking_lot", +] + [[package]] name = "quinn" version = "0.11.12" @@ -1949,6 +3235,22 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core 0.6.4", + "serde", +] + [[package]] name = "rand" version = "0.9.5" @@ -1980,6 +3282,15 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "serde", +] + [[package]] name = "rand_core" version = "0.9.5" @@ -1995,6 +3306,16 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "rand_distr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d431c2703ccf129de4d45253c03f49ebb22b97d6ad79ee3ecfc7e3f4862c1d8" +dependencies = [ + "num-traits", + "rand 0.10.4", +] + [[package]] name = "rand_pcg" version = "0.10.3" @@ -2020,14 +3341,14 @@ dependencies = [ "built", "cfg-if", "interpolate_name", - "itertools", + "itertools 0.14.0", "libc", "libfuzzer-sys", "log", "maybe-rayon", "new_debug_unreachable", "noop_proc_macro", - "num-derive", + "num-derive 0.4.2", "num-traits", "paste", "profiling", @@ -2071,7 +3392,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f" dependencies = [ "either", - "itertools", + "itertools 0.14.0", "rayon", ] @@ -2085,6 +3406,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "readme-rustdocifier" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08ad765b21a08b1a8e5cdce052719188a23772bcbefb3c439f0baaf62c56ceac" + [[package]] name = "redox_syscall" version = "0.5.18" @@ -2183,6 +3510,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rle-decode-fast" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3582f63211428f83597b51b2ddb88e2a91a9d52d12831f9d08f5e624e8977422" + [[package]] name = "rmcp" version = "3.12.0" @@ -2193,7 +3526,7 @@ dependencies = [ "bytes", "futures", "http", - "indexmap", + "indexmap 2.14.2", "jiff", "libc", "percent-encoding", @@ -2212,6 +3545,33 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "roaring" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18bd8a37d17a58532776dcdf6041ce64929adca78e8489d5cacbafe99229d3e1" +dependencies = [ + "bytemuck", + "byteorder", +] + +[[package]] +name = "robust" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e27ee8bb91ca0adcf0ecb116293afa12d393f9c2b9b9cd54d33e8078fe19839" + +[[package]] +name = "rstar" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "421400d13ccfd26dfa5858199c30a5d76f9c54e0dba7575273025b43c5175dbb" +dependencies = [ + "heapless", + "num-traits", + "smallvec", +] + [[package]] name = "rusqlite" version = "0.32.1" @@ -2261,6 +3621,12 @@ dependencies = [ "walkdir", ] +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + [[package]] name = "rustc-hash" version = "2.1.3" @@ -2276,6 +3642,32 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.46" @@ -2383,6 +3775,35 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "chrono", + "dyn-clone", + "indexmap 1.9.3", + "indexmap 2.14.2", + "schemars_derive", + "serde", + "serde_json", + "url", + "uuid", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.119", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -2412,11 +3833,31 @@ dependencies = [ "libc", ] +[[package]] +name = "seedable_hash" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47190540123956611cf01db81ad6dee21ca70e1d94a8ff5a962cf6d93b217c7c" +dependencies = [ + "wyhash", + "xxhash-rust", +] + +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + [[package]] name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] [[package]] name = "serde" @@ -2428,6 +3869,38 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-untagged" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" +dependencies = [ + "erased-serde", + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "serde-value" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" +dependencies = [ + "ordered-float 2.10.1", + "serde", +] + +[[package]] +name = "serde_cbor" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5" +dependencies = [ + "half 1.8.3", + "serde", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -2448,12 +3921,25 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "serde_json" version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ + "foldhash 0.2.0", + "indexmap 2.14.2", "itoa", "memchr", "serde", @@ -2484,6 +3970,15 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_variant" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a0068df419f9d9b6488fdded3f1c818522cdea328e02ce9d9f147380265a432" +dependencies = [ + "serde", +] + [[package]] name = "sha2" version = "0.11.1" @@ -2510,6 +4005,12 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "sif-itree" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7f45b8998ced5134fb1d75732c77842a3e888f19c1ff98481822e8fbfbf930b" + [[package]] name = "signal-hook-registry" version = "1.4.8" @@ -2551,12 +4052,24 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + [[package]] name = "slab" version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "slice-group-by" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "826167069c09b99d56f31e9ae5c99049e932a98c9dc2dac47645b08dbbf76ba7" + [[package]] name = "smallvec" version = "1.16.6" @@ -2628,6 +4141,8 @@ dependencies = [ "rust-embed", "serde", "serde_json", + "strata-memory", + "tempfile", "thiserror", "tokenizers", "tokio", @@ -2638,12 +4153,61 @@ dependencies = [ "ureq", ] +[[package]] +name = "strata-memory" +version = "0.1.0" +dependencies = [ + "qdrant-edge", + "serde", + "serde_json", + "tempfile", + "thiserror", + "ureq", +] + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "stumpalo" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7087fbef8befbb581d82b2040acf5aae5c851f60427adfcc30fefd54124fb62" +dependencies = [ + "readme-rustdocifier", + "rustc_version", +] + [[package]] name = "subtle" version = "2.6.1" @@ -2692,12 +4256,55 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "sysinfo" +version = "0.39.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2071df9448915b71c4fe6d25deaf1c22f12bd234f01540b77312bb8e41361e6" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", +] + [[package]] name = "target-features" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "2.0.21" @@ -2718,6 +4325,20 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "thread-priority" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d2e834949be5111506bb252643498af1514f600d9e1dceedaa42afae155b67f" +dependencies = [ + "bitflags", + "cfg-if", + "libc", + "log", + "rustversion", + "windows", +] + [[package]] name = "thread_local" version = "1.1.10" @@ -2735,12 +4356,42 @@ checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" dependencies = [ "fax", "flate2", - "half", + "half 2.7.1", "quick-error", "weezl", "zune-jpeg", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tinystr" version = "0.8.5" @@ -2765,13 +4416,13 @@ checksum = "7afbf6e88718afcc138bad01d6ccc3051dbbc3b2ce9793d8b8a3aeb610969cfc" dependencies = [ "ahash", "compact_str", - "daachorse", + "daachorse 3.0.3", "dary_heap", "derive_builder", "esaxx-rs", "getrandom 0.3.4", "indicatif", - "itertools", + "itertools 0.14.0", "log", "macro_rules_attribute", "monostate", @@ -2967,6 +4618,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + [[package]] name = "typenum" version = "1.20.1" @@ -3039,6 +4696,12 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" +[[package]] +name = "unty" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" + [[package]] name = "ureq" version = "3.5.2" @@ -3046,11 +4709,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" dependencies = [ "base64 0.23.1", + "cookie_store", "flate2", "log", "percent-encoding", "rustls", "rustls-pki-types", + "serde", + "serde_json", "ureq-proto", "utf8-zero", "webpki-roots", @@ -3095,12 +4761,30 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "utf_types" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + [[package]] name = "v_frame" version = "0.3.9" @@ -3112,12 +4796,52 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "validator" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43fb22e1a008ece370ce08a3e9e4447a910e92621bb49b85d6e48a45397e7cfa" +dependencies = [ + "idna", + "once_cell", + "regex", + "serde", + "serde_derive", + "serde_json", + "url", + "validator_derive", +] + +[[package]] +name = "validator_derive" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240e4b81c20a1d6d50d1d7265c658dfbd204e8b9ac4d80f3c931f39462196335" +dependencies = [ + "darling 0.23.0", + "proc-macro-error3", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "valuable" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "vaporetto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d7437bd3d45100e1ed1a284187ce4e9ee863f1fdac97b7eaa614623741464c6" +dependencies = [ + "bincode 2.0.1", + "daachorse 1.0.1", + "hashbrown 0.15.5", +] + [[package]] name = "vcpkg" version = "0.2.15" @@ -3130,6 +4854,12 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "virtue" +version = "0.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "051eb1abcf10076295e815102942cc58f9d5e3b4560e46e53c21e8ff6f3af7b1" + [[package]] name = "walkdir" version = "2.5.1" @@ -3276,6 +5006,31 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" +[[package]] +name = "whatlang" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5e8f38b596e2a359b755342473520a99421e43658548c79489ee221b728c107" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + [[package]] name = "winapi-util" version = "0.1.11" @@ -3285,12 +5040,113 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[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-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[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-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[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.52.0" @@ -3325,6 +5181,15 @@ dependencies = [ "windows_x86_64_msvc", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -3385,6 +5250,30 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "wyhash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf6e163c25e3fac820b4b453185ea2dea3b6a3e0a721d4d23d75bd33734c295" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "xxhash-rust" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40de123dbb523ebcc00d61ec01840ad192578afc378d859f3429caa38308fad5" + [[package]] name = "y4m" version = "0.8.0" @@ -3506,6 +5395,34 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zstd" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465cb081cac3a28a84ef547702dba1fe0f4a9f22e4e57a0b675ceee028c2af80" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "8.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b09bddd92c53b91833f4df03e0ea07e02d8367cfcd15a3b9acda94fc273f793" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.2.0+zstd.1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160" +dependencies = [ + "cc", + "pkg-config", +] + [[package]] name = "zune-core" version = "0.5.3" diff --git a/Cargo.toml b/Cargo.toml index db575b8..467eaea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,14 @@ edition = "2021" description = "Rust control layer for the Strata inference engine: OpenAI-compatible HTTP API over the engine's line protocol" license = "MIT" +[workspace] +# strata-ctl is both the root package and the workspace root. `strata-memory` is a +# co-located crate (promotable to its own repo later without a rewrite). `upstream/` +# is the reference Strata checkout and must never be pulled into the build. +members = ["strata-memory"] +exclude = ["upstream"] +resolver = "2" + [dependencies] anyhow = "1" thiserror = "2" @@ -29,8 +37,21 @@ rust-embed = "8" pulldown-cmark = "0.13.6" pulldown-latex = "0.8.0" rmcp = { version = "3.12.0", default-features = false, features = ["client", "transport-streamable-http-client-reqwest", "reqwest"] } +# Semantic memory capability (embedder seam + Qdrant Edge index + symbolic vector +# workspace). Co-located workspace crate; strata-ctl is its consumer. +strata-memory = { path = "strata-memory" } [dev-dependencies] http-body-util = "0.1.5" +tempfile = "3" tokio = { version = "1", features = ["full"] } tower = { version = "0.5", features = ["util"] } + +# Keep FULL debuginfo, but in separate .dwo files written once per crate instead of +# duplicated into every linked binary. This workspace statically links a heavy tree +# (qdrant-edge, tokenizers, crypto/regex natives) into 50+ test/example binaries; with +# embedded debuginfo each link wrote hundreds of MB, hammering the NVMe. `unpacked` +# preserves IDE debugging while cutting per-link write volume dramatically. Applies +# to the `test` profile too (it inherits `dev`). +[profile.dev] +split-debuginfo = "unpacked" diff --git a/README.md b/README.md index f811c1e..69e8eb1 100644 --- a/README.md +++ b/README.md @@ -201,17 +201,20 @@ advanced settings to grow on top. **Framework root.** All persistent state lives under `~/.strata-ctl/` (the Linux user's home; override with `workspace_root`), separated by content type: `sessions//` (agent workspace folders), `data/` (the SQLite database), -`uploads/` (uploaded files). A legacy DB at `~/.config/strata-ctl/sessions.db` is +`uploads/` (uploaded files), `memory/` (the rebuildable semantic index). A legacy +DB at `~/.config/strata-ctl/sessions.db` is copied into `data/` once on first run (the original is left in place). ## Agent mode -The GUI model can **act**, not just chat. Tools are **always on** — there is no -toggle, because the framework could not function without them. The agent's tool +The GUI model can **act**, not just chat. The core tools are **always on** — there +is no toggle, because the framework could not function without them. The agent's tool surface is small and deliberate: **`shell_exec`** (a shell is universal: file ops, programs, system inspection, web via curl, git, …), **`notepad`** (agent-curated persistent memory, see below) and **`share_file`** (hand the user a download link -for a file on its filesystem, see below). A bounded server-side loop drives +for a file on its filesystem, see below). A session that opts into **semantic +memory** additionally gets `remember` / `recall` / `forget` (see **Semantic vector +memory** below). A bounded server-side loop drives `model → shell_exec → result → model → … → final answer`, persisting the whole trajectory and streaming progress events — `delta` (the model's thinking and final answer, token by token), `tool_call` / `tool_result` (every command and its output @@ -264,6 +267,12 @@ shared JSON config ──► InklingFormatter ──► Engine supervisor ── per-turn `[SPEAKER]` provenance (prompt-only). - `render` — server-side Markdown → sanitized HTML with LaTeX → native MathML (`pulldown-cmark` + `pulldown-latex`) for assistant replies. +- `agent` — the bounded server-side tool loop: `shell_exec`, `notepad`, + `share_file`, MCP connectors and the per-session memory tools. +- `memory` — the semantic memory service: the authoritative `Store` plus a + rebuildable vector index, kept in step and fail-open. Backed by the + **`strata-memory`** workspace crate (swappable `Embedder` trait, HTTP BGE-M3 + client, embedded Qdrant Edge index). ## Building and running @@ -290,8 +299,9 @@ The config is the same JSON the other Strata tools use. Keys acted on here inclu `max_new` (default generation budget, see below), `sampling`, `api_key`, `allowed_hosts`, `db_path` (GUI session database), `workspace_root` (framework root), `system_prompt` (general default), `language` (UI/prompt catalog, default -`it`), and the optional `startup_timeout_secs` / `silence_timeout_secs`. Everything -else (`arch`, `mcp_servers`, `cors_origins`, …) is preserved untouched and reported +`it`), `memory_embedder_url` (semantic-memory embedder endpoint, default the free +Altair instance), and the optional `startup_timeout_secs` / `silence_timeout_secs`. +Everything else (`arch`, `mcp_servers`, `cors_origins`, …) is preserved untouched and reported as ignored — unknown keys never break startup. **Generation budget (`max_new`).** When neither the request nor the session sets @@ -318,7 +328,8 @@ later adaptation round. ## Status -Working and tested (191 tests, plus 3 real-file tests run on demand). Text, images, +Working and tested (238 tests passing; 6 ignored tests exercise the real engine, +embedder or files and run on demand). Text, images, the full client-side tool loop, the Anthropic endpoint, the web GUI (session context, streaming, stats, **file/image upload**, **file download** (`share_file` → containment-checked attachment endpoint), assistant **Markdown/LaTeX @@ -330,7 +341,10 @@ verified against the real chat template. A per-session **notepad** (agent-curate `` entries via the `notepad` tool) and a **sliding DIALOG window** (message-count main area + buffer headroom, stepped KV-cache-friendly eviction at turn boundaries, `window_start` persisted per session, full history never deleted) -are implemented and dogfooded live. A best-effort **cache pre-warm** (`GEN 0` over +are implemented and dogfooded live. Per-session **semantic memory** +(`remember` / `recall` / `forget` over an embedded Qdrant Edge index with BGE-M3 +embeddings) is implemented and validated live against the Altair embedder. A +best-effort **cache pre-warm** (`GEN 0` over the next turn's shared prefix during idle GPU time) hides the re-prefill on a pending window rotation **or a notepad change** (pre-warm-on-change: the model always sees a fresh notepad, no frozen header, no schema migration). The joint @@ -365,22 +379,41 @@ routing, images via Vision) work. Per-tool host/container sandboxing was ## Roadmap -**Important TODO (suspended) — semantic vector memory.** A Qoder-style vector -database giving the agent long-term, cross-session semantic recall, useful well -beyond coding: embed and index conversation chunks, session notes, uploaded -documents and learned facts, then retrieve by similarity to inject the relevant -context into a turn, plus explicit *remember* / *semantic search* tools. -**Suspended on purpose** while we refine what already ships: the embedder/store -choice is costly to reverse, the leading candidate (vetta / BGE-M3) emits extra -modalities this application may not use and its suitability is unverified — so -the decision stays open rather than rushed. +### Semantic vector memory — implemented -Decided so far — requirements, not products: +The agent has long-term **semantic memory**: explicit `remember` / `recall` / +`forget` tools backed by dense-vector search, shipped as the `strata-memory` +workspace crate plus the control-layer seam (`src/memory.rs`). The ratified +choices: -- **One general engine + one general embedder.** A single multilingual, - domain-agnostic embedding model and a single vector engine must decently cover - any need; specialization lives *above* the index, never in a second engine or - model. +- **Embedder: BGE-M3 dense (1024-d)** via the team's `vetta-embedder` over HTTP + (`memory_embedder_url`, default the free Altair instance at + `http://192.168.50.18:8091`; C++/ggml, no Python/ONNX, no model bundled). The + `Embedder` trait keeps the backend swappable — an in-process embedder can + replace HTTP later without touching callers. Chosen after a live **fitness + probe** (representative memory corpus, labeled positive/negative queries: + top-1 20/20, MRR 1.000, clean positive/negative separation), which also + calibrated the default recall threshold to **0.45** cosine. +- **Index: Qdrant Edge** (`qdrant-edge`, embedded in-process — no server, single + binary preserved) under `~/.strata-ctl/memory/`. The SQLite `Store` stays + **authoritative**: the shard is a disposable semantic layer, rebuilt from the + Store whenever the persisted model-id sidecar (`strata_model.json`) mismatches + the current embedder — swapping embedders never mixes incompatible vectors. +- **Fail-open.** `remember` persists to the Store first; if the embedder is + unreachable, indexing is deferred and reconciled on the next open. `recall` + falls back to a keyword scan of the Store, so memory stays useful offline. + Vectors never leave the service — the model sees text + score only. +- **Per-session, one-way opt-in.** Memory is off by default (casual chat needs + none); each session's memories are **scoped to its id** — recall and forget + never cross sessions. Enabling it (GUI checkbox or `PATCH /api/sessions/{id}`) + is an **irreversible latch** like `name_locked`, so indexed memories are never + silently orphaned, and it requires the embedder to be reachable. The memory + tools are declared to the model only on memory-enabled sessions. + +Still on the roadmap for memory: + +- **Common / cross-session memory.** A shared scope on top of the per-session + one, when the isolation model has proven itself in use. - **Layered directives.** An always-on **common core** (knowledge lifecycle: recall when relevant, record durable lessons, verify against current evidence, one topic per memory, prune duplicates) plus **enable-able domain guideline @@ -389,28 +422,13 @@ Decided so far — requirements, not products: carries structured config (categories/tags, chunking strategy, retrieval filters/boosts, exposed tools) so the same general engine serves specialized retrieval. Packs integrate with the per-session settings (copy-on-create) and - never override the core (core > pack). -- **Per-session, one-way opt-in.** Vector memory is off by default (casual chat - needs none); enabling it for a session is **irreversible** (a latch like - `name_locked`), so indexed memories are never silently orphaned by a later - disable. Enabling requires the embedder to be reachable. - -Candidates under evaluation — the concrete engine / embedder / store choice is -**still open**, to be settled against the requirements above when we implement: - -- **Embedder candidate: the team's `vetta-embedder`** (BGE-M3 dense 1024-d + - learned-sparse + ColBERT + a BGE-Reranker-v2-m3 cross-encoder sidecar), repo - `vetta-semantics`, already deployed on Linux hosts at `:8091` (C++/ggml, Vulkan - with CPU fallback, no Python/ONNX). Probed live: `/embed` and `/rerank` behave - correctly and multilingually; it would be reached over HTTP like the engine, so - no model is bundled. A strong candidate, **not yet chosen**. Alternative: a - small bundled multilingual embedder (ONNX/candle) if zero external services is - ever required. -- **Store candidate: sqlite-vec** inside the existing SQLite behind the `Store` - trait (dense KNN + metadata columns; recall → rerank → inject), keeping memory - co-located and transactional with sessions (single binary). Alternates behind - the same seam: the team's Qdrant (used by Iris) and the planned ArangoDB - (documents + vectors + search). + never override the core (core > pack). For now the tool guidance lives in the + tool declarations themselves; a dedicated prompt section will follow the + model's own feedback from real use. +- **One general engine + one general embedder** stays the rule: a single + multilingual, domain-agnostic embedding model and a single vector engine must + decently cover any need; specialization lives *above* the index, never in a + second engine or model. ### Sliding context window + per-session notepad @@ -481,8 +499,8 @@ policy ships first), common/cross-session memories, a working-memory reference a recap is out of scope**: summarizing what slides out needs an autonomous background agent, whereas strata-ctl is reactive — the agent-curated notepad plus deterministic truncation cover the resume anchor without a curator. The deep-retrieval complement -is the suspended semantic vector memory above; a simpler lexical recall over the -retained SQLite history can come first. +is the semantic vector memory above (implemented); a simpler lexical recall over +the retained SQLite history can still come as a lighter addition. ### Client surfaces (under consideration, not scheduled) diff --git a/locales/en.json b/locales/en.json index 551a76d..e68c47c 100644 --- a/locales/en.json +++ b/locales/en.json @@ -7,6 +7,8 @@ "error.name_locked": "The session name is immutable after the first interaction.", "error.name_empty": "The name must not be empty.", "error.session_not_found": "Session not found.", + "error.memory_unavailable": "Semantic memory is not available on this server.", + "error.memory_embedder_unreachable": "Cannot enable memory: the embedder is unreachable.", "upload.bad_base64": "Invalid file data (base64).", "upload.empty": "The file is empty.", "upload.too_large": "The file exceeds the maximum allowed size.", diff --git a/locales/it.json b/locales/it.json index 44e706c..11c090b 100644 --- a/locales/it.json +++ b/locales/it.json @@ -7,6 +7,8 @@ "error.name_locked": "Il nome della sessione è immutabile dopo la prima interazione.", "error.name_empty": "Il nome non può essere vuoto.", "error.session_not_found": "Sessione non trovata.", + "error.memory_unavailable": "La memoria semantica non è disponibile su questo server.", + "error.memory_embedder_unreachable": "Impossibile attivare la memoria: l'embedder non è raggiungibile.", "upload.bad_base64": "Dati del file non validi (base64).", "upload.empty": "Il file è vuoto.", "upload.too_large": "Il file supera la dimensione massima consentita.", diff --git a/src/agent/memory.rs b/src/agent/memory.rs new file mode 100644 index 0000000..988abee --- /dev/null +++ b/src/agent/memory.rs @@ -0,0 +1,400 @@ +//! The agent's long-term semantic memory tools: `remember`, `recall`, `forget`. +//! +//! These sit on top of [`crate::memory::MemoryService`] (authoritative Store + +//! rebuildable Qdrant Edge index). The model only ever sees TEXT + a relevance +//! score — never raw vectors (the symbolic-vector principle). Results are +//! rendered compactly and bounded so recall cannot blow up the context window. +//! +//! Unlike the per-session notepad (single-task state), memory is durable facts, +//! decisions, preferences and pitfalls worth recalling later. It is PER-SESSION: +//! each session remembers/recalls only its own pool (the framework forces the +//! record scope to the session id; the model never chooses it). A shared/common +//! memory across sessions is a later capability. + +use std::sync::Arc; + +use serde_json::{json, Value as Json}; + +use crate::memory::{MemoryService, RememberInput}; + +/// Default recall breadth and relevance floor (cosine). The floor is calibrated +/// from the BGE-M3 fitness probe on our content: true matches scored >=0.52 while +/// unrelated queries peaked at 0.42, so 0.45 keeps the hits and rejects the noise. +/// The model can still tune `threshold` per query. +const DEFAULT_TOP_K: usize = 5; +const DEFAULT_THRESHOLD: f32 = 0.45; +/// Per-hit content cap in the rendered result (unicode-aware), so one long +/// memory cannot dominate the context. +const MAX_HIT_CONTENT_CHARS: usize = 400; + +/// The three memory tool declarations, offered when the service is available. +pub fn memory_tools() -> Vec { + vec![ + remember_declaration(), + recall_declaration(), + forget_declaration(), + ] +} + +pub fn remember_declaration() -> Json { + json!({ + "type": "function", + "function": { + "name": "remember", + "description": "Save a durable fact, decision, preference or pitfall to this session's \ + long-term semantic memory (survives the sliding context window; private to this \ + session). Use for knowledge worth recalling later, NOT single-task ephemera (use \ + the notepad for that). `content` is required and should be self-contained; \ + `category` groups related memories (e.g. user_preference, project_fact, decision, \ + pitfall). Returns the new memory id.", + "parameters": { + "type": "object", + "properties": { + "content": { + "type": "string", + "description": "The memory text to store (required). Concise and self-contained." + }, + "title": { + "type": "string", + "description": "Short label; defaults to the first line of content." + }, + "category": { + "type": "string", + "description": "Grouping label (e.g. user_preference, project_fact, decision, pitfall). Defaults to 'general'." + }, + "keywords": { + "type": "array", + "items": { "type": "string" }, + "description": "Optional search keywords." + } + }, + "required": ["content"] + } + } + }) +} + +pub fn recall_declaration() -> Json { + json!({ + "type": "function", + "function": { + "name": "recall", + "description": "Search this session's long-term semantic memory by meaning. Returns \ + the most relevant memories as text with a relevance score (never raw vectors). Use \ + before answering questions that may depend on past facts, decisions or preferences. \ + `query` is required; optionally filter by category and tune top_k/threshold.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "What to look for, phrased naturally (required)." + }, + "top_k": { + "type": "integer", + "description": "Max results (default 5, clamped 1..20)." + }, + "category": { + "type": "string", + "description": "Restrict to this category (optional)." + }, + "threshold": { + "type": "number", + "description": "Minimum cosine relevance 0..1 (default 0.45)." + } + }, + "required": ["query"] + } + } + }) +} + +pub fn forget_declaration() -> Json { + json!({ + "type": "function", + "function": { + "name": "forget", + "description": "Delete a memory by its id (as returned by remember/recall). Use to \ + remove outdated or incorrect memories. `id` is required.", + "parameters": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The memory id to delete (required)." + } + }, + "required": ["id"] + } + } + }) +} + +/// Execute a memory tool call, returning the text the model reads. All Store + +/// index work runs off the async runtime (the service is sync). +pub async fn execute( + memory: &Arc, + session_id: &str, + name: &str, + args: &Json, +) -> String { + let mem = memory.clone(); + let scope = session_id.to_string(); + let name = name.to_string(); + let args = args.clone(); + let res = tokio::task::spawn_blocking(move || match name.as_str() { + "remember" => do_remember(&mem, &scope, &args), + "recall" => do_recall(&mem, &scope, &args), + "forget" => do_forget(&mem, &scope, &args), + other => Ok(format!("error: unknown memory tool '{other}'")), + }) + .await; + match res { + Ok(Ok(msg)) => msg, + Ok(Err(e)) => format!("error: {e}"), + Err(e) => format!("error: memory task failed: {e}"), + } +} + +fn do_remember(mem: &MemoryService, scope: &str, args: &Json) -> anyhow::Result { + let content = str_arg(args, "content").unwrap_or_default(); + if content.trim().is_empty() { + return Ok("error: remember requires non-empty 'content'".into()); + } + let title = str_arg(args, "title").unwrap_or_else(|| first_line(&content)); + let category = str_arg(args, "category").unwrap_or_else(|| "general".into()); + let keywords = args + .get("keywords") + .and_then(|v| v.as_array()) + .map(|a| { + a.iter() + .filter_map(|v| v.as_str().map(|s| s.to_string())) + .collect() + }) + .unwrap_or_default(); + let rec = mem.remember(RememberInput { + category: category.clone(), + title, + content, + keywords, + scope: scope.to_string(), + source: "agent".into(), + })?; + Ok(format!("Saved memory {} (category={category}).", rec.id)) +} + +fn do_recall(mem: &MemoryService, scope: &str, args: &Json) -> anyhow::Result { + let query = str_arg(args, "query").unwrap_or_default(); + if query.trim().is_empty() { + return Ok("error: recall requires non-empty 'query'".into()); + } + let top_k = args + .get("top_k") + .and_then(|v| v.as_u64()) + .map(|n| (n as usize).clamp(1, 20)) + .unwrap_or(DEFAULT_TOP_K); + let threshold = args + .get("threshold") + .and_then(|v| v.as_f64()) + .map(|t| (t as f32).clamp(0.0, 1.0)) + .unwrap_or(DEFAULT_THRESHOLD); + let category = str_arg(args, "category"); + let hits = mem.recall(&query, top_k, threshold, category.as_deref(), Some(scope))?; + if hits.is_empty() { + return Ok("No matching memories.".into()); + } + let mut out = format!( + "Found {} memor{}:\n", + hits.len(), + if hits.len() == 1 { "y" } else { "ies" } + ); + for (i, hit) in hits.iter().enumerate() { + let r = &hit.record; + out.push_str(&format!( + "{}. [{:.2}] ({}) {}: {}\n id: {}\n", + i + 1, + hit.score, + r.category, + r.title, + truncate_chars(&r.content, MAX_HIT_CONTENT_CHARS), + r.id + )); + } + Ok(out) +} + +fn do_forget(mem: &MemoryService, scope: &str, args: &Json) -> anyhow::Result { + let id = str_arg(args, "id").unwrap_or_default(); + if id.trim().is_empty() { + return Ok("error: forget requires non-empty 'id'".into()); + } + if mem.forget_in_scope(&id, scope)? { + Ok(format!("Forgot memory {id}.")) + } else { + Ok(format!("No memory {id} in this session (nothing removed).")) + } +} + +/// A trimmed, non-empty string argument (None when absent/blank). +fn str_arg(args: &Json, key: &str) -> Option { + args.get(key) + .and_then(|v| v.as_str()) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) +} + +fn first_line(s: &str) -> String { + truncate_chars(s.lines().next().unwrap_or(s), 80) +} + +fn truncate_chars(s: &str, max: usize) -> String { + if s.chars().count() <= max { + return s.to_string(); + } + let mut out: String = s.chars().take(max).collect(); + out.push('…'); + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::store::{SqliteStore, Store}; + use strata_memory::{EmbedError, Embedder, MemoryIndex}; + + struct StubEmbedder; + impl Embedder for StubEmbedder { + fn embed(&self, texts: &[&str]) -> Result>, EmbedError> { + Ok(texts + .iter() + .map(|t| { + let mut v = vec![0.0f32; 4]; + // Cheap deterministic hashing into a unit-ish vector so + // identical texts match and different ones mostly don't. + for (i, b) in t.bytes().enumerate() { + v[i % 4] += b as f32; + } + let n = v.iter().map(|x| x * x).sum::().sqrt(); + if n > 0.0 { + for x in &mut v { + *x /= n; + } + } + v + }) + .collect()) + } + fn dim(&self) -> usize { + 4 + } + fn model_id(&self) -> &str { + "stub" + } + } + + fn service() -> (Arc, tempfile::TempDir) { + let tmp = tempfile::tempdir().unwrap(); + let store: Arc = Arc::new(SqliteStore::open_in_memory().unwrap()); + let index = MemoryIndex::open(tmp.path(), 4, "stub", Arc::new(StubEmbedder)).unwrap(); + (Arc::new(MemoryService::from_index(store, index)), tmp) + } + + #[test] + fn declarations_shape() { + let tools = memory_tools(); + assert_eq!(tools.len(), 3); + assert_eq!(tools[0]["function"]["name"], "remember"); + assert_eq!(tools[1]["function"]["name"], "recall"); + assert_eq!(tools[2]["function"]["name"], "forget"); + assert_eq!(tools[0]["function"]["parameters"]["required"][0], "content"); + assert_eq!(tools[1]["function"]["parameters"]["required"][0], "query"); + } + + #[tokio::test] + async fn remember_then_recall_roundtrip() { + let (mem, _tmp) = service(); + let out = execute( + &mem, + "sess_a", + "remember", + &json!({"content":"Il gatto nero salta sul tavolo","category":"facts"}), + ) + .await; + assert!(out.contains("Saved memory"), "{out}"); + let out = execute( + &mem, + "sess_a", + "recall", + &json!({"query":"Il gatto nero salta sul tavolo"}), + ) + .await; + assert!(out.contains("gatto"), "{out}"); + assert!(out.contains("id:"), "{out}"); + // The rendered result must NOT leak a raw vector array. + assert!(!out.contains("[0."), "no vector floats in context: {out}"); + } + + #[tokio::test] + async fn per_session_isolation() { + let (mem, _tmp) = service(); + // Session A remembers a fact. + let out = execute( + &mem, + "sess_a", + "remember", + &json!({"content":"Il gatto nero salta sul tavolo"}), + ) + .await; + let id = out.split_whitespace().nth(2).unwrap().to_string(); + // Session B cannot recall it (different scope). + let out = execute( + &mem, + "sess_b", + "recall", + &json!({"query":"Il gatto nero salta sul tavolo"}), + ) + .await; + assert!(out.contains("No matching memories"), "{out}"); + // Session B cannot forget A's record by id. + let out = execute(&mem, "sess_b", "forget", &json!({"id": id})).await; + assert!(out.contains("nothing removed"), "{out}"); + // A still recalls its own. + let out = execute( + &mem, + "sess_a", + "recall", + &json!({"query":"Il gatto nero salta sul tavolo"}), + ) + .await; + assert!(out.contains("gatto"), "{out}"); + } + + #[tokio::test] + async fn validation_errors() { + let (mem, _tmp) = service(); + assert!(execute(&mem, "sess_a", "remember", &json!({})) + .await + .contains("content")); + assert!(execute(&mem, "sess_a", "recall", &json!({})) + .await + .contains("query")); + assert!(execute(&mem, "sess_a", "forget", &json!({})) + .await + .contains("id")); + assert!(execute(&mem, "sess_a", "bogus", &json!({})) + .await + .contains("unknown")); + } + + #[tokio::test] + async fn forget_roundtrip() { + let (mem, _tmp) = service(); + let out = execute(&mem, "sess_a", "remember", &json!({"content":"alpha"})).await; + // Extract the id from "Saved memory (...)". + let id = out.split_whitespace().nth(2).unwrap().to_string(); + let out = execute(&mem, "sess_a", "forget", &json!({"id": id})).await; + assert!(out.contains("Forgot"), "{out}"); + let out = execute(&mem, "sess_a", "forget", &json!({"id": id})).await; + assert!(out.contains("nothing removed"), "{out}"); + } +} diff --git a/src/agent/mod.rs b/src/agent/mod.rs index 769a62b..1841fb9 100644 --- a/src/agent/mod.rs +++ b/src/agent/mod.rs @@ -9,6 +9,7 @@ //! [`run_loop`] is pure orchestration — generic over the "model step" — so it is //! testable without the engine and independent of the concrete runner. +pub mod memory; pub mod notepad; pub mod share; pub mod shell; @@ -88,6 +89,7 @@ async fn execute_tool( tc: &ToolCall, default_cwd: Option<&str>, workspace_root: Option<&std::path::Path>, + memory: Option<&Arc>, ) -> String { let args: Json = match serde_json::from_str(&tc.function.arguments) { Ok(v) => v, @@ -107,6 +109,10 @@ async fn execute_tool( } "notepad" => notepad::execute(store, session_id, &args).await, "share_file" => share::execute(session_id, &args, default_cwd, workspace_root).await, + "remember" | "recall" | "forget" => match memory { + Some(m) => memory::execute(m, session_id, &tc.function.name, &args).await, + None => "error: semantic memory is not available".into(), + }, name if mcp::is_mcp_tool(name) => execute_mcp(store, session_id, name, &args).await, other => format!("error: unknown tool '{other}'"), } @@ -214,6 +220,9 @@ pub struct LoopContext { /// Parent of the per-session folders and the shared uploads dir; the second /// root `share_file` may expose files from. None in tests without a workspace. pub workspace_root: Option, + /// Long-term semantic memory (remember/recall/forget). None when the memory + /// service could not be opened or in tests without memory. + pub memory: Option>, pub max_iters: usize, pub progress: Option>, } @@ -239,6 +248,7 @@ where store, default_cwd, workspace_root, + memory, max_iters, progress, } = ctx; @@ -336,6 +346,7 @@ where tc, default_cwd.as_deref(), workspace_root.as_deref(), + memory.as_ref(), ) .await; emit( @@ -494,6 +505,7 @@ mod tests { store: store.clone(), default_cwd: None, workspace_root: None, + memory: None, max_iters: 8, progress: Some(tx), }, @@ -575,6 +587,7 @@ mod tests { store, default_cwd: None, workspace_root: None, + memory: None, max_iters: 3, progress: None, }, @@ -607,6 +620,7 @@ mod tests { store: store.clone(), default_cwd: None, workspace_root: None, + memory: None, max_iters: MAX_ITERS, progress: None, }, @@ -642,7 +656,7 @@ mod tests { arguments: "{}".into(), }, }; - let out = execute_tool(&runner, &store, &sess.id, &tc, None, None).await; + let out = execute_tool(&runner, &store, &sess.id, &tc, None, None, None).await; assert!(out.contains("unknown tool")); } @@ -681,14 +695,33 @@ mod tests { &call("mcp__gmail__gmail_send"), None, None, + None, ) .await; assert!(out.contains("not enabled"), "{out}"); // An unknown connector is refused. - let out = execute_tool(&runner, &store, &sess.id, &call("mcp__nope__x"), None, None).await; + let out = execute_tool( + &runner, + &store, + &sess.id, + &call("mcp__nope__x"), + None, + None, + None, + ) + .await; assert!(out.contains("unknown MCP connector"), "{out}"); // A malformed namespaced name is refused. - let out = execute_tool(&runner, &store, &sess.id, &call("mcp__gmail"), None, None).await; + let out = execute_tool( + &runner, + &store, + &sess.id, + &call("mcp__gmail"), + None, + None, + None, + ) + .await; assert!(out.contains("malformed"), "{out}"); } @@ -738,6 +771,7 @@ mod tests { store: store.clone(), default_cwd: None, workspace_root: None, + memory: None, max_iters: 8, progress: None, }, @@ -803,6 +837,7 @@ mod tests { store: store.clone(), default_cwd: Some("/tmp".into()), workspace_root: None, + memory: None, max_iters: 8, progress: None, }, diff --git a/src/api/routes.rs b/src/api/routes.rs index fd89da3..a019111 100644 --- a/src/api/routes.rs +++ b/src/api/routes.rs @@ -30,6 +30,7 @@ pub fn router_with_auth(service: ChatService, auth: AuthConfig) -> Router { service, store: None, workspace_root: default_workspace_root(), + memory: None, }, auth, ) @@ -42,12 +43,14 @@ pub fn router_with_store( store: Arc, auth: AuthConfig, workspace_root: std::path::PathBuf, + memory: Option>, ) -> Router { build_router( AppState { service, store: Some(store), workspace_root, + memory, }, auth, ) @@ -217,6 +220,9 @@ pub(crate) struct AppState { pub(crate) service: ChatService, pub(crate) store: Option>, pub(crate) workspace_root: std::path::PathBuf, + /// Long-term semantic memory service (remember/recall/forget). None when it + /// could not be opened; the agent then runs without the memory tools. + pub(crate) memory: Option>, } /// An OpenAI error with the HTTP status the code implies. diff --git a/src/api/sessions.rs b/src/api/sessions.rs index df1d8cd..6db2312 100644 --- a/src/api/sessions.rs +++ b/src/api/sessions.rs @@ -164,7 +164,27 @@ pub(crate) async fn patch_session( }) .await?; } - if let Some(settings) = body.settings { + if let Some(mut settings) = body.settings { + // One-way memory latch: once enabled it can never be turned off (OR merge), + // so even a partial settings payload cannot accidentally disable it. + let want_on = settings.memory_enabled; + settings.memory_enabled = sess.settings.memory_enabled || want_on; + // A FRESH enable requires the memory service AND a reachable embedder, so + // the latch only flips on when the capability actually works. + if want_on && !sess.settings.memory_enabled { + let Some(m) = st.memory.clone() else { + return Err(Error::bad_request(t("error.memory_unavailable", &[]))); + }; + let ok = tokio::task::spawn_blocking(move || m.embedder_reachable()) + .await + .unwrap_or(false); + if !ok { + return Err(Error::bad_request(t( + "error.memory_embedder_unreachable", + &[], + ))); + } + } with_store(&st, move |s| s.update_settings(&id, &settings)).await?; } Ok(StatusCode::OK) @@ -597,9 +617,14 @@ pub(crate) async fn session_chat( } // Agent mode: drive the model↔shell_exec loop, streaming progress events. + let memory_available = st.memory.is_some(); + let memory_on = memory_available && sess.settings.memory_enabled; if body.agent { let mut tools = agent::agent_tools(); if let Some(arr) = tools.as_array_mut() { + if memory_on { + arr.extend(agent::memory::memory_tools()); + } arr.extend(mcp_decls); } req.tools = Some(tools); @@ -610,6 +635,7 @@ pub(crate) async fn session_chat( let sid = id.clone(); let folder = sess.folder.clone(); let ws_root = st.workspace_root.clone(); + let memory = if memory_on { st.memory.clone() } else { None }; let tx_model = tx.clone(); let svc_pw = st.service.clone(); let store_pw = store.clone(); @@ -684,6 +710,7 @@ pub(crate) async fn session_chat( store: store2, default_cwd: folder, workspace_root: Some(ws_root), + memory, max_iters: agent::MAX_ITERS, progress: Some(tx.clone()), }, @@ -696,7 +723,14 @@ pub(crate) async fn session_chat( message: env.error.message, }); } - schedule_prewarm(svc_pw, store_pw, sid.clone(), true, notepad_fp_pw); + schedule_prewarm( + svc_pw, + store_pw, + sid.clone(), + true, + notepad_fp_pw, + memory_available, + ); }); let events = UnboundedReceiverStream::new(rx) .map(|ev| { @@ -763,7 +797,14 @@ pub(crate) async fn session_chat( let tail = futures::stream::once(async move { let a = acc_end.lock().unwrap().clone(); persist_assistant(&store, &sid, &a, prompt_len).await; - schedule_prewarm(svc_pw, store.clone(), sid.clone(), agent_pw, notepad_fp_pw); + schedule_prewarm( + svc_pw, + store.clone(), + sid.clone(), + agent_pw, + notepad_fp_pw, + memory_available, + ); Ok::<_, std::convert::Infallible>(Event::default().data("[DONE]")) }); Sse::new(events.chain(tail)) @@ -800,6 +841,7 @@ pub(crate) async fn session_chat( id.clone(), body.agent, notepad_fp.clone(), + memory_available, ); Json(resp).into_response() } @@ -860,6 +902,7 @@ fn schedule_prewarm( sid: String, agent_mode: bool, notepad_fp: String, + memory_available: bool, ) { tokio::spawn(async move { if !service.is_idle() { @@ -927,9 +970,15 @@ fn schedule_prewarm( messages: prefix, ..Default::default() }; + // Match the NEXT turn's surface: the latch is read from the freshly loaded + // session (service availability is stable for the server's lifetime). + let memory_on = memory_available && sess.settings.memory_enabled; if agent_mode { let mut tools = agent::agent_tools(); if let Some(arr) = tools.as_array_mut() { + if memory_on { + arr.extend(agent::memory::memory_tools()); + } arr.extend(mcp_decls); } req.tools = Some(tools); diff --git a/src/config.rs b/src/config.rs index 40796c8..c5a8cb5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -120,6 +120,13 @@ pub struct Config { #[serde(default)] pub db_path: Option, + /// Endpoint of the interim embedder service (vetta-embedder, BGE-M3 dense). + /// A non-secret deployment endpoint, like `exe`/`host`/`port`. Defaults to the + /// free-to-use Altair instance; the Sogliola `localhost:8091` instance is + /// reserved for Iris and must not be used here. + #[serde(default)] + pub memory_embedder_url: Option, + /// Keys we understand but don't act on yet are NOT listed above, so they /// arrive here untouched — the "ignore what isn't ours" guarantee. #[serde(flatten)] @@ -265,6 +272,19 @@ impl Config { self.workspace_root().join("uploads") } + /// Semantic index directory: `/memory` (the Qdrant Edge shard, a + /// rebuildable/disposable index over the authoritative Store records). + pub fn memory_dir(&self) -> PathBuf { + self.workspace_root().join("memory") + } + + /// Effective embedder endpoint: config > the free Altair instance (.18). + pub fn memory_embedder_url(&self) -> String { + self.memory_embedder_url + .clone() + .unwrap_or_else(|| "http://192.168.50.18:8091".to_string()) + } + /// Effective language: config > `it`. pub fn language(&self) -> String { self.language.clone().unwrap_or_else(|| "it".to_string()) @@ -445,9 +465,23 @@ mod tests { assert_eq!(cfg.sessions_dir(), PathBuf::from("/tmp/fwk/sessions")); assert_eq!(cfg.data_dir(), PathBuf::from("/tmp/fwk/data")); assert_eq!(cfg.upload_dir(), PathBuf::from("/tmp/fwk/uploads")); + assert_eq!(cfg.memory_dir(), PathBuf::from("/tmp/fwk/memory")); assert_eq!( cfg.gui_db_path(), PathBuf::from("/tmp/fwk/data/sessions.db") ); } + + #[test] + fn memory_embedder_url_default_and_override() { + let cfg = Config::parse(r#"{"exe":"/x/e"}"#, "test").unwrap(); + // default is the free Altair instance, NOT localhost (reserved for Iris) + assert_eq!(cfg.memory_embedder_url(), "http://192.168.50.18:8091"); + let cfg2 = Config::parse( + r#"{"exe":"/x/e","memory_embedder_url":"http://10.0.0.9:8091"}"#, + "test", + ) + .unwrap(); + assert_eq!(cfg2.memory_embedder_url(), "http://10.0.0.9:8091"); + } } diff --git a/src/lib.rs b/src/lib.rs index 9109593..66e7b82 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -17,6 +17,7 @@ pub mod engine; pub mod i18n; pub mod inkling; pub mod mcp; +pub mod memory; pub mod name; pub mod render; pub mod store; diff --git a/src/main.rs b/src/main.rs index 81e0a9a..eee9298 100644 --- a/src/main.rs +++ b/src/main.rs @@ -199,7 +199,29 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option) -> E if matches!(store.get_defaults(), Ok(None)) { let _ = store.set_defaults(&cfg.default_settings()); } - let app = router_with_store(svc, store, auth, cfg.workspace_root()); + // Open the semantic memory service: the authoritative Store plus a rebuildable + // Qdrant Edge index under /memory. Fail-open — if it cannot be opened the + // agent simply runs without the remember/recall/forget tools; the rest of the + // GUI and the /v1 API are unaffected. + let memory = match strata_ctl::memory::MemoryService::open( + store.clone(), + &cfg.memory_dir(), + &cfg.memory_embedder_url(), + ) { + Ok(m) => { + println!( + "memory: {} (embedder {})", + cfg.memory_dir().display(), + cfg.memory_embedder_url() + ); + Some(Arc::new(m)) + } + Err(e) => { + tracing::warn!(error = %e, "semantic memory unavailable; remember/recall disabled"); + None + } + }; + let app = router_with_store(svc, store, auth, cfg.workspace_root(), memory); let host = cfg.bind_host(cli_host); let port = cfg.bind_port(cli_port); if !is_loopback_host(&host) && cfg.api_key.is_none() { diff --git a/src/memory.rs b/src/memory.rs new file mode 100644 index 0000000..e1f3d06 --- /dev/null +++ b/src/memory.rs @@ -0,0 +1,454 @@ +//! The semantic memory service: the control-layer seam over `strata-memory`. +//! +//! Architecture (ratified): the relational [`Store`] owns the AUTHORITATIVE +//! records; the Qdrant Edge [`MemoryIndex`] is a rebuildable/disposable semantic +//! layer over them. This service keeps the two in step and fails OPEN: a record +//! is always persisted to the Store first, and indexing is deferred (not lost) +//! when the embedder is unreachable. Recall falls back to a keyword scan of the +//! Store when semantic search cannot embed the query, so memory stays useful +//! offline. Vectors never leave this layer — callers get text + score only. +//! +//! Sync by design (the Store and the index are sync); the agent loop calls it +//! from `tokio::task::spawn_blocking`. + +use std::collections::HashSet; +use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::{SystemTime, UNIX_EPOCH}; + +use anyhow::{Context, Result}; +use strata_memory::{ + Embedder, Hit, HttpEmbedder, IndexError, MemoryIndex, MemoryRecord, BGE_M3_DIM, +}; + +use crate::store::Store; + +/// Embedder tag persisted alongside the index. Switching the embedder (or its +/// quantization) changes this tag and forces a rebuild rather than silently +/// mixing incompatible vectors. The interim backend is BGE-M3 dense q8 on Altair. +pub const MODEL_ID: &str = "bge-m3-q8"; + +/// Fields the agent supplies to `remember`. `id`/`timestamp` are assigned here. +#[derive(Debug, Clone)] +pub struct RememberInput { + pub category: String, + pub title: String, + pub content: String, + pub keywords: Vec, + pub scope: String, + pub source: String, +} + +/// The semantic memory service. Holds the authoritative Store and the rebuildable +/// index; all methods are sync and fail-open on embedder transport errors. +pub struct MemoryService { + store: Arc, + index: MemoryIndex, +} + +impl MemoryService { + /// Open (or create) the service: build the interim HTTP embedder, open the + /// shard at `dir`, and reconcile any Store records missing from the index. + /// + /// On an embedder-model mismatch the stale shard is discarded and rebuilt + /// from the Store (the index is disposable by design). Reconciliation is + /// best-effort: if the embedder is down, missing records stay in the Store + /// and are indexed later — opening still succeeds. + pub fn open(store: Arc, dir: &Path, embedder_url: &str) -> Result { + let embedder: Arc = + Arc::new(HttpEmbedder::new(embedder_url, MODEL_ID, BGE_M3_DIM)); + let index = match MemoryIndex::open(dir, BGE_M3_DIM, MODEL_ID, embedder.clone()) { + Ok(ix) => ix, + Err(IndexError::ModelMismatch { index: old, .. }) => { + tracing::warn!( + old_model = %old, + new_model = MODEL_ID, + "memory index built with a different embedder: rebuilding from the Store" + ); + std::fs::remove_dir_all(dir) + .with_context(|| format!("discarding stale memory index {}", dir.display()))?; + MemoryIndex::open(dir, BGE_M3_DIM, MODEL_ID, embedder) + .context("recreating the memory index")? + } + Err(e) => return Err(e).context("opening the memory index"), + }; + let svc = Self { store, index }; + if let Err(e) = svc.reconcile() { + tracing::warn!(error = %e, "memory index reconciliation failed (will retry on next open)"); + } + Ok(svc) + } + + /// Wrap an already-built index (tests inject a stub embedder this way). + #[cfg(test)] + pub(crate) fn from_index(store: Arc, index: MemoryIndex) -> Self { + Self { store, index } + } + + pub fn model_id(&self) -> &str { + self.index.model_id() + } + + pub fn dim(&self) -> usize { + self.index.dim() + } + + /// Whether the embedder responds — the gate for enabling memory on a session + /// (the one-way opt-in latch only flips on when the capability actually works). + pub fn embedder_reachable(&self) -> bool { + self.index.embedder_reachable() + } + + /// Persist a new memory: authoritative Store write FIRST, then index it. + /// Indexing failures (embedder unreachable) are logged and deferred, never + /// losing the record — it remains in the Store and is reconciled later. + pub fn remember(&self, input: RememberInput) -> Result { + let record = MemoryRecord { + id: new_id("mem"), + category: input.category, + title: input.title, + content: input.content, + keywords: input.keywords, + scope: input.scope, + timestamp: now_secs().to_string(), + source: input.source, + }; + self.store + .upsert_memory_record(&record) + .context("persisting the memory record to the Store")?; + match self.index.upsert(&record) { + Ok(()) => { + let _ = self.index.flush(); + } + Err(e) => tracing::warn!( + error = %e, id = %record.id, + "memory saved to the Store but indexing deferred (embedder unreachable?)" + ), + } + Ok(record) + } + + /// Semantic recall. When the query cannot be embedded (embedder down), fall + /// OPEN to a keyword scan of the authoritative Store so memory stays useful. + pub fn recall( + &self, + query: &str, + top_k: usize, + threshold: f32, + category: Option<&str>, + scope: Option<&str>, + ) -> Result> { + match self.index.search(query, top_k, threshold, category, scope) { + Ok(hits) => Ok(hits), + Err(IndexError::Embed(e)) => { + tracing::warn!(error = %e, "semantic recall unavailable: keyword fallback over the Store"); + self.keyword_fallback(query, top_k, category, scope) + } + Err(e) => Err(e).context("semantic recall"), + } + } + + /// Forget a memory: remove the authoritative record, then soft-delete its + /// point (tombstone) so it is excluded from recall but retained for rebuild. + pub fn forget(&self, id: &str) -> Result { + let existed = self + .store + .delete_memory_record(id) + .context("deleting the memory record from the Store")?; + if existed { + match self.index.mark_dead(id) { + Ok(()) => { + let _ = self.index.flush(); + } + Err(e) => tracing::warn!(error = %e, id, "memory deleted but tombstoning deferred"), + } + } + Ok(existed) + } + + /// Forget a record ONLY if it belongs to `scope` (per-session isolation): a + /// session must not be able to delete another session's memories by guessing + /// an id. Returns false when the id is absent or owned by a different scope. + pub fn forget_in_scope(&self, id: &str, scope: &str) -> Result { + match self.store.get_memory_record(id)? { + Some(r) if r.scope == scope => self.forget(id), + _ => Ok(false), + } + } + + /// Index any Store records missing from the shard (saved while the embedder + /// was down, or after a rebuild). Best-effort: stops on an embedder transport + /// error rather than hammering an unreachable service; returns how many were + /// indexed. Tombstoned ids count as present so they are not resurrected. + pub fn reconcile(&self) -> Result { + let indexed: HashSet = self.index.indexed_ids()?.into_iter().collect(); + let mut n = 0usize; + for record in self.store.list_memory_records()? { + if indexed.contains(&record.id) { + continue; + } + match self.index.upsert(&record) { + Ok(()) => n += 1, + Err(IndexError::Embed(e)) => { + tracing::warn!(error = %e, "reconciliation paused: embedder unreachable"); + break; + } + Err(e) => return Err(e).context("reconciling the memory index"), + } + } + if n > 0 { + let _ = self.index.flush(); + } + Ok(n) + } + + /// Naive keyword recall over the authoritative Store (offline fallback). + /// Scores by how many query terms appear in title + content + keywords. + fn keyword_fallback( + &self, + query: &str, + top_k: usize, + category: Option<&str>, + scope: Option<&str>, + ) -> Result> { + let terms: Vec = query + .to_lowercase() + .split_whitespace() + .map(|s| s.to_string()) + .collect(); + let mut hits = Vec::new(); + for record in self.store.list_memory_records()? { + if let Some(c) = category { + if record.category != c { + continue; + } + } + if let Some(s) = scope { + if record.scope != s { + continue; + } + } + let hay = format!( + "{} {} {}", + record.title, + record.content, + record.keywords.join(" ") + ) + .to_lowercase(); + let score = terms.iter().filter(|t| hay.contains(t.as_str())).count(); + if score > 0 { + hits.push(Hit { + record, + score: score as f32, + }); + } + } + hits.sort_by(|a, b| { + b.score + .partial_cmp(&a.score) + .unwrap_or(std::cmp::Ordering::Equal) + }); + hits.truncate(top_k); + Ok(hits) + } +} + +fn now_secs() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} + +/// Unique, sortable-enough id without an extra dependency (nanos + counter), +/// mirroring the Store's own generator. +fn new_id(prefix: &str) -> String { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + format!("{prefix}_{nanos:016x}{n:08x}") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::store::SqliteStore; + use strata_memory::EmbedError; + + /// Deterministic embedder: known texts map to orthogonal unit vectors. + struct StubEmbedder; + impl Embedder for StubEmbedder { + fn embed(&self, texts: &[&str]) -> Result>, EmbedError> { + Ok(texts + .iter() + .map(|t| match *t { + "alpha" => vec![1.0, 0.0, 0.0, 0.0], + "beta" => vec![0.0, 1.0, 0.0, 0.0], + _ => vec![0.0, 0.0, 1.0, 0.0], + }) + .collect()) + } + fn dim(&self) -> usize { + 4 + } + fn model_id(&self) -> &str { + "stub" + } + } + + /// Always fails transport (simulates an unreachable embedder). + struct DownEmbedder; + impl Embedder for DownEmbedder { + fn embed(&self, _: &[&str]) -> Result>, EmbedError> { + Err(EmbedError::Transport("connection refused".into())) + } + fn dim(&self) -> usize { + 4 + } + fn model_id(&self) -> &str { + "stub" + } + } + + fn store() -> Arc { + Arc::new(SqliteStore::open_in_memory().unwrap()) + } + + fn service(dir: &Path, embedder: Arc) -> MemoryService { + let index = MemoryIndex::open(dir, 4, "stub", embedder).unwrap(); + MemoryService::from_index(store(), index) + } + + fn input(content: &str) -> RememberInput { + RememberInput { + category: "facts".into(), + title: content.into(), + content: content.into(), + keywords: vec![], + scope: "global".into(), + source: "test".into(), + } + } + + #[test] + fn remember_persists_to_store_and_index() { + let tmp = tempfile::tempdir().unwrap(); + let svc = service(tmp.path(), Arc::new(StubEmbedder)); + let rec = svc.remember(input("alpha")).unwrap(); + // Authoritative Store has it. + assert!(svc.store.get_memory_record(&rec.id).unwrap().is_some()); + // Semantic recall finds it (cosine 1.0 for the identical text). + let hits = svc.recall("alpha", 5, 0.0, None, None).unwrap(); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].record.id, rec.id); + } + + #[test] + fn remember_fails_open_when_embedder_down() { + let tmp = tempfile::tempdir().unwrap(); + let svc = service(tmp.path(), Arc::new(DownEmbedder)); + // Indexing fails, but the record is still persisted (fail-open). + let rec = svc.remember(input("alpha")).unwrap(); + assert!(svc.store.get_memory_record(&rec.id).unwrap().is_some()); + } + + #[test] + fn recall_falls_back_to_keywords_when_embedder_down() { + let tmp = tempfile::tempdir().unwrap(); + let svc = service(tmp.path(), Arc::new(DownEmbedder)); + // Seed the authoritative Store directly (no index, embedder is down). + let rec = MemoryRecord { + id: "m1".into(), + category: "facts".into(), + title: "Il gatto nero".into(), + content: "Il gatto nero salta sul tavolo".into(), + keywords: vec!["gatto".into()], + scope: "global".into(), + timestamp: "0".into(), + source: "test".into(), + }; + svc.store.upsert_memory_record(&rec).unwrap(); + // Semantic search cannot embed -> keyword fallback finds the record. + let hits = svc.recall("gatto tavolo", 5, 0.0, None, None).unwrap(); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].record.id, "m1"); + assert!(hits[0].score >= 2.0, "both terms matched"); + } + + #[test] + fn forget_removes_from_store_and_excludes_from_recall() { + let tmp = tempfile::tempdir().unwrap(); + let svc = service(tmp.path(), Arc::new(StubEmbedder)); + let rec = svc.remember(input("alpha")).unwrap(); + assert!(svc.forget(&rec.id).unwrap()); + assert!(svc.store.get_memory_record(&rec.id).unwrap().is_none()); + let hits = svc.recall("alpha", 5, 0.0, None, None).unwrap(); + assert!(hits.is_empty(), "forgotten record must be excluded"); + // Forgetting an absent id is a no-op (returns false). + assert!(!svc.forget("nope").unwrap()); + } + + #[test] + fn reconcile_indexes_store_records_missing_from_index() { + let tmp = tempfile::tempdir().unwrap(); + let svc = service(tmp.path(), Arc::new(StubEmbedder)); + // Put a record in the Store WITHOUT indexing it (as if saved while down). + let rec = MemoryRecord { + id: "m1".into(), + category: "facts".into(), + title: "alpha".into(), + content: "alpha".into(), + keywords: vec![], + scope: "global".into(), + timestamp: "0".into(), + source: "test".into(), + }; + svc.store.upsert_memory_record(&rec).unwrap(); + assert!(svc.recall("alpha", 5, 0.0, None, None).unwrap().is_empty()); + // Reconciliation indexes the missing record. + assert_eq!(svc.reconcile().unwrap(), 1); + let hits = svc.recall("alpha", 5, 0.0, None, None).unwrap(); + assert_eq!(hits.len(), 1); + // Idempotent: nothing left to reconcile. + assert_eq!(svc.reconcile().unwrap(), 0); + } + + /// End-to-end against the real Altair BGE-M3 embedder: open -> remember -> + /// semantic recall (paraphrase) -> forget. Run with `--ignored` on the LAN. + #[test] + #[ignore] + fn live_remember_recall_forget_altair() { + let tmp = tempfile::tempdir().unwrap(); + let store: Arc = Arc::new(SqliteStore::open_in_memory().unwrap()); + let svc = MemoryService::open(store, tmp.path(), "http://192.168.50.18:8091").unwrap(); + let rec = svc + .remember(RememberInput { + category: "project_fact".into(), + title: "Embedder di riserva".into(), + content: + "Il servizio di embedding BGE-M3 di riserva gira su Altair alla porta 8091." + .into(), + keywords: vec!["embedder".into(), "altair".into()], + scope: "global".into(), + source: "test".into(), + }) + .unwrap(); + // A natural-language paraphrase must retrieve the fact semantically. + let hits = svc + .recall("dove gira il modello di embedding?", 5, 0.3, None, None) + .unwrap(); + assert!(!hits.is_empty(), "semantic recall should find the fact"); + assert_eq!(hits[0].record.id, rec.id); + assert!(hits[0].score > 0.3, "score={}", hits[0].score); + // Forget excludes it from subsequent recall. + assert!(svc.forget(&rec.id).unwrap()); + let hits = svc + .recall("dove gira il modello di embedding?", 5, 0.3, None, None) + .unwrap(); + assert!(hits.iter().all(|h| h.record.id != rec.id)); + } +} diff --git a/src/store.rs b/src/store.rs index 2f34abb..523c3a1 100644 --- a/src/store.rs +++ b/src/store.rs @@ -60,6 +60,13 @@ pub struct SessionSettings { /// curated tool selection lives here, copy-on-create like other settings. #[serde(default)] pub mcp_enabled: BTreeMap>, + /// Per-session ONE-WAY opt-in for semantic memory (remember/recall/forget). + /// Off by default; once enabled it can never be disabled (irreversible latch, + /// like `name_locked`), because memories already written must stay recallable. + /// Enabling is gated on the memory service being present and the embedder + /// reachable. Copy-on-create like other settings; the global default is off. + #[serde(default)] + pub memory_enabled: bool, } impl SessionSettings { @@ -85,6 +92,8 @@ impl SessionSettings { } else { self.mcp_enabled.clone() }, + // One-way latch: once on, stays on (OR merge). + memory_enabled: self.memory_enabled || base.memory_enabled, } } } @@ -296,6 +305,15 @@ pub trait Store: Send + Sync { /// Persist the discovered tool surface (JSON array of rmcp `Tool`) for a /// connector, refreshed by live discovery. No-op if the connector is absent. fn set_mcp_tools(&self, name: &str, tools_json: &str) -> Result<()>; + /// Upsert an authoritative semantic-memory record. The relational Store is + /// the source of truth; the Qdrant Edge index is a rebuildable copy over it. + fn upsert_memory_record(&self, record: &strata_memory::MemoryRecord) -> Result<()>; + /// Fetch one memory record by id. + fn get_memory_record(&self, id: &str) -> Result>; + /// All memory records (used to rebuild the semantic index after an embedder swap). + fn list_memory_records(&self) -> Result>; + /// Remove a memory record; returns whether it existed. + fn delete_memory_record(&self, id: &str) -> Result; } fn now_secs() -> i64 { @@ -375,6 +393,18 @@ CREATE TABLE IF NOT EXISTS mcp_connectors ( created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL ); +CREATE TABLE IF NOT EXISTS memory_records ( + id TEXT PRIMARY KEY, + category TEXT NOT NULL, + title TEXT NOT NULL, + content TEXT NOT NULL, + keywords TEXT NOT NULL, + scope TEXT NOT NULL, + timestamp TEXT NOT NULL, + source TEXT NOT NULL, + updated_at INTEGER NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_memory_cat_scope ON memory_records(category, scope); "; /// SQLite-backed store (bundled SQLite, compiled into the binary). WAL mode for @@ -970,6 +1000,70 @@ impl Store for SqliteStore { )?; Ok(()) } + + fn upsert_memory_record(&self, record: &strata_memory::MemoryRecord) -> Result<()> { + let keywords = serde_json::to_string(&record.keywords)?; + let conn = self.lock(); + conn.execute( + "INSERT INTO memory_records (id, category, title, content, keywords, scope, timestamp, source, updated_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) + ON CONFLICT(id) DO UPDATE SET + category=?2, title=?3, content=?4, keywords=?5, scope=?6, timestamp=?7, source=?8, updated_at=?9", + params![ + record.id, record.category, record.title, record.content, keywords, + record.scope, record.timestamp, record.source, now_secs() + ], + )?; + Ok(()) + } + + fn get_memory_record(&self, id: &str) -> Result> { + let conn = self.lock(); + conn.query_row( + "SELECT id, category, title, content, keywords, scope, timestamp, source + FROM memory_records WHERE id = ?1", + params![id], + row_to_memory, + ) + .optional() + .map_err(Into::into) + } + + fn list_memory_records(&self) -> Result> { + let conn = self.lock(); + let mut stmt = conn.prepare( + "SELECT id, category, title, content, keywords, scope, timestamp, source + FROM memory_records ORDER BY updated_at DESC", + )?; + let rows = stmt.query_map([], row_to_memory)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + } + + fn delete_memory_record(&self, id: &str) -> Result { + let conn = self.lock(); + let n = conn.execute("DELETE FROM memory_records WHERE id = ?1", params![id])?; + Ok(n > 0) + } +} + +/// Map a `memory_records` row to the shared record shape (keywords is a JSON array). +fn row_to_memory(row: &rusqlite::Row<'_>) -> rusqlite::Result { + let keywords_json: String = row.get(4)?; + let keywords = serde_json::from_str(&keywords_json).unwrap_or_default(); + Ok(strata_memory::MemoryRecord { + id: row.get(0)?, + category: row.get(1)?, + title: row.get(2)?, + content: row.get(3)?, + keywords, + scope: row.get(5)?, + timestamp: row.get(6)?, + source: row.get(7)?, + }) } #[cfg(test)] @@ -1111,6 +1205,46 @@ mod tests { assert!(s.mcp_connectors().unwrap().is_empty()); } + #[test] + fn memory_record_crud_and_upsert() { + let s = store(); + assert!(s.list_memory_records().unwrap().is_empty()); + let rec = strata_memory::MemoryRecord { + id: "mem_1".into(), + category: "facts".into(), + title: "Gatto".into(), + content: "Il gatto nero salta sul tavolo".into(), + keywords: vec!["gatto".into(), "tavolo".into()], + scope: "global".into(), + timestamp: "0".into(), + source: "test".into(), + }; + s.upsert_memory_record(&rec).unwrap(); + let got = s.get_memory_record("mem_1").unwrap().unwrap(); + assert_eq!(got, rec); + assert_eq!( + got.keywords, + vec!["gatto".to_string(), "tavolo".to_string()] + ); + + // Upsert updates in place, keeps a single row. + let rec2 = strata_memory::MemoryRecord { + content: "Il gatto dorme".into(), + title: "Gatto 2".into(), + ..rec.clone() + }; + s.upsert_memory_record(&rec2).unwrap(); + assert_eq!(s.list_memory_records().unwrap().len(), 1); + assert_eq!( + s.get_memory_record("mem_1").unwrap().unwrap().content, + "Il gatto dorme" + ); + + assert!(s.delete_memory_record("mem_1").unwrap()); + assert!(!s.delete_memory_record("mem_1").unwrap()); + assert!(s.get_memory_record("mem_1").unwrap().is_none()); + } + #[test] fn stats_breakdown_counts_tools_and_orders_sessions() { let s = store(); @@ -1277,6 +1411,39 @@ mod tests { assert_ne!(a, b); } + #[test] + fn memory_latch_is_one_way_and_persists() { + let s = store(); + let sess = s + .create_session("Chat", "m", &SessionSettings::default()) + .unwrap(); + // Off by default. + assert!(!sess.settings.memory_enabled); + // Enable via the session's own settings instance. + let mut on = sess.settings.clone(); + on.memory_enabled = true; + s.update_settings(&sess.id, &on).unwrap(); + assert!( + s.get_session(&sess.id) + .unwrap() + .unwrap() + .settings + .memory_enabled + ); + // Overlay is a one-way OR: a false override can never turn it back off. + let off = SessionSettings { + memory_enabled: false, + ..Default::default() + }; + assert!(off.overlay(&on).memory_enabled); + // Two fresh (off) settings stay off. + assert!( + !SessionSettings::default() + .overlay(&SessionSettings::default()) + .memory_enabled + ); + } + #[test] fn migration_adds_columns_to_old_schema() { // Simulate a pre-existing database without the newer columns. diff --git a/strata-memory/Cargo.toml b/strata-memory/Cargo.toml new file mode 100644 index 0000000..dae7d83 --- /dev/null +++ b/strata-memory/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "strata-memory" +version = "0.1.0" +edition = "2021" +license = "MIT" +description = "strata-ctl semantic memory: swappable Embedder trait + HTTP (BGE-M3) backend, Qdrant Edge index" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" +# Blocking HTTP client (matches strata-ctl's existing choice). `json` enables send_json. +ureq = { version = "3.5.2", features = ["json"] } +# In-process Qdrant engine (single shard, disk-backed). The semantic index over +# memory records; rebuildable/disposable. Pinned: pre-1.0 beta. +qdrant-edge = "0.9" + +[dev-dependencies] +# Temporary shard directories for hermetic in-process index tests. +tempfile = "3" diff --git a/strata-memory/src/index.rs b/strata-memory/src/index.rs new file mode 100644 index 0000000..80b3d8e --- /dev/null +++ b/strata-memory/src/index.rs @@ -0,0 +1,501 @@ +//! Semantic index over memory records, backed by an in-process Qdrant Edge shard. +//! +//! Architecture (ratified): the relational Store owns the authoritative records; +//! this index is a REBUILDABLE/DISPOSABLE semantic layer over them. Vectors live +//! only here; what reaches the model is text + score (see the symbolic-vector +//! principle). The payload carries a copy of the record so recall can render +//! without a Store round-trip; on embedder swap the whole shard is rebuilt. +//! +//! Dense-only baseline (no sparse/ColBERT). Soft-delete via a `dead` payload flag +//! filtered out of every query (pattern from our Iris Qdrant backend). + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use qdrant_edge::{ + Condition, Distance, EdgeConfigBuilder, EdgeShard, EdgeVectorParams, FieldCondition, Filter, + Match, NamedQuery, Payload, PayloadOps, PointInsertOperations, PointOperations, PointStruct, + QueryEnum, QueryRequestBuilder, ScoringQuery, ScrollRequestBuilder, SetPayloadOp, + UpdateOperation, ValueVariants, VectorInternal, Vectors, WithPayloadInterface, WithVector, +}; +use serde::{Deserialize, Serialize}; + +use crate::{EmbedError, Embedder}; + +/// Named dense vector in the shard. +pub const DENSE_VECTOR_NAME: &str = "dense"; +/// Sidecar file recording which embedder built the shard (rebuild-on-swap guard). +const MODEL_FILE: &str = "strata_model.json"; + +/// The authoritative memory record shape. The relational Store owns these; the +/// index keeps a rebuildable copy in the point payload. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct MemoryRecord { + pub id: String, + pub category: String, + pub title: String, + pub content: String, + pub keywords: Vec, + pub scope: String, + pub timestamp: String, + pub source: String, +} + +/// A recall hit: the record (text) + its relevance score. No vector ever leaves. +#[derive(Debug, Clone)] +pub struct Hit { + pub record: MemoryRecord, + pub score: f32, +} + +#[derive(Debug, thiserror::Error)] +pub enum IndexError { + #[error("qdrant: {0}")] + Qdrant(String), + #[error("io: {0}")] + Io(String), + #[error("serde: {0}")] + Serde(String), + #[error(transparent)] + Embed(#[from] EmbedError), + #[error("model mismatch: index built with '{index}' (dim {index_dim}), current '{current}' (dim {current_dim}) — rebuild required")] + ModelMismatch { + index: String, + index_dim: usize, + current: String, + current_dim: usize, + }, +} + +impl From for IndexError { + fn from(e: qdrant_edge::OperationError) -> Self { + IndexError::Qdrant(e.to_string()) + } +} + +#[derive(Serialize, Deserialize)] +struct ModelTag { + model_id: String, + dim: usize, +} + +/// In-process semantic index. Holds the embedder so `upsert`/`search` can embed +/// text directly; the caller never handles raw vectors. +pub struct MemoryIndex { + shard: EdgeShard, + dim: usize, + model_id: String, + embedder: Arc, +} + +impl MemoryIndex { + /// Open (or create) a shard at `path`. If it already exists, its embedder tag + /// must match `model_id`/`dim`, else [`IndexError::ModelMismatch`] is returned + /// so the caller can rebuild rather than mix incompatible vectors. + pub fn open( + path: impl AsRef, + dim: usize, + model_id: impl Into, + embedder: Arc, + ) -> Result { + let path = path.as_ref(); + let model_id = model_id.into(); + let model_file = path.join(MODEL_FILE); + + if path.join("edge_config.json").exists() { + let shard = EdgeShard::load(path, None)?; + let tag = read_tag(&model_file)?; + if tag.model_id != model_id || tag.dim != dim { + return Err(IndexError::ModelMismatch { + index: tag.model_id, + index_dim: tag.dim, + current: model_id, + current_dim: dim, + }); + } + Ok(Self { + shard, + dim, + model_id, + embedder, + }) + } else { + std::fs::create_dir_all(path).map_err(|e| IndexError::Io(e.to_string()))?; + let config = EdgeConfigBuilder::new() + .vector( + DENSE_VECTOR_NAME, + EdgeVectorParams::builder(dim, Distance::Cosine).build(), + ) + .build(); + let shard = EdgeShard::new(path, config)?; + write_tag( + &model_file, + &ModelTag { + model_id: model_id.clone(), + dim, + }, + )?; + Ok(Self { + shard, + dim, + model_id, + embedder, + }) + } + } + + pub fn dim(&self) -> usize { + self.dim + } + + pub fn model_id(&self) -> &str { + &self.model_id + } + + /// Probe whether the embedder responds (gate for enabling memory on a session). + /// One tiny embed; true iff it succeeds. Trait-generic, so it also works for the + /// future in-process embedder. + pub fn embedder_reachable(&self) -> bool { + self.embedder.embed(&["ping"]).is_ok() + } + + /// Embed the record's content and upsert it (idempotent on the record id). + pub fn upsert(&self, record: &MemoryRecord) -> Result<(), IndexError> { + let vector = self + .embedder + .embed(&[record.content.as_str()])? + .pop() + .ok_or_else(|| EmbedError::Shape("embedder returned no vector".into()))?; + if vector.len() != self.dim { + return Err(IndexError::Qdrant(format!( + "vector dim {} != index dim {}", + vector.len(), + self.dim + ))); + } + let mut payload = + serde_json::to_value(record).map_err(|e| IndexError::Serde(e.to_string()))?; + payload["dead"] = serde_json::json!(false); + let point = PointStruct::new( + point_id(&record.id), + Vectors::new_named([(DENSE_VECTOR_NAME, vector)]), + payload, + ); + self.shard.update(UpdateOperation::PointOperation( + PointOperations::UpsertPoints(PointInsertOperations::PointsList(vec![point.into()])), + ))?; + Ok(()) + } + + /// Semantic recall: embed `query`, return up to `top_k` live records scoring + /// at least `threshold`, optionally filtered by category/scope. Tombstones + /// (`dead=true`) are always excluded. + pub fn search( + &self, + query: &str, + top_k: usize, + threshold: f32, + category: Option<&str>, + scope: Option<&str>, + ) -> Result, IndexError> { + let vector = self + .embedder + .embed(&[query])? + .pop() + .ok_or_else(|| EmbedError::Shape("embedder returned no vector".into()))?; + self.search_vector(&vector, top_k, threshold, category, scope) + } + + /// Vector-level search (also used by the symbolic workspace bridge: a + /// `$VEC[n]` resolved server-side is fed here without entering context). + pub fn search_vector( + &self, + vector: &[f32], + top_k: usize, + threshold: f32, + category: Option<&str>, + scope: Option<&str>, + ) -> Result, IndexError> { + let scoring = ScoringQuery::Vector(QueryEnum::Nearest(NamedQuery::new( + VectorInternal::from(vector.to_vec()), + DENSE_VECTOR_NAME.to_string(), + ))); + let request = QueryRequestBuilder::new(top_k) + .query(scoring) + .filter(live_filter(category, scope)) + .score_threshold(threshold) + .with_payload(WithPayloadInterface::Bool(true)) + .with_vector(WithVector::Bool(false)) + .build(); + let points = self.shard.query(request)?; + let mut hits = Vec::with_capacity(points.len()); + for p in points { + if let Some(record) = payload_to_record(p.payload.as_ref()) { + hits.push(Hit { + record, + score: p.score, + }); + } + } + Ok(hits) + } + + /// Soft-delete: mark the record `dead=true` so it is excluded from recall but + /// retained for rebuild/audit. The authoritative removal happens in the Store. + pub fn mark_dead(&self, id: &str) -> Result<(), IndexError> { + let payload = Payload::from( + serde_json::json!({ "dead": true }) + .as_object() + .unwrap() + .clone(), + ); + let op = SetPayloadOp { + payload, + points: None, + filter: Some(Filter::new_must(field_match_str("id", id))), + key: None, + }; + self.shard + .update(UpdateOperation::PayloadOperation(PayloadOps::SetPayload( + op, + )))?; + Ok(()) + } + + /// Persist WAL + segments to disk. + pub fn flush(&self) -> Result<(), IndexError> { + self.shard.flush()?; + Ok(()) + } + + /// Every record id present in the shard, INCLUDING tombstones. Used by the + /// service to reconcile the authoritative Store against the index (find records + /// that were saved while the embedder was down) without re-embedding everything. + /// Tombstones are included on purpose so a soft-deleted record is not resurrected. + pub fn indexed_ids(&self) -> Result, IndexError> { + let mut ids = Vec::new(); + let mut offset = None; + loop { + let mut req = ScrollRequestBuilder::new() + .limit(256) + .with_payload(WithPayloadInterface::Bool(true)) + .with_vector(WithVector::Bool(false)); + if let Some(o) = offset { + req = req.offset(o); + } + let (records, next) = self.shard.scroll(req.build())?; + for r in records { + if let Some(id) = r + .payload + .as_ref() + .and_then(|p| p.0.get("id")) + .and_then(|v| v.as_str()) + { + ids.push(id.to_string()); + } + } + match next { + Some(o) => offset = Some(o), + None => break, + } + } + Ok(ids) + } +} + +// ── helpers ── + +/// Stable numeric point id from the record id (FNV-1a). The authoritative string +/// id is kept in the payload; the numeric id only needs to be deterministic so a +/// re-upsert of the same record overwrites its point. +fn point_id(id: &str) -> u64 { + let mut h: u64 = 0xcbf29ce484222325; + for b in id.bytes() { + h ^= b as u64; + h = h.wrapping_mul(0x100000001b3); + } + h +} + +fn field_match_str(key: &str, value: &str) -> Condition { + Condition::Field(FieldCondition::new_match( + key.parse().expect("valid payload key"), + Match::new_value(ValueVariants::String(value.to_string())), + )) +} + +fn dead_condition() -> Condition { + Condition::Field(FieldCondition::new_match( + "dead".parse().expect("valid payload key"), + Match::new_value(ValueVariants::Bool(true)), + )) +} + +/// Every query excludes tombstones; optional category/scope are `must` matches. +fn live_filter(category: Option<&str>, scope: Option<&str>) -> Filter { + let mut must = Vec::new(); + if let Some(c) = category { + must.push(field_match_str("category", c)); + } + if let Some(s) = scope { + must.push(field_match_str("scope", s)); + } + Filter { + must: if must.is_empty() { None } else { Some(must) }, + must_not: Some(vec![dead_condition()]), + ..Default::default() + } +} + +fn payload_to_record(payload: Option<&Payload>) -> Option { + let map = &payload?.0; + let mut value = serde_json::Value::Object(map.clone()); + if let Some(obj) = value.as_object_mut() { + obj.remove("dead"); + } + serde_json::from_value(value).ok() +} + +fn read_tag(path: &PathBuf) -> Result { + let data = std::fs::read_to_string(path).map_err(|e| IndexError::Io(e.to_string()))?; + serde_json::from_str(&data).map_err(|e| IndexError::Serde(e.to_string())) +} + +fn write_tag(path: &Path, tag: &ModelTag) -> Result<(), IndexError> { + let data = serde_json::to_string(tag).map_err(|e| IndexError::Serde(e.to_string()))?; + std::fs::write(path, data).map_err(|e| IndexError::Io(e.to_string())) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Deterministic embedder: maps a few known texts to orthogonal unit vectors. + struct StubEmbedder; + impl Embedder for StubEmbedder { + fn embed(&self, texts: &[&str]) -> Result>, EmbedError> { + Ok(texts + .iter() + .map(|t| match *t { + "alpha" => vec![1.0, 0.0, 0.0, 0.0], + "beta" => vec![0.0, 1.0, 0.0, 0.0], + _ => vec![0.0, 0.0, 1.0, 0.0], + }) + .collect()) + } + fn dim(&self) -> usize { + 4 + } + fn model_id(&self) -> &str { + "stub" + } + } + + fn record(id: &str, content: &str, category: &str) -> MemoryRecord { + MemoryRecord { + id: id.to_string(), + category: category.to_string(), + title: id.to_string(), + content: content.to_string(), + keywords: vec![], + scope: "global".to_string(), + timestamp: "0".to_string(), + source: "test".to_string(), + } + } + + fn open(dir: &Path) -> MemoryIndex { + MemoryIndex::open(dir, 4, "stub", Arc::new(StubEmbedder)).unwrap() + } + + #[test] + fn upsert_then_search_finds_record() { + let tmp = tempfile::tempdir().unwrap(); + let idx = open(tmp.path()); + idx.upsert(&record("r1", "alpha", "facts")).unwrap(); + idx.flush().unwrap(); + let hits = idx.search("alpha", 5, 0.0, None, None).unwrap(); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].record.id, "r1"); + assert!( + (hits[0].score - 1.0).abs() < 1e-5, + "cosine score={}", + hits[0].score + ); + } + + #[test] + fn search_ranks_nearest_first() { + let tmp = tempfile::tempdir().unwrap(); + let idx = open(tmp.path()); + idx.upsert(&record("a", "alpha", "facts")).unwrap(); + idx.upsert(&record("b", "beta", "facts")).unwrap(); + // threshold -1.0 includes the orthogonal (cosine 0.0) record too, so we + // can assert ordering; a 0.0 threshold would legitimately drop it. + let hits = idx.search("alpha", 5, -1.0, None, None).unwrap(); + assert_eq!(hits.len(), 2); + assert_eq!(hits[0].record.id, "a"); + assert!(hits[0].score > hits[1].score); + } + + #[test] + fn mark_dead_excludes_from_recall() { + let tmp = tempfile::tempdir().unwrap(); + let idx = open(tmp.path()); + idx.upsert(&record("r1", "alpha", "facts")).unwrap(); + idx.mark_dead("r1").unwrap(); + let hits = idx.search("alpha", 5, 0.0, None, None).unwrap(); + assert!(hits.is_empty(), "dead record must be excluded"); + } + + #[test] + fn category_filter() { + let tmp = tempfile::tempdir().unwrap(); + let idx = open(tmp.path()); + idx.upsert(&record("a", "alpha", "facts")).unwrap(); + idx.upsert(&record("b", "alpha", "experience")).unwrap(); + let hits = idx.search("alpha", 5, 0.0, Some("facts"), None).unwrap(); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].record.id, "a"); + } + + #[test] + fn reopen_with_different_model_is_mismatch() { + let tmp = tempfile::tempdir().unwrap(); + { + let idx = open(tmp.path()); + idx.upsert(&record("a", "alpha", "facts")).unwrap(); + idx.flush().unwrap(); + } + let err = MemoryIndex::open(tmp.path(), 4, "other-model", Arc::new(StubEmbedder)); + assert!(matches!(err, Err(IndexError::ModelMismatch { .. }))); + } + + #[test] + fn indexed_ids_includes_tombstones() { + let tmp = tempfile::tempdir().unwrap(); + let idx = open(tmp.path()); + idx.upsert(&record("a", "alpha", "facts")).unwrap(); + idx.upsert(&record("b", "beta", "facts")).unwrap(); + idx.mark_dead("b").unwrap(); + let mut ids = idx.indexed_ids().unwrap(); + ids.sort(); + // Both live and soft-deleted ids are reported (so reconciliation will not + // re-embed and resurrect the tombstone). + assert_eq!(ids, vec!["a".to_string(), "b".to_string()]); + } + + #[test] + fn reopen_same_model_preserves_data() { + let tmp = tempfile::tempdir().unwrap(); + { + let idx = open(tmp.path()); + idx.upsert(&record("a", "alpha", "facts")).unwrap(); + idx.flush().unwrap(); + } + let idx = open(tmp.path()); + let hits = idx.search("alpha", 5, 0.0, None, None).unwrap(); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].record.id, "a"); + } +} diff --git a/strata-memory/src/lib.rs b/strata-memory/src/lib.rs new file mode 100644 index 0000000..04659f0 --- /dev/null +++ b/strata-memory/src/lib.rs @@ -0,0 +1,281 @@ +//! strata-memory — semantic memory primitives for strata-ctl. +//! +//! Self-contained on purpose: it knows nothing of sessions or the GUI. It exposes +//! a swappable [`Embedder`] trait (dense vectors only — the ratified retrieval +//! baseline) plus an optional [`Reranker`] capability, and an [`HttpEmbedder`] +//! backend that speaks the `vetta-embedder` (BGE-M3) HTTP contract. The later +//! in-process Rust embedder drops in behind the same trait with no caller change. +//! +//! The vector index (Qdrant Edge) and the record schema land in later increments; +//! this module fixes the embedder seam first so the spike and the production path +//! share one interface. + +use std::io::Read; +use std::time::Duration; + +pub mod workspace; +pub use workspace::{ + ExecReport, Outcome, VectorSlot, VectorSource, VectorWorkspace, WorkspaceError, +}; + +pub mod index; +pub use index::{Hit, IndexError, MemoryIndex, MemoryRecord}; + +/// Default dense dimension of BGE-M3 as served by `vetta-embedder`. +pub const BGE_M3_DIM: usize = 1024; + +/// Errors surfaced by the embedder seam. Transport failures and contract +/// violations are distinguished so callers can fail-open (e.g. persist a memory +/// record and defer re-indexing when the embedder is unreachable). +#[derive(Debug, thiserror::Error)] +pub enum EmbedError { + #[error("transport: {0}")] + Transport(String), + #[error("decode: {0}")] + Decode(String), + #[error("server error {status}: {body}")] + Server { status: u16, body: String }, + #[error("unexpected response shape: {0}")] + Shape(String), +} + +/// Dense embedding provider. One embedder for all memory content; specialization +/// happens above the index (directive packs), not by swapping models per use. +pub trait Embedder: Send + Sync { + /// Return one L2-normalized dense vector per input text, in order. + fn embed(&self, texts: &[&str]) -> Result>, EmbedError>; + + /// Vector dimension this embedder emits (used to size + validate the index). + fn dim(&self) -> usize; + + /// Stable model identifier. Persisted alongside the index so that switching + /// embedders (or quantization) is detectable and forces a rebuild instead of + /// silently mixing incompatible vectors. + fn model_id(&self) -> &str; +} + +/// A single reranked document: original input index + relevance score. Scores are +/// raw cross-encoder logits; only their ordering is meaningful. +#[derive(Debug, Clone, PartialEq)] +pub struct Reranked { + pub index: usize, + pub score: f64, +} + +/// Optional second-stage capability. Kept as a separate trait (not a method on +/// [`Embedder`]) so an embedder without a reranker still satisfies the core +/// interface, and consumers probe for reranking at runtime. +pub trait Reranker: Send + Sync { + fn rerank(&self, query: &str, docs: &[&str], top_n: usize) + -> Result, EmbedError>; +} + +/// [`Embedder`] + [`Reranker`] backend over the `vetta-embedder` HTTP contract: +/// `POST /embed {texts:[...]} -> {embeddings:[[...]]}` and +/// `POST /rerank {query,documents,top_n} -> {results:[{index,score,document}]}`. +/// +/// Synchronous by design (a library must not dictate an async runtime); strata-ctl +/// calls it from `tokio::task::spawn_blocking`. +pub struct HttpEmbedder { + base_url: String, + model_id: String, + dim: usize, + timeout: Duration, +} + +impl HttpEmbedder { + /// `base_url` is e.g. `http://192.168.50.18:8091` (supplied by the caller from + /// the DB config — deliberately not hardcoded here). `model_id` tags the index. + pub fn new(base_url: impl Into, model_id: impl Into, dim: usize) -> Self { + Self { + base_url: base_url.into(), + model_id: model_id.into(), + dim, + timeout: Duration::from_secs(8), + } + } + + pub fn with_timeout(mut self, timeout: Duration) -> Self { + self.timeout = timeout; + self + } + + fn agent(&self) -> ureq::Agent { + ureq::Agent::config_builder() + .timeout_global(Some(self.timeout)) + .build() + .new_agent() + } + + fn post_json( + &self, + path: &str, + body: &serde_json::Value, + ) -> Result { + let url = format!("{}{}", self.base_url.trim_end_matches('/'), path); + let mut resp = self + .agent() + .post(&url) + .send_json(body) + .map_err(|e| EmbedError::Transport(e.to_string()))?; + let status = resp.status().as_u16(); + let mut buf = Vec::new(); + resp.body_mut() + .as_reader() + .read_to_end(&mut buf) + .map_err(|e| EmbedError::Transport(e.to_string()))?; + if !(200..300).contains(&status) { + let body = String::from_utf8_lossy(&buf).chars().take(512).collect(); + return Err(EmbedError::Server { status, body }); + } + serde_json::from_slice(&buf).map_err(|e| EmbedError::Decode(e.to_string())) + } +} + +/// Parse `{"embeddings": [[f32, ...], ...]}`. Public-shape tolerant: reads numbers +/// via `as_f64` and narrows to f32. +fn parse_embeddings(v: &serde_json::Value) -> Result>, EmbedError> { + let arr = v + .get("embeddings") + .and_then(|e| e.as_array()) + .ok_or_else(|| EmbedError::Shape("missing 'embeddings' array".into()))?; + arr.iter() + .map(|row| { + row.as_array() + .map(|r| { + r.iter() + .filter_map(|x| x.as_f64().map(|f| f as f32)) + .collect::>() + }) + .ok_or_else(|| EmbedError::Shape("embedding row is not an array".into())) + }) + .collect() +} + +/// Parse `{"results": [{"index": n, "score": s}, ...]}` into [`Reranked`]. +fn parse_rerank(v: &serde_json::Value) -> Result, EmbedError> { + let arr = v + .get("results") + .and_then(|e| e.as_array()) + .ok_or_else(|| EmbedError::Shape("missing 'results' array".into()))?; + arr.iter() + .map(|r| { + let index = r + .get("index") + .and_then(|i| i.as_u64()) + .ok_or_else(|| EmbedError::Shape("result missing 'index'".into()))? + as usize; + let score = r + .get("score") + .and_then(|s| s.as_f64()) + .ok_or_else(|| EmbedError::Shape("result missing 'score'".into()))?; + Ok(Reranked { index, score }) + }) + .collect() +} + +impl Embedder for HttpEmbedder { + fn embed(&self, texts: &[&str]) -> Result>, EmbedError> { + let body = serde_json::json!({ "texts": texts }); + let v = self.post_json("/embed", &body)?; + let out = parse_embeddings(&v)?; + if out.len() != texts.len() { + return Err(EmbedError::Shape(format!( + "expected {} vectors, got {}", + texts.len(), + out.len() + ))); + } + for row in &out { + if row.len() != self.dim { + return Err(EmbedError::Shape(format!( + "expected dim {}, got {}", + self.dim, + row.len() + ))); + } + } + Ok(out) + } + + fn dim(&self) -> usize { + self.dim + } + + fn model_id(&self) -> &str { + &self.model_id + } +} + +impl Reranker for HttpEmbedder { + fn rerank( + &self, + query: &str, + docs: &[&str], + top_n: usize, + ) -> Result, EmbedError> { + let body = serde_json::json!({ "query": query, "documents": docs, "top_n": top_n }); + let v = self.post_json("/rerank", &body)?; + parse_rerank(&v) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_embeddings_reads_dense_rows() { + let json = serde_json::json!({"embeddings": [[0.1, 0.2, 0.3], [-0.4, 0.5, 0.6]]}); + let out = parse_embeddings(&json).unwrap(); + assert_eq!(out.len(), 2); + assert_eq!(out[0].len(), 3); + assert!((out[0][0] - 0.1).abs() < 1e-6); + } + + #[test] + fn parse_embeddings_rejects_missing_key() { + let json = serde_json::json!({"error": "no texts provided"}); + assert!(matches!(parse_embeddings(&json), Err(EmbedError::Shape(_)))); + } + + #[test] + fn parse_rerank_preserves_order_and_index() { + // Shape captured live from :8091/rerank. + let json = serde_json::json!({ + "query": "come si configura il token MCP", + "results": [ + {"index": 1, "score": -1.708251, "document": "mcp token"}, + {"index": 0, "score": -10.783061, "document": "gatto"}, + {"index": 2, "score": -11.032022, "document": "carbonara"} + ] + }); + let out = parse_rerank(&json).unwrap(); + assert_eq!(out[0].index, 1); // most relevant first + assert_eq!(out[1].index, 0); + assert_eq!(out[2].index, 2); + assert!(out[0].score > out[1].score); + } + + #[test] + fn dim_is_reported_and_used_for_validation() { + let e = HttpEmbedder::new("http://127.0.0.1:9", "bge-m3-q8", BGE_M3_DIM); + assert_eq!(e.dim(), 1024); + assert_eq!(e.model_id(), "bge-m3-q8"); + } + + /// Hits the real Altair instance; run explicitly with the LAN reachable. + /// `cargo test -- --ignored` — mirrors the repo's convention for live checks. + #[test] + #[ignore] + fn live_embed_altair_returns_unit_norm_dense() { + let e = HttpEmbedder::new("http://192.168.50.18:8091", "bge-m3-q8", BGE_M3_DIM); + let v = e.embed(&["Il gatto nero salta sul tavolo"]).unwrap(); + assert_eq!(v[0].len(), 1024); + let norm: f32 = v[0].iter().map(|x| x * x).sum::().sqrt(); + assert!( + (norm - 1.0).abs() < 1e-3, + "expected L2-normalized, got norm {norm}" + ); + } +} diff --git a/strata-memory/src/workspace.rs b/strata-memory/src/workspace.rs new file mode 100644 index 0000000..27a1633 --- /dev/null +++ b/strata-memory/src/workspace.rs @@ -0,0 +1,804 @@ +//! Symbolic vector workspace — an RPN calculator over embeddings with 16 +//! persistent per-session slots `$VEC[0..15]`. +//! +//! Design principle (Federico): vectors are handled SYMBOLICALLY. The full +//! 1024-float arrays live server-side (in the slots / the index); what reaches +//! the model is only references (`$VEC[n]`), scalar metrics (COS/DOT/NORM), +//! slot metadata, and at most an 8-value preview. [`ExecReport`] carries an +//! [`Outcome`] that structurally cannot contain a full vector, so the rendering +//! path can never dump the array into context. +//! +//! Adapted from our own Iris `vector_workspace` (RPN "Vera Core"), focused on the +//! vector algebra; the scientific-calculator extras (trig/log/HP.X bridge) are +//! intentionally trimmed. The vector primitives are reimplemented here (trivial +//! f32 ops) so the crate stays self-contained. + +use serde::{Deserialize, Serialize}; + +use crate::{EmbedError, Embedder}; + +/// Number of persistent slots per session (`$VEC[0]..$VEC[15]`). +pub const VECTOR_SLOT_COUNT: usize = 16; +/// Max floats shown when previewing a vector result (never the full array). +const PREVIEW_LEN: usize = 8; + +/// Provenance of a stored vector. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum VectorSource { + TextEmbedding, + Copied, + Derived, +} + +impl VectorSource { + pub fn as_str(self) -> &'static str { + match self { + VectorSource::TextEmbedding => "TextEmbedding", + VectorSource::Copied => "Copied", + VectorSource::Derived => "Derived", + } + } +} + +/// One persistent slot. The `vector` is the real data, kept server-side; it is +/// serialized only for DB persistence (strata-ctl owns the Store), never for the +/// model-facing report. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct VectorSlot { + pub dims: usize, + pub label: Option, + pub source: VectorSource, + pub updated_at: String, + pub vector: Vec, +} + +/// The per-session workspace. Serializable so strata-ctl can persist it in the DB. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct VectorWorkspace { + pub slots: [Option; VECTOR_SLOT_COUNT], +} + +impl Default for VectorWorkspace { + fn default() -> Self { + Self::new() + } +} + +/// Errors from lexing/evaluating a program or resolving a slot reference. +#[derive(Debug, thiserror::Error)] +pub enum WorkspaceError { + #[error("parse: {0}")] + Parse(String), + #[error("stack: {0}")] + Stack(String), + #[error("type: {0}")] + Type(String), + #[error("slot: {0}")] + Slot(String), + #[error("dims: {0}")] + Dims(String), + #[error(transparent)] + Embed(#[from] EmbedError), +} + +/// A model-facing result. Deliberately has NO full-vector variant: a vector is +/// summarized as `dims` + an ≤8-value `preview`, so the array cannot leak into +/// context through the report. +#[derive(Debug, Clone, PartialEq)] +pub enum Outcome { + Scalar(f64), + Text(String), + Vector { dims: usize, preview: String }, +} + +/// Result of executing a program: the final stack value (summarized), the slots +/// touched, and human-readable notes (INFO/LIST). +#[derive(Debug, Clone, Default)] +pub struct ExecReport { + pub result: Option, + pub touched_slots: Vec, + pub notes: Vec, +} + +// Internal runtime value: during evaluation the stack DOES hold full vectors; +// they are summarized into an Outcome only when building the report. +#[derive(Debug, Clone)] +enum Value { + Text(String), + Scalar(f64), + Vector(Vec), +} + +#[derive(Debug, Clone)] +enum Token { + Word(String), + Quoted(String), +} + +impl VectorWorkspace { + pub fn new() -> Self { + Self { + slots: std::array::from_fn(|_| None), + } + } + + /// Resolve a symbolic reference (`$VEC[n]`) to its vector, server-side. This + /// is the bridge used by search: the model passes `"$VEC[0]"`, the framework + /// resolves it here and feeds the index — the floats never enter context. + pub fn resolve(&self, reference: &str) -> Result, WorkspaceError> { + let idx = parse_slot_ref(reference)?; + self.slots[idx] + .as_ref() + .map(|s| s.vector.clone()) + .ok_or_else(|| WorkspaceError::Slot(format!("$VEC[{idx}] is empty"))) + } + + /// Execute an RPN program. `embedder` backs the `EMB` op. + pub fn execute( + &mut self, + program: &str, + embedder: &dyn Embedder, + ) -> Result { + let tokens = lex(program)?; + let mut stack: Vec = Vec::new(); + let mut touched: Vec = Vec::new(); + let mut notes: Vec = Vec::new(); + let mut i = 0; + + while i < tokens.len() { + match &tokens[i] { + Token::Quoted(text) => { + stack.push(Value::Text(text.clone())); + i += 1; + } + Token::Word(word) => { + if let Ok(v) = word.parse::() { + stack.push(Value::Scalar(v)); + i += 1; + continue; + } + let op = word.to_ascii_uppercase(); + match op.as_str() { + // ── stack ── + "DUP" => { + let top = stack.last().cloned().ok_or_else(|| under("DUP"))?; + stack.push(top); + i += 1; + } + "DROP" => { + stack.pop().ok_or_else(|| under("DROP"))?; + i += 1; + } + "SWAP" => { + need(&stack, 2, "SWAP")?; + let n = stack.len(); + stack.swap(n - 1, n - 2); + i += 1; + } + "OVER" => { + need(&stack, 2, "OVER")?; + let v = stack[stack.len() - 2].clone(); + stack.push(v); + i += 1; + } + "ROT" => { + need(&stack, 3, "ROT")?; + let a = stack.pop().unwrap(); + let b = stack.pop().unwrap(); + let c = stack.pop().unwrap(); + stack.push(b); + stack.push(a); + stack.push(c); + i += 1; + } + "CLEAR" => { + stack.clear(); + i += 1; + } + // ── scalar ── + "+" | "-" | "*" | "/" | "POW" | "^" | "GT" | ">" | "LT" | "<" | "EQ" + | "==" => { + let b = pop_scalar(&mut stack)?; + let a = pop_scalar(&mut stack)?; + let r = match op.as_str() { + "+" => a + b, + "-" => a - b, + "*" => a * b, + "/" => { + if b == 0.0 { + return Err(WorkspaceError::Stack( + "division by zero".into(), + )); + } + a / b + } + "POW" | "^" => a.powf(b), + "GT" | ">" => bool_num(a > b), + "LT" | "<" => bool_num(a < b), + _ => bool_num((a - b).abs() < 1e-9), + }; + stack.push(Value::Scalar(r)); + i += 1; + } + "SQRT" | "ABS" | "NEG" | "NOT" | "!" => { + let a = pop_scalar(&mut stack)?; + let r = match op.as_str() { + "SQRT" => a.sqrt(), + "ABS" => a.abs(), + "NEG" => -a, + _ => bool_num(a == 0.0), + }; + stack.push(Value::Scalar(r)); + i += 1; + } + // ── embeddings / slots ── + "EMB" => { + let text = pop_text(&mut stack)?; + let mut v = embedder.embed(&[text.as_str()])?; + let vec = v.pop().ok_or_else(|| { + WorkspaceError::Embed(EmbedError::Shape("empty".into())) + })?; + stack.push(Value::Vector(vec)); + i += 1; + } + "RCL" => { + let idx = parse_slot_arg(tokens.get(i + 1))?; + let stored = self.slots[idx].as_ref().ok_or_else(|| { + WorkspaceError::Slot(format!("$VEC[{idx}] is empty")) + })?; + stack.push(Value::Vector(stored.vector.clone())); + i += 2; + } + "STO" => { + let idx = parse_slot_arg(tokens.get(i + 1))?; + let vec = pop_vector(&mut stack)?; + let label = self.slots[idx].as_ref().and_then(|s| s.label.clone()); + self.slots[idx] = Some(VectorSlot { + dims: vec.len(), + label, + source: VectorSource::Copied, + updated_at: now_stamp(), + vector: vec, + }); + touch(&mut touched, idx); + i += 2; + } + "CLR" => { + let idx = parse_slot_arg(tokens.get(i + 1))?; + self.slots[idx] = None; + touch(&mut touched, idx); + i += 2; + } + "LABEL" => { + let idx = parse_slot_arg(tokens.get(i + 1))?; + let label = parse_label_arg(tokens.get(i + 2))?; + let entry = self.slots[idx].as_mut().ok_or_else(|| { + WorkspaceError::Slot(format!("cannot label empty $VEC[{idx}]")) + })?; + entry.label = Some(label); + entry.updated_at = now_stamp(); + touch(&mut touched, idx); + i += 3; + } + "INFO" => { + let idx = parse_slot_arg(tokens.get(i + 1))?; + notes.push(self.slot_line(idx)); + i += 2; + } + "LIST" => { + notes.push(self.list()); + i += 1; + } + // ── vector algebra ── + "V+" | "V-" | "AVG" | "WAVG" => { + let w = if op == "WAVG" { + Some(pop_scalar(&mut stack)? as f32) + } else { + None + }; + let rhs = pop_vector(&mut stack)?; + let lhs = pop_vector(&mut stack)?; + let r = match op.as_str() { + "V+" => v_add(&lhs, &rhs)?, + "V-" => v_sub(&lhs, &rhs)?, + "AVG" => v_scale(&v_add(&lhs, &rhs)?, 0.5), + _ => v_wavg(&lhs, &rhs, w.unwrap()), + }; + stack.push(Value::Vector(r)); + i += 1; + } + "UNIT" => { + let v = pop_vector(&mut stack)?; + stack.push(Value::Vector(v_unit(&v)?)); + i += 1; + } + "SCALE" => { + let top = stack.pop().ok_or_else(|| under("SCALE"))?; + let second = stack.pop().ok_or_else(|| under("SCALE"))?; + let (vec, s) = match (second, top) { + (Value::Vector(v), Value::Scalar(s)) => (v, s as f32), + (Value::Scalar(s), Value::Vector(v)) => (v, s as f32), + _ => { + return Err(WorkspaceError::Type( + "SCALE expects one vector and one scalar".into(), + )) + } + }; + stack.push(Value::Vector(v_scale(&vec, s))); + i += 1; + } + "COS" | "DOT" | "DIST" | "PROJ" => { + let rhs = pop_vector(&mut stack)?; + let lhs = pop_vector(&mut stack)?; + let r = match op.as_str() { + "COS" => v_cosine(&lhs, &rhs)? as f64, + "DOT" => v_dot(&lhs, &rhs)? as f64, + "DIST" => 1.0 - v_cosine(&lhs, &rhs)? as f64, + _ => v_proj(&lhs, &rhs)? as f64, + }; + stack.push(Value::Scalar(r)); + i += 1; + } + "NORM" => { + let v = pop_vector(&mut stack)?; + stack.push(Value::Scalar(v_norm(&v) as f64)); + i += 1; + } + _ => { + return Err(WorkspaceError::Parse(format!("unknown token '{word}'"))); + } + } + } + } + } + + let result = stack.last().map(summarize); + Ok(ExecReport { + result, + touched_slots: touched, + notes, + }) + } + + /// Model-facing rendering: scalars, text, slot metadata, ≤8-value previews. + /// Never the full vector. + pub fn render(&self, report: &ExecReport) -> String { + let mut lines = vec!["VectorWorkspace executed successfully.".to_string()]; + match &report.result { + Some(Outcome::Scalar(v)) => lines.push(format!("Final result: scalar {v:.6}")), + Some(Outcome::Text(t)) => lines.push(format!("Final result: text \"{t}\"")), + Some(Outcome::Vector { dims, preview }) => { + lines.push(format!("Final result: vector[{dims}] = [{preview}]")) + } + None => lines.push("Final result: no stack value.".to_string()), + } + if !report.touched_slots.is_empty() { + lines.push("Touched slots:".to_string()); + for idx in &report.touched_slots { + lines.push(self.slot_line(*idx)); + } + } + if !report.notes.is_empty() { + lines.push("Notes:".to_string()); + lines.extend(report.notes.iter().cloned()); + } + lines.join("\n") + } + + /// Occupied-slot listing (metadata only). + pub fn list(&self) -> String { + let occupied: Vec = self + .slots + .iter() + .enumerate() + .filter_map(|(idx, s)| s.as_ref().map(|_| self.slot_line(idx))) + .collect(); + if occupied.is_empty() { + "Occupied slots: none".to_string() + } else { + format!("Occupied slots:\n{}", occupied.join("\n")) + } + } + + fn slot_line(&self, idx: usize) -> String { + match &self.slots[idx] { + Some(s) => { + let label = s + .label + .as_ref() + .map(|l| format!(" label=\"{l}\"")) + .unwrap_or_default(); + format!( + "- $VEC[{idx}]: occupied=true dims={} source={}{} updated_at={}", + s.dims, + s.source.as_str(), + label, + s.updated_at + ) + } + None => format!("- $VEC[{idx}]: occupied=false"), + } + } +} + +// ── summarization / preview (the symbolic boundary) ── + +fn summarize(v: &Value) -> Outcome { + match v { + Value::Scalar(s) => Outcome::Scalar(*s), + Value::Text(t) => Outcome::Text(t.clone()), + Value::Vector(vec) => Outcome::Vector { + dims: vec.len(), + preview: preview_vector(vec), + }, + } +} + +fn preview_vector(vec: &[f32]) -> String { + let head: Vec = vec + .iter() + .take(PREVIEW_LEN) + .map(|v| format!("{v:.4}")) + .collect(); + if vec.len() > PREVIEW_LEN { + format!("{}, ...", head.join(", ")) + } else { + head.join(", ") + } +} + +// ── vector primitives (reimplemented, self-contained) ── + +fn check_dims(a: &[f32], b: &[f32]) -> Result<(), WorkspaceError> { + if a.len() != b.len() { + return Err(WorkspaceError::Dims(format!("{} vs {}", a.len(), b.len()))); + } + Ok(()) +} + +fn v_add(a: &[f32], b: &[f32]) -> Result, WorkspaceError> { + check_dims(a, b)?; + Ok(a.iter().zip(b).map(|(x, y)| x + y).collect()) +} + +fn v_sub(a: &[f32], b: &[f32]) -> Result, WorkspaceError> { + check_dims(a, b)?; + Ok(a.iter().zip(b).map(|(x, y)| x - y).collect()) +} + +fn v_scale(a: &[f32], s: f32) -> Vec { + a.iter().map(|x| x * s).collect() +} + +/// Linear interpolation: `lhs*(1-w) + rhs*w`. +fn v_wavg(a: &[f32], b: &[f32], w: f32) -> Vec { + a.iter() + .zip(b) + .map(|(x, y)| x * (1.0 - w) + y * w) + .collect() +} + +fn v_dot(a: &[f32], b: &[f32]) -> Result { + check_dims(a, b)?; + Ok(a.iter().zip(b).map(|(x, y)| x * y).sum()) +} + +fn v_norm(a: &[f32]) -> f32 { + a.iter().map(|x| x * x).sum::().sqrt() +} + +fn v_unit(a: &[f32]) -> Result, WorkspaceError> { + let n = v_norm(a); + if n <= 1e-12 { + return Err(WorkspaceError::Dims( + "cannot normalize a zero vector".into(), + )); + } + Ok(v_scale(a, 1.0 / n)) +} + +fn v_cosine(a: &[f32], b: &[f32]) -> Result { + check_dims(a, b)?; + let na = v_norm(a); + let nb = v_norm(b); + if na <= 1e-12 || nb <= 1e-12 { + return Err(WorkspaceError::Dims("cosine with a zero vector".into())); + } + Ok(v_dot(a, b)? / (na * nb)) +} + +/// Scalar projection of `a` onto `b`: `dot(a,b)/|b|`. +fn v_proj(a: &[f32], b: &[f32]) -> Result { + check_dims(a, b)?; + let nb = v_norm(b); + if nb <= 1e-12 { + return Err(WorkspaceError::Dims("projection onto a zero vector".into())); + } + Ok(v_dot(a, b)? / nb) +} + +// ── lexing / parsing helpers ── + +fn lex(input: &str) -> Result, WorkspaceError> { + let chars: Vec = input.chars().collect(); + let mut out = Vec::new(); + let mut i = 0; + while i < chars.len() { + if chars[i].is_whitespace() { + i += 1; + continue; + } + if chars[i] == '"' { + i += 1; + let mut s = String::new(); + while i < chars.len() && chars[i] != '"' { + s.push(chars[i]); + i += 1; + } + if i >= chars.len() { + return Err(WorkspaceError::Parse("unterminated quoted string".into())); + } + i += 1; // closing quote + out.push(Token::Quoted(s)); + continue; + } + let start = i; + while i < chars.len() && !chars[i].is_whitespace() { + i += 1; + } + out.push(Token::Word(chars[start..i].iter().collect())); + } + Ok(out) +} + +fn parse_slot_ref(raw: &str) -> Result { + let upper = raw.to_ascii_uppercase(); + let inner = upper + .strip_prefix("$VEC[") + .and_then(|s| s.strip_suffix(']')) + .ok_or_else(|| { + WorkspaceError::Parse(format!("invalid slot reference '{raw}', expected $VEC[n]")) + })?; + let idx: usize = inner + .parse() + .map_err(|_| WorkspaceError::Parse(format!("invalid slot index in '{raw}'")))?; + if idx >= VECTOR_SLOT_COUNT { + return Err(WorkspaceError::Slot(format!( + "$VEC[{idx}] out of range (0..{})", + VECTOR_SLOT_COUNT - 1 + ))); + } + Ok(idx) +} + +fn parse_slot_arg(token: Option<&Token>) -> Result { + match token { + Some(Token::Word(w)) => parse_slot_ref(w), + Some(Token::Quoted(_)) => Err(WorkspaceError::Parse( + "expected $VEC[n], got quoted text".into(), + )), + None => Err(WorkspaceError::Parse("missing slot reference".into())), + } +} + +fn parse_label_arg(token: Option<&Token>) -> Result { + match token { + Some(Token::Quoted(t)) | Some(Token::Word(t)) => Ok(t.clone()), + None => Err(WorkspaceError::Parse("missing label text".into())), + } +} + +fn pop_text(stack: &mut Vec) -> Result { + match stack.pop() { + Some(Value::Text(t)) => Ok(t), + Some(_) => Err(WorkspaceError::Type("expected text".into())), + None => Err(under("text")), + } +} + +fn pop_vector(stack: &mut Vec) -> Result, WorkspaceError> { + match stack.pop() { + Some(Value::Vector(v)) => Ok(v), + Some(_) => Err(WorkspaceError::Type("expected vector".into())), + None => Err(under("vector")), + } +} + +fn pop_scalar(stack: &mut Vec) -> Result { + match stack.pop() { + Some(Value::Scalar(v)) => Ok(v), + Some(_) => Err(WorkspaceError::Type("expected scalar".into())), + None => Err(under("scalar")), + } +} + +fn under(op: &str) -> WorkspaceError { + WorkspaceError::Stack(format!("underflow on {op}")) +} + +fn need(stack: &[Value], n: usize, op: &str) -> Result<(), WorkspaceError> { + if stack.len() < n { + return Err(under(op)); + } + Ok(()) +} + +fn bool_num(b: bool) -> f64 { + if b { + 1.0 + } else { + 0.0 + } +} + +fn touch(touched: &mut Vec, idx: usize) { + if !touched.contains(&idx) { + touched.push(idx); + } +} + +fn now_stamp() -> String { + // No chrono dependency in this crate: a stable UTC timestamp from SystemTime. + match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) { + Ok(d) => format!("{}", d.as_secs()), + Err(_) => "0".to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Deterministic embedder for hermetic tests: maps text to a small vector. + struct StubEmbedder; + impl Embedder for StubEmbedder { + fn embed(&self, texts: &[&str]) -> Result>, EmbedError> { + Ok(texts + .iter() + .map(|t| { + let n = t.len() as f32; + vec![n, n * 2.0, n * 3.0, 0.0] + }) + .collect()) + } + fn dim(&self) -> usize { + 4 + } + fn model_id(&self) -> &str { + "stub" + } + } + + #[test] + fn slot_ref_parse_and_range() { + assert_eq!(parse_slot_ref("$VEC[3]").unwrap(), 3); + assert_eq!(parse_slot_ref("$vec[15]").unwrap(), 15); + assert!(parse_slot_ref("$VEC[16]").is_err()); + assert!(parse_slot_ref("VEC[0]").is_err()); + } + + #[test] + fn lex_preserves_quoted_strings() { + let t = lex("\"hello world\" EMB STO $VEC[0]").unwrap(); + assert!(matches!(&t[0], Token::Quoted(s) if s == "hello world")); + assert!(matches!(&t[1], Token::Word(s) if s == "EMB")); + assert!(matches!(&t[3], Token::Word(s) if s == "$VEC[0]")); + } + + #[test] + fn emb_sto_rcl_cos_roundtrip() { + let mut ws = VectorWorkspace::new(); + let e = StubEmbedder; + // "ab" -> [2,4,6,0]; "abcd" -> [4,8,12,0] (parallel => cosine 1.0) + ws.execute("\"ab\" EMB STO $VEC[0]", &e).unwrap(); + let rep = ws.execute("\"abcd\" EMB RCL $VEC[0] COS", &e).unwrap(); + match rep.result { + Some(Outcome::Scalar(s)) => assert!((s - 1.0).abs() < 1e-5, "cos={s}"), + other => panic!("expected scalar cosine, got {other:?}"), + } + assert_eq!(ws.resolve("$VEC[0]").unwrap().len(), 4); + } + + #[test] + fn unit_normalizes_to_one() { + let mut ws = VectorWorkspace::new(); + let rep = ws.execute("\"abc\" EMB UNIT NORM", &StubEmbedder).unwrap(); + match rep.result { + Some(Outcome::Scalar(s)) => assert!((s - 1.0).abs() < 1e-5), + other => panic!("expected norm 1, got {other:?}"), + } + } + + #[test] + fn report_never_leaks_full_vector() { + let mut ws = VectorWorkspace::new(); + // 4-dim stub vector: preview shows all 4 (<=8). Use a longer one via SCALE? dims stay 4. + let rep = ws.execute("\"abc\" EMB", &StubEmbedder).unwrap(); + match &rep.result { + Some(Outcome::Vector { dims, preview }) => { + assert_eq!(*dims, 4); + // preview is a short string, not the serialized array + assert!(preview.split(',').count() <= PREVIEW_LEN); + } + other => panic!("expected vector outcome, got {other:?}"), + } + let rendered = ws.render(&rep); + assert!(rendered.contains("vector[4]")); + // The rendered report must not contain a JSON-style full array of the vector. + assert!(!rendered.contains("[3.0, 6.0, 9.0")); + } + + #[test] + fn preview_caps_at_eight() { + let long: Vec = (0..1024).map(|i| i as f32).collect(); + let p = preview_vector(&long); + assert!(p.ends_with("...")); + assert_eq!(p.trim_end_matches(", ...").split(',').count(), PREVIEW_LEN); + } + + #[test] + fn dim_mismatch_is_error() { + assert!(v_add(&[1.0, 2.0], &[1.0]).is_err()); + assert!(v_cosine(&[1.0, 2.0], &[1.0]).is_err()); + assert!(v_unit(&[0.0, 0.0]).is_err()); + } + + #[test] + fn label_and_list_metadata_only() { + let mut ws = VectorWorkspace::new(); + ws.execute( + "\"ab\" EMB STO $VEC[0] LABEL $VEC[0] \"gatto\"", + &StubEmbedder, + ) + .unwrap(); + let listing = ws.list(); + assert!(listing.contains("label=\"gatto\"")); + assert!(listing.contains("dims=4")); + // metadata listing carries no float values + assert!(!listing.contains("2.0000")); + } + + #[test] + fn scale_accepts_vector_scalar_either_order() { + let mut ws = VectorWorkspace::new(); + let rep = ws + .execute("\"ab\" EMB 0.5 SCALE NORM", &StubEmbedder) + .unwrap(); + // [2,4,6,0]*0.5 = [1,2,3,0], norm = sqrt(14) ≈ 3.7417 + match rep.result { + Some(Outcome::Scalar(s)) => assert!((s - 14.0f64.sqrt()).abs() < 1e-4), + other => panic!("expected scalar norm, got {other:?}"), + } + } + + /// Live symbolic flow against Altair: EMB two phrases into slots, COS yields a + /// scalar (never the array); slots hold 1024-dim vectors server-side while the + /// listing shows only metadata. `cargo test -p strata-memory -- --ignored`. + #[test] + #[ignore] + fn live_symbolic_cos_altair() { + let e = + crate::HttpEmbedder::new("http://192.168.50.18:8091", "bge-m3-q8", crate::BGE_M3_DIM); + let mut ws = VectorWorkspace::new(); + ws.execute("\"Il gatto nero salta sul tavolo\" EMB STO $VEC[0]", &e) + .unwrap(); + ws.execute( + "\"Un felino scuro balza sopra il tavolo\" EMB STO $VEC[1]", + &e, + ) + .unwrap(); + let rep = ws.execute("RCL $VEC[0] RCL $VEC[1] COS", &e).unwrap(); + match rep.result { + Some(Outcome::Scalar(s)) => { + assert!( + (0.5..=1.0).contains(&s), + "paraphrase cosine should be high, got {s}" + ) + } + other => panic!("expected scalar cosine, got {other:?}"), + } + let listing = ws.list(); + assert!(listing.contains("dims=1024")); + assert!(ws.render(&rep).contains("scalar")); + } +} diff --git a/tests/api_sessions.rs b/tests/api_sessions.rs index 87b9123..a5ab45a 100644 --- a/tests/api_sessions.rs +++ b/tests/api_sessions.rs @@ -75,7 +75,7 @@ async fn build_app() -> (axum::Router, Arc) { .unwrap() .as_nanos(); let root = std::env::temp_dir().join(format!("strata-ctl-test-{nanos}")); - let app = router_with_store(svc, store.clone(), AuthConfig::default(), root); + let app = router_with_store(svc, store.clone(), AuthConfig::default(), root, None); (app, store) } @@ -163,6 +163,25 @@ async fn mcp_connector_crud_and_validation() { assert_eq!(st, StatusCode::NOT_FOUND); } +#[tokio::test] +async fn memory_enable_rejected_without_service() { + let (app, _store) = build_app().await; + let id = create_session(&app).await; + // No memory service in this app -> enabling the one-way latch is refused. + let (st, text) = req( + &app, + Method::PATCH, + &format!("/api/sessions/{id}"), + Some(serde_json::json!({"settings": {"memory_enabled": true}})), + ) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST, "{text}"); + // The rejected enable did not persist: the session stays off. + let (_, text) = req(&app, Method::GET, &format!("/api/sessions/{id}"), None).await; + let v: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(v["settings"]["memory_enabled"], false); +} + #[tokio::test] async fn session_holds_context_and_persists_usage() { let (app, _store) = build_app().await; diff --git a/web/assets/app.js b/web/assets/app.js index f354f96..9dbdc0c 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -800,6 +800,17 @@ function fillSettingsForm(data, scope) { // MCP: catalog editor in Generali, per-session tool allowlist in Sessione. $("#set-mcp-catalog").hidden = scope !== "general"; $("#set-mcp-tools").hidden = scope !== "session"; + // Semantic memory: per-session ONE-WAY opt-in (hidden in Generali). Once on, + // the checkbox is disabled — it can never be turned off (irreversible latch). + $("#set-memory-field").hidden = !isSession; + if (isSession) { + const on = !!data.memory_enabled; + $("#set-memory").checked = on; + $("#set-memory").disabled = on; + $("#set-memory-hint").textContent = on + ? t("settings.memory.hint.on") + : t("settings.memory.hint.off"); + } } function readSettingsForm() { @@ -855,6 +866,10 @@ async function saveSettings() { applyFontSize(Number($("#set-fontsize").value)); // Preserve unexposed fields (seed, penalties) from the loaded instance. const settings = { ...settingsBase, ...readSettingsForm() }; + // One-way memory latch in the UI too: checking enables, never un-enables. + if (settingsScope === "session") { + settings.memory_enabled = $("#set-memory").checked || !!settingsBase.memory_enabled; + } try { if (settingsScope === "session") { const sess = currentSession(); diff --git a/web/assets/locales/en.json b/web/assets/locales/en.json index 1ed3a30..721f1ed 100644 --- a/web/assets/locales/en.json +++ b/web/assets/locales/en.json @@ -38,6 +38,10 @@ "settings.mcp.fields.required": "Name, URL and token are required.", "settings.mcp.saved": "Connector saved.", "settings.mcp.error": "MCP error: {msg}", + "settings.memory.title": "Semantic memory", + "settings.memory.label": "Enable long-term memory for this chat", + "settings.memory.hint.off": "Off by default. Once enabled it cannot be disabled (memories stay recallable). Requires a reachable embedder.", + "settings.memory.hint.on": "Enabled for this chat: remember/recall/forget. Cannot be disabled.", "settings.save": "Save", "settings.cancel": "Cancel", "settings.hint.session": "Changes apply only to this session.", diff --git a/web/assets/locales/it.json b/web/assets/locales/it.json index 5d01763..a56b680 100644 --- a/web/assets/locales/it.json +++ b/web/assets/locales/it.json @@ -38,6 +38,10 @@ "settings.mcp.fields.required": "Nome, URL e token sono obbligatori.", "settings.mcp.saved": "Connettore salvato.", "settings.mcp.error": "Errore MCP: {msg}", + "settings.memory.title": "Memoria semantica", + "settings.memory.label": "Abilita la memoria a lungo termine per questa chat", + "settings.memory.hint.off": "Off di default. Una volta attivata non si può disattivare (le memorie restano richiamabili). Richiede l'embedder raggiungibile.", + "settings.memory.hint.on": "Attiva per questa chat: remember/recall/forget. Non si può disattivare.", "settings.save": "Salva", "settings.cancel": "Annulla", "settings.hint.session": "Modifiche valide solo per questa sessione.", diff --git a/web/index.html b/web/index.html index b99ac93..2691e35 100644 --- a/web/index.html +++ b/web/index.html @@ -145,6 +145,15 @@

Scegli quali tool di ogni connettore il modello può usare in questa chat. Salva per applicare.

+ +