diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..38473e7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/target/ +.cargo-home/ +.scratch/ +.marqdo/ +*.sqlite +*.sqlite-journal +*.sqlite-wal +*.sqlite-shm diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..15a03da --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,735 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "caseless" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b6fd507454086c8edfd769ca6ada439193cdb209c7681712ef6275cccbfe5d8" +dependencies = [ + "unicode-normalization", +] + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clap" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "comrak" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d981d666dca19afb3cc090dc7c381560cb8ba76582dda6e2c14686ff39fd547f" +dependencies = [ + "caseless", + "entities", + "finl_unicode", + "memchr-n", + "phf", + "phf_codegen", + "rustc-hash", + "smallvec", + "typed-arena", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "entities" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5320ae4c3782150d900b79807611a59a99fc9a1d61d686faafc24b93fc8d7ca" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fearless_simd" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a7107516a8be9a4ffe92495f3dbfe04348be0ad18f17c67a1d846511f99e599" + +[[package]] +name = "fearless_simd_macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e91d94c6885390b81782d7ee60fd6583b33907333a8b340de25ccf468353315" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "finl_unicode" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ded33109e99472f809cb7495544506eea45e366725dacf2a383e184f660456" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libsqlite3-sys" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "marqdo-knowledge" +version = "0.1.0" +dependencies = [ + "clap", + "comrak", + "glob", + "hex", + "rusqlite", + "serde", + "serde_json", + "serde_yaml", + "sha2", + "tempfile", + "thiserror", + "unicode-normalization", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memchr-n" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f48c6352cc1185740af256ccc396af598d2366bfd90a34f5afe48744bf06a5b5" +dependencies = [ + "fearless_simd", + "fearless_simd_macros", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_shared", + "serde", +] + +[[package]] +name = "phf_codegen" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rusqlite" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "typed-arena" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..27443c6 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "marqdo-knowledge" +version = "0.1.0" +edition = "2021" +rust-version = "1.89" +license = "Apache-2.0" +description = "Deterministic, offline knowledge compiler for Markdown and Marqdo documents" +repository = "https://github.com/cflmy/marqdo-knowledge" +publish = false + +[lib] +name = "marqdo_knowledge" +path = "src/lib.rs" + +[[bin]] +name = "marqdo-knowledge" +path = "src/main.rs" + +[dependencies] +clap = { version = "=4.6.9", features = ["derive", "env"] } +comrak = { version = "=1.0.0", default-features = false } +glob = "=0.3.4" +hex = "=0.4.3" +rusqlite = { version = "=0.37.0", features = ["bundled"] } +serde = { version = "=1.0.229", features = ["derive"] } +serde_json = "=1.0.154" +serde_yaml = "=0.9.34" +sha2 = "=0.10.9" +tempfile = "=3.27.0" +thiserror = "=2.0.21" +unicode-normalization = "=0.1.26" + +[profile.release] +codegen-units = 1 +lto = "thin" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..fb90409 --- /dev/null +++ b/README.md @@ -0,0 +1,64 @@ +# marqdo-knowledge + +Deterministic, offline knowledge compiler for Markdown and Marqdo documents. + +`marqdo-knowledge` turns a directory of existing `.md` / `.mq.md` files into a +single rebuildable SQLite projection: document structure, heading scopes, +links, imports, function identities and static calls. It is a separate CLI tool +dispatched by `marqdo` through the `marqdo.cli-tool` protocol; it never executes +knowledge, never fetches documents from the network and never rewrites source +files. + +```sh +marqdo tool install ./dist/tool.json +cd my-knowledge +marqdo knowledge compile . +marqdo knowledge query '如何判断量子态是否合法' --kind function +marqdo knowledge query '概率归一化' --format markdown +marqdo knowledge check . +``` + +The only persistent artifact of normal use is `.marqdo/knowledge.sqlite`. It is +derived, can be deleted at any time and is rebuilt from the Markdown sources. +There is no project configuration file, no metadata sidecar, no node manifest +and no separate knowledge IR file. + +## Status + +This repository is an implementation in progress against the development +specification `marqdo-knowledge-development.md` (kept outside this repository's +source tree; the frozen contract is mirrored in [`spec/knowledge.md`](spec/knowledge.md)). +See [`docs/STATUS.md`](docs/STATUS.md) for the exact, evidence-based state of +each capability. **Do not infer unimplemented behavior from design documents.** + +## Building + +```sh +cargo build --release --locked +cargo test --workspace --locked +``` + +The release candidate platform is Linux x86_64. The core CLI used for static +analysis is an external dependency: this tool calls `$MARQDO_BIN` (or the +explicit `--marqdo-bin` development override) with `check ENTRY --emit PATH`. +Plain `.md` documents are parsed by this tool's own CommonMark/GFM projection; +`.mq.md` documents always use the core CLI's current public Analysis contract +(`marqdo.analysis`, revision 3). + +## Commands + +```text +marqdo knowledge compile [ROOT] [--exclude GLOB ...] [--rebuild] [--json] +marqdo knowledge check [ROOT] [--okf] [--json] +marqdo knowledge query QUERY [--root ROOT] [--exact] [--kind KIND] [--limit N] + [--depth N] [--relation KIND ...] [--reverse] [--slice document|execution|hybrid] + [--format markdown|json] [--snapshot] [--semantic] +``` + +See [`spec/knowledge.md`](spec/knowledge.md) for the contract and +[`docs/architecture/OVERVIEW.md`](docs/architecture/OVERVIEW.md) for the +internal architecture. + +## License + +Apache-2.0. See [`LICENSE-APACHE`](LICENSE-APACHE). diff --git a/docs/STATUS.md b/docs/STATUS.md new file mode 100644 index 0000000..1853699 --- /dev/null +++ b/docs/STATUS.md @@ -0,0 +1,49 @@ +# Status + +Last updated: 2026-11-25. Evidence-based; this file lists what the code does, +not what the design intends. Anything not listed as verified is **NOT RUN** and +must not be claimed as passing. + +The development baseline is `marqdo-knowledge-development.md` (kept outside +this repository). Upstream Analysis baseline for integration is +`cflmy/marqdo-cli` `3.0.0-rc.4` (`4bbefc92449ee480c8a2c89b0308feb4cda8d0e7`), +contract `marqdo.analysis` revision 3. The original static audit in the +development specification refers to `e6066e6`; the current public boundary has +since been implemented upstream as ADR-0069, so this tool targets the current +revision-3 shape and rejects everything else. + +## Capability matrix + +| Area | State | Evidence | +|---|---|---| +| Repository scaffold, CLI surface, exit codes | implemented | unit tests in `src/cli.rs` | +| Discovery, snapshot, budgets | in progress | - | +| Plain Markdown projection | in progress | - | +| Analysis v3 adapter + semantic validation | in progress | - | +| Unified graph and reference resolution | in progress | - | +| SQLite schema, transactions, atomic publish | in progress | - | +| Compile command | in progress | - | +| Lexical / fuzzy / graph query, RRF | in progress | - | +| Slices | in progress | - | +| Incremental update | in progress | - | +| OKF v0.3 recognition and check | in progress | - | +| Semantic channel (OpenAI-compatible embeddings) | in progress | - | +| Packaging (`tool.json`, release script) | in progress | - | +| Performance / retrieval benchmarks | NOT RUN | no frozen dataset yet | +| Real-model semantic benchmark | NOT RUN | requires a pinned model revision not available in this environment | +| Cold install against a real `marqdo` binary | NOT RUN | - | + +## Known limitations + +* Linux x86_64 is the only release-candidate platform. +* The exact quality/performance gates of the development specification §16 are + not yet measured; no threshold is claimed. + +## Reproduce + +```sh +scripts/cargo.sh fmt --all -- --check +scripts/cargo.sh clippy --all-targets -- -D warnings +scripts/cargo.sh test +scripts/cargo.sh build --release +``` diff --git a/docs/adr/0001-single-derived-artifact.md b/docs/adr/0001-single-derived-artifact.md new file mode 100644 index 0000000..7ac3d88 --- /dev/null +++ b/docs/adr/0001-single-derived-artifact.md @@ -0,0 +1,37 @@ +# ADR-0001: One derived SQLite artifact, one current contract + +- Status: accepted (implementation baseline) +- Date: 2026-11-25 +- Context: `marqdo-knowledge-development.md` §1, §7, §12, §17 + +## Decision + +1. `marqdo-knowledge` persists exactly one knowledge artifact per root: + `.marqdo/knowledge.sqlite`. It is derived, rebuildable and private to the + tool. No `knowledge.yaml`, node manifest, JSONL graph, vector file or + separate knowledge IR is created or read. +2. The only machine input for Marqdo program semantics is the core CLI's current + public Analysis (`marqdo.analysis`, revision 3) produced by + `check ENTRY --emit PATH`. There is no second Analysis shape, version probe, + legacy reader or fallback parser. +3. The public CLI contract is exactly three business subcommands: `compile`, + `check`, `query`. No `init/search/graph/impact/export/serve` aliases. +4. Query never writes graph facts; `compile` is the only write path; `check` + never writes. +5. Schema changes are explicit and destructive: the tool rejects an old schema + revision and asks for `compile --rebuild`. There is no automatic migration. +6. Freshness is content-based: query compares the recorded input digests with + the current root and refuses to serve a stale snapshot unless the user + explicitly passes `--snapshot`. + +## Consequences + +* Deleting the database loses nothing; a rebuild is the only recovery needed. +* Incremental compilation must prove semantic equivalence to a full compile. + The implementation keeps a digest-guarded cache of normalised document facts + inside the database so that unchanged Analysis contexts are not re-invoked; + the cache is derived data and is verified on every use. +* Schema revision, Analysis revision and product version are independent + numbers. They are not bumped for cosmetic alignment. +* There is one producer and one validator for each boundary; retiring a shape + means deleting it, not keeping a compatibility branch. diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.md new file mode 100644 index 0000000..f89d7f9 --- /dev/null +++ b/docs/architecture/OVERVIEW.md @@ -0,0 +1,209 @@ +# marqdo-knowledge architecture + +Status: current design (implementation in progress; see `docs/STATUS.md`). + +## 1. Scope + +`marqdo-knowledge` is a separate CLI tool dispatched by `marqdo` as command +`knowledge`. It compiles an existing directory of Markdown and Marqdo documents +into one derived, rebuildable SQLite projection and answers exact, lexical, +fuzzy, graph and optionally semantic queries over it. + +Non-goals are fixed by the development specification: no execution, no runtime, +no plugins, no foreign kernels, no proof/attestation, no knowledge server, no +second Markdown parser for executable semantics, no generated knowledge files. + +The knowledge truth is always the original Markdown sources plus the resources +they explicitly reference. `.marqdo/knowledge.sqlite` is a derived artifact: it +may be deleted at any moment and fully rebuilt. + +## 2. Data flow + +```text +ROOT + options + -> discovery deterministic source snapshot (exact bytes, digests) + -> documents plain .md projection | Marqdo Analysis v3 adapter + -> graph one Node/Edge graph (contains/references/imports/calls) + -> storage one SQLite transaction + derived search indexes + -> query exact | lexical FTS5 | fuzzy grams | graph | semantic + -> render human Markdown or the machine JSON envelope +``` + +`compile` is the only writer. `check` never writes. `query` opens the database +read-only, verifies freshness and never recompiles implicitly. + +## 3. Layers and dependency direction + +```text +main -> cli -> compiler / query +compiler -> document -> (plain Markdown parser | core Analysis JSON) +compiler -> graph -> model +compiler -> storage <- query +query -> fuzzy / slice / semantic -> model + read-only storage +storage -> rusqlite + model +model and diagnostic depend on neither I/O nor SQLite +``` + +Rules: + +* `model` owns the shared typed vocabulary (span, canonical key, node/edge/state + kinds, digest helpers). One definition only; no parallel JSON dictionaries. +* `document` never writes SQLite and never renders output. +* `graph` never reads the filesystem, SQLite or the network. +* `storage` never parses Markdown and never runs the core CLI. +* `query` never mutates stored graph facts; it has a read-only storage handle. +* `compiler` is the single write-transaction orchestration point. +* `cli` owns argv and rendering only; the compiler/query layers return + structured reports, they never print. +* The semantic client receives only explicitly selected snippets and the query; + it has no workspace access. + +## 4. Source snapshot and discovery + +* The root is canonicalised once. Directories are walked without following + symbolic links; `.git`, `.marqdo`, hidden entries, `target` and + `node_modules` are skipped. +* Only `.md` and `.mq.md` are knowledge documents. A root may also be a single + Markdown file (scope = that file; the root for the database is its parent). +* Files are read as exact bytes, validated as UTF-8, limited by per-file and + total budgets, and sorted by byte-wise relative path. +* Every input (document, manifest, lock, referenced local asset) is recorded in + `inputs` with its digest, so freshness and incremental invalidation compare + content, never mtime. +* Paths are validated segment by segment: no absolute path, drive/UNC prefix, + backslash, empty/`.`/`..` segment, NUL, or escape from the root. Link + fragments are percent-decoded exactly once. + +## 5. Document projections + +### 5.1 Plain `.md` + +Parsed with the pinned CommonMark/GFM parser (`comrak = 1.0.0`, fixed +options: tables, footnotes, strikethrough, task lists, dollar math, front +matter). Line/column positions are converted to exact half-open UTF-8 byte +offsets. The projection produces headings, byte spans, link/image URLs, +front-matter metadata and extractable block text. `@exec` text in a plain +`.md` file is never executable. + +### 5.2 `.mq.md` + +Never re-parsed for program semantics. The tool invokes the core CLI once per +entry candidate: + +```text +$MARQDO_BIN check --emit +``` + +and consumes the current `marqdo.analysis` revision 3 artefact as a closed +contract. It verifies the schema identity, project/module identities, every +`source_digest`, every span (range, UTF-8 boundary, module ownership), the unit +parent tree, anchors, functions, references states, calls and resources. A +module may be covered by several entries; it is merged only when identity and +source digest agree, otherwise compilation is blocked with +`knowledge.analysis_context_conflict`. The exact Analysis bytes are never +published as a knowledge artifact. + +### 5.3 OKF v0.3 + +An optional document-layer convention, not a new format and not a project type. +Front-matter `type` turns a document/heading into an OKF concept identity; +`index.md`/`log.md` stay Native documents with navigation/history roles; +unknown keys are preserved as data and never change program semantics. `check +--okf` validates the supported OKF structure and link rules; it is not a +general attestation verifier. + +## 6. Graph + +One `Node` type with `NodeKind` (document, namespace, section, function, +statement, resource, external). One `Edge` type with `EdgeKind` (contains, +references, imports, calls), `EdgeOrigin` (document, analysis) and an explicit +resolution state (resolved, not_loaded, missing, ambiguous, external, +out_of_scope, invalid, dynamic, unresolved). + +* A Marqdo unit and its function are the same node: the unit path is the node + key and the upstream FunctionId is an alias. Document roots map to the + document node; no second document node is created. +* `contains` is a single-parent tree. `references`/`imports`/`calls` may have + unresolved targets; the raw target and source span are always retained. +* Each occurrence of a repeated link is its own edge (identity includes the + source span), so a document with ten links to the same target keeps ten + locations. +* External URIs become `external` nodes and are never fetched. Missing, + ambiguous, out-of-scope, dynamic and unverified targets are reported as + states, never silently bound. +* At most these four relation kinds are stored. Similarity scores are search + signals, not edges. + +## 7. Identity + +* Logical identity: root-relative document path plus the upstream structured + unit path (or `FunctionId` alias). Canonical keys are UTF-8 percent-encoded + canonical JSON arrays, never raw `#`/`::`/`/` concatenation. +* Source position: `source_digest` plus half-open UTF-8 byte range. Human + line/column are presentation only. +* Snapshot identity: canonical input list, raw byte digests, relevant Analysis + context digests, lock/stdlib digests and compiler/index configuration. It + excludes absolute paths, wall-clock time and SQLite page layout. + +## 8. Storage + +A single SQLite file, `.marqdo/knowledge.sqlite`, with tables `build`, +`documents`, `nodes`, `aliases`, `edges`, `contexts`, `inputs`, `diagnostics`, +`search_units`, `search_fts` (FTS5), `grams` and optional `embeddings`. +`PRAGMA foreign_keys=ON` is set per connection; spans are checked; an unresolved +edge has a `NULL` target. All SQL uses parameter binding. + +`compile` stages changes in a transaction (full rebuild stages a private +database and renames it into place) and only publishes after source recheck and +integrity checks. A failed compile never overwrites the last successful +artifact. Schema revision changes are rejected with an explicit rebuild +instruction; there is no automatic migration and no legacy reader. + +Derived facts needed for a conservative incremental update (normalised document +facts + the Analysis context identity) are cached in the database and reused +only when the exact source digest and context signature still match. They are +an optimisation of derived data, not a second source of truth; deleting the +database loses nothing. + +## 9. Query pipeline + +1. Exact canonical address lookup (never fuzzy, never guesses). +2. Lexical channel: FTS5 with CJK bigram pre-segmentation and weighted fields. +3. Fuzzy channel: normalised 2/3-gram inverted index plus bounded edit + distance over candidate titles/symbols. +4. Optional semantic channel: OpenAI-compatible `POST /embeddings`, explicit + opt-in, vectors stored as float32 BLOBs and invalidated on config change. +5. Weighted Reciprocal Rank Fusion per search unit, then per node. +6. Bounded graph expansion from high-ranked seeds (depth, relations, reverse, + node/edge budgets, decay) with `truncated` reported honestly. +7. Slices: document (contains + references), execution (calls + imports), + hybrid; deterministic byte budget, original source text only. + +Fuzzy/semantic recall may be approximate. Identity and binding never are. + +## 10. Determinism and limits + +* Same inputs and configuration produce the same logical digest and ordering + regardless of checkout path, clock or SQLite page layout. +* Finite budgets: 16 MiB per file, 512 MiB total source, 100,000 documents, + AST depth 256, 2,000,000 nodes and edges, 120 s per Analysis invocation, + query input 4 KiB, 200 candidates per channel, 200 graph nodes, 32 KiB + default slice. Every truncation is reported. +* Default execution is offline; only an explicitly enabled embedding endpoint + performs network I/O. No command executes knowledge. + +## 11. Module map + +| Path | Responsibility | +|---|---| +| `src/main.rs` | process entry and exit code only | +| `src/lib.rs` | minimal public surface; `run()` | +| `src/cli.rs` | argv, validation, human/JSON rendering | +| `src/compiler.rs` | discovery -> facts -> graph -> publish orchestration, incremental invalidation | +| `src/document/` | discovery, plain Markdown projection, Analysis adapter, OKF | +| `src/graph/` | identity, node/edge building, reference/call resolution | +| `src/storage/` | SQLite schema, transactions, read/write APIs, indexes | +| `src/query/` | search, fuzzy, semantic, fusion, graph expansion, slices | +| `src/model.rs` | shared typed domain values | +| `src/diagnostic.rs` | diagnostic codes and deterministic collections | +| `src/error.rs` | unified error and exit semantics | diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..f42c8b3 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,2 @@ +edition = "2021" +max_width = 100 diff --git a/scripts/cargo.sh b/scripts/cargo.sh new file mode 100755 index 0000000..2d7ee9a --- /dev/null +++ b/scripts/cargo.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# Development helper: run cargo with the repository-local dependency cache. +# +# The cache directory `.cargo-home/` is ignored by git and is not required for a +# clean environment that can reach crates.io. It only makes repeated builds in +# an offline sandbox reproducible. +set -eu + +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) + +if ! command -v cargo >/dev/null 2>&1; then + for candidate in "$HOME/.cargo/bin" "$HOME/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin"; do + if [ -x "$candidate/cargo" ]; then + PATH="$candidate:$PATH" + export PATH + break + fi + done +fi + +if ! command -v cargo >/dev/null 2>&1; then + echo "scripts/cargo.sh: cargo not found; install a Rust toolchain (MSRV 1.89)" >&2 + exit 2 +fi + +if [ -d "$ROOT/.cargo-home" ]; then + CARGO_HOME="$ROOT/.cargo-home" + export CARGO_HOME +fi + +exec cargo "$@" diff --git a/spec/knowledge.md b/spec/knowledge.md new file mode 100644 index 0000000..0937e72 --- /dev/null +++ b/spec/knowledge.md @@ -0,0 +1,182 @@ +# marqdo-knowledge public contract + +Status: current contract for this implementation (in progress). The normative +development specification is `marqdo-knowledge-development.md`; this file +records the exact contract this repository implements. Where the two differ, +the development specification wins and this file must be corrected in place — +there is never a second active contract. + +## 1. Tool identity + +```json +{ + "schema": "marqdo.cli-tool", + "schema_version": 1, + "name": "marqdo-knowledge", + "version": "0.1.0", + "command": "knowledge", + "entrypoint": "bin/marqdo-knowledge", + "requires": {"api_revision": 1, "analysis": 3} +} +``` + +`tool.json` describes the release package; it is not a knowledge-base +configuration file. Launch through `marqdo knowledge ...`. Direct invocation is +supported for development and tests with an explicit `--marqdo-bin PATH` +(or `MARQDO_BIN`). The tool never scans `PATH` for a guessed core binary. + +## 2. Commands + +```text +marqdo knowledge compile [ROOT] [--exclude GLOB ...] [--rebuild] [--json] + [--embedding-url URL --embedding-model MODEL --embedding-revision REV + [--allow-remote-embedding]] +marqdo knowledge check [ROOT] [--okf] [--json] +marqdo knowledge query QUERY [--root ROOT] [--exact] [--kind KIND] [--limit N] + [--depth N] [--relation KIND ...] [--reverse] + [--slice document|execution|hybrid] [--format markdown|json] [--snapshot] + [--semantic] [embedding options] +``` + +| Command | Semantics | +|---|---| +| `compile` | Initialise or incrementally update `.marqdo/knowledge.sqlite`. Publishes only on success. `--rebuild` requests an explicit full replacement. | +| `check` | Static check without executing or writing the knowledge base. Validates Analysis input, diagnostics and, when a database exists, its structure and freshness. `--okf` additionally validates the supported OKF rules. | +| `query` | Read-only, offline by default. `--exact` restricts to exact identity/unique-name resolution; `--snapshot` explicitly permits a stale snapshot; `--semantic` requires the embedding channel. | + +Database location is always `/.marqdo/knowledge.sqlite`. Parent directories +are never searched for a database. `query` never compiles implicitly. + +### 2.1 Exit codes + +| Code | Meaning | +|---|---| +| 0 | success (including zero search hits) | +| 1 | invalid knowledge, definite broken link, failed check | +| 2 | usage, protocol mismatch, missing/old database, I/O, hard resource budget | + +### 2.2 Argument rules + +* `--exact` and `--semantic` conflict. `--slice` requires a unique exact seed; + a fuzzy query returns candidates and requires a canonical id instead. +* `--limit` 1..=100 (default 10); `--depth` 0..=8 (default 1). +* `--kind` filters final hits only, after candidate/graph expansion. +* `--relation` accepts `contains`, `references`, `imports`, `calls`. +* Unsupported kind/relation/format values are usage errors. +* Embedding options are all-or-nothing and are never read from the source tree. + The API key comes from the environment variable + `MARQDO_KNOWLEDGE_EMBEDDING_API_KEY`; it is never stored in the database, logs + or output. + +## 3. Machine output + +All machine output uses one envelope schema per boundary; there is no JSONL +stream and no per-query bespoke format. + +### 3.1 Success + +```json +{ + "schema": "marqdo.knowledge.result", + "schema_version": 1, + "command": "query", + "success": true, + "snapshot_digest": "sha256:...", + "current": true, + "query": "归一话", + "channels": ["lexical", "fuzzy", "graph"], + "truncated": false, + "hits": [ + { + "id": "opaque-canonical-id", + "kind": "function", + "title": "归一化检查", + "source": {"path": "state.mq.md", "digest": "sha256:...", "span": {"start": 100, "end": 180}}, + "snippet": "原文片段(非生成文本)", + "matches": [{"channel": "fuzzy", "field": "title"}], + "score": 0.031, + "callable": {"function_id": "upstream canonical id", "signature": {}}, + "related": [] + } + ], + "diagnostics": [], + "payload": {} +} +``` + +`compile` and `check` use the same envelope with `command` set accordingly and a +command-specific `payload`. `callable` is present only for functions whose +current Analysis passed static checking; it is interface information, not +execution permission. Every `snippet` is an exact source slice; external nodes +carry no fabricated path, span or snippet. + +### 3.2 Error + +```json +{ + "schema": "marqdo.knowledge.error", + "schema_version": 1, + "command": "query", + "success": false, + "error": {"code": "knowledge.database_missing", "message": "...", "hints": [], "exit_code": 2} +} +``` + +Machine mode never emits partial JSON on stdout. Diagnostics are also reported +on stderr as human lines with stable `knowledge.*` codes. + +## 4. Analysis input + +Marqdo program semantics come only from the core CLI: + +```sh +"$MARQDO_BIN" check ENTRY --emit ARTIFACT +``` + +The artifact must identify itself as `marqdo.analysis` revision 3, producer +`marqdo` with markdown profile `marqdo.md.v1`, and must pass closed-schema and +semantic validation (module/unit/anchor/function/reference/call invariants, +source digests, UTF-8 spans, tree shape). Any other revision, missing field, +unknown required kind, digest mismatch or invariant violation is rejected with +`knowledge.analysis_invalid`/`knowledge.analysis_unsupported`; there is no +fallback parsing. Plain `.md` files are parsed by this tool with the pinned +CommonMark/GFM/footnote options and never gain executable semantics. + +## 5. Databases and freshness + +The database stores one `build` row with: + +* application id and schema revision; +* compiler/tool/profile identity and index configuration; +* scope and options; +* `snapshot_digest` (logical identity of the exact source snapshot); +* input manifest (`inputs` table: path, digest, size). + +On open, the tool verifies the application id, schema revision, required +tables/columns and `PRAGMA quick_check`. A schema mismatch or foreign database is +rejected with a rebuild instruction; nothing is migrated or overwritten. A +`query` whose recorded inputs no longer match the root exits 2 with +`knowledge.database_stale` unless `--snapshot` is supplied, in which case the +result states `current: false` and the snapshot digest. + +## 6. Vocabulary + +Resolution states: `resolved`, `not_loaded`, `missing`, `ambiguous`, `external`, +`out_of_scope`, `invalid`, `dynamic`, `unresolved`. Node kinds: `document`, +`namespace`, `section`, `function`, `statement`, `resource`, `external`. +Relation kinds: `contains`, `references`, `imports`, `calls`; origins are +`document` or `analysis`. + +## 7. Security defaults + +* No execution: no `run`/`call`, plugin loading, provider, foreign kernel, + attester, HTTP document fetch, shell or script execution. +* Offline by default. Only an explicitly configured embedding endpoint performs + network I/O; non-loopback endpoints require TLS and + `--allow-remote-embedding`. +* Filesystem scope is the compiled root. Symlinks are not followed; path + traversal, absolute paths, drive/UNC paths and NUL bytes are rejected. + Referenced binary assets are recorded (path/size/digest within budget) and + never indexed as text. +* Logs and diagnostics never contain source text, credentials or machine + absolute paths. diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..75a8fd3 --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,475 @@ +//! Command-line surface, argument validation and result rendering. +//! +//! Only three business subcommands exist: `compile`, `check` and `query`. +//! Argument parsing owns usage errors; rendering owns stdout/stderr so that the +//! compiler and query layers never print. + +use crate::error::{KnowledgeError, EXIT_INPUT, EXIT_OK, EXIT_USAGE}; +use crate::model::NodeKind; +use clap::{Args, Parser, Subcommand, ValueEnum}; +use std::fmt::Write as _; +use std::path::PathBuf; + +/// Process-wide flags and the selected subcommand. +#[derive(Debug, Parser)] +#[command( + name = "marqdo-knowledge", + version, + about = "Compile Markdown and Marqdo documents into a deterministic, queryable knowledge projection.", + long_about = None, + disable_help_subcommand = true, + propagate_version = true +)] +pub struct Cli { + /// Core Marqdo binary used for static Analysis (`check --emit`). + /// + /// Normally supplied by `marqdo` through `MARQDO_BIN`. The explicit flag is + /// a development/test override; this tool never scans `PATH` for a guessed + /// core binary. + #[arg(long, global = true, value_name = "PATH", env = "MARQDO_BIN")] + pub marqdo_bin: Option, + + #[command(subcommand)] + pub command: Command, +} + +#[derive(Debug, Subcommand)] +pub enum Command { + /// Compile a knowledge root into `.marqdo/knowledge.sqlite`. + Compile(CompileArgs), + /// Statically check sources (and an existing database) without writing. + Check(CheckArgs), + /// Query the compiled knowledge projection. + Query(QueryArgs), +} + +/// Embedding backend options shared by compile and query. +/// +/// Semantic indexing is opt-in. No option here enables network access +/// implicitly and no credential is accepted on the command line. +#[derive(Debug, Clone, Args, Default)] +pub struct EmbeddingArgs { + /// OpenAI-compatible embeddings endpoint, for example + /// `http://127.0.0.1:8080/v1`. + #[arg(long, value_name = "URL")] + pub embedding_url: Option, + + /// Embedding model identifier used for the index and query vectors. + #[arg(long, value_name = "MODEL")] + pub embedding_model: Option, + + /// User-declared immutable model revision. + #[arg(long, value_name = "REVISION")] + pub embedding_revision: Option, + + /// Explicitly permit a non-loopback (remote) embeddings endpoint. Remote + /// endpoints must use TLS. + #[arg(long)] + pub allow_remote_embedding: bool, +} + +#[derive(Debug, Args)] +pub struct CompileArgs { + /// Knowledge root directory (default: current directory). A single + /// Markdown file is accepted as a one-document scope. + #[arg(value_name = "ROOT", default_value = ".")] + pub root: PathBuf, + + /// Additional root-relative glob to exclude. Repeatable. + #[arg(long, value_name = "GLOB")] + pub exclude: Vec, + + /// Explicit full rebuild. Required after a schema change; never implicit. + #[arg(long)] + pub rebuild: bool, + + /// Emit the machine result envelope on stdout. + #[arg(long)] + pub json: bool, + + #[command(flatten)] + pub embedding: EmbeddingArgs, +} + +#[derive(Debug, Args)] +pub struct CheckArgs { + /// Knowledge root directory (default: current directory). + #[arg(value_name = "ROOT", default_value = ".")] + pub root: PathBuf, + + /// Also validate OKF bundle structure and metadata rules. + #[arg(long)] + pub okf: bool, + + /// Emit the machine result envelope on stdout. + #[arg(long)] + pub json: bool, +} + +#[derive(Debug, Args)] +pub struct QueryArgs { + /// Query text, or a canonical node id when `--exact`/`--slice` is used. + #[arg(value_name = "QUERY")] + pub query: String, + + /// Knowledge root whose `.marqdo/knowledge.sqlite` is read (default: current + /// directory). + #[arg(long, value_name = "ROOT", default_value = ".")] + pub root: PathBuf, + + /// Exact identity/unique-name resolution only; never fuzzy. + #[arg(long, conflicts_with = "semantic")] + pub exact: bool, + + /// Restrict returned hits to this node kind after candidate expansion. + #[arg(long, value_name = "KIND")] + pub kind: Option, + + /// Maximum number of hits (1..=100). + #[arg(long, value_name = "N")] + pub limit: Option, + + /// Graph expansion depth for ranking (0 disables expansion; default 1). + #[arg(long, value_name = "N")] + pub depth: Option, + + /// Restrict graph expansion to a relation kind. Repeatable. + #[arg(long, value_name = "KIND")] + pub relation: Vec, + + /// Traverse selected relations in reverse direction. + #[arg(long)] + pub reverse: bool, + + /// Return a bounded reading/dependency slice from a unique seed. + #[arg(long, value_name = "KIND")] + pub slice: Option, + + /// Output format on stdout. + #[arg(long, value_name = "FORMAT", default_value = "markdown")] + pub format: OutputFormat, + + /// Explicitly allow reading a stale snapshot instead of refusing it. + #[arg(long)] + pub snapshot: bool, + + /// Require the embedding channel (implies a network request to the + /// configured endpoint). + #[arg(long)] + pub semantic: bool, + + #[command(flatten)] + pub embedding: EmbeddingArgs, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] +pub enum SliceKind { + Document, + Execution, + Hybrid, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] +pub enum OutputFormat { + Markdown, + Json, +} + +/// Rendered outcome of a subcommand. +#[derive(Debug)] +pub struct Output { + pub stdout: String, + pub stderr: String, + pub exit_code: i32, +} + +impl Output { + pub fn ok(stdout: String) -> Self { + Self { + stdout, + stderr: String::new(), + exit_code: EXIT_OK, + } + } + + pub fn with_diagnostics(mut self, diagnostics: &str) -> Self { + self.stderr = diagnostics.to_string(); + self + } +} + +/// Parse argv, execute and render. Returns the process exit code. +pub fn run() -> i32 { + let cli = match Cli::try_parse() { + Ok(cli) => cli, + Err(error) => { + // clap owns usage/help/version rendering and uses exit code 2. + error.print().ok(); + return error.exit_code(); + } + }; + let machine = cli.command.machine_output(); + match execute(&cli) { + Ok(output) => { + print!("{}", output.stdout); + eprint!("{}", output.stderr); + output.exit_code + } + Err(error) => { + if machine { + print_json_error(&cli.command, &error); + } + eprintln!("marqdo-knowledge: {error}"); + error.exit_code + } + } +} + +impl Command { + pub fn machine_output(&self) -> bool { + match self { + Command::Compile(args) => args.json, + Command::Check(args) => args.json, + Command::Query(args) => args.format == OutputFormat::Json, + } + } +} + +fn print_json_error(command: &Command, error: &KnowledgeError) { + let name = match command { + Command::Compile(_) => "compile", + Command::Check(_) => "check", + Command::Query(_) => "query", + }; + let envelope = serde_json::json!({ + "schema": "marqdo.knowledge.error", + "schema_version": 1, + "command": name, + "success": false, + "error": { + "code": error.code, + "message": error.message, + "hints": error.hints, + "exit_code": error.exit_code, + } + }); + match serde_json::to_string_pretty(&envelope) { + Ok(text) => println!("{text}"), + Err(_) => println!( + "{{\"schema\":\"marqdo.knowledge.error\",\"schema_version\":1,\"success\":false}}" + ), + } +} + +/// Validate the arguments that clap cannot express, then dispatch. +fn execute(cli: &Cli) -> Result { + match &cli.command { + Command::Compile(args) => { + validate_embedding(&args.embedding, false)?; + let mut out = crate::compiler::compile(args, cli.marqdo_bin.as_deref())?; + if !args.json { + out.stdout = render_compile_human(&out.stdout)?; + } + Ok(out) + } + Command::Check(args) => { + let mut out = crate::compiler::check(args, cli.marqdo_bin.as_deref())?; + if !args.json { + out.stdout = render_check_human(&out.stdout)?; + } + Ok(out) + } + Command::Query(args) => { + validate_query(args)?; + validate_embedding(&args.embedding, args.semantic)?; + crate::query::run_query(args, cli.marqdo_bin.as_deref()) + } + } +} + +fn validate_query(args: &QueryArgs) -> Result<(), KnowledgeError> { + if args.limit == Some(0) || args.limit.is_some_and(|n| n > 100) { + return Err(KnowledgeError::usage( + "--limit must be between 1 and 100 (default 10)", + )); + } + if let Some(depth) = args.depth { + if depth > 8 { + return Err(KnowledgeError::usage( + "--depth must be between 0 and 8 (default 1)", + )); + } + } + if let Some(kind) = &args.kind { + kind.parse::() + .map_err(|message| KnowledgeError::usage(format!("--kind: {message}")))?; + } + for relation in &args.relation { + relation + .parse::() + .map_err(|message| KnowledgeError::usage(format!("--relation: {message}")))?; + } + if args.query.trim().is_empty() { + return Err(KnowledgeError::usage("QUERY must not be empty")); + } + if args.query.len() > 4096 { + return Err(KnowledgeError::usage( + "QUERY exceeds the 4 KiB input budget", + )); + } + if args.slice.is_some() && args.semantic { + return Err(KnowledgeError::usage( + "--slice and --semantic cannot be combined: a slice needs a unique seed", + )); + } + Ok(()) +} + +fn validate_embedding( + embedding: &EmbeddingArgs, + semantic_required: bool, +) -> Result<(), KnowledgeError> { + let configured = embedding.embedding_url.is_some() + || embedding.embedding_model.is_some() + || embedding.embedding_revision.is_some(); + if semantic_required && !configured { + return Err(KnowledgeError::environment( + crate::diagnostic::code::EMBEDDING_UNAVAILABLE, + "semantic search requires --embedding-url, --embedding-model and --embedding-revision", + )); + } + if configured { + if embedding.embedding_url.is_none() + || embedding.embedding_model.is_none() + || embedding.embedding_revision.is_none() + { + return Err(KnowledgeError::usage( + "--embedding-url, --embedding-model and --embedding-revision must be given together", + )); + } + } + Ok(()) +} + +/// Human rendering is intentionally thin: the command layer already produced +/// structured facts and this function only formats them. +fn render_compile_human(json_text: &str) -> Result { + let value: serde_json::Value = serde_json::from_str(json_text) + .map_err(|_| KnowledgeError::internal("compile report is not valid JSON"))?; + let payload = value.get("payload").cloned().unwrap_or_default(); + let mut text = String::new(); + let docs = payload + .get("documents") + .and_then(|v| v.as_u64()) + .unwrap_or(0); + let nodes = payload.get("nodes").and_then(|v| v.as_u64()).unwrap_or(0); + let edges = payload.get("edges").and_then(|v| v.as_u64()).unwrap_or(0); + let mode = payload + .get("mode") + .and_then(|v| v.as_str()) + .unwrap_or("compiled"); + writeln!( + text, + "compiled {docs} document(s), {nodes} node(s), {edges} edge(s) ({mode})" + ) + .map_err(|_| KnowledgeError::internal("formatting failed"))?; + if let Some(digest) = value.get("snapshot_digest").and_then(|v| v.as_str()) { + writeln!(text, "snapshot: {digest}") + .map_err(|_| KnowledgeError::internal("formatting failed"))?; + } + let errors = payload.get("errors").and_then(|v| v.as_u64()).unwrap_or(0); + let warnings = payload + .get("warnings") + .and_then(|v| v.as_u64()) + .unwrap_or(0); + if errors + warnings > 0 { + writeln!( + text, + "diagnostics: {errors} error(s), {warnings} warning(s)" + ) + .map_err(|_| KnowledgeError::internal("formatting failed"))?; + } + Ok(text) +} + +fn render_check_human(json_text: &str) -> Result { + let value: serde_json::Value = serde_json::from_str(json_text) + .map_err(|_| KnowledgeError::internal("check report is not valid JSON"))?; + let payload = value.get("payload").cloned().unwrap_or_default(); + let documents = payload + .get("documents") + .and_then(|v| v.as_u64()) + .unwrap_or(0); + let errors = payload.get("errors").and_then(|v| v.as_u64()).unwrap_or(0); + let warnings = payload + .get("warnings") + .and_then(|v| v.as_u64()) + .unwrap_or(0); + let database = payload + .get("database") + .and_then(|v| v.as_str()) + .unwrap_or("absent"); + let mut text = String::new(); + writeln!( + text, + "checked {documents} document(s): {errors} error(s), {warnings} warning(s)" + ) + .map_err(|_| KnowledgeError::internal("formatting failed"))?; + writeln!(text, "database: {database}") + .map_err(|_| KnowledgeError::internal("formatting failed"))?; + Ok(text) +} + +/// Exit code helper for commands that produce knowledge diagnostics. +pub fn exit_code_for(errors: usize, warnings: usize) -> i32 { + if errors > 0 { + EXIT_INPUT + } else if warnings > 0 { + EXIT_OK + } else { + EXIT_OK + } +} + +/// Parse and validate a `--kind` value at the command boundary. +pub fn parse_kind(value: &str) -> Result { + value.parse::() +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::CommandFactory; + + #[test] + fn cli_definition_is_valid() { + Cli::command().debug_assert(); + } + + #[test] + fn three_business_subcommands_only() { + let command = Cli::command(); + let names: Vec<_> = command.get_subcommands().map(|c| c.get_name()).collect(); + assert_eq!(names, vec!["compile", "check", "query"]); + } + + #[test] + fn query_rejects_exact_with_semantic() { + use clap::Parser as _; + let err = Cli::try_parse_from(["marqdo-knowledge", "query", "x", "--exact", "--semantic"]) + .unwrap_err(); + assert_eq!(err.exit_code(), 2); + } + + #[test] + fn limit_and_kind_are_validated() { + use clap::Parser as _; + let cli = + Cli::try_parse_from(["marqdo-knowledge", "query", "量子", "--limit", "101"]).unwrap(); + assert!(validate_query(match &cli.command { + Command::Query(args) => args, + _ => unreachable!(), + }) + .is_err()); + } +} diff --git a/src/compiler.rs b/src/compiler.rs new file mode 100644 index 0000000..96c4e67 --- /dev/null +++ b/src/compiler.rs @@ -0,0 +1,20 @@ +//! Compile orchestration: the single write-transaction boundary. +//! +//! This module is filled in by the compiler milestone; the type signatures are +//! the stable boundary used by `cli.rs`. It owns discovery, Analysis retrieval, +//! graph linking, staging and atomic publishing. + +use crate::cli::Output; +use crate::cli::{CheckArgs, CompileArgs}; +use crate::error::KnowledgeError; +use std::path::Path; + +/// Compile or incrementally update one knowledge root. +pub fn compile(_args: &CompileArgs, _marqdo_bin: Option<&Path>) -> Result { + Err(KnowledgeError::not_implemented("compile")) +} + +/// Statically check sources and an existing database without writing. +pub fn check(_args: &CheckArgs, _marqdo_bin: Option<&Path>) -> Result { + Err(KnowledgeError::not_implemented("check")) +} diff --git a/src/diagnostic.rs b/src/diagnostic.rs new file mode 100644 index 0000000..75563de --- /dev/null +++ b/src/diagnostic.rs @@ -0,0 +1,283 @@ +//! Diagnostics: stable codes, deterministic ordering, human rendering. +//! +//! A diagnostic always names a stable `knowledge.*` code, a severity, an +//! optional root-relative path and an optional exact byte span. Diagnostics do +//! not print source text and never contain machine absolute paths. + +use crate::model::Span; +use serde::{Deserialize, Serialize}; +use std::fmt; + +/// Stable diagnostic codes. Adding a code is an interface change. +pub mod code { + // Input and scope. + pub const INVALID_ROOT: &str = "knowledge.invalid_root"; + pub const SCOPE_ESCAPE: &str = "knowledge.scope_escape"; + pub const SYMLINK_SKIPPED: &str = "knowledge.symlink_skipped"; + pub const EXCLUDED_PATH: &str = "knowledge.excluded_path"; + pub const BUDGET_EXCEEDED: &str = "knowledge.budget_exceeded"; + pub const INVALID_UTF8: &str = "knowledge.invalid_utf8"; + pub const IO: &str = "knowledge.io"; + pub const SOURCE_CHANGED: &str = "knowledge.source_changed"; + + // Core CLI integration. + pub const NOT_LAUNCHED_BY_MARQDO: &str = "knowledge.not_launched_by_marqdo"; + pub const CORE_CLI_MISSING: &str = "knowledge.core_cli_missing"; + pub const CORE_CLI_FAILED: &str = "knowledge.core_cli_failed"; + pub const CORE_CLI_TIMEOUT: &str = "knowledge.core_cli_timeout"; + pub const ANALYSIS_MISSING: &str = "knowledge.analysis_missing"; + pub const ANALYSIS_INVALID: &str = "knowledge.analysis_invalid"; + pub const ANALYSIS_UNSUPPORTED: &str = "knowledge.analysis_unsupported"; + pub const ANALYSIS_CONTEXT_CONFLICT: &str = "knowledge.analysis_context_conflict"; + + // Documents. + pub const MARKDOWN_INVALID: &str = "knowledge.markdown_invalid"; + pub const MARQDO_INVALID: &str = "knowledge.marqdo_invalid"; + pub const OKF_INVALID: &str = "knowledge.okf_invalid"; + pub const OKF_UNVERIFIED: &str = "knowledge.okf_unverified"; + pub const UNKNOWN_FRONT_MATTER: &str = "knowledge.unknown_front_matter"; + + // Graph and references. + pub const REFERENCE_MISSING: &str = "knowledge.reference_missing"; + pub const REFERENCE_AMBIGUOUS: &str = "knowledge.reference_ambiguous"; + pub const REFERENCE_OUT_OF_SCOPE: &str = "knowledge.reference_out_of_scope"; + pub const REFERENCE_INVALID: &str = "knowledge.reference_invalid"; + pub const REFERENCE_EXTERNAL: &str = "knowledge.reference_external"; + pub const REFERENCE_NOT_LOADED: &str = "knowledge.reference_not_loaded"; + pub const IDENTITY_AMBIGUOUS: &str = "knowledge.identity_ambiguous"; + pub const INTERFACE_CONFLICT: &str = "knowledge.interface_conflict"; + + // Storage and freshness. + pub const DATABASE_MISSING: &str = "knowledge.database_missing"; + pub const DATABASE_OLD_SCHEMA: &str = "knowledge.database_old_schema"; + pub const DATABASE_NOT_OURS: &str = "knowledge.database_not_ours"; + pub const DATABASE_CORRUPT: &str = "knowledge.database_corrupt"; + pub const DATABASE_STALE: &str = "knowledge.database_stale"; + pub const SNAPSHOT_STALE: &str = "knowledge.snapshot_stale"; + pub const REBUILD_REQUIRED: &str = "knowledge.rebuild_required"; + + // Query. + pub const QUERY_INVALID: &str = "knowledge.query_invalid"; + pub const QUERY_NO_RESULTS: &str = "knowledge.query_no_results"; + pub const QUERY_UNSUPPORTED: &str = "knowledge.query_unsupported"; + pub const SLICE_SEED_AMBIGUOUS: &str = "knowledge.slice_seed_ambiguous"; + pub const SLICE_SEED_MISSING: &str = "knowledge.slice_seed_missing"; + pub const BUDGET: &str = "knowledge.budget"; + + // Embeddings. + pub const EMBEDDING_DISABLED: &str = "knowledge.embedding_disabled"; + pub const EMBEDDING_CONFIG_MISMATCH: &str = "knowledge.embedding_config_mismatch"; + pub const EMBEDDING_REMOTE_NOT_ALLOWED: &str = "knowledge.embedding_remote_not_allowed"; + pub const EMBEDDING_TRANSPORT: &str = "knowledge.embedding_transport"; + pub const EMBEDDING_INVALID_RESPONSE: &str = "knowledge.embedding_invalid_response"; + pub const EMBEDDING_UNAVAILABLE: &str = "knowledge.embedding_unavailable"; + + // Usage. + pub const USAGE: &str = "knowledge.usage"; + pub const NOT_IMPLEMENTED: &str = "knowledge.not_implemented"; + pub const INTERNAL: &str = "knowledge.internal"; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Severity { + Error, + Warning, +} + +impl Severity { + pub fn as_str(self) -> &'static str { + match self { + Severity::Error => "error", + Severity::Warning => "warning", + } + } +} + +/// One deterministic diagnostic. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Diagnostic { + pub code: String, + pub severity: Severity, + pub path: Option, + pub span: Option, + pub message: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub hints: Vec, +} + +impl Diagnostic { + pub fn error(code: &str, message: impl Into) -> Self { + Self { + code: code.to_string(), + severity: Severity::Error, + path: None, + span: None, + message: message.into(), + hints: Vec::new(), + } + } + + pub fn warning(code: &str, message: impl Into) -> Self { + Self { + code: code.to_string(), + severity: Severity::Warning, + path: None, + span: None, + message: message.into(), + hints: Vec::new(), + } + } + + pub fn with_path(mut self, path: impl Into) -> Self { + self.path = Some(path.into()); + self + } + + pub fn with_span(mut self, span: Span) -> Self { + self.span = Some(span); + self + } + + pub fn with_hint(mut self, hint: impl Into) -> Self { + self.hints.push(hint.into()); + self + } + + pub fn is_error(&self) -> bool { + self.severity == Severity::Error + } +} + +impl fmt::Display for Diagnostic { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} [{}]", self.severity.as_str(), self.code)?; + if let Some(path) = &self.path { + write!(f, " {path}")?; + if let Some(span) = self.span { + write!(f, ":{span}")?; + } + } + write!(f, ": {}", self.message)?; + for hint in &self.hints { + write!(f, "\n hint: {hint}")?; + } + Ok(()) + } +} + +/// A deterministic diagnostic collection. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct DiagnosticSet { + items: Vec, +} + +impl DiagnosticSet { + pub fn new() -> Self { + Self::default() + } + + pub fn push(&mut self, diagnostic: Diagnostic) { + self.items.push(diagnostic); + } + + pub fn extend(&mut self, other: impl IntoIterator) { + self.items.extend(other); + } + + pub fn merge(&mut self, mut other: DiagnosticSet) { + self.items.append(&mut other.items); + } + + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } + + pub fn len(&self) -> usize { + self.items.len() + } + + pub fn has_errors(&self) -> bool { + self.items.iter().any(Diagnostic::is_error) + } + + pub fn error_count(&self) -> usize { + self.items.iter().filter(|d| d.is_error()).count() + } + + pub fn warning_count(&self) -> usize { + self.items.iter().filter(|d| !d.is_error()).count() + } + + pub fn iter(&self) -> impl Iterator { + self.items.iter() + } + + pub fn into_vec(self) -> Vec { + self.items + } + + pub fn as_slice(&self) -> &[Diagnostic] { + &self.items + } + + /// Sort by path, span start, code, then message for stable output and + /// stable logical digests. + pub fn sorted(&mut self) { + self.items.sort_by(|a, b| { + a.path + .cmp(&b.path) + .then(a.span.map(|s| s.start).cmp(&b.span.map(|s| s.start))) + .then(a.span.map(|s| s.end).cmp(&b.span.map(|s| s.end))) + .then(a.code.cmp(&b.code)) + .then(a.message.cmp(&b.message)) + }); + self.items.dedup(); + } +} + +impl IntoIterator for DiagnosticSet { + type Item = Diagnostic; + type IntoIter = std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.items.into_iter() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn diagnostics_sort_deterministically() { + let mut set = DiagnosticSet::new(); + set.push( + Diagnostic::error(code::IO, "b") + .with_path("a.md") + .with_span(Span::new(5, 8)), + ); + set.push( + Diagnostic::error(code::IO, "a") + .with_path("a.md") + .with_span(Span::new(1, 2)), + ); + set.push(Diagnostic::warning(code::OKF_UNVERIFIED, "w").with_path("b.md")); + set.sorted(); + let paths: Vec<_> = set.iter().map(|d| d.path.as_deref().unwrap()).collect(); + assert_eq!(paths, vec!["a.md", "a.md", "b.md"]); + assert_eq!(set.error_count(), 2); + assert_eq!(set.warning_count(), 1); + assert!(set.has_errors()); + } + + #[test] + fn diagnostic_display_has_no_source_text() { + let d = Diagnostic::error(code::REFERENCE_MISSING, "missing target") + .with_path("a.md") + .with_span(Span::new(1, 3)); + let text = d.to_string(); + assert!(text.contains("knowledge.reference_missing")); + assert!(text.contains("a.md:1..3")); + } +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..2e1509f --- /dev/null +++ b/src/error.rs @@ -0,0 +1,103 @@ +//! Unified error type and process exit semantics. +//! +//! Exit codes are part of the public contract: +//! * `0` success (an empty search result is still success); +//! * `1` input knowledge/validation failure (invalid source, definite broken +//! link, negative check result); +//! * `2` usage, protocol, database absence/old schema, I/O and hard resource +//! budget failures. +//! +//! Errors never carry source text, secrets or machine absolute paths in their +//! public message. + +use crate::diagnostic::code; +use std::fmt; + +pub const EXIT_OK: i32 = 0; +pub const EXIT_INPUT: i32 = 1; +pub const EXIT_USAGE: i32 = 2; + +/// A fatal knowledge error with a stable code and an exit class. +#[derive(Debug)] +pub struct KnowledgeError { + pub code: &'static str, + pub message: String, + pub hints: Vec, + /// `1` for invalid knowledge/input, `2` for usage/protocol/environment. + pub exit_code: i32, +} + +impl KnowledgeError { + pub fn usage(message: impl Into) -> Self { + Self { + code: code::USAGE, + message: message.into(), + hints: Vec::new(), + exit_code: EXIT_USAGE, + } + } + + pub fn input(code: &'static str, message: impl Into) -> Self { + Self { + code, + message: message.into(), + hints: Vec::new(), + exit_code: EXIT_INPUT, + } + } + + pub fn environment(code: &'static str, message: impl Into) -> Self { + Self { + code, + message: message.into(), + hints: Vec::new(), + exit_code: EXIT_USAGE, + } + } + + pub fn internal(message: impl Into) -> Self { + Self { + code: code::INTERNAL, + message: message.into(), + hints: Vec::new(), + exit_code: EXIT_USAGE, + } + } + + pub fn not_implemented(what: &str) -> Self { + Self { + code: code::NOT_IMPLEMENTED, + message: format!("{what} is not implemented in this build"), + hints: vec!["see docs/STATUS.md for the current capability matrix".to_string()], + exit_code: EXIT_USAGE, + } + } + + pub fn with_hint(mut self, hint: impl Into) -> Self { + self.hints.push(hint.into()); + self + } + + pub fn with_exit_code(mut self, exit_code: i32) -> Self { + self.exit_code = exit_code; + self + } +} + +impl fmt::Display for KnowledgeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}: {}", self.code, self.message)?; + for hint in &self.hints { + write!(f, "\n hint: {hint}")?; + } + Ok(()) + } +} + +impl std::error::Error for KnowledgeError {} + +impl From for KnowledgeError { + fn from(error: std::io::Error) -> Self { + KnowledgeError::environment(code::IO, error.to_string()) + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..d16e472 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,18 @@ +//! `marqdo-knowledge` public library surface. +//! +//! The binary is a thin wrapper: [`run`] parses argv, dispatches the internal +//! layers and returns the process exit code. Library consumers (tests, +//! independent protocol consumers) use this crate's public modules; no module +//! exposes a second query or Analysis contract. + +pub mod cli; +pub mod compiler; +pub mod diagnostic; +pub mod error; +pub mod model; +pub mod query; + +/// Run the command line. Returns the process exit code (0/1/2). +pub fn run() -> i32 { + cli::run() +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..c75b689 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,5 @@ +//! Binary entry point: only process setup and the exit code live here. + +fn main() { + std::process::exit(marqdo_knowledge::run()); +} diff --git a/src/model.rs b/src/model.rs new file mode 100644 index 0000000..90f364e --- /dev/null +++ b/src/model.rs @@ -0,0 +1,471 @@ +//! Shared typed domain values. +//! +//! This module owns the small, dependency-free vocabulary that every other +//! module exchanges: source spans, canonical node identities, node/edge kinds +//! and diagnostics. It must not depend on the filesystem, SQLite, the core +//! Marqdo CLI or any network transport. +//! +//! Identity rule: a [`NodeKey`] is the UTF-8 percent-encoded canonical JSON +//! array of its structured parts. Parts are never concatenated with `#`, `::` +//! or `/`; encoding a tuple is unambiguous and stable across runs. The encoded +//! form is an opaque public id and the unique internal key. + +use serde::{Deserialize, Serialize}; +use std::fmt; +use std::str::FromStr; + +/// Half-open byte range into a document's exact UTF-8 source. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Span { + pub start: u64, + pub end: u64, +} + +impl Span { + pub fn new(start: u64, end: u64) -> Self { + Self { start, end } + } + + pub fn len(self) -> u64 { + self.end.saturating_sub(self.start) + } + + pub fn is_empty(self) -> bool { + self.start == self.end + } + + pub fn contains(self, other: Span) -> bool { + self.start <= other.start && other.end <= self.end + } + + /// Return the exact source slice when the span is valid and lies on UTF-8 + /// boundaries. Never panics on hostile offsets. + pub fn slice<'a>(self, source: &'a [u8]) -> Option<&'a str> { + if self.start > self.end || self.end > source.len() as u64 { + return None; + } + let start = usize::try_from(self.start).ok()?; + let end = usize::try_from(self.end).ok()?; + std::str::from_utf8(&source[start..end]).ok() + } + + pub fn on_utf8_boundaries(self, source: &[u8]) -> bool { + self.slice(source).is_some() + } +} + +impl fmt::Display for Span { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}..{}", self.start, self.end) + } +} + +/// Canonical, opaque node identity. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct NodeKey(String); + +impl NodeKey { + /// Build a key from structured parts. The canonical serialisation is a + /// JSON array of strings, then RFC 3986 percent encoding of every byte + /// outside the unreserved set. + pub fn from_parts(parts: &[&str]) -> Self { + let json = serde_json::to_string(parts).expect("string array serialises"); + Self(percent_encode(json.as_bytes())) + } + + /// Parse a previously emitted key. The encoded bytes must decode to a JSON + /// string array and re-encode byte-identically (canonical form). + pub fn from_encoded(encoded: &str) -> Option { + let bytes = percent_decode(encoded.as_bytes())?; + let json = std::str::from_utf8(&bytes).ok()?; + let parts: Vec = serde_json::from_str(json).ok()?; + let reencoded = serde_json::to_string(&parts).ok()?; + if percent_encode(reencoded.as_bytes()) == encoded { + Some(Self(encoded.to_string())) + } else { + None + } + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + pub fn into_string(self) -> String { + self.0 + } +} + +impl fmt::Display for NodeKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +fn is_unreserved(b: u8) -> bool { + b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') +} + +/// RFC 3986 percent encoding over bytes (upper-case hex). +pub fn percent_encode(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len()); + for &b in bytes { + if is_unreserved(b) { + out.push(char::from(b)); + } else { + out.push('%'); + out.push(char::from(hex_upper(b >> 4))); + out.push(char::from(hex_upper(b & 0x0f))); + } + } + out +} + +/// Decode percent escapes exactly once. Returns `None` for malformed escapes +/// or embedded NUL bytes. +pub fn percent_decode(bytes: &[u8]) -> Option> { + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' { + if i + 2 >= bytes.len() { + return None; + } + let hi = hex_val(bytes[i + 1])?; + let lo = hex_val(bytes[i + 2])?; + let decoded = (hi << 4) | lo; + if decoded == 0 { + return None; + } + out.push(decoded); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + Some(out) +} + +fn hex_upper(n: u8) -> u8 { + match n { + 0..=9 => b'0' + n, + _ => b'A' + (n - 10), + } +} + +fn hex_val(b: u8) -> Option { + match b { + b'0'..=b'9' => Some(b - b'0'), + b'a'..=b'f' => Some(b - b'a' + 10), + b'A'..=b'F' => Some(b - b'A' + 10), + _ => None, + } +} + +/// Lowercase hex SHA-256 digest, always prefixed for public output. +pub fn sha256_prefixed(bytes: &[u8]) -> String { + use sha2::{Digest, Sha256}; + let mut hasher = Sha256::new(); + hasher.update(bytes); + format!("sha256:{}", hex::encode(hasher.finalize())) +} + +/// Bare lowercase hex SHA-256 digest for compact on-disk columns. +pub fn sha256_hex(bytes: &[u8]) -> String { + use sha2::{Digest, Sha256}; + let mut hasher = Sha256::new(); + hasher.update(bytes); + hex::encode(hasher.finalize()) +} + +pub fn is_sha256_prefixed(value: &str) -> bool { + value.len() == 71 + && value.starts_with("sha256:") + && value[7..] + .bytes() + .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) +} + +pub fn is_sha256_hex(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) +} + +/// Node kinds of the single knowledge graph. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NodeKind { + Document, + Namespace, + Section, + Function, + Statement, + Resource, + External, +} + +impl NodeKind { + pub const ALL: [NodeKind; 7] = [ + NodeKind::Document, + NodeKind::Namespace, + NodeKind::Section, + NodeKind::Function, + NodeKind::Statement, + NodeKind::Resource, + NodeKind::External, + ]; + + pub fn as_str(self) -> &'static str { + match self { + NodeKind::Document => "document", + NodeKind::Namespace => "namespace", + NodeKind::Section => "section", + NodeKind::Function => "function", + NodeKind::Statement => "statement", + NodeKind::Resource => "resource", + NodeKind::External => "external", + } + } +} + +impl FromStr for NodeKind { + type Err = String; + + fn from_str(value: &str) -> Result { + match value { + "document" => Ok(NodeKind::Document), + "namespace" => Ok(NodeKind::Namespace), + "section" => Ok(NodeKind::Section), + "function" => Ok(NodeKind::Function), + "statement" => Ok(NodeKind::Statement), + "resource" => Ok(NodeKind::Resource), + "external" => Ok(NodeKind::External), + other => Err(format!( + "unsupported node kind `{other}` (expected one of: document, namespace, section, function, statement, resource, external)" + )), + } + } +} + +impl fmt::Display for NodeKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// Edge kinds of the single knowledge graph. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EdgeKind { + Contains, + References, + Imports, + Calls, +} + +impl EdgeKind { + pub const ALL: [EdgeKind; 4] = [ + EdgeKind::Contains, + EdgeKind::References, + EdgeKind::Imports, + EdgeKind::Calls, + ]; + + pub fn as_str(self) -> &'static str { + match self { + EdgeKind::Contains => "contains", + EdgeKind::References => "references", + EdgeKind::Imports => "imports", + EdgeKind::Calls => "calls", + } + } +} + +impl FromStr for EdgeKind { + type Err = String; + + fn from_str(value: &str) -> Result { + match value { + "contains" => Ok(EdgeKind::Contains), + "references" => Ok(EdgeKind::References), + "imports" => Ok(EdgeKind::Imports), + "calls" => Ok(EdgeKind::Calls), + other => Err(format!( + "unsupported relation `{other}` (expected one of: contains, references, imports, calls)" + )), + } + } +} + +impl fmt::Display for EdgeKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EdgeOrigin { + Document, + Analysis, +} + +impl EdgeOrigin { + pub fn as_str(self) -> &'static str { + match self { + EdgeOrigin::Document => "document", + EdgeOrigin::Analysis => "analysis", + } + } +} + +/// Resolution state of a `references`, `imports` or `calls` edge. The graph +/// never invents a target: unresolved edges keep their raw target and state. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EdgeState { + Resolved, + NotLoaded, + Missing, + Ambiguous, + External, + OutOfScope, + Invalid, + Dynamic, + Unresolved, +} + +impl EdgeState { + pub fn as_str(self) -> &'static str { + match self { + EdgeState::Resolved => "resolved", + EdgeState::NotLoaded => "not_loaded", + EdgeState::Missing => "missing", + EdgeState::Ambiguous => "ambiguous", + EdgeState::External => "external", + EdgeState::OutOfScope => "out_of_scope", + EdgeState::Invalid => "invalid", + EdgeState::Dynamic => "dynamic", + EdgeState::Unresolved => "unresolved", + } + } + + /// Whether the edge participates in a valid dependency closure. + pub fn is_bound(self) -> bool { + matches!(self, EdgeState::Resolved) + } +} + +impl fmt::Display for EdgeState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// Parse a resolution state emitted by the core Analysis artefact. +pub fn edge_state_from_analysis(value: &str) -> Option { + match value { + "resolved" => Some(EdgeState::Resolved), + "not_loaded" => Some(EdgeState::NotLoaded), + "missing" => Some(EdgeState::Missing), + "ambiguous" => Some(EdgeState::Ambiguous), + "external" => Some(EdgeState::External), + "outside_scope" => Some(EdgeState::OutOfScope), + "invalid" => Some(EdgeState::Invalid), + "dynamic" => Some(EdgeState::Dynamic), + "unbound" | "unresolved" => Some(EdgeState::Unresolved), + _ => None, + } +} + +/// Source format of a discovered document. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DocumentFormat { + PlainMarkdown, + Marqdo, +} + +impl DocumentFormat { + pub fn as_str(self) -> &'static str { + match self { + DocumentFormat::PlainMarkdown => "plain_markdown", + DocumentFormat::Marqdo => "marqdo", + } + } + + pub fn from_path(path: &str) -> Option { + if path.ends_with(".mq.md") { + Some(DocumentFormat::Marqdo) + } else if path.ends_with(".md") { + Some(DocumentFormat::PlainMarkdown) + } else { + None + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn node_keys_are_canonical_and_unambiguous() { + let a = NodeKey::from_parts(&["unit", "a/b.md", "x/y"]); + let b = NodeKey::from_parts(&["unit", "a/b.md", "x/y"]); + assert_eq!(a, b); + // A part that itself contains the separators must not collide. + let c = NodeKey::from_parts(&["unit", "a/b.md#x/y"]); + let d = NodeKey::from_parts(&["unit", "a/b.md", "x/y"]); + assert_ne!(c, d); + // Round trip. + assert_eq!(NodeKey::from_encoded(a.as_str()).as_ref(), Some(&a)); + } + + #[test] + fn node_key_percent_encoding_escapes_reserved_bytes() { + let key = NodeKey::from_parts(&["document", "中文 #1.md"]); + assert!(!key.as_str().contains('#')); + assert!(!key.as_str().contains(' ')); + assert!(key.as_str().contains("%23")); + } + + #[test] + fn malformed_percent_escapes_are_rejected() { + assert!(percent_decode(b"%ZZ").is_none()); + assert!(percent_decode(b"%0").is_none()); + assert!(percent_decode(b"a%00b").is_none()); + assert!(NodeKey::from_encoded("%ZZ").is_none()); + } + + #[test] + fn span_rejects_out_of_range_and_non_boundary() { + let source = "a中b".as_bytes(); + assert_eq!(Span::new(0, 1).slice(source), Some("a")); + assert_eq!(Span::new(1, 4).slice(source), Some("中")); + assert_eq!(Span::new(0, 2).slice(source), None); // splits a CJK char + assert_eq!(Span::new(0, 9).slice(source), None); + assert_eq!(Span::new(5, 4).slice(source), None); + } + + #[test] + fn node_kind_parsing_is_strict() { + assert_eq!("function".parse::().unwrap(), NodeKind::Function); + assert!("knowledge".parse::().is_err()); + assert_eq!("calls".parse::().unwrap(), EdgeKind::Calls); + assert!("supports".parse::().is_err()); + } + + #[test] + fn digests_are_lowercase_prefixed() { + let digest = sha256_prefixed(b"abc"); + assert!(is_sha256_prefixed(&digest)); + assert!(is_sha256_hex(&sha256_hex(b"abc"))); + assert!(!is_sha256_prefixed("sha256:ABC")); + } +} diff --git a/src/query.rs b/src/query.rs new file mode 100644 index 0000000..7dd9731 --- /dev/null +++ b/src/query.rs @@ -0,0 +1,16 @@ +//! Read-only query surface: exact lookup, lexical/fuzzy candidates, fusion, +//! bounded graph expansion and Markdown slices. +//! +//! Filled in by the query milestones. Query never mutates graph facts or the +//! knowledge sources. + +use crate::cli::Output; +use crate::cli::QueryArgs; +use crate::error::KnowledgeError; +use std::path::Path; + +/// Execute one query against `.marqdo/knowledge.sqlite` under the requested +/// root. Does not compile implicitly. +pub fn run_query(_args: &QueryArgs, _marqdo_bin: Option<&Path>) -> Result { + Err(KnowledgeError::not_implemented("query")) +}