diff --git a/Cargo.lock b/Cargo.lock index cd0c6da..0b77b32 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "anstream" version = "1.0.0" @@ -38,7 +44,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -49,9 +55,15 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys", + "windows-sys 0.61.2", ] +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bitflags" version = "2.13.2" @@ -67,6 +79,12 @@ dependencies = [ "generic-array", ] +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + [[package]] name = "caseless" version = "0.2.2" @@ -155,6 +173,35 @@ dependencies = [ "typed-arena", ] +[[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", + "log", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + [[package]] name = "cpufeatures" version = "0.2.17" @@ -164,6 +211,15 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32fast" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -174,6 +230,12 @@ dependencies = [ "typenum", ] +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "digest" version = "0.10.7" @@ -184,6 +246,26 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + [[package]] name = "entities" version = "1.0.1" @@ -203,7 +285,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -253,12 +335,32 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ded33109e99472f809cb7495544506eea45e366725dacf2a383e184f660456" +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "foldhash" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -269,6 +371,17 @@ dependencies = [ "version_check", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -322,6 +435,126 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -367,6 +600,24 @@ 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.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + [[package]] name = "marqdo-knowledge" version = "0.1.0" @@ -382,6 +633,7 @@ dependencies = [ "sha2", "tempfile", "unicode-normalization", + "ureq", ] [[package]] @@ -400,6 +652,22 @@ dependencies = [ "fearless_simd_macros", ] +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "once_cell" version = "1.21.4" @@ -412,6 +680,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + [[package]] name = "phf" version = "0.14.0" @@ -457,6 +731,21 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -481,6 +770,20 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rusqlite" version = "0.37.0" @@ -511,7 +814,42 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] @@ -593,6 +931,12 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "siphasher" version = "1.0.4" @@ -605,12 +949,24 @@ version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "3.0.10" @@ -622,6 +978,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -629,10 +996,50 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom", + "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", ] [[package]] @@ -674,12 +1081,83 @@ version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64", + "cookie_store", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +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 = "vcpkg" version = "0.2.15" @@ -692,12 +1170,36 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -707,6 +1209,165 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zlib-rs" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index b860a8f..3c82ecf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ serde_yaml = "=0.9.34" sha2 = "=0.10.9" tempfile = "=3.27.0" unicode-normalization = "=0.1.26" +ureq = { version = "=3.5.2", features = ["json"] } [profile.release] codegen-units = 1 diff --git a/src/compiler.rs b/src/compiler.rs index 69e0cff..4f9dfb5 100644 --- a/src/compiler.rs +++ b/src/compiler.rs @@ -47,6 +47,7 @@ pub fn compile(args: &CompileArgs, marqdo_bin: Option<&Path>) -> Result = None; + let mut embedding_vectors: Option = None; + if let Some(url) = &args.embedding.embedding_url { + let model = args + .embedding + .embedding_model + .clone() + .ok_or_else(|| KnowledgeError::usage("--embedding-model is required"))?; + let revision = args + .embedding + .embedding_revision + .clone() + .ok_or_else(|| KnowledgeError::usage("--embedding-revision is required"))?; + let config = crate::embedding::EmbeddingConfig::new( + url, + &model, + &revision, + args.embedding.allow_remote_embedding, + )?; + let client = crate::embedding::EmbeddingClient::new(&config)?; + let sources = storage::index::embedding_sources(&graph)?; + if sources.is_empty() { + return Err(KnowledgeError::environment( + code::EMBEDDING_UNAVAILABLE, + "there are no search units to embed in this root", + )); + } + let mut reused: HashMap> = HashMap::new(); + let mut dimension = 0usize; + let mut stored_digest: Option = None; + if let Some(previous) = previous_ref { + if let Some(stored) = &previous.meta.embedding { + let stored_endpoint = stored.get("endpoint").and_then(|value| value.as_str()); + let stored_model = stored.get("model").and_then(|value| value.as_str()); + let stored_revision = stored.get("revision").and_then(|value| value.as_str()); + if stored_endpoint == Some(client.endpoint()) + && stored_model == Some(model.as_str()) + && stored_revision == Some(revision.as_str()) + { + dimension = stored + .get("dimension") + .and_then(|value| value.as_u64()) + .unwrap_or(0) as usize; + stored_digest = stored + .get("model_digest") + .and_then(|value| value.as_str()) + .map(str::to_string); + } + } + } + if dimension > 0 { + let digest = config.model_digest(dimension)?; + if stored_digest.as_deref() == Some(digest.as_str()) { + reused = previous_ref + .map(|previous| previous.embedding_vectors.clone()) + .unwrap_or_default(); + } + } + let mut vectors: HashMap<(String, u64, String), Vec> = HashMap::new(); + let mut missing: Vec<&crate::embedding::EmbeddingSource> = Vec::new(); + for source in &sources { + match reused.get(&source.content_digest) { + Some(vector) => { + vectors.insert( + ( + source.node_key.clone(), + source.span_start, + source.content_digest.clone(), + ), + vector.clone(), + ); + } + None => missing.push(source), + } + } + if !missing.is_empty() { + let texts: Vec = missing.iter().map(|source| source.text.clone()).collect(); + let (new_vectors, new_dimension) = client.embed(&texts)?; + if dimension == 0 { + dimension = new_dimension; + } else if dimension != new_dimension { + return Err(KnowledgeError::environment( + code::EMBEDDING_CONFIG_MISMATCH, + "embedding model returned a different dimension than the existing index", + )); + } + for (source, vector) in missing.iter().zip(new_vectors) { + vectors.insert( + ( + source.node_key.clone(), + source.span_start, + source.content_digest.clone(), + ), + vector, + ); + } + } + if dimension == 0 { + return Err(KnowledgeError::environment( + code::EMBEDDING_INVALID_RESPONSE, + "embedding endpoint returned no dimension", + )); + } + let model_digest = config.model_digest(dimension)?; + embedding_meta = Some(serde_json::json!(crate::embedding::EmbeddingMeta { + endpoint: config.endpoint()?, + model, + revision, + dimension, + distance: crate::embedding::DISTANCE.to_string(), + model_digest: model_digest.clone(), + chunking: crate::embedding::CHUNKING.to_string(), + max_input_chars: crate::embedding::MAX_INPUT_CHARS, + })); + embedding_vectors = Some(crate::embedding::EmbeddingVectors { + model_digest, + dimension, + vectors, + }); + } + // Source recheck immediately before publishing: never mix snapshots. let changed = snapshot.verify_unchanged(); if changed.has_errors() { @@ -271,6 +389,11 @@ fn compile_inner( edges, search_units: previous.meta.search_units, grams: 0, + embeddings: previous + .meta + .embedding + .as_ref() + .map_or(0, |_| previous.meta.search_units), rebuild_generation: previous.meta.rebuild_generation, }; return Ok(CompileOutcome { @@ -300,7 +423,7 @@ fn compile_inner( .unwrap_or_else(|| "native-only".into()); meta.facts_cache_version = crate::document::facts_cache_version(); meta.rebuild_generation = generation; - meta.embedding = None; + meta.embedding = embedding_meta; if contexts.is_empty() { if let Some(previous) = previous_ref { contexts = previous.contexts.clone(); @@ -325,6 +448,7 @@ fn compile_inner( graph: &graph, snapshot: &snapshot, contexts: &contexts, + embeddings: embedding_vectors.as_ref(), })?; Ok(CompileOutcome { mode: stats.mode.clone(), @@ -406,7 +530,7 @@ pub fn check(args: &CheckArgs, marqdo_bin: Option<&Path>) -> Result) -> Result, inputs: HashMap, cache: HashMap, + embedding_vectors: HashMap>, } struct PreviousMeta { @@ -524,6 +653,7 @@ struct PreviousMeta { nodes: u64, edges: u64, search_units: u64, + embedding: Option, } impl PreviousMeta { @@ -560,6 +690,7 @@ fn load_previous_state( nodes, edges, search_units: store.search_unit_count()?, + embedding: meta.embedding.clone(), }, contexts: store.contexts()?, inputs: store @@ -568,6 +699,7 @@ fn load_previous_state( .map(|input| (input.path, input.digest)) .collect(), cache: HashMap::new(), + embedding_vectors: HashMap::new(), })); } Err(error) if error.code == code::DATABASE_OLD_SCHEMA => { @@ -584,10 +716,12 @@ fn load_previous_state( nodes: 0, edges: 0, search_units: 0, + embedding: None, }, contexts: Vec::new(), inputs: HashMap::new(), cache: HashMap::new(), + embedding_vectors: HashMap::new(), })); } Err(error) => return Err(error), @@ -598,6 +732,15 @@ fn load_previous_state( let meta = store.build_meta()?; let (documents, nodes, edges) = store.counts()?; let search_units = store.search_unit_count()?; + let embedding_vectors = match meta + .embedding + .as_ref() + .and_then(|embedding| embedding.get("model_digest")) + .and_then(|digest| digest.as_str()) + { + Some(model_digest) => store.all_embeddings_by_digest(model_digest)?, + None => HashMap::new(), + }; let mut cache = HashMap::new(); if meta.facts_cache_version == crate::document::facts_cache_version() { for document in store.documents()? { @@ -621,6 +764,7 @@ fn load_previous_state( nodes, edges, search_units, + embedding: meta.embedding.clone(), }, contexts: store.contexts()?, inputs: store @@ -629,6 +773,7 @@ fn load_previous_state( .map(|input| (input.path, input.digest)) .collect(), cache, + embedding_vectors, })) } @@ -729,7 +874,7 @@ fn fatal_from_diagnostics(diagnostics: &DiagnosticSet) -> KnowledgeError { // Referenced assets and known-missing paths // --------------------------------------------------------------------------- -fn collect_assets( +pub(crate) fn collect_assets( scope: &crate::document::Scope, snapshot: &SourceSnapshot, facts_by_path: &HashMap, @@ -741,6 +886,13 @@ fn collect_assets( .collect(); let mut candidates: Vec = Vec::new(); for facts in facts_by_path.values() { + // OKF `resource` is an explicit path field and participates in the + // snapshot as a referenced asset. + if let Some(resource) = facts.okf.resource_is_relative_path() { + if let Ok(rel) = discovery::resolve_link_path(&facts.rel_path, resource) { + candidates.push(rel); + } + } for reference in &facts.references { if let Some(analysis) = &reference.analysis { let package_matches = analysis diff --git a/src/document/analysis.rs b/src/document/analysis.rs index 23d05b8..e1aa70b 100644 --- a/src/document/analysis.rs +++ b/src/document/analysis.rs @@ -1951,6 +1951,7 @@ fn module_to_facts( let mut diagnostics = DiagnosticSet::new(); let blocks = markdown::searchable_blocks(&module.document, &units); let front_matter = markdown::front_matter_fact(&module.document, &mut diagnostics, &path); + let okf = super::okf::analyze(&path, front_matter.as_ref(), &mut diagnostics); let document_title = document_title(&units, &module.relative_path); let stdlib_digest = artifact @@ -1990,6 +1991,7 @@ fn module_to_facts( resources, blocks, front_matter, + okf, analysis: Some(analysis), diagnostics: all, }) diff --git a/src/document/markdown.rs b/src/document/markdown.rs index ad418ba..711d69b 100644 --- a/src/document/markdown.rs +++ b/src/document/markdown.rs @@ -50,6 +50,7 @@ pub fn parse_plain(file: &SourceFile) -> DocumentFacts { } let front_matter = front_matter_fact(&ast, &mut diagnostics, &file.rel_path); + let okf = super::okf::analyze(&file.rel_path, front_matter.as_ref(), &mut diagnostics); let mut units = build_units(&ast, file); fix_unit_spans(&mut units, source.len() as u64); let anchors = build_anchors(&units); @@ -73,6 +74,7 @@ pub fn parse_plain(file: &SourceFile) -> DocumentFacts { resources: Vec::new(), blocks, front_matter, + okf, analysis: None::, diagnostics, } diff --git a/src/document/mod.rs b/src/document/mod.rs index ad23868..6bbe6e1 100644 --- a/src/document/mod.rs +++ b/src/document/mod.rs @@ -521,6 +521,9 @@ pub struct DocumentFacts { pub resources: Vec, pub blocks: Vec, pub front_matter: Option, + /// OKF document-layer recognition. Metadata never changes program semantics. + #[serde(default)] + pub okf: okf::OkfInfo, pub analysis: Option, pub diagnostics: DiagnosticSet, } @@ -558,11 +561,10 @@ impl DocumentFacts { } } -#[allow(dead_code)] // consumed by the incremental compiler milestone pub(crate) fn facts_cache_version() -> u32 { // Bump when the serialised DocumentFacts shape or extraction semantics // change. The cache is derived data; a mismatch forces re-extraction. - 1 + 2 } #[cfg(test)] diff --git a/src/document/okf.rs b/src/document/okf.rs index 6e344e1..b6e5589 100644 --- a/src/document/okf.rs +++ b/src/document/okf.rs @@ -1,25 +1,386 @@ //! OKF v0.3 document-layer recognition and `check --okf` validation. //! //! OKF is an optional Markdown organisation convention, not a project type and -//! not an additional knowledge format. Recognition only reads front-matter -//! metadata and fixed file roles; it never executes an executor/attester and -//! never changes program semantics. +//! not an additional knowledge format. This module only reads front-matter +//! metadata and fixed file roles: //! -//! Implemented by the OKF milestone. Until then `--okf` reports an explicit -//! unverified diagnostic instead of pretending to validate. +//! * a bundle is a directory of UTF-8 `.md` files; +//! * `index.md` and `log.md` are reserved navigation/history files at every +//! level and are never concepts, whatever front matter they carry; +//! * every other file is a concept and needs a non-empty YAML `type`; +//! * `title`, `description`, `tags` and `resource` are recognised when present; +//! * unknown types, unknown keys and unknown optional fields are preserved and +//! tolerated; no executor or attester is ever run. +//! +//! OKF metadata never changes program semantics. Compile always recognises the +//! metadata; OKF *link* semantics (bundle-root absolute paths) are only applied +//! when the user explicitly requests an OKF check. +use super::FrontMatterFact; use crate::diagnostic::{code, Diagnostic, DiagnosticSet}; use crate::document::{DocumentFacts, SourceSnapshot}; +use serde::{Deserialize, Serialize}; -/// Validate the supported OKF surface for an explicitly requested bundle. -pub fn validate_okf(_snapshot: &SourceSnapshot, _facts: &[DocumentFacts]) -> DiagnosticSet { +/// OKF specification version this implementation targets. +pub const OKF_VERSION: &str = "0.3"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OkfRole { + Native, + Concept, + Index, + Log, +} + +impl OkfRole { + pub fn as_str(self) -> &'static str { + match self { + OkfRole::Native => "native", + OkfRole::Concept => "concept", + OkfRole::Index => "index", + OkfRole::Log => "log", + } + } + + pub fn is_reserved(self) -> bool { + matches!(self, OkfRole::Index | OkfRole::Log) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct OkfInfo { + pub role: OkfRole, + /// Concept id = bundle-relative path without `.md` (never fabricated for + /// non-concepts). + pub concept_id: Option, + /// Free-form concept type (unregistered, never validated against a list). + pub concept_type: Option, + pub title: Option, + pub description: Option, + pub tags: Vec, + /// `resource` value as written; only recognised as a path when it has no URL + /// scheme. Root-absolute bundle paths are OKF-only semantics. + pub resource: Option, + /// Full parsed front-matter object, unknown keys preserved. + pub metadata: serde_json::Value, + /// Root `okf_version` when present. + pub declared_version: Option, +} + +impl Default for OkfInfo { + fn default() -> Self { + Self { + role: OkfRole::Native, + concept_id: None, + concept_type: None, + title: None, + description: None, + tags: Vec::new(), + resource: None, + metadata: serde_json::Value::Null, + declared_version: None, + } + } +} + +impl OkfInfo { + pub fn resource_is_relative_path(&self) -> Option<&str> { + let resource = self.resource.as_deref()?; + if resource.is_empty() + || resource.contains("://") + || resource.starts_with("//") + || resource.split_once(':').is_some_and(|(scheme, _)| { + !scheme.is_empty() + && scheme + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic()) + && scheme + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + }) + { + return None; + } + Some(resource) + } + + /// Document role used by storage. + pub fn role(&self) -> OkfRole { + self.role + } +} + +/// Recognise OKF metadata for one document. +pub fn analyze( + rel_path: &str, + front_matter: Option<&FrontMatterFact>, + diagnostics: &mut DiagnosticSet, +) -> OkfInfo { + let name = rel_path.rsplit('/').next().unwrap_or(rel_path); + let stem = name.strip_suffix(".md").unwrap_or(name); + let mut info = OkfInfo::default(); + let value = front_matter.and_then(|front_matter| front_matter.value.clone()); + if let Some(value) = &value { + if let Some(object) = value.as_object() { + if let Some(version) = object.get("okf_version").and_then(|value| value.as_str()) { + info.declared_version = Some(version.to_string()); + } + info.concept_type = object + .get("type") + .and_then(|value| value.as_str()) + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_string); + info.title = object + .get("title") + .and_then(|value| value.as_str()) + .map(str::to_string); + info.description = object + .get("description") + .and_then(|value| value.as_str()) + .map(str::to_string); + if let Some(tags) = object.get("tags").and_then(|value| value.as_array()) { + info.tags = tags + .iter() + .filter_map(|tag| tag.as_str()) + .map(str::to_string) + .collect(); + } + info.resource = object + .get("resource") + .and_then(|value| value.as_str()) + .map(str::to_string); + info.metadata = value.clone(); + } + } + if stem == "index" { + info.role = OkfRole::Index; + return info; + } + if stem == "log" { + info.role = OkfRole::Log; + return info; + } + if info.concept_type.is_some() { + info.role = OkfRole::Concept; + info.concept_id = Some(strip_markdown_suffix(rel_path)); + if info.title.is_none() { + info.title = None; + } + } else if front_matter.is_some() { + // Front matter without a type is not a concept. The front matter layer + // already reported parse problems; do not invent one here. + info.role = OkfRole::Native; + let _ = diagnostics; + } + info +} + +fn strip_markdown_suffix(rel_path: &str) -> String { + rel_path.strip_suffix(".md").unwrap_or(rel_path).to_string() +} + +/// `check --okf`: validate the supported conformance surface for an explicitly +/// requested bundle. This is not an attestation verifier: unknown types and +/// unknown keys are accepted, broken links are reported as notices, and nothing +/// is executed. +pub fn validate_okf(snapshot: &SourceSnapshot, facts: &[DocumentFacts]) -> DiagnosticSet { let mut diagnostics = DiagnosticSet::new(); - diagnostics.push( - Diagnostic::warning( - code::OKF_UNVERIFIED, - "OKF v0.3 validation is not implemented in this build; no OKF claim is made", - ) - .with_hint("see docs/STATUS.md for the current capability matrix"), - ); + let by_path: std::collections::HashMap<&str, &DocumentFacts> = facts + .iter() + .map(|fact| (fact.rel_path.as_str(), fact)) + .collect(); + for file in &snapshot.files { + let Some(fact) = by_path.get(file.rel_path.as_str()) else { + continue; + }; + let info = &fact.okf; + match info.role { + OkfRole::Index => { + if let Some(front_matter) = &fact.front_matter { + if let Some(value) = &front_matter.value { + if let Some(object) = value.as_object() { + let unknown: Vec<&String> = object + .keys() + .filter(|key| key.as_str() != "okf_version") + .collect(); + if !unknown.is_empty() { + diagnostics.push( + Diagnostic::warning( + code::OKF_UNVERIFIED, + format!( + "reserved index file carries extra front-matter keys ({}) ; they are preserved but not interpreted", + unknown + .iter() + .map(|key| key.as_str()) + .collect::>() + .join(", ") + ), + ) + .with_path(&file.rel_path) + .with_span(front_matter.span), + ); + } + } + } + } + } + OkfRole::Log => { + // Conformance does not require date headings; only report that + // no history semantics were interpreted. + } + OkfRole::Concept => {} + OkfRole::Native => { + // Conformance §11: every non-reserved Markdown file in a bundle + // needs parseable YAML front matter with a non-empty type. + match &fact.front_matter { + None => diagnostics.push( + Diagnostic::error( + code::OKF_INVALID, + format!( + "non-reserved file `{}` has no front matter; OKF concepts require a `type`", + file.rel_path + ), + ) + .with_path(&file.rel_path) + .with_hint("add YAML front matter with a non-empty `type`, or exclude the file"), + ), + Some(front_matter) => { + if let Some(error) = &front_matter.error { + diagnostics.push( + Diagnostic::error( + code::OKF_INVALID, + format!("front matter is not valid OKF metadata: {error}"), + ) + .with_path(&file.rel_path) + .with_span(front_matter.span), + ); + } else { + diagnostics.push( + Diagnostic::error( + code::OKF_INVALID, + format!( + "non-reserved file `{}` has no non-empty `type`", + file.rel_path + ), + ) + .with_path(&file.rel_path) + .with_span(front_matter.span), + ); + } + } + } + } + } + // Consumers must tolerate broken links; they are notices, not errors. + for reference in &fact.references { + if let Some(analysis) = &reference.analysis { + if matches!( + analysis.state, + crate::model::EdgeState::Missing | crate::model::EdgeState::Ambiguous + ) { + diagnostics.push( + Diagnostic::warning( + code::OKF_UNVERIFIED, + format!("bundle link `{}` could not be verified", reference.url), + ) + .with_path(&file.rel_path) + .with_span(reference.span), + ); + } + } + } + } + diagnostics.sorted(); diagnostics } + +#[cfg(test)] +mod tests { + use super::*; + use crate::document::FrontMatterFact; + use crate::model::Span; + + fn front(value: serde_json::Value) -> FrontMatterFact { + FrontMatterFact { + span: Span::new(0, 1), + literal: String::new(), + value: Some(value), + error: None, + } + } + + #[test] + fn typed_document_is_a_concept_with_preserved_metadata() { + let mut diagnostics = DiagnosticSet::new(); + let info = analyze( + "physics/mechanics.md", + Some(&front(serde_json::json!({ + "type": "Theory", + "title": "经典力学", + "tags": ["physics", "mechanics"], + "custom": {"a": 1} + }))), + &mut diagnostics, + ); + assert_eq!(info.role, OkfRole::Concept); + assert_eq!(info.concept_id.as_deref(), Some("physics/mechanics")); + assert_eq!(info.concept_type.as_deref(), Some("Theory")); + assert_eq!(info.tags, vec!["physics", "mechanics"]); + assert_eq!(info.metadata["custom"]["a"], 1); + } + + #[test] + fn reserved_files_are_never_concepts() { + let mut diagnostics = DiagnosticSet::new(); + let value = front(serde_json::json!({"type": "Index"})); + assert_eq!( + analyze("index.md", Some(&value), &mut diagnostics).role, + OkfRole::Index + ); + assert_eq!( + analyze("a/b/log.md", Some(&value), &mut diagnostics).role, + OkfRole::Log + ); + let info = analyze("a/b/index.md", Some(&value), &mut diagnostics); + assert!(info.concept_id.is_none()); + } + + #[test] + fn untyped_document_stays_native() { + let mut diagnostics = DiagnosticSet::new(); + let info = analyze( + "notes.md", + Some(&front(serde_json::json!({"title": "notes"}))), + &mut diagnostics, + ); + assert_eq!(info.role, OkfRole::Native); + assert!(info.concept_id.is_none()); + assert!(analyze("plain.md", None, &mut diagnostics).role == OkfRole::Native); + } + + #[test] + fn resource_paths_are_separated_from_urls() { + let mut diagnostics = DiagnosticSet::new(); + let info = analyze( + "a.md", + Some(&front(serde_json::json!({ + "type": "Dataset", + "resource": "../data/table.csv" + }))), + &mut diagnostics, + ); + assert_eq!(info.resource_is_relative_path(), Some("../data/table.csv")); + let info = analyze( + "a.md", + Some(&front(serde_json::json!({ + "type": "Dataset", + "resource": "https://example.com/x.csv" + }))), + &mut diagnostics, + ); + assert_eq!(info.resource_is_relative_path(), None); + } +} diff --git a/src/embedding.rs b/src/embedding.rs new file mode 100644 index 0000000..2f3aead --- /dev/null +++ b/src/embedding.rs @@ -0,0 +1,539 @@ +//! OpenAI-compatible embeddings transport (one current backend protocol). +//! +//! Semantic indexing is explicit. The client sends only the selected snippets +//! and the query, never the workspace, paths or unrelated metadata. The API key +//! comes from the environment and is never stored, logged or printed. +//! +//! Safety rules: +//! * no implicit network: construction only validates configuration; +//! * remote endpoints require explicit consent, HTTPS and disabled redirects; +//! * loopback HTTP is allowed for a locally deployed compatible service; +//! * bounded timeout, batch size, response size and dimension; +//! * strict response validation: count, order, dimension, finite values and +//! non-zero norm; mixed models/dimensions are rejected. + +use crate::error::KnowledgeError; +use crate::model::sha256_prefixed; +use serde::{Deserialize, Serialize}; +use std::time::Duration; + +pub const API_KEY_ENV: &str = "MARQDO_KNOWLEDGE_EMBEDDING_API_KEY"; +pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); +pub const MAX_BATCH: usize = 64; +pub const MAX_UNITS: usize = 20_000; +pub const MAX_DIMENSION: usize = 8_192; +pub const MAX_RESPONSE_BYTES: usize = 64 * 1024 * 1024; +pub const MAX_INPUT_CHARS: usize = 2_000; +pub const MAX_ATTEMPTS: usize = 2; +pub const DISTANCE: &str = "cosine"; +pub const CHUNKING: &str = "search_unit_title_body"; + +/// User-supplied embedding options. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EmbeddingConfig { + endpoint: String, + model: String, + revision: String, + allow_remote: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct UrlParts { + scheme: String, + host: String, + port: Option, + path: String, +} + +impl EmbeddingConfig { + pub fn new( + url: &str, + model: &str, + revision: &str, + allow_remote: bool, + ) -> Result { + let config = Self { + endpoint: url.trim().to_string(), + model: model.trim().to_string(), + revision: revision.trim().to_string(), + allow_remote, + }; + config.validate()?; + Ok(config) + } + + pub fn model(&self) -> &str { + &self.model + } + + pub fn revision(&self) -> &str { + &self.revision + } + + /// Sanitised endpoint without credentials, query or fragment. + pub fn endpoint(&self) -> Result { + let parts = parse_url(&self.endpoint)?; + Ok(format!( + "{}://{}{}{}", + parts.scheme, + parts.host, + parts + .port + .map(|port| format!(":{port}")) + .unwrap_or_default(), + parts.path + )) + } + + pub fn validate(&self) -> Result<(), KnowledgeError> { + if self.model.is_empty() || self.revision.is_empty() { + return Err(KnowledgeError::usage( + "embedding model and revision must not be empty", + )); + } + let parts = parse_url(&self.endpoint)?; + let loopback = is_loopback(&parts.host); + if !loopback { + if parts.scheme != "https" { + return Err(KnowledgeError::environment( + crate::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED, + "remote embeddings require TLS (https); plain http is only allowed for loopback services", + )); + } + if !self.allow_remote { + return Err(KnowledgeError::environment( + crate::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED, + "remote embeddings require explicit --allow-remote-embedding consent", + ) + .with_hint("the query/index content would leave this machine")); + } + } + Ok(()) + } + + /// Stable digest of the index configuration (never includes the API key). + pub fn model_digest(&self, dimension: usize) -> Result { + let endpoint = self.endpoint()?; + let canonical = format!( + "endpoint={endpoint}|model={}|revision={}|dimension={dimension}|distance={DISTANCE}|chunking={CHUNKING}", + self.model, self.revision + ); + Ok(sha256_prefixed(canonical.as_bytes())) + } +} + +fn parse_url(url: &str) -> Result { + let Some(scheme_end) = url.find("://") else { + return Err(KnowledgeError::usage( + "embedding endpoint must be an absolute http(s) URL", + )); + }; + let scheme = url[..scheme_end].to_ascii_lowercase(); + if scheme != "http" && scheme != "https" { + return Err(KnowledgeError::usage( + "embedding endpoint scheme must be http or https", + )); + } + if url.contains('?') || url.contains('#') { + return Err(KnowledgeError::usage( + "embedding endpoint must not contain a query or fragment", + )); + } + let rest = &url[scheme_end + 3..]; + let (authority, path) = match rest.split_once('/') { + Some((authority, path)) => (authority, format!("/{path}")), + None => (rest, "/".to_string()), + }; + if authority.is_empty() { + return Err(KnowledgeError::usage("embedding endpoint has no host")); + } + if authority.contains('@') { + return Err(KnowledgeError::usage( + "credentials must not be embedded in the embedding endpoint URL", + )); + } + let (host, port) = if let Some(stripped) = authority.strip_prefix('[') { + // IPv6 literal. + let Some((host, rest)) = stripped.split_once(']') else { + return Err(KnowledgeError::usage( + "invalid IPv6 host in embedding endpoint", + )); + }; + let port = match rest.strip_prefix(':') { + Some(port) => Some( + port.parse::() + .map_err(|_| KnowledgeError::usage("invalid embedding endpoint port"))?, + ), + None => None, + }; + (format!("[{host}]"), port) + } else { + match authority.rsplit_once(':') { + Some((host, port)) if !host.contains(':') => ( + host.to_string(), + Some( + port.parse::() + .map_err(|_| KnowledgeError::usage("invalid embedding endpoint port"))?, + ), + ), + _ => (authority.to_string(), None), + } + }; + if host.is_empty() { + return Err(KnowledgeError::usage("embedding endpoint has no host")); + } + Ok(UrlParts { + scheme, + host, + port, + path, + }) +} + +fn is_loopback(host: &str) -> bool { + let host = host.trim_start_matches('[').trim_end_matches(']'); + matches!(host, "127.0.0.1" | "::1" | "localhost") || host.starts_with("127.") +} + +/// Index configuration persisted in build metadata. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct EmbeddingMeta { + pub endpoint: String, + pub model: String, + pub revision: String, + pub dimension: usize, + pub distance: String, + pub model_digest: String, + pub chunking: String, + pub max_input_chars: usize, +} + +/// Precomputed vectors for the publish transaction. +#[derive(Debug, Clone)] +pub struct EmbeddingVectors { + pub model_digest: String, + pub dimension: usize, + /// (node canonical key, unit span start, embedded-text digest) -> vector. + pub vectors: std::collections::HashMap<(String, u64, String), Vec>, +} + +/// One text that must be embedded, keyed by its search-unit identity. +#[derive(Debug, Clone)] +pub struct EmbeddingSource { + pub node_key: String, + pub span_start: u64, + pub content_digest: String, + pub text: String, +} + +/// Build the exact text used for chunk embeddings. Deterministic and bounded. +pub fn embedding_text(title: &str, body: &str, formula: &str) -> String { + let mut text = String::new(); + if !title.is_empty() { + text.push_str(title); + text.push('\n'); + } + text.push_str(body); + if !formula.is_empty() { + text.push('\n'); + text.push_str(formula); + } + let mut end = text.len().min(MAX_INPUT_CHARS * 4); + while end > 0 && !text.is_char_boundary(end) { + end -= 1; + } + text.truncate(end); + text +} + +/// Digest of the exact embedded text, used for reuse and invalidation. +pub fn embedding_content_digest(text: &str) -> String { + sha256_prefixed(text.as_bytes()) +} + +pub struct EmbeddingClient { + agent: ureq::Agent, + url: String, + model: String, + api_key: Option, +} + +impl EmbeddingClient { + pub fn new(config: &EmbeddingConfig) -> Result { + config.validate()?; + let url = config.endpoint()?; + let agent_config = ureq::Agent::config_builder() + .timeout_global(Some(REQUEST_TIMEOUT)) + .max_redirects(0) + .build(); + let agent: ureq::Agent = agent_config.into(); + Ok(Self { + agent, + url, + model: config.model.clone(), + api_key: std::env::var(API_KEY_ENV) + .ok() + .filter(|key| !key.is_empty()), + }) + } + + pub fn endpoint(&self) -> &str { + &self.url + } + + /// Embed bounded batches. Every batch is validated before being accepted. + pub fn embed(&self, inputs: &[String]) -> Result<(Vec>, usize), KnowledgeError> { + if inputs.is_empty() { + return Err(KnowledgeError::environment( + crate::diagnostic::code::EMBEDDING_UNAVAILABLE, + "no search units to embed", + )); + } + if inputs.len() > MAX_UNITS { + return Err(KnowledgeError::environment( + crate::diagnostic::code::BUDGET_EXCEEDED, + format!( + "{} embedding inputs exceed the {MAX_UNITS} unit budget", + inputs.len() + ), + )); + } + let mut vectors = Vec::with_capacity(inputs.len()); + let mut dimension = 0usize; + for batch in inputs.chunks(MAX_BATCH) { + let batch_vectors = self.embed_batch(batch)?; + for vector in batch_vectors { + if dimension == 0 { + dimension = vector.len(); + } else if vector.len() != dimension { + return Err(invalid_response( + "embedding dimension changed between batches", + )); + } + vectors.push(vector); + } + } + Ok((vectors, dimension)) + } + + fn embed_batch(&self, inputs: &[String]) -> Result>, KnowledgeError> { + let payload = serde_json::json!({"model": self.model, "input": inputs}); + let mut last_error = None; + for attempt in 0..MAX_ATTEMPTS { + match self.send(&payload) { + Ok(response) => return validate_response(response, inputs.len()), + Err(error) + if error.code == crate::diagnostic::code::EMBEDDING_TRANSPORT + && attempt + 1 < MAX_ATTEMPTS => + { + last_error = Some(error); + std::thread::sleep(Duration::from_millis(200)); + } + Err(error) => return Err(error), + } + } + Err(last_error + .unwrap_or_else(|| invalid_response("embedding request failed without a response"))) + } + + fn send(&self, payload: &serde_json::Value) -> Result { + if payload.to_string().len() > MAX_RESPONSE_BYTES { + return Err(KnowledgeError::environment( + crate::diagnostic::code::BUDGET_EXCEEDED, + "embedding request payload exceeds the size budget", + )); + } + let mut request = self + .agent + .post(&self.url) + .header("content-type", "application/json"); + if let Some(key) = &self.api_key { + request = request.header("authorization", format!("Bearer {key}")); + } + let mut response = request.send_json(payload).map_err(|error| { + KnowledgeError::environment( + crate::diagnostic::code::EMBEDDING_TRANSPORT, + format!("embedding endpoint request failed: {error}"), + ) + })?; + let body = response.body_mut().read_to_string().map_err(|error| { + KnowledgeError::environment( + crate::diagnostic::code::EMBEDDING_TRANSPORT, + format!("embedding response could not be read: {error}"), + ) + })?; + if body.len() > MAX_RESPONSE_BYTES { + return Err(KnowledgeError::environment( + crate::diagnostic::code::BUDGET_EXCEEDED, + "embedding response exceeds the size budget", + )); + } + serde_json::from_str(&body).map_err(|error| { + invalid_response(&format!("embedding response is not valid JSON: {error}")) + }) + } +} + +fn invalid_response(message: &str) -> KnowledgeError { + KnowledgeError::environment( + crate::diagnostic::code::EMBEDDING_INVALID_RESPONSE, + message.to_string(), + ) +} + +fn validate_response( + response: serde_json::Value, + expected: usize, +) -> Result>, KnowledgeError> { + let Some(data) = response.get("data").and_then(|data| data.as_array()) else { + return Err(invalid_response("embedding response has no `data` array")); + }; + if data.len() != expected { + return Err(invalid_response(&format!( + "embedding response returned {} vector(s) for {expected} input(s)", + data.len() + ))); + } + let mut vectors: Vec>> = vec![None; expected]; + for item in data { + let index = item + .get("index") + .and_then(|index| index.as_u64()) + .ok_or_else(|| invalid_response("embedding item has no integer `index`"))? + as usize; + if index >= expected { + return Err(invalid_response("embedding item index is out of range")); + } + if vectors[index].is_some() { + return Err(invalid_response("embedding response repeats an item index")); + } + let embedding = item + .get("embedding") + .and_then(|embedding| embedding.as_array()) + .ok_or_else(|| invalid_response("embedding item has no vector"))?; + if embedding.is_empty() || embedding.len() > MAX_DIMENSION { + return Err(invalid_response( + "embedding dimension is empty or too large", + )); + } + let mut vector = Vec::with_capacity(embedding.len()); + let mut norm_squared = 0.0f64; + for value in embedding { + let value = value + .as_f64() + .ok_or_else(|| invalid_response("embedding value is not a finite number"))?; + if !value.is_finite() { + return Err(invalid_response("embedding value is not finite")); + } + vector.push(value as f32); + norm_squared += value * value; + } + if norm_squared <= 1e-12 { + return Err(invalid_response("embedding vector has zero norm")); + } + vectors[index] = Some(vector); + } + let mut out = Vec::with_capacity(expected); + for vector in vectors { + out.push(vector.ok_or_else(|| invalid_response("embedding response is missing an item"))?); + } + Ok(out) +} + +/// Cosine similarity of two equal-length vectors. Returns `None` for invalid +/// input; the caller never compares different dimensions. +pub fn cosine(left: &[f32], right: &[f32]) -> Option { + if left.len() != right.len() || left.is_empty() { + return None; + } + let mut dot = 0.0f64; + let mut left_norm = 0.0f64; + let mut right_norm = 0.0f64; + for (a, b) in left.iter().zip(right.iter()) { + let a = f64::from(*a); + let b = f64::from(*b); + if !a.is_finite() || !b.is_finite() { + return None; + } + dot += a * b; + left_norm += a * a; + right_norm += b * b; + } + if left_norm <= 0.0 || right_norm <= 0.0 { + return None; + } + Some(dot / (left_norm.sqrt() * right_norm.sqrt())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn loopback_http_is_allowed_but_remote_http_is_not() { + assert!(EmbeddingConfig::new("http://127.0.0.1:8080/v1", "m", "r", false).is_ok()); + assert!(EmbeddingConfig::new("http://localhost:8080/v1", "m", "r", false).is_ok()); + let error = EmbeddingConfig::new("http://example.com/v1", "m", "r", true).unwrap_err(); + assert_eq!( + error.code, + crate::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED + ); + let error = EmbeddingConfig::new("https://example.com/v1", "m", "r", false).unwrap_err(); + assert_eq!( + error.code, + crate::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED + ); + let error = EmbeddingConfig::new("https://example.com/v1?x=1", "m", "r", true).unwrap_err(); + assert!(error.message.contains("query") || error.message.contains("fragment")); + assert!(EmbeddingConfig::new("https://user:pass@example.com/v1", "m", "r", true).is_err()); + } + + #[test] + fn model_digest_is_stable_and_excludes_secrets() { + let config = + EmbeddingConfig::new("http://127.0.0.1:8080/v1/", "model", "r1", false).unwrap(); + let first = config.model_digest(3).unwrap(); + let second = config.model_digest(3).unwrap(); + assert_eq!(first, second); + assert!(first.starts_with("sha256:")); + let other = config.model_digest(4).unwrap(); + assert_ne!(first, other); + } + + #[test] + fn response_validation_rejects_bad_shapes() { + let good = serde_json::json!({"data": [ + {"index": 0, "embedding": [1.0, 0.0]}, + {"index": 1, "embedding": [0.0, 1.0]} + ]}); + assert_eq!(validate_response(good, 2).unwrap().len(), 2); + let wrong_count = serde_json::json!({"data": [{"index": 0, "embedding": [1.0]}]}); + assert!(validate_response(wrong_count, 2).is_err()); + let zero = serde_json::json!({"data": [{"index": 0, "embedding": [0.0, 0.0]}]}); + assert!(validate_response(zero, 1).is_err()); + let duplicate = serde_json::json!({"data": [ + {"index": 0, "embedding": [1.0]}, + {"index": 0, "embedding": [1.0]} + ]}); + assert!(validate_response(duplicate, 2).is_err()); + let huge = serde_json::json!({"data": [{"index": 0, "embedding": [1e300]}]}); + assert!(validate_response(huge, 1).is_ok()); + } + + #[test] + fn cosine_is_bounded_and_rejects_mismatch() { + assert!(cosine(&[1.0, 0.0], &[1.0, 0.0]).unwrap() > 0.999); + assert!(cosine(&[1.0, 0.0], &[0.0, 1.0]).unwrap() < 0.001); + assert!(cosine(&[1.0], &[1.0, 2.0]).is_none()); + assert!(cosine(&[0.0, 0.0], &[1.0, 0.0]).is_none()); + } + + #[test] + fn embedding_text_is_bounded_on_char_boundaries() { + let long = "量子".repeat(10_000); + let text = embedding_text("title", &long, "F=ma"); + assert!(text.len() <= MAX_INPUT_CHARS * 4); + assert!(std::str::from_utf8(text.as_bytes()).is_ok()); + assert_eq!(embedding_content_digest("abc"), sha256_prefixed(b"abc")); + } +} diff --git a/src/graph/mod.rs b/src/graph/mod.rs index b6a449f..2b5917d 100644 --- a/src/graph/mod.rs +++ b/src/graph/mod.rs @@ -138,6 +138,7 @@ pub fn build( sources: &HashMap<&str, &str>, assets: &[AssetFile], missing_paths: &std::collections::HashSet, + okf_mode: bool, ) -> Graph { let mut diagnostics = DiagnosticSet::new(); for document in &facts { @@ -188,6 +189,7 @@ pub fn build( metadata: serde_json::json!({ "format": document.format.as_str(), "title": document.document_title, + "okf": serde_json::to_value(&document.okf).unwrap_or(serde_json::Value::Null), "analysis": document.analysis.as_ref().map(|analysis| serde_json::json!({ "module_id": analysis.module_id, "context_id": analysis.context_id, @@ -389,6 +391,15 @@ pub fn build( }); } + // OKF concept identity maps to this document node; never a second node. + if let Some(concept_id) = &document.okf.concept_id { + aliases.push(AliasRecord { + alias: concept_id.clone(), + context: None, + node: doc_key.clone(), + }); + } + // Aliases for upstream identities. if let Some(analysis) = &document.analysis { aliases.push(AliasRecord { @@ -446,7 +457,7 @@ pub fn build( } // Reference, import and call edges. - let resolver = resolve::Resolver::new(&facts, assets, missing_paths); + let resolver = resolve::Resolver::new(&facts, assets, missing_paths, okf_mode); let (external_nodes, resolved_edges, resolution_diagnostics) = resolver.resolve_all(); diagnostics.merge(resolution_diagnostics); for node in external_nodes { @@ -650,7 +661,7 @@ mod tests { let (text, facts) = plain_facts("# A\n\n## B\n\ntext\n"); let mut sources: HashMap<&str, &str> = HashMap::new(); sources.insert("doc.md", text.as_str()); - let graph = build(facts, &sources, &[], &Default::default()); + let graph = build(facts, &sources, &[], &Default::default(), false); assert_eq!( graph .nodes @@ -694,7 +705,7 @@ mod tests { size: 3, digest: Some("sha256:abc".into()), }]; - let graph = build(facts, &sources, &assets, &Default::default()); + let graph = build(facts, &sources, &assets, &Default::default(), false); assert!(!graph.diagnostics.has_errors()); let states: Vec = graph .edges @@ -721,7 +732,7 @@ mod tests { let (text, facts) = plain_facts("# t\n\n[a](#t) [a](#t)\n"); let mut sources: HashMap<&str, &str> = HashMap::new(); sources.insert("doc.md", text.as_str()); - let graph = build(facts, &sources, &[], &Default::default()); + let graph = build(facts, &sources, &[], &Default::default(), false); let references: Vec<_> = graph .edges .iter() @@ -736,7 +747,7 @@ mod tests { let (text, facts) = plain_facts("# t\n\n## dup\n\na\n\n## dup\n\nb\n\n[x](#dup-1)\n"); let mut sources: HashMap<&str, &str> = HashMap::new(); sources.insert("doc.md", text.as_str()); - let graph = build(facts, &sources, &[], &Default::default()); + let graph = build(facts, &sources, &[], &Default::default(), false); let edge = graph .edges .iter() @@ -761,7 +772,7 @@ mod tests { } let mut sources: HashMap<&str, &str> = HashMap::new(); sources.insert("doc.md", text.as_str()); - let graph = build(facts, &sources, &[], &Default::default()); + let graph = build(facts, &sources, &[], &Default::default(), false); let state = graph .edges .iter() @@ -779,11 +790,11 @@ mod tests { let (text, facts) = plain_facts("# A\n\ntext\n"); let mut sources: HashMap<&str, &str> = HashMap::new(); sources.insert("doc.md", text.as_str()); - let first = build(facts, &sources, &[], &Default::default()).logical_digest(); + let first = build(facts, &sources, &[], &Default::default(), false).logical_digest(); let (text, facts) = plain_facts("# A\n\ntext\n"); let mut sources: HashMap<&str, &str> = HashMap::new(); sources.insert("doc.md", text.as_str()); - let second = build(facts, &sources, &[], &Default::default()).logical_digest(); + let second = build(facts, &sources, &[], &Default::default(), false).logical_digest(); assert_eq!(first, second); } } diff --git a/src/graph/resolve.rs b/src/graph/resolve.rs index 8f30ed2..c656a61 100644 --- a/src/graph/resolve.rs +++ b/src/graph/resolve.rs @@ -186,6 +186,7 @@ enum FragmentLookup { } pub struct Resolver<'a> { + okf_mode: bool, facts: &'a [DocumentFacts], docs: HashMap<&'a str, &'a DocumentFacts>, modules: HashMap<&'a str, &'a str>, @@ -208,6 +209,7 @@ impl<'a> Resolver<'a> { facts: &'a [DocumentFacts], assets: &'a [AssetFile], missing_paths: &'a HashSet, + okf_mode: bool, ) -> Self { let mut docs = HashMap::new(); let mut modules = HashMap::new(); @@ -256,6 +258,7 @@ impl<'a> Resolver<'a> { .map(|asset| (asset.rel_path.as_str(), asset)) .collect(); Self { + okf_mode, facts, docs, modules, @@ -294,6 +297,7 @@ impl<'a> Resolver<'a> { for call in &fact.calls { self.resolve_call(fact, call, context.as_deref()); } + self.resolve_okf_resource(fact, context.as_deref()); } let mut diagnostics = std::mem::take(&mut self.diagnostics); diagnostics.sorted(); @@ -554,6 +558,90 @@ impl<'a> Resolver<'a> { } } + /// OKF bundle-root absolute link (`/path.md`): a logical path inside the + /// explicitly requested bundle, never an OS absolute path. + fn resolve_okf_root_relative( + &mut self, + fact: &DocumentFacts, + url: &str, + span: Span, + ) -> ResolvedTarget { + let rest = url.trim_start_matches('/'); + let (raw_path, raw_fragment) = match rest.split_once('#') { + Some((path, fragment)) => (path, Some(fragment)), + None => (rest, None), + }; + let decode = |value: &str| -> Option { + let bytes = crate::model::percent_decode(value.as_bytes())?; + String::from_utf8(bytes).ok() + }; + let Some(path) = decode(raw_path) else { + return ResolvedTarget::unresolved( + EdgeState::Invalid, + Some(self.reference_diagnostic( + code::REFERENCE_INVALID, + "OKF bundle path is not valid percent encoding", + &fact.rel_path, + span, + )), + ); + }; + let fragment = match raw_fragment { + Some(fragment) => match decode(fragment) { + Some(fragment) => Some(fragment), + None => { + return ResolvedTarget::unresolved( + EdgeState::Invalid, + Some(self.reference_diagnostic( + code::REFERENCE_INVALID, + "OKF bundle fragment is not valid percent encoding", + &fact.rel_path, + span, + )), + ); + } + }, + None => None, + }; + if crate::document::discovery::validate_relative_path(&path).is_err() { + return ResolvedTarget::unresolved( + EdgeState::OutOfScope, + Some(self.reference_diagnostic( + code::REFERENCE_OUT_OF_SCOPE, + "OKF bundle path is not a safe logical path inside the bundle", + &fact.rel_path, + span, + )), + ); + } + if let Some(target) = self.docs.get(path.as_str()).copied() { + return self.resolve_document_target(target, fragment.as_deref(), span, &fact.rel_path); + } + if let Some(asset) = self.assets.get(path.as_str()) { + return ResolvedTarget::node(identity::asset_key(asset.rel_path.as_str())); + } + if self.missing_paths.contains(&path) { + return ResolvedTarget::unresolved( + EdgeState::Missing, + Some(self.reference_diagnostic( + code::REFERENCE_MISSING, + format!("OKF bundle target `/{path}` does not exist"), + &fact.rel_path, + span, + )), + ); + } + ResolvedTarget::unresolved( + EdgeState::NotLoaded, + Some(self.reference_diagnostic( + code::REFERENCE_NOT_LOADED, + format!("OKF bundle target `/{path}` is not included in the checked bundle"), + &fact.rel_path, + span, + )), + ) + } + fn resolve_not_loaded( &mut self, fact: &DocumentFacts, @@ -671,6 +759,9 @@ impl<'a> Resolver<'a> { ) -> ResolvedTarget { let span = reference.span; let path = &fact.rel_path; + if self.okf_mode && reference.url.starts_with('/') && !reference.url.starts_with("//") { + return self.resolve_okf_root_relative(fact, &reference.url, span); + } let link = match parse_link(&reference.url) { Ok(link) => link, Err(LinkError::OutsideScope) => { @@ -868,6 +959,128 @@ impl<'a> Resolver<'a> { PathResolution::Missing(rel) } + /// `resource` is the only OKF metadata field that is explicitly a path. It + /// is treated as a reference occurrence, never as execution or import. + fn resolve_okf_resource(&mut self, fact: &DocumentFacts, context: Option<&str>) { + let Some(resource) = fact.okf.resource_is_relative_path() else { + return; + }; + let source = self.doc_nodes[fact.rel_path.as_str()].clone(); + let span = fact + .front_matter + .as_ref() + .map(|front_matter| front_matter.span); + let link = match parse_link(resource) { + Ok(link) => link, + Err(LinkError::OutsideScope) => { + let diagnostic = self.reference_diagnostic( + code::REFERENCE_OUT_OF_SCOPE, + "OKF resource path escapes the bundle root and was not read", + &fact.rel_path, + span.unwrap_or(Span::new(0, 0)), + ); + self.diagnostics.push(diagnostic); + self.push_edge( + source, + None, + EdgeKind::References, + EdgeOrigin::Document, + resource.to_string(), + span, + &fact.rel_path, + EdgeState::OutOfScope, + context, + ); + return; + } + Err(LinkError::Invalid(message)) => { + let diagnostic = self.reference_diagnostic( + code::REFERENCE_INVALID, + format!("OKF resource path is invalid: {message}"), + &fact.rel_path, + span.unwrap_or(Span::new(0, 0)), + ); + self.diagnostics.push(diagnostic); + self.push_edge( + source, + None, + EdgeKind::References, + EdgeOrigin::Document, + resource.to_string(), + span, + &fact.rel_path, + EdgeState::Invalid, + context, + ); + return; + } + }; + let ParsedLink::Local { path, fragment } = link else { + return; + }; + if self.okf_mode && resource.starts_with('/') && !resource.starts_with("//") { + let resolved = + self.resolve_okf_root_relative(fact, resource, span.unwrap_or(Span::new(0, 0))); + if let Some(diagnostic) = resolved.diagnostic.clone() { + self.diagnostics.push(diagnostic); + } + self.push_edge( + source, + resolved.node, + EdgeKind::References, + EdgeOrigin::Document, + resource.to_string(), + span, + &fact.rel_path, + resolved.state, + context, + ); + return; + } + let resolution = self.resolve_path(&fact.rel_path, &path); + let (target, state) = match resolution { + PathResolution::SameDocument => ( + Some(self.doc_nodes[fact.rel_path.as_str()].clone()), + EdgeState::Resolved, + ), + PathResolution::Document(rel) => ( + Some(self.doc_nodes[rel.as_str()].clone()), + EdgeState::Resolved, + ), + PathResolution::Asset(rel) => (Some(identity::asset_key(&rel)), EdgeState::Resolved), + PathResolution::NotLoaded => (None, EdgeState::NotLoaded), + PathResolution::Missing(_) => (None, EdgeState::Missing), + PathResolution::Outside => (None, EdgeState::OutOfScope), + PathResolution::Invalid(_) => (None, EdgeState::Invalid), + }; + let _ = fragment; + if state != EdgeState::Resolved { + let diagnostic_code = match state { + EdgeState::Missing => code::REFERENCE_MISSING, + EdgeState::NotLoaded => code::REFERENCE_NOT_LOADED, + EdgeState::OutOfScope => code::REFERENCE_OUT_OF_SCOPE, + _ => code::REFERENCE_INVALID, + }; + self.diagnostics.push(self.reference_diagnostic( + diagnostic_code, + "OKF resource path could not be verified", + &fact.rel_path, + span.unwrap_or(Span::new(0, 0)), + )); + } + self.push_edge( + source, + target, + EdgeKind::References, + EdgeOrigin::Document, + resource.to_string(), + span, + &fact.rel_path, + state, + context, + ); + } + fn resolve_import( &mut self, fact: &DocumentFacts, diff --git a/src/lib.rs b/src/lib.rs index 423855f..dcf0f81 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,6 +9,7 @@ pub mod cli; pub mod compiler; pub mod diagnostic; pub mod document; +pub mod embedding; pub mod error; pub mod graph; pub mod model; diff --git a/src/query/mod.rs b/src/query/mod.rs index e342dd1..c4be611 100644 --- a/src/query/mod.rs +++ b/src/query/mod.rs @@ -34,6 +34,10 @@ pub fn run_query(args: &QueryArgs, _marqdo_bin: Option<&Path>) -> Result) -> Result Result<(), KnowledgeError> { + let mut facts = HashMap::new(); + for document in store.documents()? { + if let Some(cached) = store.load_facts(&document.path)? { + facts.insert(document.path.clone(), cached.facts); + } + } + let (assets, _missing) = crate::compiler::collect_assets(scope, snapshot, &facts)?; + snapshot.assets = assets; + Ok(()) +} + /// Query result before rendering. struct QueryResult { hits: Vec, @@ -340,14 +360,71 @@ impl<'a> Engine<'a> { "database has no semantic index; compile with embedding options first", ) })?; + let stored_endpoint = embedding + .get("endpoint") + .and_then(|value| value.as_str()) + .unwrap_or_default() + .to_string(); + let stored_model = embedding + .get("model") + .and_then(|value| value.as_str()) + .unwrap_or_default() + .to_string(); + let stored_revision = embedding + .get("revision") + .and_then(|value| value.as_str()) + .unwrap_or_default() + .to_string(); + let dimension = embedding + .get("dimension") + .and_then(|value| value.as_u64()) + .unwrap_or(0) as usize; let model_digest = embedding .get("model_digest") .and_then(|value| value.as_str()) + .unwrap_or_default() + .to_string(); + let url = args.embedding.embedding_url.clone().ok_or_else(|| { + KnowledgeError::environment( + code::EMBEDDING_UNAVAILABLE, + "semantic search requires explicit embedding options", + ) + })?; + let model = args.embedding.embedding_model.clone().unwrap_or_default(); + let revision = args + .embedding + .embedding_revision + .clone() .unwrap_or_default(); + let config = crate::embedding::EmbeddingConfig::new( + &url, + &model, + &revision, + args.embedding.allow_remote_embedding, + )?; + let client = crate::embedding::EmbeddingClient::new(&config)?; + if client.endpoint() != stored_endpoint + || model != stored_model + || revision != stored_revision + { + return Err(KnowledgeError::environment( + code::EMBEDDING_CONFIG_MISMATCH, + "query embedding configuration does not match the compiled semantic index", + ) + .with_hint("recompile with the new configuration or pass the original options")); + } + let (vectors, returned_dimension) = client.embed(std::slice::from_ref(&args.query))?; + if returned_dimension != dimension { + return Err(KnowledgeError::environment( + code::EMBEDDING_CONFIG_MISMATCH, + "query embedding dimension does not match the compiled index", + )); + } channels.push(semantic::channel( self.store, - &args.query, - model_digest, + &vectors[0], + &model_digest, + dimension, 200, )?); } diff --git a/src/query/semantic.rs b/src/query/semantic.rs index ab28d83..ee695d0 100644 --- a/src/query/semantic.rs +++ b/src/query/semantic.rs @@ -15,19 +15,51 @@ use crate::storage::read::ReadStore; /// Maximum number of stored vectors scanned by the exact cosine scan. pub const MAX_VECTOR_SCAN: usize = 50_000; -/// Run the semantic channel. The caller must have checked that semantic -/// configuration matches the build metadata first. +/// Run the semantic channel against stored vectors with the query embedding. pub fn channel( - _store: &ReadStore, - _query: &str, - _model_digest: &str, - _limit: usize, + store: &ReadStore, + query_vector: &[f32], + model_digest: &str, + dimension: usize, + limit: usize, ) -> Result { - Err(KnowledgeError::environment( - crate::diagnostic::code::EMBEDDING_UNAVAILABLE, - "semantic search is not available in this build", - ) - .with_hint("run `marqdo knowledge compile` with embedding options and a compatible endpoint")) + if query_vector.len() != dimension { + return Err(KnowledgeError::environment( + crate::diagnostic::code::EMBEDDING_CONFIG_MISMATCH, + "query embedding dimension does not match the compiled index", + )); + } + let rows = store.embeddings(model_digest, MAX_VECTOR_SCAN)?; + if rows.is_empty() { + return Err(KnowledgeError::environment( + crate::diagnostic::code::EMBEDDING_UNAVAILABLE, + "the semantic index is empty; recompile with embedding options", + )); + } + let truncated = rows.len() >= MAX_VECTOR_SCAN; + let mut best: std::collections::HashMap = std::collections::HashMap::new(); + for row in &rows { + if row.vector.len() != dimension { + return Err(KnowledgeError::environment( + crate::diagnostic::code::EMBEDDING_CONFIG_MISMATCH, + "stored vector dimension does not match the compiled index", + )); + } + let Some(score) = crate::embedding::cosine(query_vector, &row.vector) else { + continue; + }; + let entry = best.entry(row.node_id).or_insert((f64::MIN, row.unit_id)); + if score > entry.0 { + *entry = (score, row.unit_id); + } + } + let scored: Vec<(i64, Option, f64)> = best + .into_iter() + .map(|(node_id, (score, unit_id))| (node_id, Some(unit_id), score)) + .collect(); + let mut result = ranked_from_scores(scored, limit); + result.truncated |= truncated; + Ok(result) } /// Candidate ordering helper used by the vector scan. diff --git a/src/storage/index.rs b/src/storage/index.rs index 5e70b07..14cb8f5 100644 --- a/src/storage/index.rs +++ b/src/storage/index.rs @@ -7,6 +7,7 @@ //! bounded fuzzy channel. Nothing here generates facts or rewrites source. use crate::document::{BlockFact, DocumentFacts, UnitKind}; +use crate::error::KnowledgeError; use crate::graph::identity; use crate::graph::{Graph, Node}; use crate::model::Span; @@ -24,11 +25,13 @@ const MAX_BODY_GRAMS: usize = 2048; pub struct IndexStats { pub search_units: u64, pub grams: u64, + pub embeddings: u64, } #[derive(Debug, Clone)] struct UnitSpec { node_key: String, + doc_path: String, span: Span, fields: SearchFields, } @@ -74,63 +77,142 @@ pub fn build_index( graph: &Graph, doc_ids: &HashMap<&str, i64>, node_ids: &HashMap<&str, i64>, -) -> Result { + embeddings: Option<&crate::embedding::EmbeddingVectors>, +) -> Result { let mut stats = IndexStats::default(); let mut seen: HashSet<(String, u64)> = HashSet::new(); - for facts in &graph.facts { - let Some(doc_id) = doc_ids.get(facts.rel_path.as_str()).copied() else { + for spec in unit_specs(graph) { + let Some(doc_id) = doc_ids.get(spec.doc_path.as_str()).copied() else { continue; }; - let specs = unit_specs(facts, graph); - for spec in specs { - let Some(node_id) = node_ids.get(spec.node_key.as_str()).copied() else { - continue; + let Some(node_id) = node_ids.get(spec.node_key.as_str()).copied() else { + continue; + }; + if !seen.insert((spec.node_key.clone(), spec.span.start)) { + continue; + } + tx.execute( + "INSERT INTO search_units + (node_id, doc_id, span_start, span_end, + title, body, symbols, metadata, formula, tabular, links) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", + rusqlite::params![ + node_id, + doc_id, + spec.span.start as i64, + spec.span.end as i64, + text::segment(&spec.fields.title), + text::segment(&spec.fields.body), + text::segment(&spec.fields.symbols), + text::segment(&spec.fields.metadata), + text::segment(&spec.fields.formula), + text::segment(&spec.fields.tabular), + text::segment(&spec.fields.links), + ], + ) + .map_err(storage_error)?; + let unit_id = tx.last_insert_rowid(); + tx.execute( + "INSERT INTO search_fts(rowid, title, body, symbols, metadata, formula, tabular, links) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + rusqlite::params![ + unit_id, + text::segment(&spec.fields.title), + text::segment(&spec.fields.body), + text::segment(&spec.fields.symbols), + text::segment(&spec.fields.metadata), + text::segment(&spec.fields.formula), + text::segment(&spec.fields.tabular), + text::segment(&spec.fields.links), + ], + ) + .map_err(storage_error)?; + stats.search_units += 1; + stats.grams += insert_grams(tx, unit_id, &spec.fields).map_err(storage_error)?; + if let Some(embeddings) = embeddings { + let embedded_text = unit_embedding_text(&spec.fields); + let digest = crate::embedding::embedding_content_digest(&embedded_text); + let key = (spec.node_key.clone(), spec.span.start, digest.clone()); + let Some(vector) = embeddings.vectors.get(&key) else { + return Err(KnowledgeError::environment( + crate::diagnostic::code::EMBEDDING_INVALID_RESPONSE, + "missing embedding vector for a search unit; the semantic index would be incomplete", + )); }; - // One search unit per (node, span chunk): never duplicate text. - if !seen.insert((spec.node_key.clone(), spec.span.start)) { - continue; + if vector.len() != embeddings.dimension { + return Err(KnowledgeError::environment( + crate::diagnostic::code::EMBEDDING_INVALID_RESPONSE, + "embedding dimension differs from the published dimension", + )); + } + let mut blob = Vec::with_capacity(vector.len() * 4); + for value in vector { + blob.extend_from_slice(&value.to_le_bytes()); } tx.execute( - "INSERT INTO search_units - (node_id, doc_id, span_start, span_end, - title, body, symbols, metadata, formula, tabular, links) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", - rusqlite::params![ - node_id, - doc_id, - spec.span.start as i64, - spec.span.end as i64, - text::segment(&spec.fields.title), - text::segment(&spec.fields.body), - text::segment(&spec.fields.symbols), - text::segment(&spec.fields.metadata), - text::segment(&spec.fields.formula), - text::segment(&spec.fields.tabular), - text::segment(&spec.fields.links), - ], - )?; - let unit_id = tx.last_insert_rowid(); - tx.execute( - "INSERT INTO search_fts(rowid, title, body, symbols, metadata, formula, tabular, links) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + "INSERT INTO embeddings (search_unit_id, content_digest, model_digest, dimension, vector) + VALUES (?1, ?2, ?3, ?4, ?5)", rusqlite::params![ unit_id, - text::segment(&spec.fields.title), - text::segment(&spec.fields.body), - text::segment(&spec.fields.symbols), - text::segment(&spec.fields.metadata), - text::segment(&spec.fields.formula), - text::segment(&spec.fields.tabular), - text::segment(&spec.fields.links), + digest, + embeddings.model_digest, + embeddings.dimension as i64, + blob, ], - )?; - stats.search_units += 1; - stats.grams += insert_grams(tx, unit_id, &spec.fields)?; + ) + .map_err(storage_error)?; + stats.embeddings += 1; } } + if embeddings.is_some() && stats.embeddings != stats.search_units { + return Err(KnowledgeError::environment( + crate::diagnostic::code::EMBEDDING_INVALID_RESPONSE, + "semantic index would contain missing vectors; publication was aborted", + )); + } Ok(stats) } +fn storage_error(error: rusqlite::Error) -> KnowledgeError { + KnowledgeError::environment( + crate::diagnostic::code::DATABASE_CORRUPT, + format!("search index write failed: {error}"), + ) +} + +/// Exact text embedded for one search unit (same function used by index and +/// source planning). +fn unit_embedding_text(fields: &SearchFields) -> String { + crate::embedding::embedding_text(&fields.title, &fields.body, &fields.formula) +} + +/// Plan the texts that must be embedded for this graph. +pub fn embedding_sources( + graph: &Graph, +) -> Result, KnowledgeError> { + let mut sources = Vec::new(); + for spec in unit_specs(graph) { + let text = unit_embedding_text(&spec.fields); + sources.push(crate::embedding::EmbeddingSource { + node_key: spec.node_key, + span_start: spec.span.start, + content_digest: crate::embedding::embedding_content_digest(&text), + text, + }); + } + if sources.len() > crate::embedding::MAX_UNITS { + return Err(KnowledgeError::environment( + crate::diagnostic::code::BUDGET_EXCEEDED, + format!( + "{} search units exceed the {} embedding unit budget", + sources.len(), + crate::embedding::MAX_UNITS + ), + )); + } + Ok(sources) +} + fn insert_grams( tx: &Transaction<'_>, unit_id: i64, @@ -179,7 +261,15 @@ fn insert_grams( /// Generate deterministic search-unit specs for one document, chunked on block /// boundaries with a hard byte budget. -fn unit_specs(facts: &DocumentFacts, graph: &Graph) -> Vec { +fn unit_specs(graph: &Graph) -> Vec { + let mut specs = Vec::new(); + for facts in &graph.facts { + specs.extend(unit_specs_for_document(facts, graph)); + } + specs +} + +fn unit_specs_for_document(facts: &DocumentFacts, graph: &Graph) -> Vec { let mut specs = Vec::new(); let node_by_key: HashMap<&str, &Node> = graph .nodes @@ -218,6 +308,7 @@ fn unit_specs(facts: &DocumentFacts, graph: &Graph) -> Vec { }; specs.push(UnitSpec { node_key, + doc_path: facts.rel_path.clone(), span, fields: base, }); @@ -235,7 +326,8 @@ fn unit_specs(facts: &DocumentFacts, graph: &Graph) -> Vec { first: bool, specs: &mut Vec, base: &SearchFields, - node_key: &str| { + node_key: &str, + doc_path: &str| { if fields.byte_len() == 0 && !first { return; } @@ -247,6 +339,7 @@ fn unit_specs(facts: &DocumentFacts, graph: &Graph) -> Vec { } specs.push(UnitSpec { node_key: node_key.to_string(), + doc_path: doc_path.to_string(), span: Span::new(start, end), fields: merged, }); @@ -263,6 +356,7 @@ fn unit_specs(facts: &DocumentFacts, graph: &Graph) -> Vec { &mut specs, &base, &node_key, + &facts.rel_path, ); first = false; chunk_start = block.span.start; @@ -278,6 +372,7 @@ fn unit_specs(facts: &DocumentFacts, graph: &Graph) -> Vec { &mut specs, &base, &node_key, + &facts.rel_path, ); } let _ = node_by_key; diff --git a/src/storage/mod.rs b/src/storage/mod.rs index 4e01899..fb2034f 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -77,6 +77,7 @@ pub struct PublishStats { pub edges: u64, pub search_units: u64, pub grams: u64, + pub embeddings: u64, pub rebuild_generation: u64, } @@ -87,6 +88,7 @@ pub struct PublishRequest<'a> { pub graph: &'a Graph, pub snapshot: &'a SourceSnapshot, pub contexts: &'a [ProjectContext], + pub embeddings: Option<&'a crate::embedding::EmbeddingVectors>, } /// Open a connection with the mandatory safety pragmas. @@ -461,7 +463,7 @@ fn write_rows( (path, format, source_digest, source, title, front_matter_json, document_role, okf_json, analysis_context_id, module_id, facts_json, facts_digest, facts_cache_version, diagnostic_status) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'native', NULL, ?7, ?8, ?9, ?10, ?11, ?12)", + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)", rusqlite::params![ facts.rel_path, facts.format.as_str(), @@ -469,6 +471,8 @@ fn write_rows( file.text.as_bytes(), facts.document_title, front_matter, + facts.okf.role.as_str(), + serde_json::to_string(&facts.okf).unwrap_or_else(|_| "null".into()), facts .analysis .as_ref() @@ -668,10 +672,16 @@ fn write_rows( insert_diagnostic(transaction, diagnostic)?; } - let index_stats = index::build_index(transaction, request.graph, &doc_ids, &node_ids) - .map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?; + let index_stats = index::build_index( + transaction, + request.graph, + &doc_ids, + &node_ids, + request.embeddings, + )?; stats.search_units = index_stats.search_units; stats.grams = index_stats.grams; + stats.embeddings = index_stats.embeddings; Ok(stats) } diff --git a/src/storage/read.rs b/src/storage/read.rs index 3ac4265..ceb2b1d 100644 --- a/src/storage/read.rs +++ b/src/storage/read.rs @@ -672,6 +672,45 @@ impl ReadStore { Ok(out) } + /// All stored vectors for reuse during an incremental compile, keyed by the + /// embedded-text digest. Reuse is only valid for the same model digest. + pub fn all_embeddings_by_digest( + &self, + model_digest: &str, + ) -> Result>, KnowledgeError> { + let mut statement = self + .conn + .prepare( + "SELECT content_digest, dimension, vector FROM embeddings + WHERE model_digest = ?1 ORDER BY search_unit_id", + ) + .map_err(db)?; + let rows = statement + .query_map([model_digest], |row| { + let blob: Vec = row.get(2)?; + Ok((row.get::<_, String>(0)?, blob)) + }) + .map_err(db)?; + let mut out = HashMap::new(); + for row in rows { + let (digest, blob) = row.map_err(db)?; + if blob.len() % 4 != 0 { + continue; + } + let mut vector = Vec::with_capacity(blob.len() / 4); + for index in (0..blob.len()).step_by(4) { + vector.push(f32::from_le_bytes([ + blob[index], + blob[index + 1], + blob[index + 2], + blob[index + 3], + ])); + } + out.insert(digest, vector); + } + Ok(out) + } + pub fn embeddings( &self, model_digest: &str, diff --git a/src/storage/schema.sql b/src/storage/schema.sql index 53cfcdc..0bfb36a 100644 --- a/src/storage/schema.sql +++ b/src/storage/schema.sql @@ -70,7 +70,7 @@ CREATE TABLE nodes ( metadata_json TEXT NOT NULL, CHECK ((span_start IS NULL) = (span_end IS NULL)), CHECK (span_start IS NULL OR (span_start >= 0 AND span_end >= span_start)), - CHECK (kind = 'external' OR doc_id IS NOT NULL) + CHECK (kind IN ('external', 'resource') OR doc_id IS NOT NULL) ); CREATE INDEX nodes_doc ON nodes(doc_id); diff --git a/tests/embedding.rs b/tests/embedding.rs new file mode 100644 index 0000000..85893b0 --- /dev/null +++ b/tests/embedding.rs @@ -0,0 +1,334 @@ +//! Semantic channel end-to-end tests against a local mock embeddings server. +//! +//! The mock proves protocol handling, validation, storage and fusion. It is not +//! a semantic-quality benchmark: no real-model claim is made here. + +use marqdo_knowledge::cli::{CompileArgs, EmbeddingArgs, OutputFormat, QueryArgs}; +use marqdo_knowledge::compiler; +use marqdo_knowledge::query; +use marqdo_knowledge::storage::read::ReadStore; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +struct MockServer { + port: u16, + requests: Arc, +} + +impl MockServer { + /// Deterministic fake embedding: "模长"/"归一" -> [0,1,0], "量子" -> [1,0,0], + /// otherwise [0,0,1]. This lets the test assert cross-vocabulary recall. + fn start() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let requests = Arc::new(AtomicUsize::new(0)); + let counter = requests.clone(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { break }; + counter.fetch_add(1, Ordering::SeqCst); + let response = handle(&mut stream); + let _ = stream.write_all(response.as_bytes()); + } + }); + Self { port, requests } + } + + fn embed_args(&self) -> EmbeddingArgs { + EmbeddingArgs { + embedding_url: Some(format!("http://127.0.0.1:{}/v1", self.port)), + embedding_model: Some("mock-embed".into()), + embedding_revision: Some("r1".into()), + allow_remote_embedding: false, + } + } + + fn requests(&self) -> usize { + self.requests.load(Ordering::SeqCst) + } +} + +fn handle(stream: &mut TcpStream) -> String { + let mut buffer = Vec::new(); + let mut chunk = [0u8; 4096]; + let header_end = loop { + let read = stream.read(&mut chunk).unwrap_or(0); + if read == 0 { + return error_response(400, "empty request"); + } + buffer.extend_from_slice(&chunk[..read]); + if let Some(position) = find_subsequence(&buffer, b"\r\n\r\n") { + break position + 4; + } + }; + let header = String::from_utf8_lossy(&buffer[..header_end]).to_string(); + let content_length = header + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + if name.eq_ignore_ascii_case("content-length") { + value.trim().parse::().ok() + } else { + None + } + }) + .unwrap_or(0); + while buffer.len() < header_end + content_length { + let read = stream.read(&mut chunk).unwrap_or(0); + if read == 0 { + break; + } + buffer.extend_from_slice(&chunk[..read]); + } + let body = String::from_utf8_lossy( + &buffer[header_end..(header_end + content_length).min(buffer.len())], + ); + let value: serde_json::Value = match serde_json::from_str(&body) { + Ok(value) => value, + Err(error) => return error_response(400, &format!("bad request JSON: {error}")), + }; + let inputs = value["input"].as_array().cloned().unwrap_or_default(); + let data: Vec = inputs + .iter() + .enumerate() + .map(|(index, input)| { + let text = input.as_str().unwrap_or_default(); + let vector = if text.contains("模长") || text.contains("归一") { + vec![0.0, 1.0, 0.0] + } else if text.contains("量子") { + vec![1.0, 0.0, 0.0] + } else { + vec![0.0, 0.0, 1.0] + }; + serde_json::json!({"index": index, "embedding": vector}) + }) + .collect(); + let response = serde_json::json!({"model": "mock-embed", "data": data}); + let body = response.to_string(); + format!( + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}", + body.len(), + body + ) +} + +fn error_response(status: u16, message: &str) -> String { + let body = serde_json::json!({"error": message}).to_string(); + format!( + "HTTP/1.1 {status} Error\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}", + body.len(), + body + ) +} + +fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option { + haystack + .windows(needle.len()) + .position(|window| window == needle) +} + +fn project() -> PathBuf { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().to_path_buf(); + std::fs::create_dir_all(root.join("physics")).unwrap(); + std::fs::write( + root.join("physics/quantum.md"), + "# 量子态\n\n量子态是否合法取决于归一化。\n", + ) + .unwrap(); + std::fs::create_dir_all(root.join("math")).unwrap(); + std::fs::write( + root.join("math/normalize.md"), + "# 归一化\n\n消除向量模长影响是归一化的常见写法。\n", + ) + .unwrap(); + std::mem::forget(temp); + root +} + +fn compile_with( + root: &Path, + embedding: EmbeddingArgs, +) -> Result<(), marqdo_knowledge::error::KnowledgeError> { + let args = CompileArgs { + root: root.to_path_buf(), + exclude: Vec::new(), + rebuild: false, + json: true, + embedding, + }; + compiler::compile(&args, None).map(|_| ()) +} + +fn query_args(root: &Path, query: &str, semantic: bool, embedding: EmbeddingArgs) -> QueryArgs { + QueryArgs { + query: query.to_string(), + root: root.to_path_buf(), + exact: false, + kind: None, + limit: None, + depth: None, + relation: Vec::new(), + reverse: false, + slice: None, + format: OutputFormat::Json, + snapshot: false, + semantic, + embedding, + } +} + +#[test] +fn semantic_index_is_built_and_queried_with_explicit_opt_in() { + let server = MockServer::start(); + let root = project(); + compile_with(&root, server.embed_args()).unwrap(); + let store = ReadStore::open(&root.join(".marqdo/knowledge.sqlite")).unwrap(); + let (_, _, _) = store.counts().unwrap(); + let search_units = store.search_unit_count().unwrap(); + let stored_vectors = store + .embeddings( + store.build_meta().unwrap().embedding.unwrap()["model_digest"] + .as_str() + .unwrap(), + 100, + ) + .unwrap(); + assert!(!stored_vectors.is_empty()); + assert!(stored_vectors.len() as u64 <= search_units); + let before = server.requests(); + + // The query has no lexical overlap with the target ("消除模长影响" vs + // "归一化") but the mock maps both to the same vector. + let output = query::run_query( + &query_args(&root, "消除模长影响", true, server.embed_args()), + None, + ) + .unwrap(); + assert_eq!(output.exit_code, 0, "{}", output.stderr); + let value: serde_json::Value = serde_json::from_str(&output.stdout).unwrap(); + assert!(value["channels"] + .as_array() + .unwrap() + .iter() + .any(|channel| channel == "semantic")); + let hits = value["hits"].as_array().unwrap(); + assert!( + hits.iter().any(|hit| hit["title"] == "归一化"), + "semantic channel must recall the cross-vocabulary target: {hits:?}" + ); + assert!(server.requests() > before); + + // A normal query stays offline even though vectors exist. + let before = server.requests(); + let output = query::run_query( + &query_args(&root, "量子态", false, EmbeddingArgs::default()), + None, + ) + .unwrap(); + assert_eq!(output.exit_code, 0); + assert_eq!( + server.requests(), + before, + "default query must not perform network I/O" + ); +} + +#[test] +fn remote_endpoint_requires_explicit_consent_and_tls() { + let config = EmbeddingArgs { + embedding_url: Some("https://example.com/v1".into()), + embedding_model: Some("m".into()), + embedding_revision: Some("r".into()), + allow_remote_embedding: false, + }; + let error = marqdo_knowledge::embedding::EmbeddingConfig::new( + config.embedding_url.as_deref().unwrap(), + "m", + "r", + false, + ) + .unwrap_err(); + assert_eq!( + error.code, + marqdo_knowledge::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED + ); + let error = + marqdo_knowledge::embedding::EmbeddingConfig::new("http://example.com/v1", "m", "r", true) + .unwrap_err(); + assert_eq!( + error.code, + marqdo_knowledge::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED + ); + // Plain http loopback is allowed without remote consent. + assert!(marqdo_knowledge::embedding::EmbeddingConfig::new( + "http://127.0.0.1:9/v1", + "m", + "r", + false + ) + .is_ok()); +} + +#[test] +fn invalid_embedding_response_does_not_publish_a_mixed_index() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { break }; + let mut buffer = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + let read = stream.read(&mut chunk).unwrap_or(0); + if read == 0 { + break; + } + buffer.extend_from_slice(&chunk[..read]); + if find_subsequence(&buffer, b"\r\n\r\n").is_some() { + break; + } + } + let body = serde_json::json!({"data": [ + {"index": 0, "embedding": [1.0, 0.0]} + ]}); + let body = body.to_string(); + let response = format!( + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}", + body.len(), + body + ); + let _ = stream.write_all(response.as_bytes()); + } + }); + let root = project(); + let embedding = EmbeddingArgs { + embedding_url: Some(format!("http://127.0.0.1:{port}/v1")), + embedding_model: Some("m".into()), + embedding_revision: Some("r".into()), + allow_remote_embedding: false, + }; + let error = compile_with(&root, embedding).unwrap_err(); + assert!( + error.code == marqdo_knowledge::diagnostic::code::EMBEDDING_INVALID_RESPONSE + || error.code == marqdo_knowledge::diagnostic::code::EMBEDDING_TRANSPORT, + "unexpected error: {error:?}" + ); + assert!(!root.join(".marqdo/knowledge.sqlite").exists()); +} + +#[test] +fn semantic_query_without_a_compiled_index_is_an_error() { + let server = MockServer::start(); + let root = project(); + compile_with(&root, EmbeddingArgs::default()).unwrap(); + let error = + query::run_query(&query_args(&root, "模长", true, server.embed_args()), None).unwrap_err(); + assert_eq!( + error.code, + marqdo_knowledge::diagnostic::code::EMBEDDING_CONFIG_MISMATCH + ); +} diff --git a/tests/okf.rs b/tests/okf.rs new file mode 100644 index 0000000..9cc6dfa --- /dev/null +++ b/tests/okf.rs @@ -0,0 +1,242 @@ +//! OKF v0.3 recognition, metadata preservation and `check --okf` conformance. + +use marqdo_knowledge::cli::{CheckArgs, CompileArgs, EmbeddingArgs, OutputFormat, QueryArgs}; +use marqdo_knowledge::compiler; +use marqdo_knowledge::document::discovery::{discover, resolve_scope}; +use marqdo_knowledge::document::markdown::parse_plain; +use marqdo_knowledge::graph; +use marqdo_knowledge::model::EdgeState; +use marqdo_knowledge::query; +use marqdo_knowledge::storage::read::ReadStore; +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; + +fn project(files: &[(&str, &str)]) -> PathBuf { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().to_path_buf(); + for (path, content) in files { + let absolute = root.join(path); + if let Some(parent) = absolute.parent() { + std::fs::create_dir_all(parent).unwrap(); + } + std::fs::write(absolute, content).unwrap(); + } + std::mem::forget(temp); + root +} + +fn compile(root: &Path) { + let args = CompileArgs { + root: root.to_path_buf(), + exclude: Vec::new(), + rebuild: false, + json: true, + embedding: EmbeddingArgs::default(), + }; + let output = compiler::compile(&args, None).unwrap(); + assert_eq!(output.exit_code, 0, "{}", output.stderr); +} + +fn check_okf(root: &Path) -> (i32, serde_json::Value) { + let args = CheckArgs { + root: root.to_path_buf(), + okf: true, + json: true, + }; + let output = compiler::check(&args, None).unwrap(); + ( + output.exit_code, + serde_json::from_str(&output.stdout).unwrap(), + ) +} + +fn bundle() -> PathBuf { + project(&[ + ("index.md", "# Knowledge\n\n- [经典力学](physics/mechanics.md)\n"), + ("log.md", "# Change log\n\n## 2026-11-25\n\n- initial concept\n"), + ( + "physics/mechanics.md", + "---\ntype: Theory\ntitle: 经典力学\ntags: [physics, mechanics]\ndescription: 力学总览\ncustom_key: preserved\n---\n\n# 经典力学\n\n## 牛顿第二定律\n\n合外力等于质量与加速度的乘积。\n", + ), + ( + "datasets/table.md", + "---\ntype: Dataset\ntitle: 数据表\nresource: ../data/values.csv\n---\n\n# 数据表\n\n数据说明。\n", + ), + ("data/values.csv", "a,b\n1,2\n"), + ]) +} + +#[test] +fn concept_metadata_and_roles_are_recognised() { + let root = bundle(); + compile(&root); + let store = ReadStore::open(&root.join(".marqdo/knowledge.sqlite")).unwrap(); + let mut roles: Vec<(String, String)> = store + .documents() + .unwrap() + .into_iter() + .map(|document| (document.path, document.role)) + .collect(); + roles.sort(); + assert_eq!( + roles, + vec![ + ("datasets/table.md".to_string(), "concept".to_string()), + ("index.md".to_string(), "index".to_string()), + ("log.md".to_string(), "log".to_string()), + ("physics/mechanics.md".to_string(), "concept".to_string()), + ] + ); + // Concept identity maps to the document node through an exact alias. + let aliases = store.aliases_for("physics/mechanics").unwrap(); + assert_eq!(aliases.len(), 1); + let node = &aliases[0].1; + assert_eq!(node.kind, marqdo_knowledge::model::NodeKind::Document); + assert_eq!(node.metadata["okf"]["concept_type"], "Theory"); + assert_eq!(node.metadata["okf"]["tags"][0], "physics"); + assert_eq!(node.metadata["okf"]["metadata"]["custom_key"], "preserved"); + // Reserved files never get concept ids. + assert!(store.aliases_for("index").unwrap().is_empty()); + assert!(store.aliases_for("log").unwrap().is_empty()); +} + +#[test] +fn exact_query_resolves_a_concept_id() { + let root = bundle(); + compile(&root); + let args = QueryArgs { + query: "physics/mechanics".into(), + root: root.clone(), + exact: true, + kind: None, + limit: None, + depth: None, + relation: Vec::new(), + reverse: false, + slice: None, + format: OutputFormat::Json, + snapshot: false, + semantic: false, + embedding: EmbeddingArgs::default(), + }; + let output = query::run_query(&args, None).unwrap(); + assert_eq!(output.exit_code, 0); + let value: serde_json::Value = serde_json::from_str(&output.stdout).unwrap(); + assert_eq!(value["hits"][0]["title"], "经典力学"); + assert_eq!(value["hits"][0]["kind"], "document"); +} + +#[test] +fn okf_resource_is_a_reference_edge_to_the_asset() { + let root = bundle(); + compile(&root); + let store = ReadStore::open(&root.join(".marqdo/knowledge.sqlite")).unwrap(); + let document = store + .node_by_key(graph::identity::document_key("datasets/table.md").as_str()) + .unwrap() + .unwrap(); + let edges = store + .edges_from( + &[document.id], + &[marqdo_knowledge::model::EdgeKind::References], + ) + .unwrap(); + let resource_edge = edges + .iter() + .find(|edge| edge.raw_target == "../data/values.csv") + .expect("resource reference edge"); + assert_eq!(resource_edge.state, EdgeState::Resolved); + let target = store + .node_by_id(resource_edge.target_id.unwrap()) + .unwrap() + .unwrap(); + assert_eq!(target.kind, marqdo_knowledge::model::NodeKind::Resource); + assert_eq!(target.metadata["path"], "data/values.csv"); +} + +#[test] +fn valid_bundle_passes_okf_check() { + let root = bundle(); + let (exit, value) = check_okf(&root); + assert_eq!(exit, 0, "{value:?}"); + assert_eq!(value["payload"]["errors"], 0); +} + +#[test] +fn non_reserved_file_without_type_fails_okf_check_only() { + let root = project(&[ + ("index.md", "# Knowledge\n"), + ("concept.md", "---\ntype: Note\ntitle: ok\n---\n\n# ok\n"), + ("loose.md", "# no front matter\n"), + ]); + // Native compile still works: ordinary documents remain knowledge. + compile(&root); + let (exit, value) = check_okf(&root); + assert_eq!(exit, 1); + assert!(value["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|diagnostic| diagnostic["code"] == "knowledge.okf_invalid")); +} + +#[test] +fn broken_links_are_tolerated_in_okf_mode_but_not_in_plain_check() { + let root = project(&[ + ("index.md", "# Knowledge\n"), + ( + "concept.md", + "---\ntype: Note\n---\n\n# note\n\n[missing](missing-target.md)\n", + ), + ]); + let (exit, _) = check_okf(&root); + assert_eq!(exit, 0, "OKF conformance tolerates broken links"); + let plain = compiler::check( + &CheckArgs { + root: root.clone(), + okf: false, + json: true, + }, + None, + ) + .unwrap(); + assert_eq!( + plain.exit_code, 1, + "plain check fails on a definite broken link" + ); +} + +#[test] +fn root_absolute_okf_links_resolve_inside_the_bundle() { + let root = project(&[ + ("index.md", "# Knowledge\n"), + ("a.md", "---\ntype: Note\n---\n\n# a\n\n[b](/b.md#b)\n"), + ("b.md", "---\ntype: Note\n---\n\n# b\n\ncontent\n"), + ]); + let scope = resolve_scope(&root, &[]).unwrap(); + let snapshot = discover(&scope).unwrap(); + let facts: Vec<_> = snapshot.files.iter().map(parse_plain).collect(); + let mut sources: HashMap<&str, &str> = HashMap::new(); + for file in &snapshot.files { + sources.insert(file.rel_path.as_str(), file.text.as_str()); + } + let missing: HashSet = HashSet::new(); + let native = graph::build(facts.clone(), &sources, &snapshot.assets, &missing, false); + let native_edge = native + .edges + .iter() + .find(|edge| edge.raw_target == "/b.md#b") + .unwrap(); + assert_eq!(native_edge.state, EdgeState::OutOfScope); + let okf = graph::build(facts, &sources, &snapshot.assets, &missing, true); + let okf_edge = okf + .edges + .iter() + .find(|edge| edge.raw_target == "/b.md#b") + .unwrap(); + assert_eq!(okf_edge.state, EdgeState::Resolved); + assert!(okf_edge.target.is_some()); + assert!(okf.diagnostics.iter().all(|diagnostic| !diagnostic + .message + .contains("escapes the allowed knowledge root"))); +} diff --git a/tests/storage.rs b/tests/storage.rs index 79ced12..508ccf5 100644 --- a/tests/storage.rs +++ b/tests/storage.rs @@ -44,7 +44,7 @@ fn build_graph(snapshot: &SourceSnapshot) -> marqdo_knowledge::graph::Graph { sources.insert(file.rel_path.as_str(), file.text.as_str()); } let missing: HashSet = HashSet::new(); - graph::build(facts, &sources, &snapshot.assets, &missing) + graph::build(facts, &sources, &snapshot.assets, &missing, false) } fn meta( @@ -81,6 +81,7 @@ fn publish( graph, snapshot, contexts: &[], + embeddings: None, }; storage::publish(request).unwrap(); } @@ -197,6 +198,7 @@ fn foreign_database_is_never_overwritten() { graph: &graph, snapshot: &snapshot, contexts: &[], + embeddings: None, }; let error = storage::publish(request).unwrap_err(); assert_eq!(error.code, "knowledge.database_not_ours");