Compare commits
672
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cdcaff184f | ||
|
|
25ec3880bb | ||
|
|
edbd8f0ca8 | ||
|
|
a4272c17a9 | ||
|
|
c8cdf218f2 | ||
|
|
b3833f2051 | ||
|
|
a272c39613 | ||
|
|
6df9b54626 | ||
|
|
156c2c2fd5 | ||
|
|
6011b96fc1 | ||
|
|
7639bb8472 | ||
|
|
c61b66b49d | ||
|
|
cf49715c66 | ||
|
|
bf8a814c58 | ||
|
|
8fadec5c2c | ||
|
|
7263fee4c7 | ||
|
|
4204c2c974 | ||
|
|
9372cfb8ca | ||
|
|
179949b289 | ||
|
|
cd3946bd11 | ||
|
|
12e374bc05 | ||
|
|
fd2fac7112 | ||
|
|
60092b378b | ||
|
|
9025af62f0 | ||
|
|
83bb18b6a7 | ||
|
|
ec759dd1dc | ||
|
|
c454fc40bb | ||
|
|
bfb42cfc24 | ||
|
|
49dd91fee0 | ||
|
|
56c1862205 | ||
|
|
dbefd30dce | ||
|
|
bc06ce5b90 | ||
|
|
b26d9fd10e | ||
|
|
909ee338d2 | ||
|
|
84e319a42f | ||
|
|
efd9c74cd3 | ||
|
|
eccdf43cd3 | ||
|
|
9e25e5b26b | ||
|
|
cee8fc05c2 | ||
|
|
9a55d45832 | ||
|
|
48de6aed8c | ||
|
|
8772271648 | ||
|
|
0cb216c2bc | ||
|
|
eb45d78c47 | ||
|
|
582aed61ec | ||
|
|
0294414d26 | ||
|
|
3a2a78e0fd | ||
|
|
245a96809a | ||
|
|
bb41b11cce | ||
|
|
af73ab9371 | ||
|
|
cba1337066 | ||
|
|
d50ed70467 | ||
|
|
f313f0873b | ||
|
|
f7a4dab707 | ||
|
|
3861246ac6 | ||
|
|
053c22bc15 | ||
|
|
bbfa2049eb | ||
|
|
0b47ffdcb6 | ||
|
|
cf91730e45 | ||
|
|
ae0768e4de | ||
|
|
ccc848f2e2 | ||
|
|
c6ccad1d18 | ||
|
|
4e8512c812 | ||
|
|
f1bcbb1543 | ||
|
|
537a2883bf | ||
|
|
72a3988e49 | ||
|
|
93b8bc48e4 | ||
|
|
19f8d76e21 | ||
|
|
772a202d6e | ||
|
|
dc16bbf8a4 | ||
|
|
028ad7e941 | ||
|
|
620858a575 | ||
|
|
0bb5f57cc6 | ||
|
|
0a4374dc8c | ||
|
|
8afa402118 | ||
|
|
1eee189a49 | ||
|
|
d2e0b48aa5 | ||
|
|
302e2a3d24 | ||
|
|
faaa3ef55f | ||
|
|
70ffa5cd4e | ||
|
|
65bcea71ee | ||
|
|
16af07dd21 | ||
|
|
fc4c868eaa | ||
|
|
1fe9582cbe | ||
|
|
d34f388ee1 | ||
|
|
4cd82d1d2b | ||
|
|
fb6e35ed01 | ||
|
|
0ba8ae8d1e | ||
|
|
1121d63383 | ||
|
|
0b8f0a6c22 | ||
|
|
30047f8e00 | ||
|
|
7b6cc8da7c | ||
|
|
c5e613d2b1 | ||
|
|
d965d96cde | ||
|
|
65bc7622f8 | ||
|
|
844d13316a | ||
|
|
a403d8baf6 | ||
|
|
d25d623b9c | ||
|
|
1e3fcc1633 | ||
|
|
0d28a6c1a7 | ||
|
|
87083355ee | ||
|
|
7e9e496d86 | ||
|
|
d93b9b30ae | ||
|
|
7fc316d284 | ||
|
|
e27b1f4621 | ||
|
|
3c19e192bc | ||
|
|
df971f9c56 | ||
|
|
ecc2b60427 | ||
|
|
2826cbadbc | ||
|
|
a2856bfe87 | ||
|
|
69617802c3 | ||
|
|
135c02bc9a | ||
|
|
cd28a9d35c | ||
|
|
49cdc9a13f | ||
|
|
3629bc3fb9 | ||
|
|
37c0f526ec | ||
|
|
bf40169662 | ||
|
|
9fbf0b7c91 | ||
|
|
652d22e8e8 | ||
|
|
94dbaafc72 | ||
|
|
69ad7bc823 | ||
|
|
d59bd1885d | ||
|
|
f6d8751f23 | ||
|
|
9a38daafc0 | ||
|
|
e5bc77b93e | ||
|
|
2bcf1930fe | ||
|
|
2d58220a3c | ||
|
|
8436f4192d | ||
|
|
13ab2b7d68 | ||
|
|
714763f92f | ||
|
|
a1cd0741c9 | ||
|
|
c741cc7d1b | ||
|
|
e8b8c9a350 | ||
|
|
f016a16c68 | ||
|
|
5bf91d51da | ||
|
|
00aecf692d | ||
|
|
b815f6235f | ||
|
|
a1a58727fd | ||
|
|
b1cf89982b | ||
|
|
5fa02aed2d | ||
|
|
1fde4ed72a | ||
|
|
52210a91fd | ||
|
|
9d792e11ce | ||
|
|
2677ad7269 | ||
|
|
98c395b5de | ||
|
|
b4ebbe5c28 | ||
|
|
88e2cbf254 | ||
|
|
b153571933 | ||
|
|
aba6f0c38b | ||
|
|
f4299db347 | ||
|
|
06f77fe8b7 | ||
|
|
54e38d58c3 | ||
|
|
fd47a954bd | ||
|
|
5aae33f578 | ||
|
|
4ed04039e5 | ||
|
|
e7cec6acc6 | ||
|
|
a7cda3f51c | ||
|
|
d2ee48555a | ||
|
|
8639791914 | ||
|
|
765fad6a8d | ||
|
|
408c4ace93 | ||
|
|
565d34fb7b | ||
|
|
0170d9291f | ||
|
|
865b261294 | ||
|
|
62aa24a4bc | ||
|
|
f2de556c16 | ||
|
|
67d865d373 | ||
|
|
5c0a36c9ea | ||
|
|
f50ae4c934 | ||
|
|
1fefc538ac | ||
|
|
a520b62d08 | ||
|
|
1063c94f5d | ||
|
|
954e21ca81 | ||
|
|
fd39211801 | ||
|
|
ff23ce6f00 | ||
|
|
86464cec11 | ||
|
|
ba57e8b43f | ||
|
|
be406d230f | ||
|
|
38abde8516 | ||
|
|
9bb6566419 | ||
|
|
2acaf3c060 | ||
|
|
ec33163d98 | ||
|
|
2d0913cf3b | ||
|
|
76ea8e3350 | ||
|
|
bbc1e589f5 | ||
|
|
987e297c07 | ||
|
|
046aa2cf48 | ||
|
|
0bc0e66a85 | ||
|
|
2310633de3 | ||
|
|
bd36d78025 | ||
|
|
d2270fafdd | ||
|
|
86faf5b8f0 | ||
|
|
902f26ee95 | ||
|
|
ea9fe1a6ed | ||
|
|
6c2074166c | ||
|
|
bd44af2b68 | ||
|
|
972cd0dfac | ||
|
|
9cc16bb220 | ||
|
|
03594424a1 | ||
|
|
97985371ca | ||
|
|
3c5c01998f | ||
|
|
2fa24cb1bd | ||
|
|
0304bae9f4 | ||
|
|
ac6d34731a | ||
|
|
be5ad7e080 | ||
|
|
32128c06c1 | ||
|
|
07b7f419de | ||
|
|
4d6fce2d93 | ||
|
|
b398168b1f | ||
|
|
6b397fea2e | ||
|
|
d20386e0a7 | ||
|
|
fcb90db2d0 | ||
|
|
5d8e96372f | ||
|
|
0d1a98279e | ||
|
|
73641abf8a | ||
|
|
a4873b3d45 | ||
|
|
4f171e5245 | ||
|
|
d48b671314 | ||
|
|
b9d73af062 | ||
|
|
21904e62ee | ||
|
|
f9af30b195 | ||
|
|
531e3790b3 | ||
|
|
7745b71832 | ||
|
|
b39663408c | ||
|
|
9c4696e9d5 | ||
|
|
cf5e53f341 | ||
|
|
e512f768ff | ||
|
|
c3ef65d069 | ||
|
|
90f0be6baf | ||
|
|
eba51eba0f | ||
|
|
fbaa07ba88 | ||
|
|
d0ecc5316f | ||
|
|
9ee39277ae | ||
|
|
9d3fd21c88 | ||
|
|
d7217672a3 | ||
|
|
e39b685b1e | ||
|
|
5b9399361d | ||
|
|
7631b93900 | ||
|
|
f98eb8fc16 | ||
|
|
ab60106fb9 | ||
|
|
caab41a760 | ||
|
|
78d8ab11ed | ||
|
|
d49da1b5fe | ||
|
|
27497fd6be | ||
|
|
466ce3ca82 | ||
|
|
8b5af5ec65 | ||
|
|
34cbc0c0eb | ||
|
|
52ff4bbff5 | ||
|
|
9e7104e362 | ||
|
|
882ae5368f | ||
|
|
12a424ce23 | ||
|
|
c3230761e8 | ||
|
|
f5104008c2 | ||
|
|
013e8c6d0c | ||
|
|
603bba533b | ||
|
|
e202a8d88b | ||
|
|
c56a31c6bc | ||
|
|
b73b18bf9a | ||
|
|
0f351252b2 | ||
|
|
d7d7411fa0 | ||
|
|
45af7f074c | ||
|
|
70ab118612 | ||
|
|
ba0cdea9d0 | ||
|
|
09500ff764 | ||
|
|
b29ce4a0a6 | ||
|
|
311e598b69 | ||
|
|
413dca770c | ||
|
|
9d9239b11e | ||
|
|
a571c41c61 | ||
|
|
ba1fab9dcf | ||
|
|
5dc9c13a71 | ||
|
|
70821bae5a | ||
|
|
486abf82dd | ||
|
|
19afe3af33 | ||
|
|
113042b7f4 | ||
|
|
f8eebd91cb | ||
|
|
00297fc354 | ||
|
|
5baac082f9 | ||
|
|
611b0aa54e | ||
|
|
110f0dbcf5 | ||
|
|
1688cf0a1e | ||
|
|
13b7c8858a | ||
|
|
b8b6f243d1 | ||
|
|
eaa6e805ce | ||
|
|
05dbb21c58 | ||
|
|
f1f4358dee | ||
|
|
3374c41f07 | ||
|
|
95affe87e5 | ||
|
|
5e86398fcd | ||
|
|
844f0cbe42 | ||
|
|
4d5d7847e5 | ||
|
|
06795feed6 | ||
|
|
a4548a7ee1 | ||
|
|
42216865e2 | ||
|
|
e48bdb2401 | ||
|
|
c67eb4b2f3 | ||
|
|
fafa74b0b8 | ||
|
|
049a39aba3 | ||
|
|
cd26430a61 | ||
|
|
aab010ff17 | ||
|
|
9a7bc32051 | ||
|
|
bfdd8ac6be | ||
|
|
018669fb87 | ||
|
|
fb2de78d62 | ||
|
|
7e8d6c1954 | ||
|
|
d21230c6c3 | ||
|
|
4e98d5bfa1 | ||
|
|
8998269377 | ||
|
|
6e9a227ad2 | ||
|
|
4e7506da5a | ||
|
|
06ad93c77c | ||
|
|
0bb7b34259 | ||
|
|
859c17b49d | ||
|
|
46b26c9624 | ||
|
|
fd215c18e4 | ||
|
|
efa3afc7dc | ||
|
|
e03dd66051 | ||
|
|
3476fe5fae | ||
|
|
3e08c8347e | ||
|
|
c691123d2d | ||
|
|
a4b81535e8 | ||
|
|
a898cf4b65 | ||
|
|
10009a0a43 | ||
|
|
4dfe47ff99 | ||
|
|
bd997e61d6 | ||
|
|
23d0670126 | ||
|
|
12c600edbe | ||
|
|
e4115e705e | ||
|
|
0cbc4a2d72 | ||
|
|
cea6d35729 | ||
|
|
4c56918d8a | ||
|
|
f17263417e | ||
|
|
6f0b463489 | ||
|
|
28c01caa1a | ||
|
|
95b59e9b0a | ||
|
|
bc967f1f6e | ||
|
|
4228b8a74f | ||
|
|
300086fc83 | ||
|
|
688eb262a9 | ||
|
|
bfb6f5dede | ||
|
|
88c0fbe56b | ||
|
|
3d74eff224 | ||
|
|
22d08afe2d | ||
|
|
a97f757e34 | ||
|
|
bbc8f13944 | ||
|
|
f18a40d76c | ||
|
|
c7644a36aa | ||
|
|
f394f31c12 | ||
|
|
0513673c2a | ||
|
|
a73542a391 | ||
|
|
c465797654 | ||
|
|
7ce3f982f2 | ||
|
|
6311456917 | ||
|
|
3c06559c5d | ||
|
|
5c9f2e8c83 | ||
|
|
62902faaca | ||
|
|
d22fd77b22 | ||
|
|
2f86f493d6 | ||
|
|
eafa0fad85 | ||
|
|
2e7c497b69 | ||
|
|
79dcfdcf9a | ||
|
|
487e28a904 | ||
|
|
c492f97a67 | ||
|
|
ec2ff74514 | ||
|
|
c501f8d6e6 | ||
|
|
b4287cbfda | ||
|
|
26724a1db1 | ||
|
|
d6368ee709 | ||
|
|
ea211a5c0b | ||
|
|
9e8b433c95 | ||
|
|
2a1c62aeed | ||
|
|
948d6f4b47 | ||
|
|
725271a7da | ||
|
|
4ea62e6886 | ||
|
|
c01cf3b078 | ||
|
|
c67777a6b9 | ||
|
|
e5e5e7560c | ||
|
|
6e1cd5fbbc | ||
|
|
8bd8f7c0bb | ||
|
|
1c42cd1f78 | ||
|
|
be090a43f2 | ||
|
|
2c81fa0cb5 | ||
|
|
c3815afcd4 | ||
|
|
8800160564 | ||
|
|
bdbc4a1bf7 | ||
|
|
597090bc45 | ||
|
|
af36c410b4 | ||
|
|
4dcd606c10 | ||
|
|
bbd5a7fa48 | ||
|
|
6dc37ccb66 | ||
|
|
b84906283e | ||
|
|
af0dcdf76a | ||
|
|
f1e1cde597 | ||
|
|
a7c5630e5b | ||
|
|
82151d6bc3 | ||
|
|
c93e7ad598 | ||
|
|
290b271cf6 | ||
|
|
a686bdbeaf | ||
|
|
2b84c62875 | ||
|
|
2de786fc64 | ||
|
|
2ddf034983 | ||
|
|
b2043f4f84 | ||
|
|
52eae52061 | ||
|
|
e451ea64ae | ||
|
|
eb6e4028ff | ||
|
|
ea45493941 | ||
|
|
da70f0e00c | ||
|
|
8bf3707511 | ||
|
|
804eeef858 | ||
|
|
36658f12fe | ||
|
|
f0e675ffd8 | ||
|
|
90911c1074 | ||
|
|
1729e0b40d | ||
|
|
70b3169e7f | ||
|
|
315a1c0945 | ||
|
|
b9316c693d | ||
|
|
820e52d869 | ||
|
|
444e8e4206 | ||
|
|
e6f2c8b4e8 | ||
|
|
f6b7652219 | ||
|
|
3cd00ab5cf | ||
|
|
0feae50d90 | ||
|
|
d79c55fc64 | ||
|
|
98a6f5c480 | ||
|
|
0fa4aa7280 | ||
|
|
3b192e2eed | ||
|
|
2794d26181 | ||
|
|
7b56f696d6 | ||
|
|
ead1b8c1bc | ||
|
|
b8126e00c4 | ||
|
|
62f8f4b313 | ||
|
|
21924541dc | ||
|
|
197242ca42 | ||
|
|
7922734dce | ||
|
|
afd7675425 | ||
|
|
8b3b343645 | ||
|
|
6713f342c3 | ||
|
|
79bb8a143c | ||
|
|
d03a181536 | ||
|
|
8e5304c156 | ||
|
|
c487db6534 | ||
|
|
0ca54f429e | ||
|
|
6c62f64784 | ||
|
|
3282f85007 | ||
|
|
b186569750 | ||
|
|
7cde2462ec | ||
|
|
c0b96f7c05 | ||
|
|
3a88caac69 | ||
|
|
31457e9240 | ||
|
|
307335a733 | ||
|
|
4eb5e34ea7 | ||
|
|
f4be219790 | ||
|
|
53591b6f27 | ||
|
|
a14d0bb7cb | ||
|
|
c2802e7cb3 | ||
|
|
c7f2815f1d | ||
|
|
afc90fe992 | ||
|
|
2f9ce824a0 | ||
|
|
a39b2a6950 | ||
|
|
70fa95966c | ||
|
|
10479014d5 | ||
|
|
148e22aa7d | ||
|
|
a9fe6196f7 | ||
|
|
ae20665a66 | ||
|
|
ccbf078463 | ||
|
|
cd1e46784f | ||
|
|
b49d97b8d7 | ||
|
|
3d44de9d87 | ||
|
|
987b3c1770 | ||
|
|
25bc6544c4 | ||
|
|
b241ae753b | ||
|
|
2041771b14 | ||
|
|
b5958a9f63 | ||
|
|
c05dbd4b3b | ||
|
|
44e468fc21 | ||
|
|
5f358d329b | ||
|
|
59fe8154f2 | ||
|
|
d5b2e9bb8f | ||
|
|
3a3907e1b6 | ||
|
|
f66cdc70b2 | ||
|
|
e299a497a7 | ||
|
|
eefb29d2ad | ||
|
|
668c485037 | ||
|
|
c83d5bb970 | ||
|
|
8638b3c95b | ||
|
|
c9b55c16f7 | ||
|
|
a3b9d53d06 | ||
|
|
215915cee2 | ||
|
|
df9271ed81 | ||
|
|
97e73a0fa0 | ||
|
|
e2ebe98e7f | ||
|
|
345e30de71 | ||
|
|
0084160e12 | ||
|
|
7280c111f0 | ||
|
|
763de11d2b | ||
|
|
9c0de3eeb2 | ||
|
|
9c81e9fbf1 | ||
|
|
40603f1652 | ||
|
|
4a34da31ad | ||
|
|
6e394faab1 | ||
|
|
25d0895cac | ||
|
|
f5f93cfb12 | ||
|
|
cf1ebe9d6f | ||
|
|
dd0d4ff8b1 | ||
|
|
98103f3270 | ||
|
|
a740ebb42e | ||
|
|
7c79f820cb | ||
|
|
f3b2326304 | ||
|
|
4eded247c5 | ||
|
|
3ffb857181 | ||
|
|
ec92906399 | ||
|
|
87671640ea | ||
|
|
c725e984bb | ||
|
|
8f05b57744 | ||
|
|
120b0147f2 | ||
|
|
ae695b4b15 | ||
|
|
89fee685c3 | ||
|
|
23eb9a21c8 | ||
|
|
a009efe91c | ||
|
|
dbd3111adf | ||
|
|
2b35e0c07a | ||
|
|
ba3354df03 | ||
|
|
7c8c19f416 | ||
|
|
35f83241cb | ||
|
|
5297f9b47e | ||
|
|
cbc50ec4eb | ||
|
|
198cc291e2 | ||
|
|
cb8c3a6ea6 | ||
|
|
66f597bbba | ||
|
|
fe237c8b4b | ||
|
|
ec7b08a625 | ||
|
|
9dd728579d | ||
|
|
0a6ca00f64 | ||
|
|
6e856ce05f | ||
|
|
1b8b78cfe9 | ||
|
|
49508d9f87 | ||
|
|
63a660223e | ||
|
|
2cbc2e2f43 | ||
|
|
eb2ad44755 | ||
|
|
c3979142a6 | ||
|
|
1a30de6bfc | ||
|
|
8c0df47966 | ||
|
|
4c177378ae | ||
|
|
a2db175819 | ||
|
|
2d0f050524 | ||
|
|
2d2b78edb3 | ||
|
|
627fa80f3e | ||
|
|
96cbbb093e | ||
|
|
6551308f14 | ||
|
|
9ccc2badd4 | ||
|
|
07a83bdeb7 | ||
|
|
224dfb6588 | ||
|
|
d8d6c68ac2 | ||
|
|
3e369e5464 | ||
|
|
abaaba97f9 | ||
|
|
bd49467d26 | ||
|
|
b44524e1a9 | ||
|
|
0319667f8e | ||
|
|
4c3ad1f83c | ||
|
|
a7a845187a | ||
|
|
e14a9a11d2 | ||
|
|
d7ce757d65 | ||
|
|
6f5447c316 | ||
|
|
727b67811c | ||
|
|
a85fb68015 | ||
|
|
2dfe7328cc | ||
|
|
cfc0a0ca8f | ||
|
|
2b1c7fe20d | ||
|
|
d5e1d9c09b | ||
|
|
554540451e | ||
|
|
c10134c22b | ||
|
|
9175b3a045 | ||
|
|
0ecae44888 | ||
|
|
a9c2a10fb5 | ||
|
|
e11094e5fa | ||
|
|
38913dc3e1 | ||
|
|
dd2b7932a2 | ||
|
|
2051e187ba | ||
|
|
ca817a8cc4 | ||
|
|
2d815f5902 | ||
|
|
0abdc647c9 | ||
|
|
fded2db73e | ||
|
|
2274c9faf5 | ||
|
|
280b236490 | ||
|
|
ef2c144cdd | ||
|
|
634cf0ff1b | ||
|
|
2dc3d5c169 | ||
|
|
fcad1fdfaa | ||
|
|
5c6cdfb5e1 | ||
|
|
1d6ba761a8 | ||
|
|
893ba6c8f4 | ||
|
|
a835eff14b | ||
|
|
029b4d8a6e | ||
|
|
0053b45691 | ||
|
|
f46812d1d2 | ||
|
|
8495df961b | ||
|
|
abc8be1077 | ||
|
|
84baf27f7e | ||
|
|
1a08d904f9 | ||
|
|
31ca9a95d7 | ||
|
|
ade91b26c3 | ||
|
|
d797957abc | ||
|
|
104ddddb96 | ||
|
|
c8c4c7fa00 | ||
|
|
3111a26229 | ||
|
|
26ef257e06 | ||
|
|
6864ea7b53 | ||
|
|
c2ecc15d89 | ||
|
|
9bbcc0952b | ||
|
|
179ec4d38b | ||
|
|
02a61cdf0d | ||
|
|
6a84b4e5aa | ||
|
|
497a9b9d58 | ||
|
|
c5972be618 | ||
|
|
43e77c4c6b | ||
|
|
d66985e597 | ||
|
|
ff4bed99c9 | ||
|
|
2b4c1b83bd | ||
|
|
f85aa8f604 | ||
|
|
e5ca3c4177 | ||
|
|
0f2f8208e3 | ||
|
|
ba17516814 | ||
|
|
c0979b69e2 | ||
|
|
4b5c33bb90 | ||
|
|
1ea4d53061 | ||
|
|
17b548e9b0 | ||
|
|
5755eb1f08 | ||
|
|
e2f15324d7 | ||
|
|
b0b0802a56 | ||
|
|
e14cc8b758 | ||
|
|
55c6a5058c | ||
|
|
52d5d01337 | ||
|
|
93ceff7f17 | ||
|
|
0a891cfd95 | ||
|
|
66adc6a354 | ||
|
|
e99f1c2ba0 | ||
|
|
f52a9face8 | ||
|
|
4fcf22131c | ||
|
|
d27324f8dd | ||
|
|
dd86a15555 | ||
|
|
28d173b8fd | ||
|
|
b4b7ea76ab | ||
|
|
6ea452cc3f | ||
|
|
6e0e965883 | ||
|
|
6b4b3ce2ba | ||
|
|
18cdbab885 | ||
|
|
ebca9b4caf | ||
|
|
6945ef8ddc | ||
|
|
f20bf03ee1 | ||
|
|
7cda15553d | ||
|
|
3c67fd5f9b | ||
|
|
0150931df4 | ||
|
|
5ff1b06009 | ||
|
|
5279bcae18 | ||
|
|
daa58e6b27 | ||
|
|
589d021744 | ||
|
|
e58b9c8ada | ||
|
|
507c28e006 | ||
|
|
2d74fe4057 | ||
|
|
e8312268d2 | ||
|
|
f4cd1e51c0 | ||
|
|
60e707e7df | ||
|
|
0d6eb4dac4 | ||
|
|
80d8f986bd | ||
|
|
9ee3bb9007 | ||
|
|
8a07010704 | ||
|
|
314fc8ac94 | ||
|
|
b46e5461a7 | ||
|
|
ada7c1797d | ||
|
|
54197995f5 | ||
|
|
13e510dd9c | ||
|
|
5c937fbffe |
No files matched your search
+31
-12
@@ -1,22 +1,36 @@
|
|||||||
# .gitea/workflows/deploy.yml
|
# .gitea/workflows/deploy.yml
|
||||||
name: Deploy mindnet to llm-node
|
name: Deploy mindnet to llm-node
|
||||||
on: { push: { branches: [ "main" ] } }
|
|
||||||
# on: {}
|
|
||||||
|
|
||||||
concurrency: { group: deploy-mindnet, cancel-in-progress: false }
|
on:
|
||||||
|
push:
|
||||||
|
branches: ["main"]
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: deploy-mindnet
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
deploy:
|
deploy:
|
||||||
runs-on: linux_host
|
runs-on: linux_host
|
||||||
env:
|
env:
|
||||||
DEPLOY_DIRS: "app scripts schemas docker requirements.txt README.md"
|
TARGET_BASE: /home/llmadmin/mindnet
|
||||||
TARGET_BASE: "/home/llmadmin/mindnet"
|
DEPLOY_DIRS: "app scripts schemas docker tests config requirements.txt README.md"
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: https://github.com/actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- name: Ensure target base
|
|
||||||
|
- name: Ensure target base exists
|
||||||
run: install -d "$TARGET_BASE"
|
run: install -d "$TARGET_BASE"
|
||||||
- name: Deploy whitelisted
|
|
||||||
|
- name: Stop API (graceful)
|
||||||
|
continue-on-error: true
|
||||||
|
run: |
|
||||||
|
if systemctl --user list-unit-files | grep -q '^mindnet-api.service'; then
|
||||||
|
systemctl --user stop mindnet-api.service || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Deploy whitelisted (rsync)
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
IFS=' ' read -r -a DIRS <<< "$DEPLOY_DIRS"
|
IFS=' ' read -r -a DIRS <<< "$DEPLOY_DIRS"
|
||||||
@@ -24,22 +38,27 @@ jobs:
|
|||||||
if [ -e "$d" ]; then
|
if [ -e "$d" ]; then
|
||||||
if [ -d "$d" ]; then
|
if [ -d "$d" ]; then
|
||||||
install -d "$TARGET_BASE/$d"
|
install -d "$TARGET_BASE/$d"
|
||||||
rsync -a --delete --exclude='.git' \
|
rsync -a --delete \
|
||||||
--exclude='.env' --exclude='.env.*' --exclude='**/.env*' \
|
--exclude='.git' \
|
||||||
|
--exclude='.env*' \
|
||||||
|
--exclude='.venv' \
|
||||||
|
--exclude='hf_cache' --exclude='hf_cache/**' \
|
||||||
"$d"/ "$TARGET_BASE/$d"/
|
"$d"/ "$TARGET_BASE/$d"/
|
||||||
else
|
else
|
||||||
rsync -a "$d" "$TARGET_BASE/$d"
|
rsync -a "$d" "$TARGET_BASE/$d"
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
- name: Python venv (idempotent)
|
|
||||||
|
- name: Python venv & requirements
|
||||||
run: |
|
run: |
|
||||||
cd "$TARGET_BASE"
|
cd "$TARGET_BASE"
|
||||||
[ -d .venv ] || python3 -m venv .venv
|
[ -d .venv ] || python3 -m venv .venv
|
||||||
source .venv/bin/activate
|
source .venv/bin/activate
|
||||||
pip install --upgrade pip
|
pip install --upgrade pip
|
||||||
[ -f requirements.txt ] && pip install -r requirements.txt || true
|
[ -f requirements.txt ] && pip install -r requirements.txt || true
|
||||||
- name: Optional — restart mindnet-api
|
|
||||||
|
- name: Start/Restart mindnet-api
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
run: |
|
run: |
|
||||||
if systemctl --user list-unit-files | grep -q '^mindnet-api.service'; then
|
if systemctl --user list-unit-files | grep -q '^mindnet-api.service'; then
|
||||||
|
|||||||
Vendored
+3
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"CodeGPT.apiKey": "Google AI Studio"
|
||||||
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
# mindnet API (bundle)
|
# mindnet API (bundle)
|
||||||
|
|
||||||
This bundle provides a minimal FastAPI app for embeddings and Qdrant upserts/queries plus a Markdown importer.
|
This bundle provides a minimal FastAPI app for embeddings and Qdrant upserts/queries plus a Markdown importer.
|
||||||
@@ -33,3 +32,7 @@ python3 scripts/import_markdown.py --vault /path/to/Obsidian
|
|||||||
- `POST /qdrant/query` → semantic search over chunks with optional filters
|
- `POST /qdrant/query` → semantic search over chunks with optional filters
|
||||||
|
|
||||||
See `scripts/quick_test.sh` for a runnable example.
|
See `scripts/quick_test.sh` for a runnable example.
|
||||||
|
|
||||||
|
>Anmerkung:
|
||||||
|
Diese Datei ist veraltet und muss auf Stand 2.6.0 gebracht werden
|
||||||
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/__init__.py
|
||||||
|
DESCRIPTION: Paket-Initialisierung.
|
||||||
|
VERSION: 0.1.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: None
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
__version__ = "0.1.0"
|
||||||
+26
-1
@@ -1,9 +1,15 @@
|
|||||||
"""
|
"""
|
||||||
Version 0.1
|
FILE: app/config.py
|
||||||
|
DESCRIPTION: Zentrale Pydantic-Konfiguration (Env-Vars für Qdrant, LLM, Retriever).
|
||||||
|
VERSION: 0.4.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: os, functools, pathlib
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
import os
|
import os
|
||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
class Settings:
|
class Settings:
|
||||||
# Qdrant
|
# Qdrant
|
||||||
@@ -12,10 +18,29 @@ class Settings:
|
|||||||
COLLECTION_PREFIX: str = os.getenv("MINDNET_PREFIX", "mindnet")
|
COLLECTION_PREFIX: str = os.getenv("MINDNET_PREFIX", "mindnet")
|
||||||
VECTOR_SIZE: int = int(os.getenv("MINDNET_VECTOR_SIZE", "384"))
|
VECTOR_SIZE: int = int(os.getenv("MINDNET_VECTOR_SIZE", "384"))
|
||||||
DISTANCE: str = os.getenv("MINDNET_DISTANCE", "Cosine")
|
DISTANCE: str = os.getenv("MINDNET_DISTANCE", "Cosine")
|
||||||
|
|
||||||
# Embeddings
|
# Embeddings
|
||||||
MODEL_NAME: str = os.getenv("MINDNET_MODEL", "sentence-transformers/all-MiniLM-L6-v2")
|
MODEL_NAME: str = os.getenv("MINDNET_MODEL", "sentence-transformers/all-MiniLM-L6-v2")
|
||||||
|
|
||||||
|
# WP-05 LLM / Ollama
|
||||||
|
OLLAMA_URL: str = os.getenv("MINDNET_OLLAMA_URL", "http://127.0.0.1:11434")
|
||||||
|
LLM_MODEL: str = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
||||||
|
PROMPTS_PATH: str = os.getenv("MINDNET_PROMPTS_PATH", "config/prompts.yaml")
|
||||||
|
|
||||||
|
# NEU für WP-06
|
||||||
|
LLM_TIMEOUT: float = float(os.getenv("MINDNET_LLM_TIMEOUT", "120.0"))
|
||||||
|
DECISION_CONFIG_PATH: str = os.getenv("MINDNET_DECISION_CONFIG", "config/decision_engine.yaml")
|
||||||
|
|
||||||
# API
|
# API
|
||||||
DEBUG: bool = os.getenv("DEBUG", "false").lower() == "true"
|
DEBUG: bool = os.getenv("DEBUG", "false").lower() == "true"
|
||||||
|
|
||||||
|
# WP-04 Retriever Defaults
|
||||||
|
RETRIEVER_W_SEM: float = float(os.getenv("MINDNET_WP04_W_SEM", "0.70"))
|
||||||
|
RETRIEVER_W_EDGE: float = float(os.getenv("MINDNET_WP04_W_EDGE", "0.25"))
|
||||||
|
RETRIEVER_W_CENT: float = float(os.getenv("MINDNET_WP04_W_CENT", "0.05"))
|
||||||
|
RETRIEVER_TOP_K: int = int(os.getenv("MINDNET_WP04_TOP_K", "10"))
|
||||||
|
RETRIEVER_EXPAND_DEPTH: int = int(os.getenv("MINDNET_WP04_EXPAND_DEPTH", "1"))
|
||||||
|
RETRIEVER_EDGE_TYPES: str = os.getenv("MINDNET_WP04_EDGE_TYPES", "references,belongs_to,prev,next")
|
||||||
|
|
||||||
@lru_cache
|
@lru_cache
|
||||||
def get_settings() -> Settings:
|
def get_settings() -> Settings:
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
TYPE_SIZES = {
|
|
||||||
"thought": {"target": (150, 250), "max": 300, "overlap": (30, 40)},
|
|
||||||
"experience":{"target": (250, 350), "max": 450, "overlap": (40, 60)},
|
|
||||||
"journal": {"target": (200, 300), "max": 400, "overlap": (30, 50)},
|
|
||||||
"task": {"target": (120, 200), "max": 250, "overlap": (20, 30)},
|
|
||||||
"project": {"target": (300, 450), "max": 600, "overlap": (50, 70)},
|
|
||||||
"concept": {"target": (250, 400), "max": 550, "overlap": (40, 60)},
|
|
||||||
"source": {"target": (200, 350), "max": 500, "overlap": (30, 50)},
|
|
||||||
}
|
|
||||||
DEFAULT = {"target": (250, 350), "max": 500, "overlap": (40, 60)}
|
|
||||||
|
|
||||||
def get_sizes(note_type: str):
|
|
||||||
return TYPE_SIZES.get(str(note_type).lower(), DEFAULT)
|
|
||||||
+163
-240
@@ -1,253 +1,176 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
Modul: app/core/chunk_payload.py
|
FILE: app/core/chunk_payload.py
|
||||||
Version: 2.0.0
|
DESCRIPTION: Baut das JSON-Objekt für 'mindnet_chunks'.
|
||||||
Datum: 2025-09-09
|
FEATURES:
|
||||||
|
- Inkludiert Nachbarschafts-IDs (prev/next) und Titel.
|
||||||
Kurzbeschreibung
|
- FIX 3: Robuste Erkennung des Inputs (Frontmatter-Dict vs. Note-Objekt), damit Overrides ankommen.
|
||||||
----------------
|
VERSION: 2.3.0
|
||||||
Erzeugt **Chunk-Payloads** für die Qdrant-Collection `<prefix>_chunks` auf Basis der
|
STATUS: Active
|
||||||
vom Chunker gelieferten `Chunk`-Objekte. Ziel:
|
DEPENDENCIES: yaml, os
|
||||||
- *Verlustfreie Rekonstruktion*: Jeder Chunk enthält seinen **Text** (payload["text"]).
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
- *Schnelle Abfragen*: Wichtige Note-Metadaten werden gespiegelt, um Filter ohne Join zu erlauben.
|
|
||||||
- *Graph-Kompatibilität*: Wikilinks und externe Links werden extrahiert; Nachbarschaften werden übernommen.
|
|
||||||
- *Monitoring*: Token- und Längenmetriken sowie Text-Hash erleichtern Audits und Re-Embeddings.
|
|
||||||
|
|
||||||
Kompatibilität
|
|
||||||
--------------
|
|
||||||
- **Abwärtskompatibel** zur bisherigen `make_chunk_payloads`-Signatur.
|
|
||||||
- Zusätzliche Felder stören bestehende Upserts nicht (Payload ist schema-flexibel).
|
|
||||||
- Erwartet, dass `Chunk` u. a. die Attribute `id`, `index`, `text`, `char_start`, `char_end`,
|
|
||||||
`section_title`, `section_path`, `neighbors_prev`, `neighbors_next` liefert.
|
|
||||||
|
|
||||||
CLI (Schnelltest)
|
|
||||||
-----------------
|
|
||||||
# Preview aus einer Markdown-Datei
|
|
||||||
python3 -m app.core.chunk_payload --from-file ./test_vault/20_experiences/exp-two.md --vault-root ./test_vault
|
|
||||||
|
|
||||||
# Nur IDs & Tokenmengen
|
|
||||||
python3 -m app.core.chunk_payload --from-file ./test_vault/20_experiences/exp-two.md --vault-root ./test_vault --summary
|
|
||||||
|
|
||||||
Felder (Auszug)
|
|
||||||
---------------
|
|
||||||
id : "<note_id>#cNN"
|
|
||||||
scope : "chunk"
|
|
||||||
note_id : "<note_id>"
|
|
||||||
note_title : str
|
|
||||||
note_type : str
|
|
||||||
note_status : str
|
|
||||||
area, project : optional
|
|
||||||
tags : list[str]
|
|
||||||
note_path : str (relativ, Slashes normalisiert)
|
|
||||||
chunk_index : int
|
|
||||||
section_title : str | None
|
|
||||||
section_path : str | None
|
|
||||||
char_start : int | None
|
|
||||||
char_end : int | None
|
|
||||||
char_len : int
|
|
||||||
token_est : int (≈ len(text)/4)
|
|
||||||
neighbors : {"prev": str|None, "next": str|None}
|
|
||||||
text : str (Chunk-Text, **Pflicht**)
|
|
||||||
text_sha256 : str "sha256:<hex>"
|
|
||||||
lang : optional
|
|
||||||
wikilinks : list[str]
|
|
||||||
external_links : list[{"href": str, "label": str|None}]
|
|
||||||
references : list[{"target_id": str, "kind": "wikilink"}]
|
|
||||||
embed_model : optional (durchreichbar)
|
|
||||||
embed_dim : optional
|
|
||||||
embed_version : optional
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
import os, yaml
|
||||||
|
|
||||||
import argparse
|
def _env(n: str, d: Optional[str]=None) -> str:
|
||||||
import hashlib
|
v = os.getenv(n)
|
||||||
import json
|
return v if v is not None else (d or "")
|
||||||
import os
|
|
||||||
import re
|
|
||||||
from typing import Dict, List, Optional, Tuple
|
|
||||||
|
|
||||||
try:
|
def _load_types() -> dict:
|
||||||
# Paket-Import (normaler Betrieb)
|
p = _env("MINDNET_TYPES_FILE", "./config/types.yaml")
|
||||||
from app.core.chunker import Chunk
|
|
||||||
from app.core.parser import extract_wikilinks, read_markdown, normalize_frontmatter, validate_required_frontmatter
|
|
||||||
except Exception: # pragma: no cover
|
|
||||||
# Relativ (lokale Tests)
|
|
||||||
from .chunker import Chunk # type: ignore
|
|
||||||
from .parser import extract_wikilinks, read_markdown, normalize_frontmatter, validate_required_frontmatter # type: ignore
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Utilities
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
RE_MD_LINK = re.compile(r"\[([^\]]*)\]\(([^)\s]+)(?:\s+\"([^\"]+)\")?\)")
|
|
||||||
RE_HTTP_SCHEMES = ("http://", "https://", "mailto:", "obsidian://", "tel:")
|
|
||||||
|
|
||||||
def _estimate_tokens(text: str) -> int:
|
|
||||||
"""Grobe Token-Schätzung (≈ 1 Token pro 4 Zeichen)."""
|
|
||||||
return max(0, int(round(len((text or '').strip()) / 4)))
|
|
||||||
|
|
||||||
def _sha256_text(text: str) -> str:
|
|
||||||
h = hashlib.sha256()
|
|
||||||
h.update((text or "").encode("utf-8"))
|
|
||||||
return "sha256:" + h.hexdigest()
|
|
||||||
|
|
||||||
def _normalize_rel_path(path: Optional[str], vault_root: Optional[str]) -> Optional[str]:
|
|
||||||
if not path:
|
|
||||||
return None
|
|
||||||
p = str(path)
|
|
||||||
p = p.replace("\\", "/")
|
|
||||||
if vault_root and os.path.isabs(p):
|
|
||||||
try:
|
|
||||||
p = os.path.relpath(p, vault_root)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
p = p.replace("\\", "/").lstrip("/")
|
|
||||||
return p
|
|
||||||
|
|
||||||
def _extract_external_links(text: str) -> List[Dict[str, Optional[str]]]:
|
|
||||||
"""Findet Markdown-Links [label](href "title") mit erlaubten Schemes."""
|
|
||||||
out: List[Dict[str, Optional[str]]] = []
|
|
||||||
if not text:
|
|
||||||
return out
|
|
||||||
for m in RE_MD_LINK.finditer(text):
|
|
||||||
label = (m.group(1) or "").strip() or None
|
|
||||||
href = (m.group(2) or "").strip()
|
|
||||||
title = (m.group(3) or "").strip() or None
|
|
||||||
if any(href.startswith(s) for s in RE_HTTP_SCHEMES):
|
|
||||||
out.append({"href": href, "label": label or title})
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Public API
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def make_chunk_payloads(note_meta: Dict, path: str, chunks: List[Chunk]) -> List[Dict]:
|
|
||||||
"""
|
|
||||||
Erzeugt Payload-Dicts für alle Chunks einer Note.
|
|
||||||
|
|
||||||
Parameters
|
|
||||||
----------
|
|
||||||
note_meta : Dict
|
|
||||||
Normalisierte Frontmatter der Note (mind.: id, title, type, status, tags, [area, project, lang]).
|
|
||||||
path : str
|
|
||||||
Pfad zur Note (sollte relativ zum Vault sein; wird hier zur Sicherheit normalisiert).
|
|
||||||
chunks : List[Chunk]
|
|
||||||
Vom Chunker erzeugte Chunks.
|
|
||||||
|
|
||||||
Returns
|
|
||||||
-------
|
|
||||||
List[Dict]
|
|
||||||
Liste von Payloads (ein Eintrag pro Chunk).
|
|
||||||
"""
|
|
||||||
res: List[Dict] = []
|
|
||||||
rel_path = _normalize_rel_path(path, vault_root=None)
|
|
||||||
|
|
||||||
for ch in chunks:
|
|
||||||
text: str = getattr(ch, "text", "") or ""
|
|
||||||
wikilinks = extract_wikilinks(text)
|
|
||||||
ext_links = _extract_external_links(text)
|
|
||||||
|
|
||||||
payload: Dict = {
|
|
||||||
"id": getattr(ch, "id", None),
|
|
||||||
"scope": "chunk",
|
|
||||||
"note_id": note_meta.get("id"),
|
|
||||||
"note_title": note_meta.get("title"),
|
|
||||||
# gespiegelt für schnelle Filter:
|
|
||||||
"note_type": note_meta.get("type"),
|
|
||||||
"note_status": note_meta.get("status"),
|
|
||||||
"area": note_meta.get("area"),
|
|
||||||
"project": note_meta.get("project"),
|
|
||||||
"tags": note_meta.get("tags"),
|
|
||||||
# Pfad
|
|
||||||
"note_path": rel_path,
|
|
||||||
"path": rel_path, # Back-compat
|
|
||||||
# Reihenfolge & Section
|
|
||||||
"chunk_index": getattr(ch, "index", None),
|
|
||||||
"section_title": getattr(ch, "section_title", None),
|
|
||||||
"section_path": getattr(ch, "section_path", None),
|
|
||||||
# Position
|
|
||||||
"char_start": getattr(ch, "char_start", None),
|
|
||||||
"char_end": getattr(ch, "char_end", None),
|
|
||||||
"char_len": max(0, int(getattr(ch, "char_end", 0) or 0) - int(getattr(ch, "char_start", 0) or 0)) or len(text),
|
|
||||||
# Nachbarn
|
|
||||||
"neighbors": {
|
|
||||||
"prev": getattr(ch, "neighbors_prev", None),
|
|
||||||
"next": getattr(ch, "neighbors_next", None),
|
|
||||||
},
|
|
||||||
# Inhalt & Metrik
|
|
||||||
"text": text,
|
|
||||||
"text_sha256": _sha256_text(text),
|
|
||||||
"token_est": _estimate_tokens(text),
|
|
||||||
# Sprache
|
|
||||||
"lang": note_meta.get("lang"),
|
|
||||||
# Links
|
|
||||||
"wikilinks": wikilinks,
|
|
||||||
"external_links": ext_links,
|
|
||||||
"references": [{"target_id": w, "kind": "wikilink"} for w in wikilinks],
|
|
||||||
}
|
|
||||||
|
|
||||||
# Entferne Nones/Leeres, aber **text** bleibt (darf leer sein z. B. bei Bild-Only-Chunks)
|
|
||||||
cleaned = {}
|
|
||||||
for k, v in payload.items():
|
|
||||||
if v in (None, [], {}):
|
|
||||||
# immer behalten:
|
|
||||||
if k in ("text", "neighbors"):
|
|
||||||
cleaned[k] = v
|
|
||||||
else:
|
|
||||||
continue
|
|
||||||
else:
|
|
||||||
cleaned[k] = v
|
|
||||||
|
|
||||||
res.append(cleaned)
|
|
||||||
|
|
||||||
return res
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# CLI zum schnellen Testen
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _cli() -> None:
|
|
||||||
ap = argparse.ArgumentParser(description="Chunk-Payloads aus einer einzelnen Markdown-Datei erzeugen")
|
|
||||||
ap.add_argument("--from-file", required=True, help="Pfad zur Markdown-Datei")
|
|
||||||
ap.add_argument("--vault-root", default=None, help="Vault-Wurzel (zur Pfad-Relativierung)")
|
|
||||||
ap.add_argument("--summary", action="store_true", help="Nur kurze Übersicht je Chunk ausgeben")
|
|
||||||
args = ap.parse_args()
|
|
||||||
|
|
||||||
parsed = read_markdown(args.from_file)
|
|
||||||
fm = normalize_frontmatter(parsed.frontmatter)
|
|
||||||
validate_required_frontmatter(fm)
|
|
||||||
|
|
||||||
# lazy import, um Zyklen zu vermeiden
|
|
||||||
try:
|
try:
|
||||||
from app.core.chunker import assemble_chunks
|
with open(p, "r", encoding="utf-8") as f:
|
||||||
|
return yaml.safe_load(f) or {}
|
||||||
except Exception:
|
except Exception:
|
||||||
from .chunker import assemble_chunks # type: ignore
|
return {}
|
||||||
|
|
||||||
chunks = assemble_chunks(fm["id"], parsed.body, fm.get("type", "concept"))
|
def _get_types_map(reg: dict) -> dict:
|
||||||
rel = _normalize_rel_path(parsed.path, args.vault_root)
|
if isinstance(reg, dict) and isinstance(reg.get("types"), dict):
|
||||||
|
return reg["types"]
|
||||||
|
return reg if isinstance(reg, dict) else {}
|
||||||
|
|
||||||
pls = make_chunk_payloads(fm, rel or parsed.path, chunks)
|
def _get_defaults(reg: dict) -> dict:
|
||||||
|
if isinstance(reg, dict) and isinstance(reg.get("defaults"), dict):
|
||||||
|
return reg["defaults"]
|
||||||
|
if isinstance(reg, dict) and isinstance(reg.get("global"), dict):
|
||||||
|
return reg["global"]
|
||||||
|
return {}
|
||||||
|
|
||||||
if args.summary:
|
def _as_float(x: Any):
|
||||||
out = []
|
try: return float(x)
|
||||||
for p in pls:
|
except Exception: return None
|
||||||
out.append({
|
|
||||||
"id": p.get("id"),
|
def _resolve_chunk_profile_from_config(note_type: str, reg: dict) -> Optional[str]:
|
||||||
"chunk_index": p.get("chunk_index"),
|
# 1. Type Level
|
||||||
"token_est": p.get("token_est"),
|
types = _get_types_map(reg)
|
||||||
"wikilinks": p.get("wikilinks"),
|
if isinstance(types, dict):
|
||||||
"ext_links": [e.get("href") for e in p.get("external_links", [])],
|
t = types.get(note_type, {})
|
||||||
"prev": (p.get("neighbors") or {}).get("prev"),
|
if isinstance(t, dict):
|
||||||
"next": (p.get("neighbors") or {}).get("next"),
|
cp = t.get("chunking_profile") or t.get("chunk_profile")
|
||||||
})
|
if isinstance(cp, str) and cp: return cp
|
||||||
print(json.dumps(out, ensure_ascii=False, indent=2))
|
# 2. Defaults Level
|
||||||
|
defs = _get_defaults(reg)
|
||||||
|
if isinstance(defs, dict):
|
||||||
|
cp = defs.get("chunking_profile") or defs.get("chunk_profile")
|
||||||
|
if isinstance(cp, str) and cp: return cp
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _resolve_retriever_weight_from_config(note_type: str, reg: dict) -> float:
|
||||||
|
"""
|
||||||
|
Liest Weight nur aus Config (Type > Default).
|
||||||
|
Wird aufgerufen, wenn im Frontmatter nichts steht.
|
||||||
|
"""
|
||||||
|
# 1. Type Level
|
||||||
|
types = _get_types_map(reg)
|
||||||
|
if isinstance(types, dict):
|
||||||
|
t = types.get(note_type, {})
|
||||||
|
if isinstance(t, dict) and (t.get("retriever_weight") is not None):
|
||||||
|
v = _as_float(t.get("retriever_weight"))
|
||||||
|
if v is not None: return float(v)
|
||||||
|
|
||||||
|
# 2. Defaults Level
|
||||||
|
defs = _get_defaults(reg)
|
||||||
|
if isinstance(defs, dict) and (defs.get("retriever_weight") is not None):
|
||||||
|
v = _as_float(defs.get("retriever_weight"))
|
||||||
|
if v is not None: return float(v)
|
||||||
|
|
||||||
|
return 1.0
|
||||||
|
|
||||||
|
def _as_list(x):
|
||||||
|
if x is None: return []
|
||||||
|
if isinstance(x, list): return x
|
||||||
|
return [x]
|
||||||
|
|
||||||
|
def make_chunk_payloads(note: Dict[str, Any],
|
||||||
|
note_path: str,
|
||||||
|
chunks_from_chunker: List[Any],
|
||||||
|
*,
|
||||||
|
note_text: str = "",
|
||||||
|
types_cfg: Optional[dict] = None,
|
||||||
|
file_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Erstellt die Payloads für die Chunks.
|
||||||
|
|
||||||
|
Argument 'note' kann sein:
|
||||||
|
A) Ein komplexes Objekt/Dict mit Key "frontmatter" (Legacy / Tests)
|
||||||
|
B) Direkt das Frontmatter-Dictionary (Call aus ingestion.py)
|
||||||
|
"""
|
||||||
|
|
||||||
|
# --- FIX 3: Intelligente Erkennung der Input-Daten ---
|
||||||
|
# Wir prüfen: Ist 'note' ein Container MIT 'frontmatter', oder IST es das 'frontmatter'?
|
||||||
|
if isinstance(note, dict) and "frontmatter" in note and isinstance(note["frontmatter"], dict):
|
||||||
|
# Fall A: Container (wir müssen auspacken)
|
||||||
|
fm = note["frontmatter"]
|
||||||
else:
|
else:
|
||||||
print(json.dumps(pls, ensure_ascii=False, indent=2))
|
# Fall B: Direktes Dict (so ruft ingestion.py es auf!)
|
||||||
|
fm = note or {}
|
||||||
|
|
||||||
|
note_type = fm.get("type") or note.get("type") or "concept"
|
||||||
|
|
||||||
|
# Title Extraction (Fallback Chain)
|
||||||
|
title = fm.get("title") or note.get("title") or fm.get("id") or "Untitled"
|
||||||
|
|
||||||
if __name__ == "__main__": # pragma: no cover
|
reg = types_cfg if isinstance(types_cfg, dict) else _load_types()
|
||||||
_cli()
|
|
||||||
|
# --- Profil-Ermittlung ---
|
||||||
|
# Da wir 'fm' jetzt korrekt haben, funktionieren diese lookups:
|
||||||
|
cp = fm.get("chunking_profile") or fm.get("chunk_profile")
|
||||||
|
|
||||||
|
if not cp:
|
||||||
|
cp = _resolve_chunk_profile_from_config(note_type, reg)
|
||||||
|
if not cp:
|
||||||
|
cp = "sliding_standard"
|
||||||
|
|
||||||
|
# --- Retriever Weight Ermittlung ---
|
||||||
|
rw = fm.get("retriever_weight")
|
||||||
|
|
||||||
|
if rw is None:
|
||||||
|
rw = _resolve_retriever_weight_from_config(note_type, reg)
|
||||||
|
|
||||||
|
try:
|
||||||
|
rw = float(rw)
|
||||||
|
except Exception:
|
||||||
|
rw = 1.0
|
||||||
|
|
||||||
|
tags = fm.get("tags") or []
|
||||||
|
if isinstance(tags, str):
|
||||||
|
tags = [tags]
|
||||||
|
|
||||||
|
out: List[Dict[str, Any]] = []
|
||||||
|
for idx, ch in enumerate(chunks_from_chunker):
|
||||||
|
# Attribute extrahieren
|
||||||
|
cid = getattr(ch, "id", None) or (ch.get("id") if isinstance(ch, dict) else None)
|
||||||
|
nid = getattr(ch, "note_id", None) or (ch.get("note_id") if isinstance(ch, dict) else fm.get("id"))
|
||||||
|
index = getattr(ch, "index", None) or (ch.get("index") if isinstance(ch, dict) else idx)
|
||||||
|
text = getattr(ch, "text", None) or (ch.get("text") if isinstance(ch, dict) else "")
|
||||||
|
window = getattr(ch, "window", None) or (ch.get("window") if isinstance(ch, dict) else text)
|
||||||
|
prev_id = getattr(ch, "neighbors_prev", None) or (ch.get("neighbors_prev") if isinstance(ch, dict) else None)
|
||||||
|
next_id = getattr(ch, "neighbors_next", None) or (ch.get("neighbors_next") if isinstance(ch, dict) else None)
|
||||||
|
|
||||||
|
pl: Dict[str, Any] = {
|
||||||
|
"note_id": nid,
|
||||||
|
"chunk_id": cid,
|
||||||
|
"title": title,
|
||||||
|
"index": int(index),
|
||||||
|
"ord": int(index) + 1,
|
||||||
|
"type": note_type,
|
||||||
|
"tags": tags,
|
||||||
|
"text": text,
|
||||||
|
"window": window,
|
||||||
|
"neighbors_prev": _as_list(prev_id),
|
||||||
|
"neighbors_next": _as_list(next_id),
|
||||||
|
"section": getattr(ch, "section", None) or (ch.get("section") if isinstance(ch, dict) else ""),
|
||||||
|
"path": note_path,
|
||||||
|
"source_path": file_path or note_path,
|
||||||
|
"retriever_weight": float(rw),
|
||||||
|
"chunk_profile": cp, # Jetzt endlich mit dem Override-Wert!
|
||||||
|
}
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
for alias in ("chunk_num", "Chunk_Number"):
|
||||||
|
pl.pop(alias, None)
|
||||||
|
|
||||||
|
out.append(pl)
|
||||||
|
|
||||||
|
return out
|
||||||
+388
-190
@@ -1,226 +1,424 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/chunker.py
|
||||||
|
DESCRIPTION: Zerlegt Texte in Chunks (Sliding Window oder nach Headings). Orchestriert die Smart-Edge-Allocation via SemanticAnalyzer.
|
||||||
|
VERSION: 2.9.0 (Feat: Hybrid Strict Splitting with Size Safety)
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.services.semantic_analyzer, app.core.derive_edges, markdown_it, yaml, asyncio
|
||||||
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
|
LAST_ANALYSIS: 2025-12-16
|
||||||
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import List, Dict, Optional, Tuple
|
from typing import List, Dict, Optional, Tuple, Any, Set
|
||||||
import re
|
import re
|
||||||
import math
|
import math
|
||||||
from markdown_it import MarkdownIt
|
import yaml
|
||||||
from markdown_it.token import Token
|
from pathlib import Path
|
||||||
from .chunk_config import get_sizes
|
import asyncio
|
||||||
|
import logging
|
||||||
|
|
||||||
# --- Hilfen ---
|
# Services
|
||||||
_SENT_SPLIT = re.compile(r'(?<=[.!?])\s+(?=[A-ZÄÖÜ0-9„(])')
|
from app.services.semantic_analyzer import get_semantic_analyzer
|
||||||
_WS = re.compile(r'\s+')
|
|
||||||
|
# Core Imports
|
||||||
|
try:
|
||||||
|
from app.core.derive_edges import build_edges_for_note
|
||||||
|
except ImportError:
|
||||||
|
# Mock für Tests
|
||||||
|
def build_edges_for_note(note_id, chunks, note_level_references=None, include_note_scope_refs=False): return []
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# ==========================================
|
||||||
|
# 1. HELPER & CONFIG
|
||||||
|
# ==========================================
|
||||||
|
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
||||||
|
CONFIG_PATH = BASE_DIR / "config" / "types.yaml"
|
||||||
|
DEFAULT_PROFILE = {"strategy": "sliding_window", "target": 400, "max": 600, "overlap": (50, 80)}
|
||||||
|
_CONFIG_CACHE = None
|
||||||
|
|
||||||
|
def _load_yaml_config() -> Dict[str, Any]:
|
||||||
|
global _CONFIG_CACHE
|
||||||
|
if _CONFIG_CACHE is not None: return _CONFIG_CACHE
|
||||||
|
if not CONFIG_PATH.exists(): return {}
|
||||||
|
try:
|
||||||
|
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||||
|
data = yaml.safe_load(f)
|
||||||
|
_CONFIG_CACHE = data
|
||||||
|
return data
|
||||||
|
except Exception: return {}
|
||||||
|
|
||||||
|
def get_chunk_config(note_type: str) -> Dict[str, Any]:
|
||||||
|
full_config = _load_yaml_config()
|
||||||
|
profiles = full_config.get("chunking_profiles", {})
|
||||||
|
type_def = full_config.get("types", {}).get(note_type.lower(), {})
|
||||||
|
profile_name = type_def.get("chunking_profile")
|
||||||
|
if not profile_name:
|
||||||
|
profile_name = full_config.get("defaults", {}).get("chunking_profile", "sliding_standard")
|
||||||
|
|
||||||
|
config = profiles.get(profile_name, DEFAULT_PROFILE).copy()
|
||||||
|
if "overlap" in config and isinstance(config["overlap"], list):
|
||||||
|
config["overlap"] = tuple(config["overlap"])
|
||||||
|
return config
|
||||||
|
|
||||||
|
def extract_frontmatter_from_text(md_text: str) -> Tuple[Dict[str, Any], str]:
|
||||||
|
fm_match = re.match(r'^\s*---\s*\n(.*?)\n---', md_text, re.DOTALL)
|
||||||
|
if not fm_match: return {}, md_text
|
||||||
|
try:
|
||||||
|
frontmatter = yaml.safe_load(fm_match.group(1))
|
||||||
|
if not isinstance(frontmatter, dict): frontmatter = {}
|
||||||
|
except yaml.YAMLError:
|
||||||
|
frontmatter = {}
|
||||||
|
text_without_fm = re.sub(r'^\s*---\s*\n(.*?)\n---', '', md_text, flags=re.DOTALL)
|
||||||
|
return frontmatter, text_without_fm.strip()
|
||||||
|
|
||||||
|
# ==========================================
|
||||||
|
# 2. DATA CLASSES
|
||||||
|
# ==========================================
|
||||||
|
|
||||||
|
_SENT_SPLIT = re.compile(r'(?<=[.!?])\s+(?=[A-ZÄÖÜ0-9„(])'); _WS = re.compile(r'\s+')
|
||||||
|
|
||||||
def estimate_tokens(text: str) -> int:
|
def estimate_tokens(text: str) -> int:
|
||||||
# leichte Approximation: 1 Token ≈ 4 Zeichen; robust + schnell
|
return max(1, math.ceil(len(text.strip()) / 4))
|
||||||
t = len(text.strip())
|
|
||||||
return max(1, math.ceil(t / 4))
|
|
||||||
|
|
||||||
def split_sentences(text: str) -> list[str]:
|
def split_sentences(text: str) -> list[str]:
|
||||||
text = _WS.sub(' ', text.strip())
|
text = _WS.sub(' ', text.strip())
|
||||||
if not text:
|
if not text: return []
|
||||||
return []
|
|
||||||
parts = _SENT_SPLIT.split(text)
|
parts = _SENT_SPLIT.split(text)
|
||||||
return [p.strip() for p in parts if p.strip()]
|
return [p.strip() for p in parts if p.strip()]
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class RawBlock:
|
class RawBlock:
|
||||||
kind: str # "heading" | "paragraph" | "list" | "code" | "table" | "thematic_break" | "blockquote"
|
kind: str; text: str; level: Optional[int]; section_path: str; section_title: Optional[str]
|
||||||
text: str
|
|
||||||
level: Optional[int] # heading level (2,3,...) or None
|
|
||||||
section_path: str # e.g., "/H2 Title/H3 Subtitle"
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Chunk:
|
class Chunk:
|
||||||
id: str
|
id: str; note_id: str; index: int; text: str; window: str; token_count: int
|
||||||
note_id: str
|
section_title: Optional[str]; section_path: str
|
||||||
index: int
|
neighbors_prev: Optional[str]; neighbors_next: Optional[str]
|
||||||
text: str
|
suggested_edges: Optional[List[str]] = None
|
||||||
token_count: int
|
|
||||||
section_title: Optional[str]
|
|
||||||
section_path: str
|
|
||||||
neighbors_prev: Optional[str]
|
|
||||||
neighbors_next: Optional[str]
|
|
||||||
char_start: int
|
|
||||||
char_end: int
|
|
||||||
|
|
||||||
# --- Markdown zu RawBlocks: H2/H3 als Sections, andere Blöcke gruppiert ---
|
# ==========================================
|
||||||
def parse_blocks(md_text: str) -> List[RawBlock]:
|
# 3. PARSING & STRATEGIES
|
||||||
md = MarkdownIt("commonmark").enable("table")
|
# ==========================================
|
||||||
tokens: List[Token] = md.parse(md_text)
|
|
||||||
|
|
||||||
blocks: List[RawBlock] = []
|
def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
||||||
h2, h3 = None, None
|
"""Zerlegt Text in logische Blöcke (Absätze, Header)."""
|
||||||
|
blocks = []
|
||||||
|
h1_title = "Dokument"
|
||||||
section_path = "/"
|
section_path = "/"
|
||||||
cur_text = []
|
current_h2 = None
|
||||||
cur_kind = None
|
|
||||||
|
fm, text_without_fm = extract_frontmatter_from_text(md_text)
|
||||||
|
|
||||||
|
h1_match = re.search(r'^#\s+(.*)', text_without_fm, re.MULTILINE)
|
||||||
|
if h1_match:
|
||||||
|
h1_title = h1_match.group(1).strip()
|
||||||
|
|
||||||
def push(kind: str, txt: str, lvl: Optional[int]):
|
lines = text_without_fm.split('\n')
|
||||||
nonlocal section_path
|
buffer = []
|
||||||
txt = txt.strip()
|
|
||||||
if not txt:
|
for line in lines:
|
||||||
return
|
stripped = line.strip()
|
||||||
title = None
|
if stripped.startswith('# '):
|
||||||
if kind == "heading" and lvl:
|
if buffer:
|
||||||
title = txt
|
content = "\n".join(buffer).strip()
|
||||||
blocks.append(RawBlock(kind=kind, text=txt, level=lvl, section_path=section_path))
|
if content:
|
||||||
|
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
||||||
|
buffer = []
|
||||||
|
blocks.append(RawBlock("heading", stripped, 1, section_path, current_h2))
|
||||||
|
|
||||||
|
elif stripped.startswith('## '):
|
||||||
|
if buffer:
|
||||||
|
content = "\n".join(buffer).strip()
|
||||||
|
if content:
|
||||||
|
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
||||||
|
buffer = []
|
||||||
|
current_h2 = stripped[3:].strip()
|
||||||
|
section_path = f"/{current_h2}"
|
||||||
|
blocks.append(RawBlock("heading", stripped, 2, section_path, current_h2))
|
||||||
|
|
||||||
|
elif stripped.startswith('### '):
|
||||||
|
if buffer:
|
||||||
|
content = "\n".join(buffer).strip()
|
||||||
|
if content:
|
||||||
|
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
||||||
|
buffer = []
|
||||||
|
blocks.append(RawBlock("heading", stripped, 3, section_path, current_h2))
|
||||||
|
|
||||||
i = 0
|
elif not stripped:
|
||||||
while i < len(tokens):
|
if buffer:
|
||||||
t = tokens[i]
|
content = "\n".join(buffer).strip()
|
||||||
if t.type == "heading_open":
|
if content:
|
||||||
lvl = int(t.tag[1])
|
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
||||||
# Sammle heading inline
|
buffer = []
|
||||||
i += 1
|
|
||||||
title_txt = ""
|
|
||||||
while i < len(tokens) and tokens[i].type != "heading_close":
|
|
||||||
if tokens[i].type == "inline":
|
|
||||||
title_txt += tokens[i].content
|
|
||||||
i += 1
|
|
||||||
title_txt = title_txt.strip()
|
|
||||||
# Section-Pfad aktualisieren
|
|
||||||
if lvl == 2:
|
|
||||||
h2, h3 = title_txt, None
|
|
||||||
section_path = f"/{h2}"
|
|
||||||
elif lvl == 3:
|
|
||||||
h3 = title_txt
|
|
||||||
section_path = f"/{h2}/{h3}" if h2 else f"/{h3}"
|
|
||||||
push("heading", title_txt, lvl)
|
|
||||||
elif t.type in ("paragraph_open", "bullet_list_open", "ordered_list_open",
|
|
||||||
"fence", "code_block", "blockquote_open", "table_open", "hr"):
|
|
||||||
kind = {
|
|
||||||
"paragraph_open": "paragraph",
|
|
||||||
"bullet_list_open": "list",
|
|
||||||
"ordered_list_open": "list",
|
|
||||||
"fence": "code",
|
|
||||||
"code_block": "code",
|
|
||||||
"blockquote_open": "blockquote",
|
|
||||||
"table_open": "table",
|
|
||||||
"hr": "thematic_break",
|
|
||||||
}[t.type]
|
|
||||||
|
|
||||||
if t.type in ("fence", "code_block"):
|
|
||||||
# Codeblock hat eigenen content im selben Token
|
|
||||||
content = t.content or ""
|
|
||||||
push(kind, content, None)
|
|
||||||
else:
|
|
||||||
# inline sammeln bis close
|
|
||||||
content = ""
|
|
||||||
i += 1
|
|
||||||
depth = 1
|
|
||||||
while i < len(tokens) and depth > 0:
|
|
||||||
tk = tokens[i]
|
|
||||||
if tk.type.endswith("_open"):
|
|
||||||
depth += 1
|
|
||||||
elif tk.type.endswith("_close"):
|
|
||||||
depth -= 1
|
|
||||||
elif tk.type == "inline":
|
|
||||||
content += tk.content
|
|
||||||
i += 1
|
|
||||||
push(kind, content, None)
|
|
||||||
continue # wir sind schon auf nächstem Token
|
|
||||||
i += 1
|
|
||||||
|
|
||||||
return blocks
|
|
||||||
|
|
||||||
def assemble_chunks(note_id: str, md_text: str, note_type: str) -> List[Chunk]:
|
|
||||||
sizes = get_sizes(note_type)
|
|
||||||
target = sum(sizes["target"]) // 2 # mittlerer Zielwert
|
|
||||||
max_tokens = sizes["max"]
|
|
||||||
ov_min, ov_max = sizes["overlap"]
|
|
||||||
overlap = (ov_min + ov_max) // 2
|
|
||||||
|
|
||||||
blocks = parse_blocks(md_text)
|
|
||||||
|
|
||||||
chunks: List[Chunk] = []
|
|
||||||
buf: List[Tuple[str, str, str]] = [] # (text, section_title, section_path)
|
|
||||||
char_pos = 0
|
|
||||||
|
|
||||||
def flush_buffer(force=False):
|
|
||||||
nonlocal buf, chunks, char_pos
|
|
||||||
if not buf:
|
|
||||||
return
|
|
||||||
text = "\n\n".join([b[0] for b in buf]).strip()
|
|
||||||
if not text:
|
|
||||||
buf = []
|
|
||||||
return
|
|
||||||
|
|
||||||
# Wenn zu groß, satzbasiert weich umbrechen
|
|
||||||
toks = estimate_tokens(text)
|
|
||||||
if toks > max_tokens:
|
|
||||||
sentences = split_sentences(text)
|
|
||||||
cur = []
|
|
||||||
cur_tokens = 0
|
|
||||||
for s in sentences:
|
|
||||||
st = estimate_tokens(s)
|
|
||||||
if cur_tokens + st > target and cur:
|
|
||||||
_emit("\n".join(cur))
|
|
||||||
# Overlap: letzte Sätze wiederverwenden
|
|
||||||
ov_text = " ".join(cur)[-overlap*4:] # 4 chars/token Heuristik
|
|
||||||
cur = [ov_text, s] if ov_text else [s]
|
|
||||||
cur_tokens = estimate_tokens(" ".join(cur))
|
|
||||||
else:
|
|
||||||
cur.append(s)
|
|
||||||
cur_tokens += st
|
|
||||||
if cur:
|
|
||||||
_emit("\n".join(cur))
|
|
||||||
else:
|
else:
|
||||||
_emit(text)
|
buffer.append(line)
|
||||||
|
|
||||||
|
if buffer:
|
||||||
|
content = "\n".join(buffer).strip()
|
||||||
|
if content:
|
||||||
|
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
||||||
|
|
||||||
|
return blocks, h1_title
|
||||||
|
|
||||||
|
def _create_chunk_obj(chunks_list: List[Chunk], note_id: str, txt: str, win: str, sec: Optional[str], path: str):
|
||||||
|
idx = len(chunks_list)
|
||||||
|
chunks_list.append(Chunk(
|
||||||
|
id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx,
|
||||||
|
text=txt, window=win, token_count=estimate_tokens(txt),
|
||||||
|
section_title=sec, section_path=path, neighbors_prev=None, neighbors_next=None,
|
||||||
|
suggested_edges=[]
|
||||||
|
))
|
||||||
|
|
||||||
|
def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "", context_prefix: str = "") -> List[Chunk]:
|
||||||
|
target = config.get("target", 400)
|
||||||
|
max_tokens = config.get("max", 600)
|
||||||
|
overlap_val = config.get("overlap", (50, 80))
|
||||||
|
overlap = sum(overlap_val) // 2 if isinstance(overlap_val, tuple) else overlap_val
|
||||||
|
chunks = []; buf = []
|
||||||
|
|
||||||
|
def flush_buffer():
|
||||||
|
nonlocal buf
|
||||||
|
if not buf: return
|
||||||
|
|
||||||
|
text_body = "\n\n".join([b.text for b in buf])
|
||||||
|
win_body = f"{context_prefix}\n{text_body}".strip() if context_prefix else text_body
|
||||||
|
|
||||||
|
# Basis-Info vom ersten Block im Buffer
|
||||||
|
sec = buf[0].section_title if buf else None
|
||||||
|
path = buf[0].section_path if buf else "/"
|
||||||
|
|
||||||
|
if estimate_tokens(text_body) <= max_tokens:
|
||||||
|
_create_chunk_obj(chunks, note_id, text_body, win_body, sec, path)
|
||||||
|
else:
|
||||||
|
# Fallback: Wenn Block zu groß, intern splitten (Sentence-Level)
|
||||||
|
sentences = split_sentences(text_body)
|
||||||
|
current_chunk_sents = []
|
||||||
|
current_len = 0
|
||||||
|
|
||||||
|
for sent in sentences:
|
||||||
|
sent_len = estimate_tokens(sent)
|
||||||
|
if current_len + sent_len > target and current_chunk_sents:
|
||||||
|
c_txt = " ".join(current_chunk_sents)
|
||||||
|
c_win = f"{context_prefix}\n{c_txt}".strip() if context_prefix else c_txt
|
||||||
|
_create_chunk_obj(chunks, note_id, c_txt, c_win, sec, path)
|
||||||
|
|
||||||
|
overlap_sents = []
|
||||||
|
ov_len = 0
|
||||||
|
for s in reversed(current_chunk_sents):
|
||||||
|
if ov_len + estimate_tokens(s) < overlap:
|
||||||
|
overlap_sents.insert(0, s)
|
||||||
|
ov_len += estimate_tokens(s)
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
current_chunk_sents = list(overlap_sents)
|
||||||
|
current_chunk_sents.append(sent)
|
||||||
|
current_len = ov_len + sent_len
|
||||||
|
else:
|
||||||
|
current_chunk_sents.append(sent)
|
||||||
|
current_len += sent_len
|
||||||
|
|
||||||
|
if current_chunk_sents:
|
||||||
|
c_txt = " ".join(current_chunk_sents)
|
||||||
|
c_win = f"{context_prefix}\n{c_txt}".strip() if context_prefix else c_txt
|
||||||
|
_create_chunk_obj(chunks, note_id, c_txt, c_win, sec, path)
|
||||||
|
|
||||||
buf = []
|
buf = []
|
||||||
|
|
||||||
def _emit(text_block: str):
|
|
||||||
nonlocal chunks, char_pos
|
|
||||||
idx = len(chunks)
|
|
||||||
chunk_id = f"{note_id}#c{idx:02d}"
|
|
||||||
token_count = estimate_tokens(text_block)
|
|
||||||
# section aus letztem buffer-entry ableiten
|
|
||||||
sec_title = buf[-1][1] if buf else None
|
|
||||||
sec_path = buf[-1][2] if buf else "/"
|
|
||||||
start = char_pos
|
|
||||||
end = start + len(text_block)
|
|
||||||
chunks.append(Chunk(
|
|
||||||
id=chunk_id,
|
|
||||||
note_id=note_id,
|
|
||||||
index=idx,
|
|
||||||
text=text_block,
|
|
||||||
token_count=token_count,
|
|
||||||
section_title=sec_title,
|
|
||||||
section_path=sec_path,
|
|
||||||
neighbors_prev=None,
|
|
||||||
neighbors_next=None,
|
|
||||||
char_start=start,
|
|
||||||
char_end=end
|
|
||||||
))
|
|
||||||
char_pos = end + 1
|
|
||||||
|
|
||||||
# Blocks in Puffer sammeln; bei Überschreiten Zielbereich flushen
|
|
||||||
cur_sec_title = None
|
|
||||||
for b in blocks:
|
for b in blocks:
|
||||||
if b.kind == "heading" and b.level in (2, 3):
|
if b.kind == "heading":
|
||||||
# Sectionwechsel ⇒ Buffer flushen
|
|
||||||
flush_buffer()
|
flush_buffer()
|
||||||
cur_sec_title = b.text.strip()
|
|
||||||
# Heading selbst nicht als Chunk, aber als Kontexttitel nutzen
|
current_buf_text = "\n\n".join([x.text for x in buf])
|
||||||
continue
|
if buf and (estimate_tokens(current_buf_text) + estimate_tokens(b.text) >= target):
|
||||||
|
|
||||||
txt = b.text.strip()
|
|
||||||
if not txt:
|
|
||||||
continue
|
|
||||||
|
|
||||||
tentative = "\n\n".join([*(x[0] for x in buf), txt]).strip()
|
|
||||||
if estimate_tokens(tentative) > max(get_sizes(note_type)["target"]):
|
|
||||||
# weicher Schnitt vor Hinzufügen
|
|
||||||
flush_buffer()
|
flush_buffer()
|
||||||
buf.append((txt, cur_sec_title, b.section_path))
|
|
||||||
|
buf.append(b)
|
||||||
|
|
||||||
|
flush_buffer()
|
||||||
|
return chunks
|
||||||
|
|
||||||
# bei Erreichen ~Target flushen
|
def _strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
|
||||||
if estimate_tokens("\n\n".join([x[0] for x in buf])) >= target:
|
"""
|
||||||
flush_buffer()
|
MODUS: Structured / Heading Split
|
||||||
|
- split_level: Ebene für logische Trennung (z.B. H2).
|
||||||
|
- strict_heading_split:
|
||||||
|
True: Trennt an jedem Header <= split_level.
|
||||||
|
NEU v2.9: Wenn Inhalt > max_tokens, wird trotzdem gesplittet (Safety Split).
|
||||||
|
False: Fasst zusammen bis 'target' erreicht ist.
|
||||||
|
"""
|
||||||
|
split_level = config.get("split_level", 2)
|
||||||
|
target = config.get("target", 400)
|
||||||
|
max_limit = config.get("max", 600)
|
||||||
|
strict_mode = config.get("strict_heading_split", False)
|
||||||
|
|
||||||
|
chunks = []
|
||||||
|
current_chunk_blocks = []
|
||||||
|
|
||||||
|
context_prefix = f"# {doc_title}"
|
||||||
|
|
||||||
flush_buffer(force=True)
|
def has_content(blk_list):
|
||||||
|
return any(b.kind != "heading" for b in blk_list)
|
||||||
|
|
||||||
|
def flush_current_chunk():
|
||||||
|
nonlocal current_chunk_blocks
|
||||||
|
if not current_chunk_blocks:
|
||||||
|
return
|
||||||
|
|
||||||
|
text_body = "\n\n".join([b.text for b in current_chunk_blocks])
|
||||||
|
win_body = f"{context_prefix}\n{text_body}".strip()
|
||||||
|
|
||||||
|
first_b = current_chunk_blocks[0]
|
||||||
|
sec = first_b.section_title
|
||||||
|
path = first_b.section_path
|
||||||
|
|
||||||
|
_create_chunk_obj(chunks, note_id, text_body, win_body, sec, path)
|
||||||
|
current_chunk_blocks = []
|
||||||
|
|
||||||
|
def get_current_size():
|
||||||
|
txt = "\n\n".join([b.text for b in current_chunk_blocks])
|
||||||
|
return estimate_tokens(txt)
|
||||||
|
|
||||||
|
for b in blocks:
|
||||||
|
# 1. Header Logic (Struktur-Trigger)
|
||||||
|
is_splitter = (b.kind == "heading" and b.level is not None and b.level <= split_level)
|
||||||
|
|
||||||
|
if is_splitter:
|
||||||
|
is_higher_hierarchy = (b.level < split_level)
|
||||||
|
|
||||||
|
if strict_mode:
|
||||||
|
# STRICT:
|
||||||
|
# Wir splitten immer, außer der Vor-Chunk ist leer.
|
||||||
|
if current_chunk_blocks and has_content(current_chunk_blocks):
|
||||||
|
flush_current_chunk()
|
||||||
|
current_chunk_blocks.append(b)
|
||||||
|
else:
|
||||||
|
# SOFT:
|
||||||
|
# Split bei Hierarchie-Wechsel ODER wenn voll.
|
||||||
|
if is_higher_hierarchy:
|
||||||
|
flush_current_chunk()
|
||||||
|
current_chunk_blocks.append(b)
|
||||||
|
elif current_chunk_blocks and get_current_size() >= target:
|
||||||
|
flush_current_chunk()
|
||||||
|
current_chunk_blocks.append(b)
|
||||||
|
else:
|
||||||
|
current_chunk_blocks.append(b)
|
||||||
|
else:
|
||||||
|
# 2. Content Logic (Safety Trigger für Monster-Abschnitte)
|
||||||
|
# Bevor wir den Block anhängen: Würde er das Fass zum Überlaufen bringen?
|
||||||
|
# Wir nutzen hier 'max' als harte Grenze für den Safety-Split.
|
||||||
|
current_size = get_current_size()
|
||||||
|
block_size = estimate_tokens(b.text)
|
||||||
|
|
||||||
|
if current_chunk_blocks and (current_size + block_size > max_limit):
|
||||||
|
# NOTBREMSE: Chunk wird zu groß.
|
||||||
|
# Wir splitten hier, auch wenn kein Header da ist.
|
||||||
|
# Der Kontext (Section Title) bleibt erhalten, da er aus `current_h2` kommt (siehe parse_blocks).
|
||||||
|
flush_current_chunk()
|
||||||
|
current_chunk_blocks.append(b)
|
||||||
|
else:
|
||||||
|
current_chunk_blocks.append(b)
|
||||||
|
|
||||||
|
# Letzten Rest flushen
|
||||||
|
flush_current_chunk()
|
||||||
|
|
||||||
|
return chunks
|
||||||
|
|
||||||
|
# ==========================================
|
||||||
|
# 4. ORCHESTRATION (ASYNC)
|
||||||
|
# ==========================================
|
||||||
|
|
||||||
|
async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Optional[Dict] = None) -> List[Chunk]:
|
||||||
|
if config is None:
|
||||||
|
config = get_chunk_config(note_type)
|
||||||
|
|
||||||
|
fm, body_text = extract_frontmatter_from_text(md_text)
|
||||||
|
note_status = fm.get("status", "").lower()
|
||||||
|
|
||||||
|
primary_strategy = config.get("strategy", "sliding_window")
|
||||||
|
enable_smart_edges = config.get("enable_smart_edge_allocation", False)
|
||||||
|
|
||||||
|
if enable_smart_edges and note_status in ["draft", "initial_gen"]:
|
||||||
|
logger.info(f"Chunker: Skipping Smart Edges for draft '{note_id}'.")
|
||||||
|
enable_smart_edges = False
|
||||||
|
|
||||||
|
blocks, doc_title = parse_blocks(md_text)
|
||||||
|
|
||||||
|
if primary_strategy == "by_heading":
|
||||||
|
chunks = await asyncio.to_thread(_strategy_by_heading, blocks, config, note_id, doc_title)
|
||||||
|
else:
|
||||||
|
chunks = await asyncio.to_thread(_strategy_sliding_window, blocks, config, note_id, doc_title)
|
||||||
|
|
||||||
|
if not chunks:
|
||||||
|
return []
|
||||||
|
|
||||||
|
if enable_smart_edges:
|
||||||
|
chunks = await _run_smart_edge_allocation(chunks, md_text, note_id, note_type)
|
||||||
|
|
||||||
# neighbors setzen
|
|
||||||
for i, ch in enumerate(chunks):
|
for i, ch in enumerate(chunks):
|
||||||
ch.neighbors_prev = chunks[i-1].id if i > 0 else None
|
ch.neighbors_prev = chunks[i-1].id if i > 0 else None
|
||||||
ch.neighbors_next = chunks[i+1].id if i < len(chunks)-1 else None
|
ch.neighbors_next = chunks[i+1].id if i < len(chunks)-1 else None
|
||||||
|
|
||||||
return chunks
|
return chunks
|
||||||
|
|
||||||
|
def _extract_all_edges_from_md(md_text: str, note_id: str, note_type: str) -> List[str]:
|
||||||
|
dummy_chunk = {
|
||||||
|
"chunk_id": f"{note_id}#full",
|
||||||
|
"text": md_text,
|
||||||
|
"content": md_text,
|
||||||
|
"window": md_text,
|
||||||
|
"type": note_type
|
||||||
|
}
|
||||||
|
raw_edges = build_edges_for_note(
|
||||||
|
note_id,
|
||||||
|
[dummy_chunk],
|
||||||
|
note_level_references=None,
|
||||||
|
include_note_scope_refs=False
|
||||||
|
)
|
||||||
|
all_candidates = set()
|
||||||
|
for e in raw_edges:
|
||||||
|
kind = e.get("kind")
|
||||||
|
target = e.get("target_id")
|
||||||
|
if target and kind not in ["belongs_to", "next", "prev", "backlink"]:
|
||||||
|
all_candidates.add(f"{kind}:{target}")
|
||||||
|
return list(all_candidates)
|
||||||
|
|
||||||
|
async def _run_smart_edge_allocation(chunks: List[Chunk], full_text: str, note_id: str, note_type: str) -> List[Chunk]:
|
||||||
|
analyzer = get_semantic_analyzer()
|
||||||
|
candidate_list = _extract_all_edges_from_md(full_text, note_id, note_type)
|
||||||
|
|
||||||
|
if not candidate_list:
|
||||||
|
return chunks
|
||||||
|
|
||||||
|
tasks = []
|
||||||
|
for chunk in chunks:
|
||||||
|
tasks.append(analyzer.assign_edges_to_chunk(chunk.text, candidate_list, note_type))
|
||||||
|
|
||||||
|
results_per_chunk = await asyncio.gather(*tasks)
|
||||||
|
|
||||||
|
assigned_edges_global = set()
|
||||||
|
|
||||||
|
for i, confirmed_edges in enumerate(results_per_chunk):
|
||||||
|
chunk = chunks[i]
|
||||||
|
chunk.suggested_edges = confirmed_edges
|
||||||
|
assigned_edges_global.update(confirmed_edges)
|
||||||
|
|
||||||
|
if confirmed_edges:
|
||||||
|
injection_str = "\n" + " ".join([f"[[rel:{e.split(':')[0]}|{e.split(':')[1]}]]" for e in confirmed_edges if ':' in e])
|
||||||
|
chunk.text += injection_str
|
||||||
|
chunk.window += injection_str
|
||||||
|
|
||||||
|
unassigned = set(candidate_list) - assigned_edges_global
|
||||||
|
if unassigned:
|
||||||
|
fallback_str = "\n" + " ".join([f"[[rel:{e.split(':')[0]}|{e.split(':')[1]}]]" for e in unassigned if ':' in e])
|
||||||
|
for chunk in chunks:
|
||||||
|
chunk.text += fallback_str
|
||||||
|
chunk.window += fallback_str
|
||||||
|
if chunk.suggested_edges is None: chunk.suggested_edges = []
|
||||||
|
chunk.suggested_edges.extend(list(unassigned))
|
||||||
|
|
||||||
|
return chunks
|
||||||
+405
-111
@@ -1,126 +1,420 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
Name: app/core/derive_edges.py
|
FILE: app/core/derive_edges.py
|
||||||
Version: v1.1.0 (2025-09-05)
|
DESCRIPTION: Extrahiert Graph-Kanten aus Text. Unterstützt Wikilinks, Inline-Relations ([[rel:type|target]]) und Obsidian Callouts.
|
||||||
|
VERSION: 2.0.0
|
||||||
Kurzbeschreibung
|
STATUS: Active
|
||||||
Leitet Edges aus Wikilinks ([[…]]) ab und löst Zielnoten robust auf.
|
DEPENDENCIES: re, os, yaml, typing
|
||||||
Erzeugt:
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
- "references" (Note -> Note) mit seq="body", pro Match eine eigene Occurrence 'occ'
|
LAST_ANALYSIS: 2025-12-15
|
||||||
- "backlink" (inverse zu "references", gleiche seq/occ)
|
|
||||||
- "references_at" (Chunk -> Note) mit seq=<chunk_index> und eigener 'occ' je Match
|
|
||||||
|
|
||||||
Aufruf
|
|
||||||
from app.core.derive_edges import build_note_index, derive_wikilink_edges
|
|
||||||
|
|
||||||
Parameter / Felder
|
|
||||||
- note_payload: {"note_id","title","path","fulltext": <body> , …}
|
|
||||||
- chunks_payloads: [{"chunk_id","text",…}, …]
|
|
||||||
- note_index: build_note_index([...]) -> (by_id, by_slug, by_file_slug)
|
|
||||||
|
|
||||||
Kompatibilität
|
|
||||||
- Rückwärtskompatible Payload-Felder, nur erweitert um 'seq' und 'occ'.
|
|
||||||
|
|
||||||
Changelog
|
|
||||||
v1.1.0: Occurrence-Zählung ('occ') je Match; 'seq="body"' für references.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
import re
|
import re
|
||||||
import unicodedata
|
from typing import Iterable, List, Optional, Tuple, Set, Dict
|
||||||
from typing import Dict, List, Tuple
|
|
||||||
|
|
||||||
# [[Ziel]], [[Ziel|Alias]], [[Ziel#Heading]], [[Ziel#Heading|Alias]]
|
try:
|
||||||
WIKILINK_RE = re.compile(r"\[\[([^\]|#]+)(?:#([^\]|]+))?(?:\|([^\]]+))?\]\]")
|
import yaml # optional, nur für types.yaml
|
||||||
|
except Exception: # pragma: no cover
|
||||||
|
yaml = None
|
||||||
|
|
||||||
def _slug(s: str) -> str:
|
# --------------------------------------------------------------------------- #
|
||||||
s = s.strip()
|
# Utilities
|
||||||
if s.endswith(".md"):
|
# --------------------------------------------------------------------------- #
|
||||||
s = s[:-3]
|
|
||||||
s = unicodedata.normalize("NFKD", s)
|
|
||||||
s = "".join(ch for ch in s if not unicodedata.combining(ch))
|
|
||||||
s = s.replace("\\", "/")
|
|
||||||
s = s.split("/")[-1]
|
|
||||||
s = s.lower().replace(" ", "-")
|
|
||||||
s = re.sub(r"[^a-z0-9\-]+", "", s)
|
|
||||||
s = re.sub(r"-{2,}", "-", s).strip("-")
|
|
||||||
return s
|
|
||||||
|
|
||||||
def build_note_index(notes_payloads: List[dict]) -> Tuple[Dict[str, dict], Dict[str, dict], Dict[str, dict]]:
|
def _get(d: dict, *keys, default=None):
|
||||||
by_id: Dict[str, dict] = {}
|
for k in keys:
|
||||||
by_slug: Dict[str, dict] = {}
|
if isinstance(d, dict) and k in d and d[k] is not None:
|
||||||
by_file_slug: Dict[str, dict] = {}
|
return d[k]
|
||||||
for n in notes_payloads:
|
return default
|
||||||
nid = n.get("note_id") or n.get("id")
|
|
||||||
if not nid:
|
def _chunk_text_for_refs(chunk: dict) -> str:
|
||||||
|
# bevorzugt 'window' → dann 'text' → 'content' → 'raw'
|
||||||
|
return (
|
||||||
|
_get(chunk, "window")
|
||||||
|
or _get(chunk, "text")
|
||||||
|
or _get(chunk, "content")
|
||||||
|
or _get(chunk, "raw")
|
||||||
|
or ""
|
||||||
|
)
|
||||||
|
|
||||||
|
def _dedupe_seq(seq: Iterable[str]) -> List[str]:
|
||||||
|
seen: Set[str] = set()
|
||||||
|
out: List[str] = []
|
||||||
|
for s in seq:
|
||||||
|
if s not in seen:
|
||||||
|
seen.add(s)
|
||||||
|
out.append(s)
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _edge(kind: str, scope: str, source_id: str, target_id: str, note_id: str, extra: Optional[dict] = None) -> dict:
|
||||||
|
pl = {
|
||||||
|
"kind": kind,
|
||||||
|
"relation": kind, # Alias (v2)
|
||||||
|
"scope": scope, # "chunk" | "note"
|
||||||
|
"source_id": source_id,
|
||||||
|
"target_id": target_id,
|
||||||
|
"note_id": note_id, # Träger-Note der Kante
|
||||||
|
}
|
||||||
|
if extra:
|
||||||
|
pl.update(extra)
|
||||||
|
return pl
|
||||||
|
|
||||||
|
def _mk_edge_id(kind: str, s: str, t: str, scope: str, rule_id: Optional[str] = None) -> str:
|
||||||
|
base = f"{kind}:{s}->{t}#{scope}"
|
||||||
|
if rule_id:
|
||||||
|
base += f"|{rule_id}"
|
||||||
|
try:
|
||||||
|
import hashlib
|
||||||
|
return hashlib.blake2s(base.encode("utf-8"), digest_size=12).hexdigest()
|
||||||
|
except Exception: # pragma: no cover
|
||||||
|
return base
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Typen-Registry (types.yaml)
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def _env(n: str, default: Optional[str] = None) -> str:
|
||||||
|
v = os.getenv(n)
|
||||||
|
return v if v is not None else (default or "")
|
||||||
|
|
||||||
|
def _load_types_registry() -> dict:
|
||||||
|
"""Lädt die YAML-Registry aus MINDNET_TYPES_FILE oder ./config/types.yaml"""
|
||||||
|
p = _env("MINDNET_TYPES_FILE", "./config/types.yaml")
|
||||||
|
if not os.path.isfile(p) or yaml is None:
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
with open(p, "r", encoding="utf-8") as f:
|
||||||
|
data = yaml.safe_load(f) or {}
|
||||||
|
return data
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _get_types_map(reg: dict) -> dict:
|
||||||
|
if isinstance(reg, dict) and isinstance(reg.get("types"), dict):
|
||||||
|
return reg["types"]
|
||||||
|
return reg if isinstance(reg, dict) else {}
|
||||||
|
|
||||||
|
def _edge_defaults_for(note_type: Optional[str], reg: dict) -> List[str]:
|
||||||
|
"""
|
||||||
|
Liefert die edge_defaults-Liste für den gegebenen Notiztyp.
|
||||||
|
Fallback-Reihenfolge:
|
||||||
|
1) reg['types'][note_type]['edge_defaults']
|
||||||
|
2) reg['defaults']['edge_defaults'] (oder 'default'/'global')
|
||||||
|
3) []
|
||||||
|
"""
|
||||||
|
types_map = _get_types_map(reg)
|
||||||
|
if note_type and isinstance(types_map, dict):
|
||||||
|
t = types_map.get(note_type)
|
||||||
|
if isinstance(t, dict) and isinstance(t.get("edge_defaults"), list):
|
||||||
|
return [str(x) for x in t["edge_defaults"] if isinstance(x, str)]
|
||||||
|
for key in ("defaults", "default", "global"):
|
||||||
|
v = reg.get(key)
|
||||||
|
if isinstance(v, dict) and isinstance(v.get("edge_defaults"), list):
|
||||||
|
return [str(x) for x in v["edge_defaults"] if isinstance(x, str)]
|
||||||
|
return []
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Parser für Links / Relationen
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
# Normale Wikilinks (Fallback)
|
||||||
|
_WIKILINK_RE = re.compile(r"\[\[(?:[^\|\]]+\|)?([a-zA-Z0-9_\-#:. ]+)\]\]")
|
||||||
|
|
||||||
|
# Getypte Inline-Relationen:
|
||||||
|
# [[rel:KIND | Target]]
|
||||||
|
# [[rel:KIND Target]]
|
||||||
|
_REL_PIPE = re.compile(r"\[\[\s*rel:(?P<kind>[a-z_]+)\s*\|\s*(?P<target>[^\]]+?)\s*\]\]", re.IGNORECASE)
|
||||||
|
_REL_SPACE = re.compile(r"\[\[\s*rel:(?P<kind>[a-z_]+)\s+(?P<target>[^\]]+?)\s*\]\]", re.IGNORECASE)
|
||||||
|
# rel: KIND [[Target]] (reines Textmuster)
|
||||||
|
_REL_TEXT = re.compile(r"rel\s*:\s*(?P<kind>[a-z_]+)\s*\[\[\s*(?P<target>[^\]]+?)\s*\]\]", re.IGNORECASE)
|
||||||
|
|
||||||
|
def _extract_typed_relations(text: str) -> Tuple[List[Tuple[str,str]], str]:
|
||||||
|
"""
|
||||||
|
Gibt Liste (kind, target) zurück und den Text mit entfernten getypten Relation-Links,
|
||||||
|
damit die generische Wikilink-Erkennung sie nicht doppelt zählt.
|
||||||
|
Unterstützt drei Varianten:
|
||||||
|
- [[rel:KIND | Target]]
|
||||||
|
- [[rel:KIND Target]]
|
||||||
|
- rel: KIND [[Target]]
|
||||||
|
"""
|
||||||
|
pairs: List[Tuple[str,str]] = []
|
||||||
|
def _collect(m):
|
||||||
|
k = (m.group("kind") or "").strip().lower()
|
||||||
|
t = (m.group("target") or "").strip()
|
||||||
|
if k and t:
|
||||||
|
pairs.append((k, t))
|
||||||
|
return "" # Link entfernen
|
||||||
|
|
||||||
|
text = _REL_PIPE.sub(_collect, text)
|
||||||
|
text = _REL_SPACE.sub(_collect, text)
|
||||||
|
text = _REL_TEXT.sub(_collect, text)
|
||||||
|
return pairs, text
|
||||||
|
|
||||||
|
# Obsidian Callout Parser
|
||||||
|
_CALLOUT_START = re.compile(r"^\s*>\s*\[!edge\]\s*(.*)$", re.IGNORECASE)
|
||||||
|
_REL_LINE = re.compile(r"^(?P<kind>[a-z_]+)\s*:\s*(?P<targets>.+?)\s*$", re.IGNORECASE)
|
||||||
|
_WIKILINKS_IN_LINE = re.compile(r"\[\[([^\]]+)\]\]")
|
||||||
|
|
||||||
|
def _extract_callout_relations(text: str) -> Tuple[List[Tuple[str,str]], str]:
|
||||||
|
"""
|
||||||
|
Findet [!edge]-Callouts und extrahiert (kind, target). Entfernt den gesamten
|
||||||
|
Callout-Block aus dem Text (damit Wikilinks daraus nicht zusätzlich als
|
||||||
|
"references" gezählt werden).
|
||||||
|
"""
|
||||||
|
if not text:
|
||||||
|
return [], text
|
||||||
|
|
||||||
|
lines = text.splitlines()
|
||||||
|
out_pairs: List[Tuple[str,str]] = []
|
||||||
|
keep_lines: List[str] = []
|
||||||
|
i = 0
|
||||||
|
|
||||||
|
while i < len(lines):
|
||||||
|
m = _CALLOUT_START.match(lines[i])
|
||||||
|
if not m:
|
||||||
|
keep_lines.append(lines[i])
|
||||||
|
i += 1
|
||||||
continue
|
continue
|
||||||
by_id[nid] = n
|
|
||||||
title = n.get("title", "")
|
|
||||||
path = n.get("path", "")
|
|
||||||
file_slug = _slug(path.split("/")[-1]) if path else ""
|
|
||||||
if title:
|
|
||||||
by_slug[_slug(title)] = n
|
|
||||||
if file_slug:
|
|
||||||
by_file_slug[file_slug] = n
|
|
||||||
return by_id, by_slug, by_file_slug
|
|
||||||
|
|
||||||
def resolve_target(note_like: str, idx: Tuple[Dict[str,dict],Dict[str,dict],Dict[str,dict]]):
|
block_lines: List[str] = []
|
||||||
by_id, by_slug, by_file_slug = idx
|
first_rest = m.group(1) or ""
|
||||||
key = note_like.strip()
|
if first_rest.strip():
|
||||||
if key in by_id:
|
block_lines.append(first_rest)
|
||||||
return by_id[key]["note_id"], "by_id"
|
|
||||||
s = _slug(key)
|
|
||||||
if s in by_slug:
|
|
||||||
return by_slug[s]["note_id"], "by_slug"
|
|
||||||
if s in by_file_slug:
|
|
||||||
return by_file_slug[s]["note_id"], "by_file_slug"
|
|
||||||
return None, "unresolved"
|
|
||||||
|
|
||||||
def derive_wikilink_edges(note_payload: dict, chunks_payloads: List[dict], note_index) -> List[dict]:
|
i += 1
|
||||||
|
while i < len(lines) and lines[i].lstrip().startswith('>'):
|
||||||
|
block_lines.append(lines[i].lstrip()[1:].lstrip())
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
for bl in block_lines:
|
||||||
|
mrel = _REL_LINE.match(bl)
|
||||||
|
if not mrel:
|
||||||
|
continue
|
||||||
|
kind = (mrel.group("kind") or "").strip().lower()
|
||||||
|
targets = mrel.group("targets") or ""
|
||||||
|
found = _WIKILINKS_IN_LINE.findall(targets)
|
||||||
|
if found:
|
||||||
|
for t in found:
|
||||||
|
t = t.strip()
|
||||||
|
if t:
|
||||||
|
out_pairs.append((kind, t))
|
||||||
|
else:
|
||||||
|
for raw in re.split(r"[,;]", targets):
|
||||||
|
t = raw.strip()
|
||||||
|
if t:
|
||||||
|
out_pairs.append((kind, t))
|
||||||
|
|
||||||
|
# Callout wird NICHT in keep_lines übernommen
|
||||||
|
continue
|
||||||
|
|
||||||
|
remainder = "\n".join(keep_lines)
|
||||||
|
return out_pairs, remainder
|
||||||
|
|
||||||
|
def _extract_wikilinks(text: str) -> List[str]:
|
||||||
|
ids: List[str] = []
|
||||||
|
for m in _WIKILINK_RE.finditer(text or ""):
|
||||||
|
ids.append(m.group(1).strip())
|
||||||
|
return ids
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Hauptfunktion
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def build_edges_for_note(
|
||||||
|
note_id: str,
|
||||||
|
chunks: List[dict],
|
||||||
|
note_level_references: Optional[List[str]] = None,
|
||||||
|
include_note_scope_refs: bool = False,
|
||||||
|
) -> List[dict]:
|
||||||
|
"""
|
||||||
|
Erzeugt Kanten für eine Note.
|
||||||
|
|
||||||
|
- belongs_to: für jeden Chunk (chunk -> note)
|
||||||
|
- next / prev: zwischen aufeinanderfolgenden Chunks
|
||||||
|
- references: pro Chunk aus window/text (via Wikilinks)
|
||||||
|
- typed inline relations: [[rel:KIND | Target]] / [[rel:KIND Target]] / rel: KIND [[Target]]
|
||||||
|
- Obsidian Callouts: > [!edge] KIND: [[Target]] [[Target2]]
|
||||||
|
- optional note-scope references/backlinks: dedupliziert über alle Chunk-Funde + note_level_references
|
||||||
|
- typenbasierte Default-Kanten (edge_defaults) je gefundener Referenz
|
||||||
|
"""
|
||||||
edges: List[dict] = []
|
edges: List[dict] = []
|
||||||
source_note_id = note_payload["note_id"]
|
|
||||||
|
|
||||||
def _make_edge(kind: str, src: str, tgt: str, seq=None, occ=None, extra: dict|None=None):
|
# Note-Typ (aus erstem Chunk erwartet)
|
||||||
e = {"edge_id": None, "kind": kind, "source_id": src, "target_id": tgt}
|
note_type = None
|
||||||
if seq is not None:
|
if chunks:
|
||||||
e["seq"] = seq
|
note_type = _get(chunks[0], "type")
|
||||||
if occ is not None:
|
|
||||||
e["occ"] = occ
|
|
||||||
if extra:
|
|
||||||
e.update(extra)
|
|
||||||
return e
|
|
||||||
|
|
||||||
# Volltext (Note-Ebene)
|
# 1) belongs_to
|
||||||
fulltext = note_payload.get("fulltext") or note_payload.get("body") or ""
|
for ch in chunks:
|
||||||
if fulltext:
|
cid = _get(ch, "chunk_id", "id")
|
||||||
for k, m in enumerate(WIKILINK_RE.finditer(fulltext), start=1):
|
if not cid:
|
||||||
raw_target, heading, alias = m.groups()
|
|
||||||
target_id, how = resolve_target(raw_target, note_index)
|
|
||||||
extra = {"raw": raw_target, "alias": alias, "heading": heading, "resolution": how}
|
|
||||||
if target_id:
|
|
||||||
edges.append(_make_edge("references", source_note_id, target_id, seq="body", occ=k, extra=extra))
|
|
||||||
edges.append(_make_edge("backlink", target_id, source_note_id, seq="body", occ=k, extra=extra))
|
|
||||||
else:
|
|
||||||
extra["status"] = "unresolved"
|
|
||||||
extra["target_label"] = raw_target
|
|
||||||
edges.append(_make_edge("references", source_note_id, raw_target, seq="body", occ=k, extra=extra))
|
|
||||||
|
|
||||||
# Chunks (Chunk-Ebene)
|
|
||||||
for i, ch in enumerate(chunks_payloads, start=1):
|
|
||||||
txt = ch.get("text") or ch.get("content") or ""
|
|
||||||
if not txt:
|
|
||||||
continue
|
continue
|
||||||
occ = 0
|
edges.append(_edge("belongs_to", "chunk", cid, note_id, note_id, {
|
||||||
for m in WIKILINK_RE.finditer(txt):
|
"chunk_id": cid,
|
||||||
occ += 1
|
"edge_id": _mk_edge_id("belongs_to", cid, note_id, "chunk", "structure:belongs_to"),
|
||||||
raw_target, heading, alias = m.groups()
|
"provenance": "rule",
|
||||||
target_id, how = resolve_target(raw_target, note_index)
|
"rule_id": "structure:belongs_to",
|
||||||
extra = {"raw": raw_target, "alias": alias, "heading": heading, "resolution": how}
|
"confidence": 1.0,
|
||||||
if target_id:
|
}))
|
||||||
edges.append(_make_edge("references_at", ch["chunk_id"], target_id, seq=i, occ=occ, extra=extra))
|
|
||||||
else:
|
# 2) next / prev
|
||||||
extra["status"] = "unresolved"
|
for i in range(len(chunks) - 1):
|
||||||
extra["target_label"] = raw_target
|
a, b = chunks[i], chunks[i + 1]
|
||||||
edges.append(_make_edge("references_at", ch["chunk_id"], raw_target, seq=i, occ=occ, extra=extra))
|
a_id = _get(a, "chunk_id", "id")
|
||||||
return edges
|
b_id = _get(b, "chunk_id", "id")
|
||||||
|
if not a_id or not b_id:
|
||||||
|
continue
|
||||||
|
edges.append(_edge("next", "chunk", a_id, b_id, note_id, {
|
||||||
|
"chunk_id": a_id,
|
||||||
|
"edge_id": _mk_edge_id("next", a_id, b_id, "chunk", "structure:order"),
|
||||||
|
"provenance": "rule",
|
||||||
|
"rule_id": "structure:order",
|
||||||
|
"confidence": 0.95,
|
||||||
|
}))
|
||||||
|
edges.append(_edge("prev", "chunk", b_id, a_id, note_id, {
|
||||||
|
"chunk_id": b_id,
|
||||||
|
"edge_id": _mk_edge_id("prev", b_id, a_id, "chunk", "structure:order"),
|
||||||
|
"provenance": "rule",
|
||||||
|
"rule_id": "structure:order",
|
||||||
|
"confidence": 0.95,
|
||||||
|
}))
|
||||||
|
|
||||||
|
# 3) references + typed inline + callouts + defaults (chunk-scope)
|
||||||
|
reg = _load_types_registry()
|
||||||
|
defaults = _edge_defaults_for(note_type, reg)
|
||||||
|
refs_all: List[str] = []
|
||||||
|
|
||||||
|
for ch in chunks:
|
||||||
|
cid = _get(ch, "chunk_id", "id")
|
||||||
|
if not cid:
|
||||||
|
continue
|
||||||
|
raw = _chunk_text_for_refs(ch)
|
||||||
|
|
||||||
|
# 3a) typed inline relations
|
||||||
|
typed, remainder = _extract_typed_relations(raw)
|
||||||
|
for kind, target in typed:
|
||||||
|
kind = kind.strip().lower()
|
||||||
|
if not kind or not target:
|
||||||
|
continue
|
||||||
|
edges.append(_edge(kind, "chunk", cid, target, note_id, {
|
||||||
|
"chunk_id": cid,
|
||||||
|
"edge_id": _mk_edge_id(kind, cid, target, "chunk", "inline:rel"),
|
||||||
|
"provenance": "explicit",
|
||||||
|
"rule_id": "inline:rel",
|
||||||
|
"confidence": 0.95,
|
||||||
|
}))
|
||||||
|
if kind in {"related_to", "similar_to"}:
|
||||||
|
edges.append(_edge(kind, "chunk", target, cid, note_id, {
|
||||||
|
"chunk_id": cid,
|
||||||
|
"edge_id": _mk_edge_id(kind, target, cid, "chunk", "inline:rel"),
|
||||||
|
"provenance": "explicit",
|
||||||
|
"rule_id": "inline:rel",
|
||||||
|
"confidence": 0.95,
|
||||||
|
}))
|
||||||
|
|
||||||
|
# 3b) callouts
|
||||||
|
call_pairs, remainder2 = _extract_callout_relations(remainder)
|
||||||
|
for kind, target in call_pairs:
|
||||||
|
k = (kind or "").strip().lower()
|
||||||
|
if not k or not target:
|
||||||
|
continue
|
||||||
|
edges.append(_edge(k, "chunk", cid, target, note_id, {
|
||||||
|
"chunk_id": cid,
|
||||||
|
"edge_id": _mk_edge_id(k, cid, target, "chunk", "callout:edge"),
|
||||||
|
"provenance": "explicit",
|
||||||
|
"rule_id": "callout:edge",
|
||||||
|
"confidence": 0.95,
|
||||||
|
}))
|
||||||
|
if k in {"related_to", "similar_to"}:
|
||||||
|
edges.append(_edge(k, "chunk", target, cid, note_id, {
|
||||||
|
"chunk_id": cid,
|
||||||
|
"edge_id": _mk_edge_id(k, target, cid, "chunk", "callout:edge"),
|
||||||
|
"provenance": "explicit",
|
||||||
|
"rule_id": "callout:edge",
|
||||||
|
"confidence": 0.95,
|
||||||
|
}))
|
||||||
|
|
||||||
|
# 3c) generische Wikilinks → references (+ defaults je Ref)
|
||||||
|
refs = _extract_wikilinks(remainder2)
|
||||||
|
for r in refs:
|
||||||
|
edges.append(_edge("references", "chunk", cid, r, note_id, {
|
||||||
|
"chunk_id": cid,
|
||||||
|
"ref_text": r,
|
||||||
|
"edge_id": _mk_edge_id("references", cid, r, "chunk", "explicit:wikilink"),
|
||||||
|
"provenance": "explicit",
|
||||||
|
"rule_id": "explicit:wikilink",
|
||||||
|
"confidence": 1.0,
|
||||||
|
}))
|
||||||
|
for rel in defaults:
|
||||||
|
if rel == "references":
|
||||||
|
continue
|
||||||
|
edges.append(_edge(rel, "chunk", cid, r, note_id, {
|
||||||
|
"chunk_id": cid,
|
||||||
|
"edge_id": _mk_edge_id(rel, cid, r, "chunk", f"edge_defaults:{note_type}:{rel}"),
|
||||||
|
"provenance": "rule",
|
||||||
|
"rule_id": f"edge_defaults:{note_type}:{rel}",
|
||||||
|
"confidence": 0.7,
|
||||||
|
}))
|
||||||
|
if rel in {"related_to", "similar_to"}:
|
||||||
|
edges.append(_edge(rel, "chunk", r, cid, note_id, {
|
||||||
|
"chunk_id": cid,
|
||||||
|
"edge_id": _mk_edge_id(rel, r, cid, "chunk", f"edge_defaults:{note_type}:{rel}"),
|
||||||
|
"provenance": "rule",
|
||||||
|
"rule_id": f"edge_defaults:{note_type}:{rel}",
|
||||||
|
"confidence": 0.7,
|
||||||
|
}))
|
||||||
|
|
||||||
|
refs_all.extend(refs)
|
||||||
|
|
||||||
|
# 4) optional note-scope refs/backlinks (+ defaults)
|
||||||
|
if include_note_scope_refs:
|
||||||
|
refs_note = list(refs_all or [])
|
||||||
|
if note_level_references:
|
||||||
|
refs_note.extend([r for r in note_level_references if isinstance(r, str) and r])
|
||||||
|
refs_note = _dedupe_seq(refs_note)
|
||||||
|
for r in refs_note:
|
||||||
|
edges.append(_edge("references", "note", note_id, r, note_id, {
|
||||||
|
"edge_id": _mk_edge_id("references", note_id, r, "note", "explicit:note_scope"),
|
||||||
|
"provenance": "explicit",
|
||||||
|
"rule_id": "explicit:note_scope",
|
||||||
|
"confidence": 1.0,
|
||||||
|
}))
|
||||||
|
edges.append(_edge("backlink", "note", r, note_id, note_id, {
|
||||||
|
"edge_id": _mk_edge_id("backlink", r, note_id, "note", "derived:backlink"),
|
||||||
|
"provenance": "rule",
|
||||||
|
"rule_id": "derived:backlink",
|
||||||
|
"confidence": 0.9,
|
||||||
|
}))
|
||||||
|
for rel in defaults:
|
||||||
|
if rel == "references":
|
||||||
|
continue
|
||||||
|
edges.append(_edge(rel, "note", note_id, r, note_id, {
|
||||||
|
"edge_id": _mk_edge_id(rel, note_id, r, "note", f"edge_defaults:{note_type}:{rel}"),
|
||||||
|
"provenance": "rule",
|
||||||
|
"rule_id": f"edge_defaults:{note_type}:{rel}",
|
||||||
|
"confidence": 0.7,
|
||||||
|
}))
|
||||||
|
if rel in {"related_to", "similar_to"}:
|
||||||
|
edges.append(_edge(rel, "note", r, note_id, note_id, {
|
||||||
|
"edge_id": _mk_edge_id(rel, r, note_id, "note", f"edge_defaults:{note_type}:{rel}"),
|
||||||
|
"provenance": "rule",
|
||||||
|
"rule_id": f"edge_defaults:{note_type}:{rel}",
|
||||||
|
"confidence": 0.7,
|
||||||
|
}))
|
||||||
|
|
||||||
|
# 5) De-Dupe (source_id, target_id, relation, rule_id)
|
||||||
|
seen: Set[Tuple[str,str,str,str]] = set()
|
||||||
|
out: List[dict] = []
|
||||||
|
for e in edges:
|
||||||
|
s = str(e.get("source_id") or "")
|
||||||
|
t = str(e.get("target_id") or "")
|
||||||
|
rel = str(e.get("relation") or e.get("kind") or "edge")
|
||||||
|
rule = str(e.get("rule_id") or "")
|
||||||
|
key = (s, t, rel, rule)
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
out.append(e)
|
||||||
|
return out
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
Modul: app/core/edges.py
|
|
||||||
Version: 1.0.0
|
|
||||||
Datum: 2025-09-09
|
|
||||||
|
|
||||||
Zweck
|
|
||||||
-----
|
|
||||||
Zentrale, konsistente Erzeugung von Edge-Payloads im **neuen Schema**:
|
|
||||||
- kind : "belongs_to" | "next" | "prev" | "references" | "backlink"
|
|
||||||
- source_id : ID des Quellknotens (Chunk- oder Note-ID)
|
|
||||||
- target_id : ID des Zielknotens
|
|
||||||
- scope : "chunk" | "note"
|
|
||||||
- note_id : Owner-Note (für performantes Filtern/Löschen)
|
|
||||||
- seq : optional (z. B. Reihenfolge von Vorkommen)
|
|
||||||
|
|
||||||
Hinweise
|
|
||||||
--------
|
|
||||||
- Edges werden dedupliziert (key=(kind,source_id,target_id,scope)).
|
|
||||||
- Für Chunk-Edges wird `note_id` aus dem Chunk-Payload entnommen.
|
|
||||||
- Für Note-Scope-Edges ist `note_id` die Quell-Note-ID.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
from typing import Dict, List
|
|
||||||
|
|
||||||
def build_edges_for_note(
|
|
||||||
note_id: str,
|
|
||||||
chunk_payloads: List[Dict],
|
|
||||||
note_level_refs: List[str] | None,
|
|
||||||
*,
|
|
||||||
include_note_scope_refs: bool = False,
|
|
||||||
) -> List[Dict]:
|
|
||||||
edges: List[Dict] = []
|
|
||||||
|
|
||||||
# Chunk-Scope: belongs_to / prev / next / references
|
|
||||||
for ch in chunk_payloads:
|
|
||||||
cid = ch["id"]
|
|
||||||
owner = ch.get("note_id") or note_id
|
|
||||||
# belongs_to
|
|
||||||
edges.append({
|
|
||||||
"kind": "belongs_to",
|
|
||||||
"source_id": cid,
|
|
||||||
"target_id": note_id,
|
|
||||||
"scope": "chunk",
|
|
||||||
"note_id": owner,
|
|
||||||
})
|
|
||||||
# Nachbarn
|
|
||||||
nb = ch.get("neighbors") or {}
|
|
||||||
prev_id = nb.get("prev")
|
|
||||||
next_id = nb.get("next")
|
|
||||||
if prev_id:
|
|
||||||
edges.append({
|
|
||||||
"kind": "prev",
|
|
||||||
"source_id": cid,
|
|
||||||
"target_id": prev_id,
|
|
||||||
"scope": "chunk",
|
|
||||||
"note_id": owner,
|
|
||||||
})
|
|
||||||
edges.append({
|
|
||||||
"kind": "next",
|
|
||||||
"source_id": prev_id,
|
|
||||||
"target_id": cid,
|
|
||||||
"scope": "chunk",
|
|
||||||
"note_id": owner,
|
|
||||||
})
|
|
||||||
if next_id:
|
|
||||||
edges.append({
|
|
||||||
"kind": "next",
|
|
||||||
"source_id": cid,
|
|
||||||
"target_id": next_id,
|
|
||||||
"scope": "chunk",
|
|
||||||
"note_id": owner,
|
|
||||||
})
|
|
||||||
edges.append({
|
|
||||||
"kind": "prev",
|
|
||||||
"source_id": next_id,
|
|
||||||
"target_id": cid,
|
|
||||||
"scope": "chunk",
|
|
||||||
"note_id": owner,
|
|
||||||
})
|
|
||||||
# references aus Chunk
|
|
||||||
for ref in (ch.get("references") or []):
|
|
||||||
tid = ref.get("target_id")
|
|
||||||
if not tid:
|
|
||||||
continue
|
|
||||||
edges.append({
|
|
||||||
"kind": "references",
|
|
||||||
"source_id": cid,
|
|
||||||
"target_id": tid,
|
|
||||||
"scope": "chunk",
|
|
||||||
"note_id": owner,
|
|
||||||
})
|
|
||||||
|
|
||||||
# Note-Scope: backlink (immer); references (optional)
|
|
||||||
unique_refs = list(dict.fromkeys(note_level_refs or []))
|
|
||||||
for tid in unique_refs:
|
|
||||||
if include_note_scope_refs:
|
|
||||||
edges.append({
|
|
||||||
"kind": "references",
|
|
||||||
"source_id": note_id,
|
|
||||||
"target_id": tid,
|
|
||||||
"scope": "note",
|
|
||||||
"note_id": note_id,
|
|
||||||
})
|
|
||||||
edges.append({
|
|
||||||
"kind": "backlink",
|
|
||||||
"source_id": tid,
|
|
||||||
"target_id": note_id,
|
|
||||||
"scope": "note",
|
|
||||||
"note_id": note_id,
|
|
||||||
})
|
|
||||||
|
|
||||||
# Dedupe
|
|
||||||
dedup = {}
|
|
||||||
for e in edges:
|
|
||||||
k = (e["kind"], e["source_id"], e["target_id"], e.get("scope", ""))
|
|
||||||
dedup[k] = e
|
|
||||||
return list(dedup.values())
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
import os, time, json
|
|
||||||
import urllib.request
|
|
||||||
from typing import List, Dict, Any
|
|
||||||
|
|
||||||
# Backend-Auswahl:
|
|
||||||
# - EMBED_BACKEND=ollama -> EMBED_URL=/api/embeddings (Ollama), EMBED_MODEL=z.B. nomic-embed-text
|
|
||||||
# - EMBED_BACKEND=mini -> EMBED_URL=/embed (unser MiniLM-Server), EMBED_MODEL=minilm-384
|
|
||||||
EMBED_BACKEND = os.getenv("EMBED_BACKEND", "mini").lower()
|
|
||||||
EMBED_URL = os.getenv("EMBED_URL", "http://127.0.0.1:8990/embed")
|
|
||||||
EMBED_MODEL = os.getenv("EMBED_MODEL", "minilm-384")
|
|
||||||
EMBED_BATCH = int(os.getenv("EMBED_BATCH", "64"))
|
|
||||||
TIMEOUT = 60
|
|
||||||
|
|
||||||
class EmbedError(RuntimeError): ...
|
|
||||||
|
|
||||||
def _post_json(url: str, payload: Dict[str, Any]) -> Dict[str, Any]:
|
|
||||||
data = json.dumps(payload).encode("utf-8")
|
|
||||||
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
|
|
||||||
with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
|
|
||||||
return json.loads(resp.read().decode("utf-8"))
|
|
||||||
|
|
||||||
def _embed_mini(inputs: List[str], model: str, batch: int) -> List[List[float]]:
|
|
||||||
out: List[List[float]] = []
|
|
||||||
i = 0
|
|
||||||
while i < len(inputs):
|
|
||||||
chunk = inputs[i:i+batch]
|
|
||||||
# einfache Retries
|
|
||||||
for attempt in range(5):
|
|
||||||
try:
|
|
||||||
resp = _post_json(EMBED_URL, {"model": model, "inputs": chunk})
|
|
||||||
vecs = resp.get("embeddings") or resp.get("vectors") or resp.get("data")
|
|
||||||
if not isinstance(vecs, list):
|
|
||||||
raise EmbedError(f"Bad embed response keys: {list(resp.keys())}")
|
|
||||||
out.extend(vecs)
|
|
||||||
break
|
|
||||||
except Exception:
|
|
||||||
if attempt == 4:
|
|
||||||
raise
|
|
||||||
time.sleep(1.5 * (attempt + 1))
|
|
||||||
i += batch
|
|
||||||
return out
|
|
||||||
|
|
||||||
def _embed_ollama(inputs: List[str], model: str, batch: int) -> List[List[float]]:
|
|
||||||
# Ollama /api/embeddings akzeptiert "input" als String ODER Array.
|
|
||||||
# Die Response enthält:
|
|
||||||
# - für single input: {"embedding":[...], "model":"...", ...}
|
|
||||||
# - für array input: {"embeddings":[[...],[...],...], "model":"...", ...} (je nach Version)
|
|
||||||
# Um maximal kompatibel zu sein, rufen wir pro Text einzeln auf.
|
|
||||||
out: List[List[float]] = []
|
|
||||||
for text in inputs:
|
|
||||||
# Retries
|
|
||||||
for attempt in range(5):
|
|
||||||
try:
|
|
||||||
resp = _post_json(EMBED_URL, {"model": model, "input": text})
|
|
||||||
if "embedding" in resp and isinstance(resp["embedding"], list):
|
|
||||||
out.append(resp["embedding"])
|
|
||||||
elif "embeddings" in resp and isinstance(resp["embeddings"], list):
|
|
||||||
# Falls Server array zurückgibt, nimm das erste Element
|
|
||||||
vecs = resp["embeddings"]
|
|
||||||
out.append(vecs[0] if vecs else [])
|
|
||||||
else:
|
|
||||||
raise EmbedError(f"Ollama response unexpected keys: {list(resp.keys())}")
|
|
||||||
break
|
|
||||||
except Exception:
|
|
||||||
if attempt == 4:
|
|
||||||
raise
|
|
||||||
time.sleep(1.5 * (attempt + 1))
|
|
||||||
return out
|
|
||||||
|
|
||||||
def embed_texts(texts: List[str], model: str | None = None, batch_size: int | None = None) -> List[List[float]]:
|
|
||||||
model = model or EMBED_MODEL
|
|
||||||
batch = batch_size or EMBED_BATCH
|
|
||||||
if not texts:
|
|
||||||
return []
|
|
||||||
if EMBED_BACKEND == "ollama":
|
|
||||||
return _embed_ollama(texts, model, batch)
|
|
||||||
# default: mini
|
|
||||||
return _embed_mini(texts, model, batch)
|
|
||||||
|
|
||||||
def embed_one(text: str, model: str | None = None) -> List[float]:
|
|
||||||
return embed_texts([text], model=model, batch_size=1)[0]
|
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/graph_adapter.py
|
||||||
|
DESCRIPTION: Lädt Kanten aus Qdrant und baut einen In-Memory Subgraphen für Scoring (Centrality) und Explanation.
|
||||||
|
VERSION: 0.4.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: qdrant_client, app.core.qdrant
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Dict, List, Optional, DefaultDict, Any
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
|
from qdrant_client import QdrantClient
|
||||||
|
from qdrant_client.http import models as rest
|
||||||
|
|
||||||
|
from app.core.qdrant import collection_names
|
||||||
|
|
||||||
|
# Legacy-Import Fallback
|
||||||
|
try: # pragma: no cover
|
||||||
|
from app.core.qdrant_points import get_edges_for_sources # type: ignore
|
||||||
|
except Exception: # pragma: no cover
|
||||||
|
get_edges_for_sources = None # type: ignore
|
||||||
|
|
||||||
|
|
||||||
|
# Basisgewichte je Edge-Typ (WP-04a Config)
|
||||||
|
EDGE_BASE_WEIGHTS: Dict[str, float] = {
|
||||||
|
# Struktur
|
||||||
|
"belongs_to": 0.10,
|
||||||
|
"next": 0.06,
|
||||||
|
"prev": 0.06,
|
||||||
|
"backlink": 0.04,
|
||||||
|
"references_at": 0.08,
|
||||||
|
|
||||||
|
# Wissen
|
||||||
|
"references": 0.20,
|
||||||
|
"depends_on": 0.18,
|
||||||
|
"related_to": 0.15,
|
||||||
|
"similar_to": 0.12,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _edge_weight(pl: Dict) -> float:
|
||||||
|
"""Berechnet das effektive Edge-Gewicht aus kind + confidence."""
|
||||||
|
kind = pl.get("kind", "edge")
|
||||||
|
base = EDGE_BASE_WEIGHTS.get(kind, 0.0)
|
||||||
|
|
||||||
|
conf_raw = pl.get("confidence", None)
|
||||||
|
try:
|
||||||
|
conf = float(conf_raw) if conf_raw is not None else None
|
||||||
|
except Exception:
|
||||||
|
conf = None
|
||||||
|
|
||||||
|
if conf is None:
|
||||||
|
return base
|
||||||
|
|
||||||
|
if conf < 0.0: conf = 0.0
|
||||||
|
if conf > 1.0: conf = 1.0
|
||||||
|
|
||||||
|
return base * conf
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_edges(
|
||||||
|
client: QdrantClient,
|
||||||
|
prefix: str,
|
||||||
|
seeds: List[str],
|
||||||
|
edge_types: Optional[List[str]] = None,
|
||||||
|
limit: int = 2048,
|
||||||
|
) -> List[Dict]:
|
||||||
|
"""
|
||||||
|
Holt Edges direkt aus der *_edges Collection.
|
||||||
|
Filter: source_id IN seeds OR target_id IN seeds OR note_id IN seeds
|
||||||
|
"""
|
||||||
|
if not seeds or limit <= 0:
|
||||||
|
return []
|
||||||
|
|
||||||
|
_, _, edges_col = collection_names(prefix)
|
||||||
|
|
||||||
|
seed_conditions = []
|
||||||
|
for field in ("source_id", "target_id", "note_id"):
|
||||||
|
for s in seeds:
|
||||||
|
seed_conditions.append(
|
||||||
|
rest.FieldCondition(key=field, match=rest.MatchValue(value=str(s)))
|
||||||
|
)
|
||||||
|
seeds_filter = rest.Filter(should=seed_conditions) if seed_conditions else None
|
||||||
|
|
||||||
|
type_filter = None
|
||||||
|
if edge_types:
|
||||||
|
type_conds = [
|
||||||
|
rest.FieldCondition(key="kind", match=rest.MatchValue(value=str(k)))
|
||||||
|
for k in edge_types
|
||||||
|
]
|
||||||
|
type_filter = rest.Filter(should=type_conds)
|
||||||
|
|
||||||
|
must = []
|
||||||
|
if seeds_filter: must.append(seeds_filter)
|
||||||
|
if type_filter: must.append(type_filter)
|
||||||
|
|
||||||
|
flt = rest.Filter(must=must) if must else None
|
||||||
|
|
||||||
|
pts, _ = client.scroll(
|
||||||
|
collection_name=edges_col,
|
||||||
|
scroll_filter=flt,
|
||||||
|
limit=limit,
|
||||||
|
with_payload=True,
|
||||||
|
with_vectors=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
out: List[Dict] = []
|
||||||
|
for p in pts or []:
|
||||||
|
pl = dict(p.payload or {})
|
||||||
|
if pl:
|
||||||
|
out.append(pl)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
class Subgraph:
|
||||||
|
"""Leichtgewichtiger Subgraph mit Adjazenzlisten & Kennzahlen."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
# Forward: source -> [targets]
|
||||||
|
self.adj: DefaultDict[str, List[Dict]] = defaultdict(list)
|
||||||
|
# Reverse: target -> [sources] (Neu für WP-04b Explanation)
|
||||||
|
self.reverse_adj: DefaultDict[str, List[Dict]] = defaultdict(list)
|
||||||
|
|
||||||
|
self.in_degree: DefaultDict[str, int] = defaultdict(int)
|
||||||
|
self.out_degree: DefaultDict[str, int] = defaultdict(int)
|
||||||
|
|
||||||
|
def add_edge(self, e: Dict) -> None:
|
||||||
|
"""
|
||||||
|
Fügt eine Kante hinzu und aktualisiert Forward/Reverse Indizes.
|
||||||
|
e muss enthalten: source, target, kind, weight.
|
||||||
|
"""
|
||||||
|
src = e.get("source")
|
||||||
|
tgt = e.get("target")
|
||||||
|
kind = e.get("kind")
|
||||||
|
weight = e.get("weight", EDGE_BASE_WEIGHTS.get(kind, 0.0))
|
||||||
|
owner = e.get("note_id")
|
||||||
|
|
||||||
|
if not src or not tgt:
|
||||||
|
return
|
||||||
|
|
||||||
|
# 1. Primäre Adjazenz (Forward)
|
||||||
|
edge_data = {"target": tgt, "kind": kind, "weight": weight}
|
||||||
|
self.adj[src].append(edge_data)
|
||||||
|
self.out_degree[src] += 1
|
||||||
|
self.in_degree[tgt] += 1
|
||||||
|
|
||||||
|
# 2. Reverse Adjazenz (Neu für Explanation)
|
||||||
|
# Wir speichern, woher die Kante kam.
|
||||||
|
rev_data = {"source": src, "kind": kind, "weight": weight}
|
||||||
|
self.reverse_adj[tgt].append(rev_data)
|
||||||
|
|
||||||
|
# 3. Kontext-Note Handling (Forward & Reverse)
|
||||||
|
# Wenn eine Kante "im Kontext einer Note" (owner) definiert ist,
|
||||||
|
# schreiben wir sie der Note gut, damit der Retriever Scores auf Note-Ebene findet.
|
||||||
|
if owner and owner != src:
|
||||||
|
# Forward: Owner -> Target
|
||||||
|
self.adj[owner].append(edge_data)
|
||||||
|
self.out_degree[owner] += 1
|
||||||
|
|
||||||
|
# Reverse: Target wird vom Owner referenziert (indirekt)
|
||||||
|
if owner != tgt:
|
||||||
|
rev_owner_data = {"source": owner, "kind": kind, "weight": weight, "via_context": True}
|
||||||
|
self.reverse_adj[tgt].append(rev_owner_data)
|
||||||
|
self.in_degree[owner] += 1 # Leichter Centrality Boost für den Owner
|
||||||
|
|
||||||
|
def aggregate_edge_bonus(self, node_id: str) -> float:
|
||||||
|
"""Summe der ausgehenden Kantengewichte (Hub-Score)."""
|
||||||
|
return sum(edge["weight"] for edge in self.adj.get(node_id, []))
|
||||||
|
|
||||||
|
def edge_bonus(self, node_id: str) -> float:
|
||||||
|
"""API für Retriever (WP-04a Kompatibilität)."""
|
||||||
|
return self.aggregate_edge_bonus(node_id)
|
||||||
|
|
||||||
|
def centrality_bonus(self, node_id: str) -> float:
|
||||||
|
"""Log-gedämpfte Zentralität (In-Degree)."""
|
||||||
|
import math
|
||||||
|
indeg = self.in_degree.get(node_id, 0)
|
||||||
|
if indeg <= 0:
|
||||||
|
return 0.0
|
||||||
|
return min(math.log1p(indeg) / 10.0, 0.15)
|
||||||
|
|
||||||
|
# --- WP-04b Explanation Helpers ---
|
||||||
|
|
||||||
|
def get_outgoing_edges(self, node_id: str) -> List[Dict[str, Any]]:
|
||||||
|
"""Liefert Liste aller Ziele, auf die dieser Knoten zeigt."""
|
||||||
|
return self.adj.get(node_id, [])
|
||||||
|
|
||||||
|
def get_incoming_edges(self, node_id: str) -> List[Dict[str, Any]]:
|
||||||
|
"""Liefert Liste aller Quellen, die auf diesen Knoten zeigen."""
|
||||||
|
return self.reverse_adj.get(node_id, [])
|
||||||
|
|
||||||
|
|
||||||
|
def expand(
|
||||||
|
client: QdrantClient,
|
||||||
|
prefix: str,
|
||||||
|
seeds: List[str],
|
||||||
|
depth: int = 1,
|
||||||
|
edge_types: Optional[List[str]] = None,
|
||||||
|
) -> Subgraph:
|
||||||
|
"""
|
||||||
|
Expandiert ab Seeds entlang von Edges (bis `depth`).
|
||||||
|
"""
|
||||||
|
sg = Subgraph()
|
||||||
|
frontier = set(seeds)
|
||||||
|
visited = set()
|
||||||
|
|
||||||
|
max_depth = max(depth, 0)
|
||||||
|
|
||||||
|
for _ in range(max_depth):
|
||||||
|
if not frontier:
|
||||||
|
break
|
||||||
|
|
||||||
|
edges_payloads = _fetch_edges(
|
||||||
|
client=client,
|
||||||
|
prefix=prefix,
|
||||||
|
seeds=list(frontier),
|
||||||
|
edge_types=edge_types,
|
||||||
|
limit=2048,
|
||||||
|
)
|
||||||
|
|
||||||
|
next_frontier = set()
|
||||||
|
for pl in edges_payloads:
|
||||||
|
src = pl.get("source_id")
|
||||||
|
tgt = pl.get("target_id")
|
||||||
|
|
||||||
|
# Skip invalid edges
|
||||||
|
if not src or not tgt:
|
||||||
|
continue
|
||||||
|
|
||||||
|
e = {
|
||||||
|
"source": src,
|
||||||
|
"target": tgt,
|
||||||
|
"kind": pl.get("kind", "edge"),
|
||||||
|
"weight": _edge_weight(pl),
|
||||||
|
"note_id": pl.get("note_id"),
|
||||||
|
}
|
||||||
|
sg.add_edge(e)
|
||||||
|
|
||||||
|
# Nur weitersuchen, wenn Target noch nicht besucht
|
||||||
|
if tgt and tgt not in visited:
|
||||||
|
next_frontier.add(tgt)
|
||||||
|
|
||||||
|
visited |= frontier
|
||||||
|
frontier = next_frontier - visited
|
||||||
|
|
||||||
|
return sg
|
||||||
@@ -0,0 +1,332 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/ingestion.py
|
||||||
|
DESCRIPTION: Haupt-Ingestion-Logik.
|
||||||
|
FIX: Korrekte Priorisierung von Frontmatter für chunk_profile und retriever_weight.
|
||||||
|
Lade Chunk-Config basierend auf dem effektiven Profil, nicht nur dem Notiz-Typ.
|
||||||
|
VERSION: 2.7.0 (Fix: Frontmatter Overrides & Config Loading)
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.core.parser, app.core.note_payload, app.core.chunker, app.core.derive_edges, app.core.qdrant*, app.services.embeddings_client
|
||||||
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
import asyncio
|
||||||
|
import time
|
||||||
|
from typing import Dict, List, Optional, Tuple, Any
|
||||||
|
|
||||||
|
# Core Module Imports
|
||||||
|
from app.core.parser import (
|
||||||
|
read_markdown,
|
||||||
|
normalize_frontmatter,
|
||||||
|
validate_required_frontmatter,
|
||||||
|
)
|
||||||
|
from app.core.note_payload import make_note_payload
|
||||||
|
from app.core.chunker import assemble_chunks, get_chunk_config
|
||||||
|
from app.core.chunk_payload import make_chunk_payloads
|
||||||
|
|
||||||
|
# Fallback für Edges
|
||||||
|
try:
|
||||||
|
from app.core.derive_edges import build_edges_for_note
|
||||||
|
except ImportError:
|
||||||
|
def build_edges_for_note(*args, **kwargs): return []
|
||||||
|
|
||||||
|
from app.core.qdrant import QdrantConfig, get_client, ensure_collections, ensure_payload_indexes
|
||||||
|
from app.core.qdrant_points import (
|
||||||
|
points_for_chunks,
|
||||||
|
points_for_note,
|
||||||
|
points_for_edges,
|
||||||
|
upsert_batch,
|
||||||
|
)
|
||||||
|
|
||||||
|
from app.services.embeddings_client import EmbeddingsClient
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# --- Helper ---
|
||||||
|
def load_type_registry(custom_path: Optional[str] = None) -> dict:
|
||||||
|
import yaml
|
||||||
|
path = custom_path or os.getenv("MINDNET_TYPES_FILE", "config/types.yaml")
|
||||||
|
if not os.path.exists(path): return {}
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f: return yaml.safe_load(f) or {}
|
||||||
|
except Exception: return {}
|
||||||
|
|
||||||
|
def resolve_note_type(requested: Optional[str], reg: dict) -> str:
|
||||||
|
types = reg.get("types", {})
|
||||||
|
if requested and requested in types: return requested
|
||||||
|
return "concept"
|
||||||
|
|
||||||
|
def effective_chunk_profile_name(fm: dict, note_type: str, reg: dict) -> str:
|
||||||
|
"""
|
||||||
|
Ermittelt den Namen des Chunk-Profils.
|
||||||
|
Prio: 1. Frontmatter -> 2. Type-Config -> 3. Default
|
||||||
|
"""
|
||||||
|
# 1. Frontmatter Override
|
||||||
|
override = fm.get("chunking_profile") or fm.get("chunk_profile")
|
||||||
|
if override and isinstance(override, str):
|
||||||
|
return override
|
||||||
|
|
||||||
|
# 2. Type Config
|
||||||
|
t_cfg = reg.get("types", {}).get(note_type, {})
|
||||||
|
if t_cfg:
|
||||||
|
cp = t_cfg.get("chunking_profile") or t_cfg.get("chunk_profile")
|
||||||
|
if cp: return cp
|
||||||
|
|
||||||
|
# 3. Global Default
|
||||||
|
return reg.get("defaults", {}).get("chunking_profile", "sliding_standard")
|
||||||
|
|
||||||
|
def effective_retriever_weight(fm: dict, note_type: str, reg: dict) -> float:
|
||||||
|
"""
|
||||||
|
Ermittelt das Retriever Weight.
|
||||||
|
Prio: 1. Frontmatter -> 2. Type-Config -> 3. Default
|
||||||
|
"""
|
||||||
|
# 1. Frontmatter Override
|
||||||
|
override = fm.get("retriever_weight")
|
||||||
|
if override is not None:
|
||||||
|
try: return float(override)
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
# 2. Type Config
|
||||||
|
t_cfg = reg.get("types", {}).get(note_type, {})
|
||||||
|
if t_cfg and "retriever_weight" in t_cfg:
|
||||||
|
return float(t_cfg["retriever_weight"])
|
||||||
|
|
||||||
|
# 3. Global Default
|
||||||
|
return float(reg.get("defaults", {}).get("retriever_weight", 1.0))
|
||||||
|
|
||||||
|
|
||||||
|
class IngestionService:
|
||||||
|
def __init__(self, collection_prefix: str = None):
|
||||||
|
env_prefix = os.getenv("COLLECTION_PREFIX", "mindnet")
|
||||||
|
self.prefix = collection_prefix or env_prefix
|
||||||
|
|
||||||
|
self.cfg = QdrantConfig.from_env()
|
||||||
|
self.cfg.prefix = self.prefix
|
||||||
|
self.client = get_client(self.cfg)
|
||||||
|
self.dim = self.cfg.dim
|
||||||
|
self.registry = load_type_registry()
|
||||||
|
self.embedder = EmbeddingsClient()
|
||||||
|
|
||||||
|
# ACTIVE HASH MODE aus ENV lesen (Default: full)
|
||||||
|
self.active_hash_mode = os.getenv("MINDNET_CHANGE_DETECTION_MODE", "full")
|
||||||
|
|
||||||
|
try:
|
||||||
|
ensure_collections(self.client, self.prefix, self.dim)
|
||||||
|
ensure_payload_indexes(self.client, self.prefix)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"DB init warning: {e}")
|
||||||
|
|
||||||
|
def _get_chunk_config_by_profile(self, profile_name: str, note_type: str) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Lädt die konkrete Config (target, max, overlap) für einen Profilnamen.
|
||||||
|
"""
|
||||||
|
# Suche direkt in den definierten Profilen der Registry
|
||||||
|
profiles = self.registry.get("chunking_profiles", {})
|
||||||
|
if profile_name in profiles:
|
||||||
|
cfg = profiles[profile_name].copy()
|
||||||
|
# Tuple-Fix für Overlap (wie in chunker.py)
|
||||||
|
if "overlap" in cfg and isinstance(cfg["overlap"], list):
|
||||||
|
cfg["overlap"] = tuple(cfg["overlap"])
|
||||||
|
return cfg
|
||||||
|
|
||||||
|
# Fallback: Wenn Profilname unbekannt, nutze Standard für den Typ via Chunker
|
||||||
|
logger.warning(f"Profile '{profile_name}' not found in registry. Falling back to type defaults.")
|
||||||
|
return get_chunk_config(note_type)
|
||||||
|
|
||||||
|
async def process_file(
|
||||||
|
self,
|
||||||
|
file_path: str,
|
||||||
|
vault_root: str,
|
||||||
|
force_replace: bool = False,
|
||||||
|
apply: bool = False,
|
||||||
|
purge_before: bool = False,
|
||||||
|
note_scope_refs: bool = False,
|
||||||
|
hash_source: str = "parsed",
|
||||||
|
hash_normalize: str = "canonical"
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
|
||||||
|
result = {"path": file_path, "status": "skipped", "changed": False, "error": None}
|
||||||
|
|
||||||
|
# 1. Parse & Frontmatter Validation
|
||||||
|
try:
|
||||||
|
parsed = read_markdown(file_path)
|
||||||
|
if not parsed: return {**result, "error": "Empty or unreadable file"}
|
||||||
|
fm = normalize_frontmatter(parsed.frontmatter)
|
||||||
|
validate_required_frontmatter(fm)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Validation failed for {file_path}: {e}")
|
||||||
|
return {**result, "error": f"Validation failed: {str(e)}"}
|
||||||
|
|
||||||
|
# 2. Type & Config Resolution (FIXED)
|
||||||
|
# Wir ermitteln erst den Typ
|
||||||
|
note_type = resolve_note_type(fm.get("type"), self.registry)
|
||||||
|
fm["type"] = note_type
|
||||||
|
|
||||||
|
# Dann ermitteln wir die effektiven Werte unter Berücksichtigung des Frontmatters!
|
||||||
|
# Hier lag der Fehler: Vorher wurde einfach überschrieben.
|
||||||
|
effective_profile = effective_chunk_profile_name(fm, note_type, self.registry)
|
||||||
|
effective_weight = effective_retriever_weight(fm, note_type, self.registry)
|
||||||
|
|
||||||
|
# Wir schreiben die effektiven Werte zurück ins FM, damit note_payload sie sicher hat
|
||||||
|
fm["chunk_profile"] = effective_profile
|
||||||
|
fm["retriever_weight"] = effective_weight
|
||||||
|
|
||||||
|
# 3. Build Note Payload
|
||||||
|
try:
|
||||||
|
note_pl = make_note_payload(
|
||||||
|
parsed,
|
||||||
|
vault_root=vault_root,
|
||||||
|
hash_normalize=hash_normalize,
|
||||||
|
hash_source=hash_source,
|
||||||
|
file_path=file_path
|
||||||
|
)
|
||||||
|
# Text Body Fallback
|
||||||
|
if not note_pl.get("fulltext"): note_pl["fulltext"] = getattr(parsed, "body", "") or ""
|
||||||
|
|
||||||
|
# Update Payload with explicit effective values (Sicherheit)
|
||||||
|
note_pl["retriever_weight"] = effective_weight
|
||||||
|
note_pl["chunk_profile"] = effective_profile
|
||||||
|
|
||||||
|
note_id = note_pl["note_id"]
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Payload build failed: {e}")
|
||||||
|
return {**result, "error": f"Payload build failed: {str(e)}"}
|
||||||
|
|
||||||
|
# 4. Change Detection
|
||||||
|
old_payload = None
|
||||||
|
if not force_replace:
|
||||||
|
old_payload = self._fetch_note_payload(note_id)
|
||||||
|
|
||||||
|
has_old = old_payload is not None
|
||||||
|
check_key = f"{self.active_hash_mode}:{hash_source}:{hash_normalize}"
|
||||||
|
|
||||||
|
old_hashes = (old_payload or {}).get("hashes")
|
||||||
|
if isinstance(old_hashes, dict): old_hash = old_hashes.get(check_key)
|
||||||
|
elif isinstance(old_hashes, str) and self.active_hash_mode == "body": old_hash = old_hashes
|
||||||
|
else: old_hash = None
|
||||||
|
|
||||||
|
new_hash = note_pl.get("hashes", {}).get(check_key)
|
||||||
|
hash_changed = (old_hash != new_hash)
|
||||||
|
chunks_missing, edges_missing = self._artifacts_missing(note_id)
|
||||||
|
|
||||||
|
should_write = force_replace or (not has_old) or hash_changed or chunks_missing or edges_missing
|
||||||
|
|
||||||
|
if not should_write:
|
||||||
|
return {**result, "status": "unchanged", "note_id": note_id}
|
||||||
|
|
||||||
|
if not apply:
|
||||||
|
return {**result, "status": "dry-run", "changed": True, "note_id": note_id}
|
||||||
|
|
||||||
|
# 5. Processing
|
||||||
|
try:
|
||||||
|
body_text = getattr(parsed, "body", "") or ""
|
||||||
|
|
||||||
|
# FIX: Wir laden jetzt die Config für das SPEZIFISCHE Profil
|
||||||
|
# (z.B. wenn User "sliding_short" wollte, laden wir dessen Params)
|
||||||
|
chunk_config = self._get_chunk_config_by_profile(effective_profile, note_type)
|
||||||
|
|
||||||
|
chunks = await assemble_chunks(fm["id"], body_text, fm["type"], config=chunk_config)
|
||||||
|
|
||||||
|
# chunk_payloads werden mit den aktualisierten FM-Werten gebaut
|
||||||
|
chunk_pls = make_chunk_payloads(fm, note_pl["path"], chunks, note_text=body_text)
|
||||||
|
|
||||||
|
vecs = []
|
||||||
|
if chunk_pls:
|
||||||
|
texts = [c.get("window") or c.get("text") or "" for c in chunk_pls]
|
||||||
|
try:
|
||||||
|
if hasattr(self.embedder, 'embed_documents'):
|
||||||
|
vecs = await self.embedder.embed_documents(texts)
|
||||||
|
else:
|
||||||
|
for t in texts:
|
||||||
|
v = await self.embedder.embed_query(t)
|
||||||
|
vecs.append(v)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Embedding failed: {e}")
|
||||||
|
raise RuntimeError(f"Embedding failed: {e}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
edges = build_edges_for_note(
|
||||||
|
note_id,
|
||||||
|
chunk_pls,
|
||||||
|
note_level_references=note_pl.get("references", []),
|
||||||
|
include_note_scope_refs=note_scope_refs
|
||||||
|
)
|
||||||
|
except TypeError:
|
||||||
|
edges = build_edges_for_note(note_id, chunk_pls)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Processing failed: {e}", exc_info=True)
|
||||||
|
return {**result, "error": f"Processing failed: {str(e)}"}
|
||||||
|
|
||||||
|
# 6. Upsert
|
||||||
|
try:
|
||||||
|
if purge_before and has_old:
|
||||||
|
self._purge_artifacts(note_id)
|
||||||
|
|
||||||
|
n_name, n_pts = points_for_note(self.prefix, note_pl, None, self.dim)
|
||||||
|
upsert_batch(self.client, n_name, n_pts)
|
||||||
|
|
||||||
|
if chunk_pls and vecs:
|
||||||
|
c_name, c_pts = points_for_chunks(self.prefix, chunk_pls, vecs)
|
||||||
|
upsert_batch(self.client, c_name, c_pts)
|
||||||
|
|
||||||
|
if edges:
|
||||||
|
e_name, e_pts = points_for_edges(self.prefix, edges)
|
||||||
|
upsert_batch(self.client, e_name, e_pts)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"path": file_path,
|
||||||
|
"status": "success",
|
||||||
|
"changed": True,
|
||||||
|
"note_id": note_id,
|
||||||
|
"chunks_count": len(chunk_pls),
|
||||||
|
"edges_count": len(edges)
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Upsert failed: {e}", exc_info=True)
|
||||||
|
return {**result, "error": f"DB Upsert failed: {e}"}
|
||||||
|
|
||||||
|
# ... (Restliche Methoden wie _fetch_note_payload bleiben unverändert) ...
|
||||||
|
def _fetch_note_payload(self, note_id: str) -> Optional[dict]:
|
||||||
|
from qdrant_client.http import models as rest
|
||||||
|
col = f"{self.prefix}_notes"
|
||||||
|
try:
|
||||||
|
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
||||||
|
pts, _ = self.client.scroll(collection_name=col, scroll_filter=f, limit=1, with_payload=True)
|
||||||
|
return pts[0].payload if pts else None
|
||||||
|
except: return None
|
||||||
|
|
||||||
|
def _artifacts_missing(self, note_id: str) -> Tuple[bool, bool]:
|
||||||
|
from qdrant_client.http import models as rest
|
||||||
|
c_col = f"{self.prefix}_chunks"
|
||||||
|
e_col = f"{self.prefix}_edges"
|
||||||
|
try:
|
||||||
|
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
||||||
|
c_pts, _ = self.client.scroll(collection_name=c_col, scroll_filter=f, limit=1)
|
||||||
|
e_pts, _ = self.client.scroll(collection_name=e_col, scroll_filter=f, limit=1)
|
||||||
|
return (not bool(c_pts)), (not bool(e_pts))
|
||||||
|
except: return True, True
|
||||||
|
|
||||||
|
def _purge_artifacts(self, note_id: str):
|
||||||
|
from qdrant_client.http import models as rest
|
||||||
|
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
||||||
|
selector = rest.FilterSelector(filter=f)
|
||||||
|
for suffix in ["chunks", "edges"]:
|
||||||
|
try:
|
||||||
|
self.client.delete(collection_name=f"{self.prefix}_{suffix}", points_selector=selector)
|
||||||
|
except Exception: pass
|
||||||
|
|
||||||
|
async def create_from_text(self, markdown_content: str, filename: str, vault_root: str, folder: str = "00_Inbox") -> Dict[str, Any]:
|
||||||
|
target_dir = os.path.join(vault_root, folder)
|
||||||
|
os.makedirs(target_dir, exist_ok=True)
|
||||||
|
file_path = os.path.join(target_dir, filename)
|
||||||
|
try:
|
||||||
|
with open(file_path, "w", encoding="utf-8") as f:
|
||||||
|
f.write(markdown_content)
|
||||||
|
f.flush()
|
||||||
|
os.fsync(f.fileno())
|
||||||
|
await asyncio.sleep(0.1)
|
||||||
|
logger.info(f"Written file to {file_path}")
|
||||||
|
except Exception as e:
|
||||||
|
return {"status": "error", "error": f"Disk write failed: {str(e)}"}
|
||||||
|
return await self.process_file(file_path=file_path, vault_root=vault_root, apply=True, force_replace=True, purge_before=True)
|
||||||
+227
-188
@@ -1,229 +1,268 @@
|
|||||||
#!/usr/bin/env python3
|
"""
|
||||||
# -*- coding: utf-8 -*-
|
FILE: app/core/note_payload.py
|
||||||
# Modul: app/core/note_payload.py
|
DESCRIPTION: Baut das JSON-Objekt.
|
||||||
# Version: 1.7.0
|
FEATURES:
|
||||||
# Datum: 2025-09-09
|
1. Multi-Hash: Berechnet immer 'body' AND 'full' Hashes für flexible Change Detection.
|
||||||
|
2. Config-Fix: Liest korrekt 'chunking_profile' aus types.yaml (statt Legacy 'chunk_profile').
|
||||||
|
VERSION: 2.3.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: yaml, os, json, pathlib, hashlib
|
||||||
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
from typing import Any, Dict, Tuple, Optional
|
||||||
import hashlib
|
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
from typing import Any, Dict, Optional, Tuple
|
import json
|
||||||
|
import pathlib
|
||||||
|
import hashlib
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from app.core.parser import read_markdown, extract_wikilinks, FRONTMATTER_RE
|
import yaml # type: ignore
|
||||||
except Exception: # pragma: no cover
|
except Exception:
|
||||||
from .parser import read_markdown, extract_wikilinks, FRONTMATTER_RE # type: ignore
|
yaml = None
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Helpers
|
# Helper
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
def _canon_frontmatter(fm: Dict[str, Any]) -> str:
|
def _as_dict(x) -> Dict[str, Any]:
|
||||||
return json.dumps(fm or {}, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
|
"""Versucht, ein ParsedMarkdown-ähnliches Objekt in ein Dict zu überführen."""
|
||||||
|
if isinstance(x, dict):
|
||||||
|
return dict(x)
|
||||||
|
|
||||||
def _normalize_body(body: str, mode: str) -> str:
|
out: Dict[str, Any] = {}
|
||||||
if mode == "none":
|
for attr in (
|
||||||
return body if body is not None else ""
|
"frontmatter",
|
||||||
text = (body or "").replace("\r\n", "\n").replace("\r", "\n")
|
"body",
|
||||||
text = "\n".join(line.rstrip() for line in text.split("\n"))
|
"id",
|
||||||
return text
|
"note_id",
|
||||||
|
"title",
|
||||||
|
"path",
|
||||||
|
"tags",
|
||||||
|
"type",
|
||||||
|
"created",
|
||||||
|
"modified",
|
||||||
|
"date",
|
||||||
|
):
|
||||||
|
if hasattr(x, attr):
|
||||||
|
val = getattr(x, attr)
|
||||||
|
if val is not None:
|
||||||
|
out[attr] = val
|
||||||
|
|
||||||
def _resolve_hash_mode(explicit: Optional[str]) -> str:
|
if not out:
|
||||||
if explicit:
|
out["raw"] = str(x)
|
||||||
val = explicit.strip().lower()
|
|
||||||
else:
|
|
||||||
val = (os.environ.get("MINDNET_HASH_MODE")
|
|
||||||
or os.environ.get("MINDNET_HASH_COMPARE")
|
|
||||||
or "body").strip().lower()
|
|
||||||
if val in ("full", "fulltext", "body+frontmatter", "bodyplusfrontmatter"):
|
|
||||||
return "full"
|
|
||||||
if val in ("frontmatter", "fm"):
|
|
||||||
return "frontmatter"
|
|
||||||
return "body"
|
|
||||||
|
|
||||||
def _read_raw_body_from_file(file_path: Optional[str]) -> Tuple[str, Dict[str, Any]]:
|
return out
|
||||||
if not file_path or not os.path.exists(file_path):
|
|
||||||
return "", {}
|
|
||||||
|
def _pick_args(*args, **kwargs) -> Tuple[Optional[str], Optional[dict]]:
|
||||||
|
path = kwargs.get("path") or (args[0] if args else None)
|
||||||
|
types_cfg = kwargs.get("types_cfg") or kwargs.get("types") or None
|
||||||
|
return path, types_cfg
|
||||||
|
|
||||||
|
|
||||||
|
def _env_float(name: str, default: float) -> float:
|
||||||
try:
|
try:
|
||||||
with open(file_path, "r", encoding="utf-8") as f:
|
return float(os.environ.get(name, default))
|
||||||
raw = f.read()
|
|
||||||
except Exception:
|
except Exception:
|
||||||
return "", {}
|
return default
|
||||||
m = FRONTMATTER_RE.match(raw)
|
|
||||||
fm = {}
|
|
||||||
if m:
|
|
||||||
fm_txt = m.group(1)
|
|
||||||
try:
|
|
||||||
import yaml # lazy
|
|
||||||
fm = yaml.safe_load(fm_txt) or {}
|
|
||||||
except Exception:
|
|
||||||
fm = {}
|
|
||||||
body = raw[m.end():]
|
|
||||||
else:
|
|
||||||
body = raw
|
|
||||||
return body, fm
|
|
||||||
|
|
||||||
def _sha256(s: str) -> str:
|
|
||||||
h = hashlib.sha256()
|
|
||||||
h.update(s.encode("utf-8"))
|
|
||||||
return h.hexdigest()
|
|
||||||
|
|
||||||
def _hash_for(mode: str, *, body: str, fm: Dict[str, Any], normalize: str) -> str:
|
def _ensure_list(x) -> list:
|
||||||
body_n = _normalize_body(body or "", normalize)
|
if x is None:
|
||||||
fm_s = _canon_frontmatter(fm or {})
|
return []
|
||||||
if mode == "frontmatter":
|
if isinstance(x, list):
|
||||||
return _sha256(fm_s)
|
return [str(i) for i in x]
|
||||||
|
if isinstance(x, (set, tuple)):
|
||||||
|
return [str(i) for i in x]
|
||||||
|
return [str(x)]
|
||||||
|
|
||||||
|
# --- Hash Logic ---
|
||||||
|
def _compute_hash(content: str) -> str:
|
||||||
|
"""Berechnet einen SHA-256 Hash für den gegebenen String."""
|
||||||
|
if not content:
|
||||||
|
return ""
|
||||||
|
return hashlib.sha256(content.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
def _get_hash_source_content(n: Dict[str, Any], mode: str) -> str:
|
||||||
|
"""
|
||||||
|
Stellt den String zusammen, der gehasht werden soll.
|
||||||
|
"""
|
||||||
|
body = str(n.get("body") or "")
|
||||||
|
|
||||||
|
if mode == "body":
|
||||||
|
return body
|
||||||
|
|
||||||
if mode == "full":
|
if mode == "full":
|
||||||
return _sha256(body_n + "\n--FM--\n" + fm_s)
|
fm = n.get("frontmatter") or {}
|
||||||
# default: body
|
# Wichtig: Sortierte Keys für deterministisches Verhalten!
|
||||||
return _sha256(body_n)
|
# Wir nehmen alle steuernden Metadaten auf
|
||||||
|
meta_parts = []
|
||||||
|
# Hier checken wir keys, die eine Neu-Indizierung rechtfertigen würden
|
||||||
|
for k in sorted(["title", "type", "status", "tags", "chunking_profile", "chunk_profile", "retriever_weight"]):
|
||||||
|
val = fm.get(k)
|
||||||
|
if val is not None:
|
||||||
|
meta_parts.append(f"{k}:{val}")
|
||||||
|
|
||||||
|
meta_str = "|".join(meta_parts)
|
||||||
|
return f"{meta_str}||{body}"
|
||||||
|
|
||||||
|
return body
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Kernfunktion
|
# Type-Registry laden
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
def make_note_payload(
|
def _load_types_config(explicit_cfg: Optional[dict] = None) -> dict:
|
||||||
parsed: Any,
|
if explicit_cfg and isinstance(explicit_cfg, dict):
|
||||||
vault_root: Optional[str] = None,
|
return explicit_cfg
|
||||||
*,
|
|
||||||
hash_mode: Optional[str] = None,
|
path = os.getenv("MINDNET_TYPES_FILE") or "./config/types.yaml"
|
||||||
hash_normalize: Optional[str] = None,
|
if not os.path.isfile(path) or yaml is None:
|
||||||
hash_source: Optional[str] = None,
|
return {}
|
||||||
file_path: Optional[str] = None,
|
|
||||||
) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Liefert den Note-Payload inkl. Mehrfach-Hashes.
|
|
||||||
- Es werden IMMER die drei Hashes für (body|frontmatter|full) unter
|
|
||||||
'parsed:canonical' erzeugt (Schlüssel: z. B. 'body:parsed:canonical').
|
|
||||||
- Zusätzlich werden – falls die aktuelle Konfig (source/normalize) davon
|
|
||||||
abweicht – die drei Hashes unter den entsprechenden Schlüsseln erzeugt,
|
|
||||||
z. B. 'frontmatter:raw:none'.
|
|
||||||
- 'hash_fulltext' und 'hash_signature' repräsentieren den *aktuellen* Modus.
|
|
||||||
"""
|
|
||||||
# dict oder Objekt akzeptieren
|
|
||||||
if isinstance(parsed, dict):
|
|
||||||
fm = parsed.get("frontmatter") or {}
|
|
||||||
body_parsed = parsed.get("body") or ""
|
|
||||||
path = parsed.get("path") or ""
|
|
||||||
else:
|
|
||||||
fm = getattr(parsed, "frontmatter", {}) or {}
|
|
||||||
body_parsed = getattr(parsed, "body", "") or ""
|
|
||||||
path = getattr(parsed, "path", "") or ""
|
|
||||||
|
|
||||||
# Zielpfad relativieren
|
|
||||||
rel_path = path
|
|
||||||
try:
|
try:
|
||||||
if vault_root:
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
rel = os.path.relpath(path, vault_root)
|
data = yaml.safe_load(f) or {}
|
||||||
rel = rel.replace("\\", "/").lstrip("/")
|
return data if isinstance(data, dict) else {}
|
||||||
rel_path = rel
|
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
return {}
|
||||||
|
|
||||||
# Konfiguration auflösen
|
|
||||||
mode_resolved = _resolve_hash_mode(hash_mode) # body|frontmatter|full
|
|
||||||
src = (hash_source or os.environ.get("MINDNET_HASH_SOURCE", "parsed")).strip().lower() # parsed|raw
|
|
||||||
norm = (hash_normalize or os.environ.get("MINDNET_HASH_NORMALIZE", "canonical")).strip().lower() # canonical|none
|
|
||||||
|
|
||||||
# Body-Quelle laden
|
def _cfg_for_type(note_type: str, reg: dict) -> dict:
|
||||||
raw_body, raw_fm = ("", {})
|
if not isinstance(reg, dict):
|
||||||
if src == "raw":
|
return {}
|
||||||
raw_body, raw_fm = _read_raw_body_from_file(file_path or path)
|
types = reg.get("types") if isinstance(reg.get("types"), dict) else reg
|
||||||
if isinstance(raw_fm, dict) and raw_fm:
|
return types.get(note_type, {}) if isinstance(types, dict) else {}
|
||||||
merged_fm = dict(fm)
|
|
||||||
for k, v in raw_fm.items():
|
|
||||||
merged_fm.setdefault(k, v)
|
|
||||||
fm = merged_fm
|
|
||||||
body_for_hash = raw_body
|
|
||||||
else:
|
|
||||||
body_for_hash = body_parsed
|
|
||||||
|
|
||||||
# --- 1) Standard-Tripel (parsed:canonical) immer erzeugen ---
|
|
||||||
std_src = "parsed"
|
def _cfg_defaults(reg: dict) -> dict:
|
||||||
std_norm = "canonical"
|
if not isinstance(reg, dict):
|
||||||
std_hashes: Dict[str, str] = {}
|
return {}
|
||||||
for m in ("body", "frontmatter", "full"):
|
for key in ("defaults", "default", "global"):
|
||||||
std_hashes[f"{m}:{std_src}:{std_norm}"] = _hash_for(
|
v = reg.get(key)
|
||||||
m, body=body_parsed, fm=fm, normalize=std_norm
|
if isinstance(v, dict):
|
||||||
|
return v
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Haupt-API
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Baut das Note-Payload für mindnet_notes auf.
|
||||||
|
Inkludiert Hash-Berechnung (Body & Full) und korrigierte Config-Lookups.
|
||||||
|
"""
|
||||||
|
n = _as_dict(note)
|
||||||
|
path_arg, types_cfg_explicit = _pick_args(*args, **kwargs)
|
||||||
|
reg = _load_types_config(types_cfg_explicit)
|
||||||
|
|
||||||
|
# Hash Config (Parameter für Source/Normalize, Mode ist hardcoded auf 'beide')
|
||||||
|
hash_source = kwargs.get("hash_source", "parsed")
|
||||||
|
hash_normalize = kwargs.get("hash_normalize", "canonical")
|
||||||
|
|
||||||
|
fm = n.get("frontmatter") or {}
|
||||||
|
fm_type = fm.get("type") or n.get("type") or "concept"
|
||||||
|
note_type = str(fm_type)
|
||||||
|
|
||||||
|
cfg_type = _cfg_for_type(note_type, reg)
|
||||||
|
cfg_def = _cfg_defaults(reg)
|
||||||
|
|
||||||
|
# --- retriever_weight ---
|
||||||
|
default_rw = _env_float("MINDNET_DEFAULT_RETRIEVER_WEIGHT", 1.0)
|
||||||
|
retriever_weight = fm.get("retriever_weight")
|
||||||
|
if retriever_weight is None:
|
||||||
|
retriever_weight = cfg_type.get(
|
||||||
|
"retriever_weight",
|
||||||
|
cfg_def.get("retriever_weight", default_rw),
|
||||||
)
|
)
|
||||||
|
try:
|
||||||
|
retriever_weight = float(retriever_weight)
|
||||||
|
except Exception:
|
||||||
|
retriever_weight = default_rw
|
||||||
|
|
||||||
# Convenience-Felder (für Tools)
|
# --- chunk_profile (FIXED LOGIC) ---
|
||||||
hash_body = std_hashes["body:parsed:canonical"]
|
# 1. Frontmatter Override (beide Schreibweisen erlaubt)
|
||||||
hash_frontmatter = std_hashes["frontmatter:parsed:canonical"]
|
chunk_profile = fm.get("chunking_profile") or fm.get("chunk_profile")
|
||||||
hash_full = std_hashes["full:parsed:canonical"]
|
|
||||||
|
# 2. Type Config (Korrekter Key 'chunking_profile' aus types.yaml)
|
||||||
|
if chunk_profile is None:
|
||||||
|
chunk_profile = cfg_type.get("chunking_profile")
|
||||||
|
|
||||||
# --- 2) Hashes für die *aktuelle* Konfiguration (falls abweichend) ---
|
# 3. Default Config (Fallback auf sliding_standard statt medium)
|
||||||
cur_hashes: Dict[str, str] = {}
|
if chunk_profile is None:
|
||||||
if not (src == std_src and norm == std_norm):
|
chunk_profile = cfg_def.get("chunking_profile", "sliding_standard")
|
||||||
for m in ("body", "frontmatter", "full"):
|
|
||||||
cur_hashes[f"{m}:{src}:{norm}"] = _hash_for(
|
|
||||||
m, body=body_for_hash, fm=fm, normalize=norm
|
|
||||||
)
|
|
||||||
|
|
||||||
# --- 3) Aktueller Modus für Backwards-Compat Felder ---
|
# 4. Safety Fallback
|
||||||
current_hash = _hash_for(mode_resolved, body=body_for_hash, fm=fm, normalize=norm)
|
if not isinstance(chunk_profile, str) or not chunk_profile:
|
||||||
hash_signature = f"{mode_resolved}:{src}:{norm}:{current_hash}"
|
chunk_profile = "sliding_standard"
|
||||||
|
|
||||||
# Wikilinks (Note-Ebene)
|
# --- edge_defaults ---
|
||||||
refs = list(dict.fromkeys(extract_wikilinks(body_parsed))) if body_parsed else []
|
edge_defaults = fm.get("edge_defaults")
|
||||||
|
if edge_defaults is None:
|
||||||
|
edge_defaults = cfg_type.get(
|
||||||
|
"edge_defaults",
|
||||||
|
cfg_def.get("edge_defaults", []),
|
||||||
|
)
|
||||||
|
edge_defaults = _ensure_list(edge_defaults)
|
||||||
|
|
||||||
|
# --- Basis-Metadaten ---
|
||||||
|
note_id = n.get("note_id") or n.get("id") or fm.get("id")
|
||||||
|
title = n.get("title") or fm.get("title") or ""
|
||||||
|
path = n.get("path") or path_arg
|
||||||
|
if isinstance(path, pathlib.Path):
|
||||||
|
path = str(path)
|
||||||
|
|
||||||
payload: Dict[str, Any] = {
|
payload: Dict[str, Any] = {
|
||||||
"note_id": fm.get("id") or fm.get("note_id"),
|
"note_id": note_id,
|
||||||
"title": fm.get("title"),
|
"title": title,
|
||||||
"type": fm.get("type"),
|
"type": note_type,
|
||||||
"status": fm.get("status"),
|
"path": path or "",
|
||||||
"created": fm.get("created"),
|
"retriever_weight": retriever_weight,
|
||||||
"updated": fm.get("updated"),
|
"chunk_profile": chunk_profile,
|
||||||
"path": rel_path or fm.get("path"),
|
"edge_defaults": edge_defaults,
|
||||||
"tags": fm.get("tags"),
|
"hashes": {} # Init Hash Dict
|
||||||
# Volltext für verlustfreien Export
|
|
||||||
"fulltext": body_parsed,
|
|
||||||
# Backwards-Compat:
|
|
||||||
"hash_fulltext": current_hash,
|
|
||||||
"hash_signature": hash_signature,
|
|
||||||
# Option C: Mehrfach-Hashes
|
|
||||||
"hashes": {**std_hashes, **cur_hashes},
|
|
||||||
"hash_body": hash_body,
|
|
||||||
"hash_frontmatter": hash_frontmatter,
|
|
||||||
"hash_full": hash_full,
|
|
||||||
# Fallback-Refs
|
|
||||||
"references": refs,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# --- MULTI-HASH CALCULATION (Strategy Decoupling) ---
|
||||||
|
# Wir berechnen immer BEIDE Strategien und speichern sie.
|
||||||
|
# ingestion.py entscheidet dann anhand der ENV-Variable, welcher verglichen wird.
|
||||||
|
modes_to_calc = ["body", "full"]
|
||||||
|
|
||||||
|
for mode in modes_to_calc:
|
||||||
|
content_to_hash = _get_hash_source_content(n, mode)
|
||||||
|
computed_hash = _compute_hash(content_to_hash)
|
||||||
|
# Key Schema: mode:source:normalize (z.B. "full:parsed:canonical")
|
||||||
|
key = f"{mode}:{hash_source}:{hash_normalize}"
|
||||||
|
payload["hashes"][key] = computed_hash
|
||||||
|
|
||||||
for k in ("area", "project", "source", "lang", "slug", "aliases"):
|
# Tags / Keywords
|
||||||
if k in fm:
|
tags = fm.get("tags") or fm.get("keywords") or n.get("tags")
|
||||||
payload[k] = fm[k]
|
if tags:
|
||||||
|
payload["tags"] = _ensure_list(tags)
|
||||||
|
|
||||||
return payload
|
# Aliases
|
||||||
|
aliases = fm.get("aliases")
|
||||||
|
if aliases:
|
||||||
|
payload["aliases"] = _ensure_list(aliases)
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# Zeit
|
||||||
# CLI – Sichtprüfung
|
for k in ("created", "modified", "date"):
|
||||||
# ---------------------------------------------------------------------------
|
v = fm.get(k) or n.get(k)
|
||||||
|
if v:
|
||||||
|
payload[k] = str(v)
|
||||||
|
|
||||||
|
# Fulltext
|
||||||
|
if "body" in n and n["body"]:
|
||||||
|
payload["fulltext"] = str(n["body"])
|
||||||
|
|
||||||
def _cli() -> None:
|
# JSON Validation
|
||||||
ap = argparse.ArgumentParser(description="Note-Payload aus Markdown erzeugen und anzeigen")
|
json.loads(json.dumps(payload, ensure_ascii=False))
|
||||||
ap.add_argument("--from-file", dest="src", required=True)
|
|
||||||
ap.add_argument("--vault-root", dest="vault_root", default=None)
|
|
||||||
ap.add_argument("--print", dest="do_print", action="store_true")
|
|
||||||
ap.add_argument("--hash-mode", choices=["body", "frontmatter", "full"], default=None)
|
|
||||||
ap.add_argument("--hash-normalize", choices=["canonical", "none"], default=None)
|
|
||||||
ap.add_argument("--hash-source", choices=["parsed", "raw"], default=None)
|
|
||||||
args = ap.parse_args()
|
|
||||||
|
|
||||||
parsed = read_markdown(args.src)
|
return payload
|
||||||
payload = make_note_payload(
|
|
||||||
parsed,
|
|
||||||
vault_root=args.vault_root,
|
|
||||||
hash_mode=args.hash_mode,
|
|
||||||
hash_normalize=args.hash_normalize,
|
|
||||||
hash_source=args.hash_source,
|
|
||||||
file_path=args.src,
|
|
||||||
)
|
|
||||||
if args.do_print:
|
|
||||||
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
||||||
|
|
||||||
if __name__ == "__main__": # pragma: no cover
|
|
||||||
_cli()
|
|
||||||
+210
-44
@@ -1,67 +1,233 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/parser.py
|
||||||
|
DESCRIPTION: Liest Markdown-Dateien fehlertolerant (Encoding-Fallback). Trennt Frontmatter (YAML) vom Body.
|
||||||
|
VERSION: 1.7.1
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: yaml, re, dataclasses, json, io, os
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from dataclasses import dataclass
|
|
||||||
import re
|
|
||||||
import os
|
|
||||||
import unicodedata
|
|
||||||
import yaml
|
|
||||||
from typing import Tuple, Dict
|
|
||||||
|
|
||||||
FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n?", re.DOTALL) # YAML-Frontmatter am Anfang
|
from dataclasses import dataclass
|
||||||
|
from typing import Any, Dict, Optional, Tuple, Iterable, List
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
|
||||||
|
try:
|
||||||
|
import yaml # PyYAML
|
||||||
|
except Exception as e: # pragma: no cover
|
||||||
|
yaml = None # Fehler wird zur Laufzeit geworfen, falls wirklich benötigt
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------
|
||||||
|
# Datamodell
|
||||||
|
# ---------------------------------------------------------------------
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class ParsedNote:
|
class ParsedNote:
|
||||||
frontmatter: Dict
|
frontmatter: Dict[str, Any]
|
||||||
body: str
|
body: str
|
||||||
path: str
|
path: str
|
||||||
|
|
||||||
def _strip_bom(text: str) -> str:
|
|
||||||
return text.lstrip("\ufeff")
|
|
||||||
|
|
||||||
def _normalize_text(t: str) -> str:
|
# ---------------------------------------------------------------------
|
||||||
# Unicode-NFKC + vereinheitlichte Zeilenenden + Trim
|
# Frontmatter-Erkennung
|
||||||
t = unicodedata.normalize("NFKC", t)
|
# ---------------------------------------------------------------------
|
||||||
t = t.replace("\r\n", "\n").replace("\r", "\n")
|
|
||||||
return t
|
|
||||||
|
|
||||||
def read_markdown(path: str) -> ParsedNote:
|
# Öffentliche Kompatibilitäts-Konstante: frühere Skripte importieren FRONTMATTER_RE
|
||||||
with open(path, "r", encoding="utf-8") as f:
|
FRONTMATTER_RE = re.compile(r"^\s*---\s*$") # <— public
|
||||||
raw = _strip_bom(f.read())
|
# Zusätzlich interner Alias (falls jemand ihn referenziert)
|
||||||
raw = _normalize_text(raw)
|
FRONTMATTER_END = FRONTMATTER_RE # <— public alias
|
||||||
|
|
||||||
m = FRONTMATTER_RE.match(raw)
|
# interne Namen bleiben bestehen
|
||||||
front, body = {}, raw
|
_FRONTMATTER_HEAD = FRONTMATTER_RE
|
||||||
if m:
|
_FRONTMATTER_END = FRONTMATTER_RE
|
||||||
yaml_block = m.group(1)
|
|
||||||
body = raw[m.end():]
|
|
||||||
|
def _split_frontmatter(text: str) -> Tuple[Dict[str, Any], str]:
|
||||||
|
"""
|
||||||
|
Zerlegt Text in (frontmatter: dict, body: str).
|
||||||
|
Erkennt Frontmatter nur, wenn die erste Zeile '---' ist und später ein zweites '---' folgt.
|
||||||
|
YAML-Fehler im Frontmatter führen NICHT zum Abbruch: es wird dann ein leeres dict benutzt.
|
||||||
|
"""
|
||||||
|
lines = text.splitlines(True) # keep line endings
|
||||||
|
if not lines:
|
||||||
|
return {}, ""
|
||||||
|
|
||||||
|
if not _FRONTMATTER_HEAD.match(lines[0]):
|
||||||
|
# kein Frontmatter-Header → gesamter Text ist Body
|
||||||
|
return {}, text
|
||||||
|
|
||||||
|
end_idx = None
|
||||||
|
# Suche nach nächstem '---' (max. 2000 Zeilen als Sicherheitslimit)
|
||||||
|
for i in range(1, min(len(lines), 2000)):
|
||||||
|
if _FRONTMATTER_END.match(lines[i]):
|
||||||
|
end_idx = i
|
||||||
|
break
|
||||||
|
|
||||||
|
if end_idx is None:
|
||||||
|
# unvollständiger Frontmatter-Block → behandle alles als Body
|
||||||
|
return {}, text
|
||||||
|
|
||||||
|
fm_raw = "".join(lines[1:end_idx])
|
||||||
|
body = "".join(lines[end_idx + 1:])
|
||||||
|
|
||||||
|
data: Dict[str, Any] = {}
|
||||||
|
if yaml is None:
|
||||||
|
raise RuntimeError("PyYAML ist nicht installiert (pip install pyyaml).")
|
||||||
|
|
||||||
|
try:
|
||||||
|
loaded = yaml.safe_load(fm_raw) or {}
|
||||||
|
if isinstance(loaded, dict):
|
||||||
|
data = loaded
|
||||||
|
else:
|
||||||
|
data = {}
|
||||||
|
except Exception as e:
|
||||||
|
# YAML-Fehler nicht fatal machen
|
||||||
|
print(json.dumps({"warn": "frontmatter_yaml_parse_failed", "error": str(e)}))
|
||||||
|
data = {}
|
||||||
|
|
||||||
|
# optionales kosmetisches Trim: eine führende Leerzeile im Body entfernen
|
||||||
|
if body.startswith("\n"):
|
||||||
|
body = body[1:]
|
||||||
|
|
||||||
|
return data, body
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------
|
||||||
|
# Robustes Lesen mit Encoding-Fallback
|
||||||
|
# ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
_FALLBACK_ENCODINGS: Tuple[str, ...] = ("utf-8", "utf-8-sig", "cp1252", "latin-1")
|
||||||
|
|
||||||
|
|
||||||
|
def _read_text_with_fallback(path: str) -> Tuple[str, str, bool]:
|
||||||
|
"""
|
||||||
|
Liest Datei mit mehreren Decodierungsversuchen.
|
||||||
|
Rückgabe: (text, used_encoding, had_fallback)
|
||||||
|
- had_fallback=True, falls NICHT 'utf-8' verwendet wurde (oder 'utf-8-sig').
|
||||||
|
"""
|
||||||
|
last_err: Optional[str] = None
|
||||||
|
for enc in _FALLBACK_ENCODINGS:
|
||||||
try:
|
try:
|
||||||
front = yaml.safe_load(yaml_block) or {}
|
with io.open(path, "r", encoding=enc, errors="strict") as f:
|
||||||
if not isinstance(front, dict):
|
text = f.read()
|
||||||
raise ValueError("Frontmatter must be a mapping")
|
# 'utf-8-sig' zählt hier als Fallback (weil BOM), aber ist unproblematisch
|
||||||
except yaml.YAMLError as e:
|
return text, enc, (enc != "utf-8")
|
||||||
raise ValueError(f"Invalid YAML frontmatter in {path}: {e}") from e
|
except UnicodeDecodeError as e:
|
||||||
|
last_err = f"{type(e).__name__}: {e}"
|
||||||
|
continue
|
||||||
|
|
||||||
return ParsedNote(frontmatter=front, body=body, path=path)
|
# Letzter, extrem defensiver Fallback: Bytes → UTF-8 mit REPLACE (keine Exception)
|
||||||
|
with open(path, "rb") as fb:
|
||||||
|
raw = fb.read()
|
||||||
|
text = raw.decode("utf-8", errors="replace")
|
||||||
|
print(json.dumps({
|
||||||
|
"path": path,
|
||||||
|
"warn": "encoding_fallback_exhausted",
|
||||||
|
"info": last_err or "unknown"
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
return text, "utf-8(replace)", True
|
||||||
|
|
||||||
RE_WIKILINK = re.compile(r"\[\[([^\]\|#]+)(?:#[^\]]+)?(?:\|[^\]]+)?\]\]") # [[id]] | [[id#anchor]] | [[id|label]]
|
|
||||||
|
|
||||||
def extract_wikilinks(text: str) -> list[str]:
|
# ---------------------------------------------------------------------
|
||||||
return list({m.group(1).strip() for m in RE_WIKILINK.finditer(text)})
|
# Öffentliche API
|
||||||
|
# ---------------------------------------------------------------------
|
||||||
|
|
||||||
def validate_required_frontmatter(fm: dict, required=("title","id","type","status","created")):
|
def read_markdown(path: str) -> Optional[ParsedNote]:
|
||||||
missing = [k for k in required if k not in fm or fm[k] in (None, "")]
|
"""
|
||||||
|
Liest eine Markdown-Datei fehlertolerant:
|
||||||
|
- Erlaubt verschiedene Encodings (UTF-8 bevorzugt, cp1252/latin-1 als Fallback).
|
||||||
|
- Schlägt NICHT mit UnicodeDecodeError fehl.
|
||||||
|
- Gibt ParsedNote(frontmatter, body, path) zurück oder None, falls die Datei nicht existiert.
|
||||||
|
|
||||||
|
Bei Decoding-Fallback wird ein JSON-Warnhinweis geloggt:
|
||||||
|
{"path": "...", "warn": "encoding_fallback_used", "used": "cp1252"}
|
||||||
|
"""
|
||||||
|
if not os.path.exists(path):
|
||||||
|
return None
|
||||||
|
|
||||||
|
text, enc, had_fb = _read_text_with_fallback(path)
|
||||||
|
if had_fb:
|
||||||
|
print(json.dumps({"path": path, "warn": "encoding_fallback_used", "used": enc}, ensure_ascii=False))
|
||||||
|
|
||||||
|
fm, body = _split_frontmatter(text)
|
||||||
|
return ParsedNote(frontmatter=fm or {}, body=body or "", path=path)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_required_frontmatter(fm: Dict[str, Any],
|
||||||
|
required: Tuple[str, ...] = ("id", "title")) -> None:
|
||||||
|
"""
|
||||||
|
Prüft, ob alle Pflichtfelder vorhanden sind.
|
||||||
|
Default-kompatibel: ('id', 'title'), kann aber vom Aufrufer erweitert werden, z. B.:
|
||||||
|
validate_required_frontmatter(fm, required=("id","title","type","status","created"))
|
||||||
|
|
||||||
|
Hebt ValueError, falls Felder fehlen oder leer sind.
|
||||||
|
"""
|
||||||
|
if fm is None:
|
||||||
|
fm = {}
|
||||||
|
missing = []
|
||||||
|
for k in required:
|
||||||
|
v = fm.get(k)
|
||||||
|
if v is None:
|
||||||
|
missing.append(k)
|
||||||
|
elif isinstance(v, str) and not v.strip():
|
||||||
|
missing.append(k)
|
||||||
if missing:
|
if missing:
|
||||||
raise ValueError(f"Missing required frontmatter fields: {', '.join(missing)}")
|
raise ValueError(f"Missing required frontmatter fields: {', '.join(missing)}")
|
||||||
|
|
||||||
# einfache Plausibilitäten
|
# Plausibilitäten: 'tags' sollte eine Liste sein, wenn vorhanden
|
||||||
if not isinstance(fm.get("tags", []), (list, tuple)):
|
if "tags" in fm and fm["tags"] not in (None, "") and not isinstance(fm["tags"], (list, tuple)):
|
||||||
if "tags" in fm and fm["tags"] not in (None, ""):
|
raise ValueError("frontmatter 'tags' must be a list of strings")
|
||||||
raise ValueError("tags must be a list of strings")
|
|
||||||
|
|
||||||
def normalize_frontmatter(fm: dict) -> dict:
|
|
||||||
# kleinere Normalisierungen ohne die Semantik zu verändern
|
def normalize_frontmatter(fm: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
out = dict(fm)
|
"""
|
||||||
if "tags" in out and isinstance(out["tags"], list):
|
Sanfte Normalisierung ohne Semantikänderung:
|
||||||
out["tags"] = [str(t).strip() for t in out["tags"]]
|
- 'tags' → Liste von Strings (Trim)
|
||||||
|
- 'embedding_exclude' → bool
|
||||||
|
- andere Felder unverändert
|
||||||
|
"""
|
||||||
|
out = dict(fm or {})
|
||||||
|
if "tags" in out:
|
||||||
|
if isinstance(out["tags"], str):
|
||||||
|
out["tags"] = [out["tags"].strip()] if out["tags"].strip() else []
|
||||||
|
elif isinstance(out["tags"], list):
|
||||||
|
out["tags"] = [str(t).strip() for t in out["tags"] if t is not None]
|
||||||
|
else:
|
||||||
|
out["tags"] = [str(out["tags"]).strip()] if out["tags"] not in (None, "") else []
|
||||||
if "embedding_exclude" in out:
|
if "embedding_exclude" in out:
|
||||||
out["embedding_exclude"] = bool(out["embedding_exclude"])
|
out["embedding_exclude"] = bool(out["embedding_exclude"])
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------ Wikilinks ---------------------------- #
|
||||||
|
|
||||||
|
# Basismuster für [[...]]; die Normalisierung (id vor '#', vor '|') macht extract_wikilinks
|
||||||
|
_WIKILINK_RE = re.compile(r"\[\[([^\]]+)\]\]")
|
||||||
|
|
||||||
|
|
||||||
|
def extract_wikilinks(text: str) -> List[str]:
|
||||||
|
"""
|
||||||
|
Extrahiert Wikilinks wie [[id]], [[id#anchor]], [[id|label]], [[id#anchor|label]].
|
||||||
|
Rückgabe sind NUR die Ziel-IDs (ohne Anchor/Label), führend/folgend getrimmt.
|
||||||
|
Keine aggressive Slug-Normalisierung (die kann später im Resolver erfolgen).
|
||||||
|
"""
|
||||||
|
if not text:
|
||||||
|
return []
|
||||||
|
out: List[str] = []
|
||||||
|
for m in _WIKILINK_RE.finditer(text):
|
||||||
|
raw = (m.group(1) or "").strip()
|
||||||
|
if not raw:
|
||||||
|
continue
|
||||||
|
# Split an Pipe (Label) → links vor '|'
|
||||||
|
if "|" in raw:
|
||||||
|
raw = raw.split("|", 1)[0].strip()
|
||||||
|
# Split an Anchor
|
||||||
|
if "#" in raw:
|
||||||
|
raw = raw.split("#", 1)[0].strip()
|
||||||
|
if raw:
|
||||||
|
out.append(raw)
|
||||||
|
return out
|
||||||
+133
-96
@@ -1,124 +1,161 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
Name: app/core/qdrant.py
|
FILE: app/core/qdrant.py
|
||||||
Version: v1.4.0 (2025-09-09)
|
DESCRIPTION: Qdrant-Client Factory und Schema-Management. Erstellt Collections und Payload-Indizes.
|
||||||
|
VERSION: 2.2.0
|
||||||
Kurzbeschreibung:
|
STATUS: Active
|
||||||
Qdrant-Client & Collection-Setup für mindnet.
|
DEPENDENCIES: qdrant_client, dataclasses, os
|
||||||
- Stellt sicher, dass {prefix}_notes / {prefix}_chunks / {prefix}_edges existieren.
|
LAST_ANALYSIS: 2025-12-15
|
||||||
- Edges-Collection nutzt 1D Dummy-Vektor.
|
|
||||||
- NEW: ensure_payload_indexes(...) legt sinnvolle Payload-Indizes an.
|
|
||||||
|
|
||||||
Aufruf:
|
|
||||||
from app.core.qdrant import QdrantConfig, get_client, ensure_collections, ensure_payload_indexes
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Optional, Tuple
|
from typing import Optional, Tuple, Dict, List
|
||||||
|
|
||||||
from qdrant_client import QdrantClient
|
from qdrant_client import QdrantClient
|
||||||
from qdrant_client.http import models as rest
|
from qdrant_client.http import models as rest
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Konfiguration
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class QdrantConfig:
|
class QdrantConfig:
|
||||||
url: str
|
host: Optional[str] = None
|
||||||
api_key: Optional[str]
|
port: Optional[int] = None
|
||||||
prefix: str
|
url: Optional[str] = None
|
||||||
dim: int
|
api_key: Optional[str] = None
|
||||||
|
prefix: str = "mindnet"
|
||||||
|
dim: int = 384
|
||||||
|
distance: str = "Cosine" # Cosine | Dot | Euclid
|
||||||
|
on_disk_payload: bool = True
|
||||||
|
|
||||||
@staticmethod
|
@classmethod
|
||||||
def from_env() -> "QdrantConfig":
|
def from_env(cls) -> "QdrantConfig":
|
||||||
url = os.getenv("QDRANT_URL")
|
# Entweder URL ODER Host/Port, API-Key optional
|
||||||
if not url:
|
url = os.getenv("QDRANT_URL") or None
|
||||||
host = os.getenv("QDRANT_HOST", "127.0.0.1")
|
host = os.getenv("QDRANT_HOST") or None
|
||||||
port = int(os.getenv("QDRANT_PORT", "6333"))
|
port = os.getenv("QDRANT_PORT")
|
||||||
url = f"http://{host}:{port}"
|
port = int(port) if port else None
|
||||||
api_key = os.getenv("QDRANT_API_KEY") or None
|
api_key = os.getenv("QDRANT_API_KEY") or None
|
||||||
prefix = os.getenv("COLLECTION_PREFIX", "mindnet")
|
prefix = os.getenv("COLLECTION_PREFIX") or "mindnet"
|
||||||
dim = int(os.getenv("VECTOR_DIM", "384"))
|
dim = int(os.getenv("VECTOR_DIM") or 384)
|
||||||
return QdrantConfig(url=url, api_key=api_key, prefix=prefix, dim=dim)
|
distance = os.getenv("DISTANCE", "Cosine")
|
||||||
|
on_disk_payload = (os.getenv("ON_DISK_PAYLOAD", "true").lower() == "true")
|
||||||
|
return cls(
|
||||||
|
host=host, port=port, url=url, api_key=api_key,
|
||||||
|
prefix=prefix, dim=dim, distance=distance, on_disk_payload=on_disk_payload
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def get_client(cfg: QdrantConfig) -> QdrantClient:
|
def get_client(cfg: QdrantConfig) -> QdrantClient:
|
||||||
return QdrantClient(url=cfg.url, api_key=cfg.api_key)
|
# QdrantClient akzeptiert entweder url=... oder host/port
|
||||||
|
if cfg.url:
|
||||||
|
return QdrantClient(url=cfg.url, api_key=cfg.api_key, timeout=60.0)
|
||||||
|
return QdrantClient(host=cfg.host or "127.0.0.1", port=cfg.port or 6333, api_key=cfg.api_key, timeout=60.0)
|
||||||
|
|
||||||
|
|
||||||
def _create_notes(client: QdrantClient, name: str, dim: int) -> None:
|
# ---------------------------------------------------------------------------
|
||||||
if not client.collection_exists(name):
|
# Collections
|
||||||
client.create_collection(
|
# ---------------------------------------------------------------------------
|
||||||
collection_name=name,
|
|
||||||
vectors_config=rest.VectorParams(size=dim, distance=rest.Distance.COSINE),
|
|
||||||
)
|
|
||||||
|
|
||||||
def _create_chunks(client: QdrantClient, name: str, dim: int) -> None:
|
|
||||||
if not client.collection_exists(name):
|
|
||||||
client.create_collection(
|
|
||||||
collection_name=name,
|
|
||||||
vectors_config=rest.VectorParams(size=dim, distance=rest.Distance.COSINE),
|
|
||||||
)
|
|
||||||
|
|
||||||
def _create_edges(client: QdrantClient, name: str) -> None:
|
|
||||||
if not client.collection_exists(name):
|
|
||||||
client.create_collection(
|
|
||||||
collection_name=name,
|
|
||||||
vectors_config=rest.VectorParams(size=1, distance=rest.Distance.DOT), # 1D-Dummy
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def ensure_collections(client: QdrantClient, prefix: str, dim: int, destructive: bool = False) -> None:
|
|
||||||
notes = f"{prefix}_notes"
|
|
||||||
chunks = f"{prefix}_chunks"
|
|
||||||
edges = f"{prefix}_edges"
|
|
||||||
|
|
||||||
_create_notes(client, notes, dim)
|
|
||||||
_create_chunks(client, chunks, dim)
|
|
||||||
|
|
||||||
if client.collection_exists(edges):
|
|
||||||
try:
|
|
||||||
info = client.get_collection(edges)
|
|
||||||
vectors_cfg = getattr(getattr(info.result, "config", None), "params", None)
|
|
||||||
has_vectors = getattr(vectors_cfg, "vectors", None) is not None
|
|
||||||
except Exception:
|
|
||||||
has_vectors = True
|
|
||||||
if not has_vectors:
|
|
||||||
if destructive:
|
|
||||||
client.delete_collection(edges)
|
|
||||||
_create_edges(client, edges)
|
|
||||||
else:
|
|
||||||
print(f"[ensure_collections] WARN: '{edges}' ohne VectorConfig; destructive=False.", flush=True)
|
|
||||||
else:
|
|
||||||
_create_edges(client, edges)
|
|
||||||
|
|
||||||
|
|
||||||
def collection_names(prefix: str) -> Tuple[str, str, str]:
|
def collection_names(prefix: str) -> Tuple[str, str, str]:
|
||||||
return (f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges")
|
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
||||||
|
|
||||||
|
|
||||||
# -------------------------------
|
def _vector_params(dim: int, distance: str) -> rest.VectorParams:
|
||||||
# NEW: Payload-Indexing
|
# Distance: "Cosine" | "Dot" | "Euclid"
|
||||||
# -------------------------------
|
dist = getattr(rest.Distance, distance.capitalize(), rest.Distance.COSINE)
|
||||||
|
return rest.VectorParams(size=dim, distance=dist)
|
||||||
|
|
||||||
def _safe_create_index(client: QdrantClient, col: str, field: str, schema: rest.PayloadSchemaType):
|
|
||||||
try:
|
def ensure_collections(client: QdrantClient, prefix: str, dim: int) -> None:
|
||||||
client.create_payload_index(
|
"""Legt mindnet_notes, mindnet_chunks, mindnet_edges an (falls nicht vorhanden)."""
|
||||||
collection_name=col,
|
notes, chunks, edges = collection_names(prefix)
|
||||||
field_name=field,
|
|
||||||
field_schema=schema,
|
# notes
|
||||||
|
if not client.collection_exists(notes):
|
||||||
|
client.create_collection(
|
||||||
|
collection_name=notes,
|
||||||
|
vectors_config=_vector_params(dim, os.getenv("DISTANCE", "Cosine")),
|
||||||
|
on_disk_payload=True,
|
||||||
)
|
)
|
||||||
except Exception:
|
# chunks
|
||||||
# bereits vorhanden oder nicht unterstütztes Schema → ignorieren
|
if not client.collection_exists(chunks):
|
||||||
pass
|
client.create_collection(
|
||||||
|
collection_name=chunks,
|
||||||
|
vectors_config=_vector_params(dim, os.getenv("DISTANCE", "Cosine")),
|
||||||
|
on_disk_payload=True,
|
||||||
|
)
|
||||||
|
# edges (Dummy-Vektor, Filter via Payload)
|
||||||
|
if not client.collection_exists(edges):
|
||||||
|
client.create_collection(
|
||||||
|
collection_name=edges,
|
||||||
|
vectors_config=_vector_params(1, "Dot"),
|
||||||
|
on_disk_payload=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Payload-Indizes
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _ensure_index(client: QdrantClient, collection: str, field: str, schema: rest.PayloadSchemaType) -> None:
|
||||||
|
"""Idempotentes Anlegen eines Payload-Indexes für ein Feld."""
|
||||||
|
try:
|
||||||
|
client.create_payload_index(collection_name=collection, field_name=field, field_schema=schema, wait=True)
|
||||||
|
except Exception as e:
|
||||||
|
# Fehler ignorieren, falls Index bereits existiert oder Server "already indexed" meldet.
|
||||||
|
# Für Debugging ggf. Logging ergänzen.
|
||||||
|
_ = e
|
||||||
|
|
||||||
|
|
||||||
def ensure_payload_indexes(client: QdrantClient, prefix: str) -> None:
|
def ensure_payload_indexes(client: QdrantClient, prefix: str) -> None:
|
||||||
|
"""
|
||||||
|
Stellt sicher, dass alle benötigten Payload-Indizes existieren.
|
||||||
|
- notes: note_id(KEYWORD), type(KEYWORD), title(TEXT), updated(INTEGER), tags(KEYWORD)
|
||||||
|
- chunks: note_id(KEYWORD), chunk_id(KEYWORD), index(INTEGER), type(KEYWORD), tags(KEYWORD)
|
||||||
|
- edges: note_id(KEYWORD), kind(KEYWORD), scope(KEYWORD), source_id(KEYWORD), target_id(KEYWORD), chunk_id(KEYWORD)
|
||||||
|
"""
|
||||||
notes, chunks, edges = collection_names(prefix)
|
notes, chunks, edges = collection_names(prefix)
|
||||||
# Notes
|
|
||||||
_safe_create_index(client, notes, "note_id", rest.PayloadSchemaType.KEYWORD)
|
# NOTES
|
||||||
# Chunks
|
for field, schema in [
|
||||||
_safe_create_index(client, chunks, "note_id", rest.PayloadSchemaType.KEYWORD)
|
("note_id", rest.PayloadSchemaType.KEYWORD),
|
||||||
_safe_create_index(client, chunks, "chunk_index", rest.PayloadSchemaType.INTEGER)
|
("type", rest.PayloadSchemaType.KEYWORD),
|
||||||
# Edges
|
("title", rest.PayloadSchemaType.TEXT),
|
||||||
for f in ("kind", "scope", "source_id", "target_id", "note_id"):
|
("updated", rest.PayloadSchemaType.INTEGER),
|
||||||
_safe_create_index(client, edges, f, rest.PayloadSchemaType.KEYWORD)
|
("tags", rest.PayloadSchemaType.KEYWORD),
|
||||||
|
]:
|
||||||
|
_ensure_index(client, notes, field, schema)
|
||||||
|
|
||||||
|
# CHUNKS
|
||||||
|
for field, schema in [
|
||||||
|
("note_id", rest.PayloadSchemaType.KEYWORD),
|
||||||
|
("chunk_id", rest.PayloadSchemaType.KEYWORD),
|
||||||
|
("index", rest.PayloadSchemaType.INTEGER),
|
||||||
|
("type", rest.PayloadSchemaType.KEYWORD),
|
||||||
|
("tags", rest.PayloadSchemaType.KEYWORD),
|
||||||
|
]:
|
||||||
|
_ensure_index(client, chunks, field, schema)
|
||||||
|
|
||||||
|
# EDGES
|
||||||
|
for field, schema in [
|
||||||
|
("note_id", rest.PayloadSchemaType.KEYWORD),
|
||||||
|
("kind", rest.PayloadSchemaType.KEYWORD),
|
||||||
|
("scope", rest.PayloadSchemaType.KEYWORD),
|
||||||
|
("source_id", rest.PayloadSchemaType.KEYWORD),
|
||||||
|
("target_id", rest.PayloadSchemaType.KEYWORD),
|
||||||
|
("chunk_id", rest.PayloadSchemaType.KEYWORD),
|
||||||
|
]:
|
||||||
|
_ensure_index(client, edges, field, schema)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"QdrantConfig",
|
||||||
|
"get_client",
|
||||||
|
"ensure_collections",
|
||||||
|
"ensure_payload_indexes",
|
||||||
|
"collection_names",
|
||||||
|
]
|
||||||
+229
-73
@@ -1,55 +1,30 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
app/core/qdrant_points.py
|
FILE: app/core/qdrant_points.py
|
||||||
|
DESCRIPTION: Object-Mapper für Qdrant. Konvertiert JSON-Payloads (Notes, Chunks, Edges) in PointStructs und generiert deterministische UUIDs.
|
||||||
Zweck
|
VERSION: 1.5.0
|
||||||
- Gemeinsame Helfer zum Erzeugen von Qdrant-Points für Notes, Chunks und Edges.
|
STATUS: Active
|
||||||
- Abwärtskompatibel zu altem Edge-Payload-Schema aus edges.py:
|
DEPENDENCIES: qdrant_client, uuid, os
|
||||||
- alt: {'edge_type','src_id','dst_id', ...}
|
LAST_ANALYSIS: 2025-12-15
|
||||||
- neu: {'kind','source_id','target_id', ...}
|
|
||||||
|
|
||||||
Version
|
|
||||||
- 1.3 (2025-09-08)
|
|
||||||
|
|
||||||
Änderungen (ggü. 1.2)
|
|
||||||
- points_for_edges() akzeptiert jetzt beide Edge-Schemata.
|
|
||||||
- Normalisiert alte Felder auf 'kind' / 'source_id' / 'target_id' und schreibt eine
|
|
||||||
stabile 'edge_id' zurück in die Payload.
|
|
||||||
- Verhindert, dass mehrere Edges dieselbe Point-ID erhalten (Root Cause deiner 1-Edge-Sammlung).
|
|
||||||
|
|
||||||
Aufruf / Verwendung
|
|
||||||
- Wird von Import-/Backfill-Skripten via:
|
|
||||||
from app.core.qdrant_points import points_for_note, points_for_chunks, points_for_edges, upsert_batch
|
|
||||||
eingebunden. Keine CLI.
|
|
||||||
|
|
||||||
Hinweise
|
|
||||||
- Edges bekommen absichtlich einen 1D-Dummy-Vektor [0.0], damit Qdrant das Objekt akzeptiert.
|
|
||||||
- Die Point-IDs werden deterministisch aus stabilen Strings (UUIDv5) abgeleitet.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
import os
|
||||||
import uuid
|
import uuid
|
||||||
from typing import List, Tuple
|
from typing import List, Tuple, Iterable, Optional, Dict, Any
|
||||||
from qdrant_client.http import models as rest
|
|
||||||
|
|
||||||
|
from qdrant_client.http import models as rest
|
||||||
|
from qdrant_client import QdrantClient
|
||||||
|
|
||||||
|
# --------------------- ID helpers ---------------------
|
||||||
|
|
||||||
|
def _to_uuid(stable_key: str) -> str:
|
||||||
|
return str(uuid.uuid5(uuid.NAMESPACE_URL, stable_key))
|
||||||
|
|
||||||
def _names(prefix: str) -> Tuple[str, str, str]:
|
def _names(prefix: str) -> Tuple[str, str, str]:
|
||||||
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
||||||
|
|
||||||
|
# --------------------- Points builders ---------------------
|
||||||
|
|
||||||
def _to_uuid(stable_key: str) -> str:
|
def points_for_note(prefix: str, note_payload: dict, note_vec: List[float] | None, dim: int) -> Tuple[str, List[rest.PointStruct]]:
|
||||||
"""Stabile UUIDv5 aus einem String-Key (deterministisch)."""
|
|
||||||
return str(uuid.uuid5(uuid.NAMESPACE_URL, stable_key))
|
|
||||||
|
|
||||||
|
|
||||||
def points_for_note(
|
|
||||||
prefix: str,
|
|
||||||
note_payload: dict,
|
|
||||||
note_vec: List[float] | None,
|
|
||||||
dim: int,
|
|
||||||
) -> Tuple[str, List[rest.PointStruct]]:
|
|
||||||
"""Notes-Collection: falls kein Note-Embedding -> Nullvektor der Länge dim."""
|
|
||||||
notes_col, _, _ = _names(prefix)
|
notes_col, _, _ = _names(prefix)
|
||||||
vector = note_vec if note_vec is not None else [0.0] * int(dim)
|
vector = note_vec if note_vec is not None else [0.0] * int(dim)
|
||||||
raw_note_id = note_payload.get("note_id") or note_payload.get("id") or "missing-note-id"
|
raw_note_id = note_payload.get("note_id") or note_payload.get("id") or "missing-note-id"
|
||||||
@@ -57,18 +32,7 @@ def points_for_note(
|
|||||||
pt = rest.PointStruct(id=point_id, vector=vector, payload=note_payload)
|
pt = rest.PointStruct(id=point_id, vector=vector, payload=note_payload)
|
||||||
return notes_col, [pt]
|
return notes_col, [pt]
|
||||||
|
|
||||||
|
def points_for_chunks(prefix: str, chunk_payloads: List[dict], vectors: List[List[float]]) -> Tuple[str, List[rest.PointStruct]]:
|
||||||
def points_for_chunks(
|
|
||||||
prefix: str,
|
|
||||||
chunk_payloads: List[dict],
|
|
||||||
vectors: List[List[float]],
|
|
||||||
) -> Tuple[str, List[rest.PointStruct]]:
|
|
||||||
"""
|
|
||||||
Chunks-Collection: erwartet pro Chunk einen Vektor.
|
|
||||||
Robustheit:
|
|
||||||
- Fehlt 'chunk_id', nutze 'id', sonst baue '${note_id}#${i}' (1-basiert).
|
|
||||||
- Schreibe die abgeleitete ID zurück in die Payload (pl['chunk_id']).
|
|
||||||
"""
|
|
||||||
_, chunks_col, _ = _names(prefix)
|
_, chunks_col, _ = _names(prefix)
|
||||||
points: List[rest.PointStruct] = []
|
points: List[rest.PointStruct] = []
|
||||||
for i, (pl, vec) in enumerate(zip(chunk_payloads, vectors), start=1):
|
for i, (pl, vec) in enumerate(zip(chunk_payloads, vectors), start=1):
|
||||||
@@ -81,22 +45,12 @@ def points_for_chunks(
|
|||||||
points.append(rest.PointStruct(id=point_id, vector=vec, payload=pl))
|
points.append(rest.PointStruct(id=point_id, vector=vec, payload=pl))
|
||||||
return chunks_col, points
|
return chunks_col, points
|
||||||
|
|
||||||
|
|
||||||
def _normalize_edge_payload(pl: dict) -> dict:
|
def _normalize_edge_payload(pl: dict) -> dict:
|
||||||
"""
|
|
||||||
Sorgt für kompatible Feldnamen.
|
|
||||||
akzeptiert:
|
|
||||||
- neu: kind, source_id, target_id, seq?
|
|
||||||
- alt: edge_type, src_id, dst_id, order?/index?
|
|
||||||
schreibt zurück: kind, source_id, target_id, seq?
|
|
||||||
"""
|
|
||||||
# bereits neu?
|
|
||||||
kind = pl.get("kind") or pl.get("edge_type") or "edge"
|
kind = pl.get("kind") or pl.get("edge_type") or "edge"
|
||||||
source_id = pl.get("source_id") or pl.get("src_id") or "unknown-src"
|
source_id = pl.get("source_id") or pl.get("src_id") or "unknown-src"
|
||||||
target_id = pl.get("target_id") or pl.get("dst_id") or "unknown-tgt"
|
target_id = pl.get("target_id") or pl.get("dst_id") or "unknown-tgt"
|
||||||
seq = pl.get("seq") or pl.get("order") or pl.get("index")
|
seq = pl.get("seq") or pl.get("order") or pl.get("index")
|
||||||
|
|
||||||
# in Payload zurückschreiben (ohne alte Felder zu entfernen → maximal kompatibel)
|
|
||||||
pl.setdefault("kind", kind)
|
pl.setdefault("kind", kind)
|
||||||
pl.setdefault("source_id", source_id)
|
pl.setdefault("source_id", source_id)
|
||||||
pl.setdefault("target_id", target_id)
|
pl.setdefault("target_id", target_id)
|
||||||
@@ -104,18 +58,11 @@ def _normalize_edge_payload(pl: dict) -> dict:
|
|||||||
pl["seq"] = seq
|
pl["seq"] = seq
|
||||||
return pl
|
return pl
|
||||||
|
|
||||||
|
|
||||||
def points_for_edges(prefix: str, edge_payloads: List[dict]) -> Tuple[str, List[rest.PointStruct]]:
|
def points_for_edges(prefix: str, edge_payloads: List[dict]) -> Tuple[str, List[rest.PointStruct]]:
|
||||||
"""
|
|
||||||
Edges-Collection mit 1D-Dummy-Vektor.
|
|
||||||
- Akzeptiert sowohl neues als auch altes Edge-Schema (siehe _normalize_edge_payload).
|
|
||||||
- Fehlt 'edge_id', wird sie stabil aus (kind, source_id, target_id, seq) konstruiert.
|
|
||||||
"""
|
|
||||||
_, _, edges_col = _names(prefix)
|
_, _, edges_col = _names(prefix)
|
||||||
points: List[rest.PointStruct] = []
|
points: List[rest.PointStruct] = []
|
||||||
for raw in edge_payloads:
|
for raw in edge_payloads:
|
||||||
pl = _normalize_edge_payload(raw)
|
pl = _normalize_edge_payload(raw)
|
||||||
|
|
||||||
edge_id = pl.get("edge_id")
|
edge_id = pl.get("edge_id")
|
||||||
if not edge_id:
|
if not edge_id:
|
||||||
kind = pl.get("kind", "edge")
|
kind = pl.get("kind", "edge")
|
||||||
@@ -124,13 +71,222 @@ def points_for_edges(prefix: str, edge_payloads: List[dict]) -> Tuple[str, List[
|
|||||||
seq = pl.get("seq") or ""
|
seq = pl.get("seq") or ""
|
||||||
edge_id = f"{kind}:{s}->{t}#{seq}"
|
edge_id = f"{kind}:{s}->{t}#{seq}"
|
||||||
pl["edge_id"] = edge_id
|
pl["edge_id"] = edge_id
|
||||||
|
|
||||||
point_id = _to_uuid(edge_id)
|
point_id = _to_uuid(edge_id)
|
||||||
points.append(rest.PointStruct(id=point_id, vector=[0.0], payload=pl))
|
points.append(rest.PointStruct(id=point_id, vector=[0.0], payload=pl))
|
||||||
return edges_col, points
|
return edges_col, points
|
||||||
|
|
||||||
|
# --------------------- Vector schema & overrides ---------------------
|
||||||
|
|
||||||
def upsert_batch(client, collection: str, points: List[rest.PointStruct]) -> None:
|
def _preferred_name(candidates: List[str]) -> str:
|
||||||
|
for k in ("text", "default", "embedding", "content"):
|
||||||
|
if k in candidates:
|
||||||
|
return k
|
||||||
|
return sorted(candidates)[0]
|
||||||
|
|
||||||
|
def _env_override_for_collection(collection: str) -> Optional[str]:
|
||||||
|
"""
|
||||||
|
Returns:
|
||||||
|
- "__single__" to force single-vector
|
||||||
|
- concrete name (str) to force named-vector with that name
|
||||||
|
- None to auto-detect
|
||||||
|
"""
|
||||||
|
base = os.getenv("MINDNET_VECTOR_NAME")
|
||||||
|
if collection.endswith("_notes"):
|
||||||
|
base = os.getenv("NOTES_VECTOR_NAME", base)
|
||||||
|
elif collection.endswith("_chunks"):
|
||||||
|
base = os.getenv("CHUNKS_VECTOR_NAME", base)
|
||||||
|
elif collection.endswith("_edges"):
|
||||||
|
base = os.getenv("EDGES_VECTOR_NAME", base)
|
||||||
|
|
||||||
|
if not base:
|
||||||
|
return None
|
||||||
|
val = base.strip()
|
||||||
|
if val.lower() in ("__single__", "single"):
|
||||||
|
return "__single__"
|
||||||
|
return val # concrete name
|
||||||
|
|
||||||
|
def _get_vector_schema(client: QdrantClient, collection_name: str) -> dict:
|
||||||
|
"""
|
||||||
|
Return {"kind": "single", "size": int} or {"kind": "named", "names": [...], "primary": str}.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
info = client.get_collection(collection_name=collection_name)
|
||||||
|
vecs = getattr(info, "vectors", None)
|
||||||
|
# Single-vector config
|
||||||
|
if hasattr(vecs, "size") and isinstance(vecs.size, int):
|
||||||
|
return {"kind": "single", "size": vecs.size}
|
||||||
|
# Named-vectors config (dict-like in .config)
|
||||||
|
cfg = getattr(vecs, "config", None)
|
||||||
|
if isinstance(cfg, dict) and cfg:
|
||||||
|
names = list(cfg.keys())
|
||||||
|
if names:
|
||||||
|
return {"kind": "named", "names": names, "primary": _preferred_name(names)}
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return {"kind": "single", "size": None}
|
||||||
|
|
||||||
|
def _as_named(points: List[rest.PointStruct], name: str) -> List[rest.PointStruct]:
|
||||||
|
out: List[rest.PointStruct] = []
|
||||||
|
for pt in points:
|
||||||
|
vec = getattr(pt, "vector", None)
|
||||||
|
if isinstance(vec, dict):
|
||||||
|
if name in vec:
|
||||||
|
out.append(pt)
|
||||||
|
else:
|
||||||
|
# take any existing entry; if empty dict fallback to [0.0]
|
||||||
|
fallback_vec = None
|
||||||
|
try:
|
||||||
|
fallback_vec = list(next(iter(vec.values())))
|
||||||
|
except Exception:
|
||||||
|
fallback_vec = [0.0]
|
||||||
|
out.append(rest.PointStruct(id=pt.id, vector={name: fallback_vec}, payload=pt.payload))
|
||||||
|
elif vec is not None:
|
||||||
|
out.append(rest.PointStruct(id=pt.id, vector={name: vec}, payload=pt.payload))
|
||||||
|
else:
|
||||||
|
out.append(pt)
|
||||||
|
return out
|
||||||
|
|
||||||
|
# --------------------- Qdrant ops ---------------------
|
||||||
|
|
||||||
|
def upsert_batch(client: QdrantClient, collection: str, points: List[rest.PointStruct]) -> None:
|
||||||
if not points:
|
if not points:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# 1) ENV overrides come first
|
||||||
|
override = _env_override_for_collection(collection)
|
||||||
|
if override == "__single__":
|
||||||
|
client.upsert(collection_name=collection, points=points, wait=True)
|
||||||
|
return
|
||||||
|
elif isinstance(override, str):
|
||||||
|
client.upsert(collection_name=collection, points=_as_named(points, override), wait=True)
|
||||||
|
return
|
||||||
|
|
||||||
|
# 2) Auto-detect schema
|
||||||
|
schema = _get_vector_schema(client, collection)
|
||||||
|
if schema.get("kind") == "named":
|
||||||
|
name = schema.get("primary") or _preferred_name(schema.get("names") or [])
|
||||||
|
client.upsert(collection_name=collection, points=_as_named(points, name), wait=True)
|
||||||
|
return
|
||||||
|
|
||||||
|
# 3) Fallback single-vector
|
||||||
client.upsert(collection_name=collection, points=points, wait=True)
|
client.upsert(collection_name=collection, points=points, wait=True)
|
||||||
|
|
||||||
|
# --- Optional search helpers ---
|
||||||
|
|
||||||
|
def _filter_any(field: str, values: Iterable[str]) -> rest.Filter:
|
||||||
|
return rest.Filter(should=[rest.FieldCondition(key=field, match=rest.MatchValue(value=v)) for v in values])
|
||||||
|
|
||||||
|
def _merge_filters(*filters: Optional[rest.Filter]) -> Optional[rest.Filter]:
|
||||||
|
fs = [f for f in filters if f is not None]
|
||||||
|
if not fs:
|
||||||
|
return None
|
||||||
|
if len(fs) == 1:
|
||||||
|
return fs[0]
|
||||||
|
must = []
|
||||||
|
for f in fs:
|
||||||
|
if getattr(f, "must", None):
|
||||||
|
must.extend(f.must)
|
||||||
|
if getattr(f, "should", None):
|
||||||
|
must.append(rest.Filter(should=f.should))
|
||||||
|
return rest.Filter(must=must)
|
||||||
|
|
||||||
|
def _filter_from_dict(filters: Optional[Dict[str, Any]]) -> Optional[rest.Filter]:
|
||||||
|
if not filters:
|
||||||
|
return None
|
||||||
|
parts = []
|
||||||
|
for k, v in filters.items():
|
||||||
|
if isinstance(v, (list, tuple, set)):
|
||||||
|
parts.append(_filter_any(k, [str(x) for x in v]))
|
||||||
|
else:
|
||||||
|
parts.append(rest.Filter(must=[rest.FieldCondition(key=k, match=rest.MatchValue(value=v))]))
|
||||||
|
return _merge_filters(*parts)
|
||||||
|
|
||||||
|
def search_chunks_by_vector(client: QdrantClient, prefix: str, vector: List[float], top: int = 10, filters: Optional[Dict[str, Any]] = None) -> List[Tuple[str, float, dict]]:
|
||||||
|
_, chunks_col, _ = _names(prefix)
|
||||||
|
flt = _filter_from_dict(filters)
|
||||||
|
res = client.search(collection_name=chunks_col, query_vector=vector, limit=top, with_payload=True, with_vectors=False, query_filter=flt)
|
||||||
|
out: List[Tuple[str, float, dict]] = []
|
||||||
|
for r in res:
|
||||||
|
out.append((str(r.id), float(r.score), dict(r.payload or {})))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# --- Edge retrieval helper ---
|
||||||
|
|
||||||
|
def get_edges_for_sources(
|
||||||
|
client: QdrantClient,
|
||||||
|
prefix: str,
|
||||||
|
source_ids: Iterable[str],
|
||||||
|
edge_types: Optional[Iterable[str]] = None,
|
||||||
|
limit: int = 2048,
|
||||||
|
) -> List[Dict[str, Any]]:
|
||||||
|
"""Retrieve edge payloads from the <prefix>_edges collection.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
client: QdrantClient instance.
|
||||||
|
prefix: Mindnet collection prefix (e.g. "mindnet").
|
||||||
|
source_ids: Iterable of source_id values (typically chunk_ids or note_ids).
|
||||||
|
edge_types: Optional iterable of edge kinds (e.g. ["references", "depends_on"]). If None,
|
||||||
|
all kinds are returned.
|
||||||
|
limit: Maximum number of edge payloads to return.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A list of edge payload dicts, e.g.:
|
||||||
|
{
|
||||||
|
"note_id": "...",
|
||||||
|
"chunk_id": "...",
|
||||||
|
"kind": "references" | "depends_on" | ...,
|
||||||
|
"scope": "chunk",
|
||||||
|
"source_id": "...",
|
||||||
|
"target_id": "...",
|
||||||
|
"rule_id": "...",
|
||||||
|
"confidence": 0.7,
|
||||||
|
...
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
source_ids = list(source_ids)
|
||||||
|
if not source_ids or limit <= 0:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# Resolve collection name
|
||||||
|
_, _, edges_col = _names(prefix)
|
||||||
|
|
||||||
|
# Build filter: source_id IN source_ids
|
||||||
|
src_filter = _filter_any("source_id", [str(s) for s in source_ids])
|
||||||
|
|
||||||
|
# Optional: kind IN edge_types
|
||||||
|
kind_filter = None
|
||||||
|
if edge_types:
|
||||||
|
kind_filter = _filter_any("kind", [str(k) for k in edge_types])
|
||||||
|
|
||||||
|
flt = _merge_filters(src_filter, kind_filter)
|
||||||
|
|
||||||
|
out: List[Dict[str, Any]] = []
|
||||||
|
next_page = None
|
||||||
|
remaining = int(limit)
|
||||||
|
|
||||||
|
# Use paginated scroll API; we don't need vectors, only payloads.
|
||||||
|
while remaining > 0:
|
||||||
|
batch_limit = min(256, remaining)
|
||||||
|
res, next_page = client.scroll(
|
||||||
|
collection_name=edges_col,
|
||||||
|
scroll_filter=flt,
|
||||||
|
limit=batch_limit,
|
||||||
|
with_payload=True,
|
||||||
|
with_vectors=False,
|
||||||
|
offset=next_page,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not res:
|
||||||
|
break
|
||||||
|
|
||||||
|
for r in res:
|
||||||
|
out.append(dict(r.payload or {}))
|
||||||
|
remaining -= 1
|
||||||
|
if remaining <= 0:
|
||||||
|
break
|
||||||
|
|
||||||
|
if next_page is None or remaining <= 0:
|
||||||
|
break
|
||||||
|
|
||||||
|
return out
|
||||||
@@ -0,0 +1,338 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/retriever.py
|
||||||
|
DESCRIPTION: Implementiert die Hybrid-Suche (Vektor + Graph-Expansion) und das Scoring-Modell (Explainability).
|
||||||
|
VERSION: 0.5.3
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.config, app.models.dto, app.core.qdrant*, app.services.embeddings_client, app.core.graph_adapter
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from functools import lru_cache
|
||||||
|
from typing import Any, Dict, List, Tuple, Iterable, Optional
|
||||||
|
|
||||||
|
from app.config import get_settings
|
||||||
|
from app.models.dto import (
|
||||||
|
QueryRequest,
|
||||||
|
QueryResponse,
|
||||||
|
QueryHit,
|
||||||
|
Explanation,
|
||||||
|
ScoreBreakdown,
|
||||||
|
Reason,
|
||||||
|
EdgeDTO
|
||||||
|
)
|
||||||
|
import app.core.qdrant as qdr
|
||||||
|
import app.core.qdrant_points as qp
|
||||||
|
import app.services.embeddings_client as ec
|
||||||
|
import app.core.graph_adapter as ga
|
||||||
|
|
||||||
|
try:
|
||||||
|
import yaml # type: ignore[import]
|
||||||
|
except Exception: # pragma: no cover
|
||||||
|
yaml = None # type: ignore[assignment]
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def _get_scoring_weights() -> Tuple[float, float, float]:
|
||||||
|
"""Liefert (semantic_weight, edge_weight, centrality_weight) für den Retriever."""
|
||||||
|
settings = get_settings()
|
||||||
|
sem = float(getattr(settings, "RETRIEVER_W_SEM", 1.0))
|
||||||
|
edge = float(getattr(settings, "RETRIEVER_W_EDGE", 0.0))
|
||||||
|
cent = float(getattr(settings, "RETRIEVER_W_CENT", 0.0))
|
||||||
|
|
||||||
|
config_path = os.getenv("MINDNET_RETRIEVER_CONFIG", "config/retriever.yaml")
|
||||||
|
if yaml is None:
|
||||||
|
return sem, edge, cent
|
||||||
|
try:
|
||||||
|
if os.path.exists(config_path):
|
||||||
|
with open(config_path, "r", encoding="utf-8") as f:
|
||||||
|
data = yaml.safe_load(f) or {}
|
||||||
|
scoring = data.get("scoring", {}) or {}
|
||||||
|
sem = float(scoring.get("semantic_weight", sem))
|
||||||
|
edge = float(scoring.get("edge_weight", edge))
|
||||||
|
cent = float(scoring.get("centrality_weight", cent))
|
||||||
|
except Exception:
|
||||||
|
return sem, edge, cent
|
||||||
|
return sem, edge, cent
|
||||||
|
|
||||||
|
|
||||||
|
def _get_client_and_prefix() -> Tuple[Any, str]:
|
||||||
|
"""Liefert (QdrantClient, prefix)."""
|
||||||
|
cfg = qdr.QdrantConfig.from_env()
|
||||||
|
client = qdr.get_client(cfg)
|
||||||
|
return client, cfg.prefix
|
||||||
|
|
||||||
|
|
||||||
|
def _get_query_vector(req: QueryRequest) -> List[float]:
|
||||||
|
"""Liefert den Query-Vektor aus dem Request."""
|
||||||
|
if req.query_vector:
|
||||||
|
return list(req.query_vector)
|
||||||
|
|
||||||
|
if not req.query:
|
||||||
|
raise ValueError("QueryRequest benötigt entweder query oder query_vector")
|
||||||
|
|
||||||
|
settings = get_settings()
|
||||||
|
model_name = settings.MODEL_NAME
|
||||||
|
|
||||||
|
try:
|
||||||
|
return ec.embed_text(req.query, model_name=model_name)
|
||||||
|
except TypeError:
|
||||||
|
return ec.embed_text(req.query)
|
||||||
|
|
||||||
|
|
||||||
|
def _semantic_hits(
|
||||||
|
client: Any,
|
||||||
|
prefix: str,
|
||||||
|
vector: List[float],
|
||||||
|
top_k: int,
|
||||||
|
filters: Dict[str, Any] | None = None,
|
||||||
|
) -> List[Tuple[str, float, Dict[str, Any]]]:
|
||||||
|
"""Führt eine semantische Suche aus."""
|
||||||
|
flt = filters or None
|
||||||
|
raw_hits = qp.search_chunks_by_vector(client, prefix, vector, top=top_k, filters=flt)
|
||||||
|
results: List[Tuple[str, float, Dict[str, Any]]] = []
|
||||||
|
for pid, score, payload in raw_hits:
|
||||||
|
results.append((str(pid), float(score), dict(payload or {})))
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def _compute_total_score(
|
||||||
|
semantic_score: float,
|
||||||
|
payload: Dict[str, Any],
|
||||||
|
edge_bonus: float = 0.0,
|
||||||
|
cent_bonus: float = 0.0,
|
||||||
|
) -> Tuple[float, float, float]:
|
||||||
|
"""Berechnet total_score."""
|
||||||
|
raw_weight = payload.get("retriever_weight", 1.0)
|
||||||
|
try:
|
||||||
|
weight = float(raw_weight)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
weight = 1.0
|
||||||
|
if weight < 0.0:
|
||||||
|
weight = 0.0
|
||||||
|
|
||||||
|
sem_w, edge_w, cent_w = _get_scoring_weights()
|
||||||
|
total = (sem_w * float(semantic_score) * weight) + (edge_w * edge_bonus) + (cent_w * cent_bonus)
|
||||||
|
return float(total), float(edge_bonus), float(cent_bonus)
|
||||||
|
|
||||||
|
|
||||||
|
# --- WP-04b Explanation Logic ---
|
||||||
|
|
||||||
|
def _build_explanation(
|
||||||
|
semantic_score: float,
|
||||||
|
payload: Dict[str, Any],
|
||||||
|
edge_bonus: float,
|
||||||
|
cent_bonus: float,
|
||||||
|
subgraph: Optional[ga.Subgraph],
|
||||||
|
node_key: Optional[str]
|
||||||
|
) -> Explanation:
|
||||||
|
"""Erstellt ein Explanation-Objekt."""
|
||||||
|
sem_w, _edge_w, _cent_w = _get_scoring_weights()
|
||||||
|
# Scoring weights erneut laden für Reason-Details
|
||||||
|
_, edge_w_cfg, cent_w_cfg = _get_scoring_weights()
|
||||||
|
|
||||||
|
try:
|
||||||
|
type_weight = float(payload.get("retriever_weight", 1.0))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
type_weight = 1.0
|
||||||
|
|
||||||
|
note_type = payload.get("type", "unknown")
|
||||||
|
|
||||||
|
breakdown = ScoreBreakdown(
|
||||||
|
semantic_contribution=(sem_w * semantic_score * type_weight),
|
||||||
|
edge_contribution=(edge_w_cfg * edge_bonus),
|
||||||
|
centrality_contribution=(cent_w_cfg * cent_bonus),
|
||||||
|
raw_semantic=semantic_score,
|
||||||
|
raw_edge_bonus=edge_bonus,
|
||||||
|
raw_centrality=cent_bonus,
|
||||||
|
node_weight=type_weight
|
||||||
|
)
|
||||||
|
|
||||||
|
reasons: List[Reason] = []
|
||||||
|
edges_dto: List[EdgeDTO] = []
|
||||||
|
|
||||||
|
if semantic_score > 0.85:
|
||||||
|
reasons.append(Reason(kind="semantic", message="Sehr hohe textuelle Übereinstimmung.", score_impact=breakdown.semantic_contribution))
|
||||||
|
elif semantic_score > 0.70:
|
||||||
|
reasons.append(Reason(kind="semantic", message="Gute textuelle Übereinstimmung.", score_impact=breakdown.semantic_contribution))
|
||||||
|
|
||||||
|
if type_weight != 1.0:
|
||||||
|
msg = "Bevorzugt" if type_weight > 1.0 else "Leicht abgewertet"
|
||||||
|
reasons.append(Reason(kind="type", message=f"{msg} aufgrund des Typs '{note_type}'.", score_impact=(sem_w * semantic_score * (type_weight - 1.0))))
|
||||||
|
|
||||||
|
if subgraph and node_key and edge_bonus > 0:
|
||||||
|
if hasattr(subgraph, "get_outgoing_edges"):
|
||||||
|
outgoing = subgraph.get_outgoing_edges(node_key)
|
||||||
|
for edge in outgoing:
|
||||||
|
target = edge.get("target", "Unknown")
|
||||||
|
kind = edge.get("kind", "edge")
|
||||||
|
weight = edge.get("weight", 0.0)
|
||||||
|
if weight > 0.05:
|
||||||
|
edges_dto.append(EdgeDTO(id=f"{node_key}->{target}:{kind}", kind=kind, source=node_key, target=target, weight=weight, direction="out"))
|
||||||
|
|
||||||
|
if hasattr(subgraph, "get_incoming_edges"):
|
||||||
|
incoming = subgraph.get_incoming_edges(node_key)
|
||||||
|
for edge in incoming:
|
||||||
|
src = edge.get("source", "Unknown")
|
||||||
|
kind = edge.get("kind", "edge")
|
||||||
|
weight = edge.get("weight", 0.0)
|
||||||
|
if weight > 0.05:
|
||||||
|
edges_dto.append(EdgeDTO(id=f"{src}->{node_key}:{kind}", kind=kind, source=src, target=node_key, weight=weight, direction="in"))
|
||||||
|
|
||||||
|
all_edges = sorted(edges_dto, key=lambda e: e.weight, reverse=True)
|
||||||
|
for top_edge in all_edges[:3]:
|
||||||
|
impact = edge_w_cfg * top_edge.weight
|
||||||
|
dir_txt = "Verweist auf" if top_edge.direction == "out" else "Referenziert von"
|
||||||
|
tgt_txt = top_edge.target if top_edge.direction == "out" else top_edge.source
|
||||||
|
reasons.append(Reason(kind="edge", message=f"{dir_txt} '{tgt_txt}' via '{top_edge.kind}'", score_impact=impact, details={"kind": top_edge.kind}))
|
||||||
|
|
||||||
|
if cent_bonus > 0.01:
|
||||||
|
reasons.append(Reason(kind="centrality", message="Knoten liegt zentral im Kontext.", score_impact=breakdown.centrality_contribution))
|
||||||
|
|
||||||
|
return Explanation(breakdown=breakdown, reasons=reasons, related_edges=edges_dto if edges_dto else None)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_expand_options(req: QueryRequest) -> Tuple[int, List[str] | None]:
|
||||||
|
"""Extrahiert depth und edge_types."""
|
||||||
|
expand = getattr(req, "expand", None)
|
||||||
|
if not expand:
|
||||||
|
return 0, None
|
||||||
|
|
||||||
|
depth = 1
|
||||||
|
edge_types: List[str] | None = None
|
||||||
|
|
||||||
|
if hasattr(expand, "depth") or hasattr(expand, "edge_types"):
|
||||||
|
depth = int(getattr(expand, "depth", 1) or 1)
|
||||||
|
types_val = getattr(expand, "edge_types", None)
|
||||||
|
if types_val:
|
||||||
|
edge_types = list(types_val)
|
||||||
|
return depth, edge_types
|
||||||
|
|
||||||
|
if isinstance(expand, dict):
|
||||||
|
if "depth" in expand:
|
||||||
|
depth = int(expand.get("depth") or 1)
|
||||||
|
if "edge_types" in expand and expand["edge_types"] is not None:
|
||||||
|
edge_types = list(expand["edge_types"])
|
||||||
|
return depth, edge_types
|
||||||
|
|
||||||
|
return 0, None
|
||||||
|
|
||||||
|
|
||||||
|
def _build_hits_from_semantic(
|
||||||
|
hits: Iterable[Tuple[str, float, Dict[str, Any]]],
|
||||||
|
top_k: int,
|
||||||
|
used_mode: str,
|
||||||
|
subgraph: ga.Subgraph | None = None,
|
||||||
|
explain: bool = False,
|
||||||
|
) -> QueryResponse:
|
||||||
|
"""Baut strukturierte QueryHits."""
|
||||||
|
t0 = time.time()
|
||||||
|
enriched: List[Tuple[str, float, Dict[str, Any], float, float, float]] = []
|
||||||
|
|
||||||
|
for pid, semantic_score, payload in hits:
|
||||||
|
edge_bonus = 0.0
|
||||||
|
cent_bonus = 0.0
|
||||||
|
node_key = payload.get("chunk_id") or payload.get("note_id")
|
||||||
|
|
||||||
|
if subgraph is not None and node_key:
|
||||||
|
try:
|
||||||
|
edge_bonus = float(subgraph.edge_bonus(node_key))
|
||||||
|
except Exception:
|
||||||
|
edge_bonus = 0.0
|
||||||
|
try:
|
||||||
|
cent_bonus = float(subgraph.centrality_bonus(node_key))
|
||||||
|
except Exception:
|
||||||
|
cent_bonus = 0.0
|
||||||
|
|
||||||
|
total, edge_bonus, cent_bonus = _compute_total_score(semantic_score, payload, edge_bonus=edge_bonus, cent_bonus=cent_bonus)
|
||||||
|
enriched.append((pid, float(semantic_score), payload, total, edge_bonus, cent_bonus))
|
||||||
|
|
||||||
|
enriched_sorted = sorted(enriched, key=lambda h: h[3], reverse=True)
|
||||||
|
limited = enriched_sorted[: max(1, top_k)]
|
||||||
|
|
||||||
|
results: List[QueryHit] = []
|
||||||
|
for pid, semantic_score, payload, total, edge_bonus, cent_bonus in limited:
|
||||||
|
explanation_obj = None
|
||||||
|
if explain:
|
||||||
|
explanation_obj = _build_explanation(
|
||||||
|
semantic_score=float(semantic_score),
|
||||||
|
payload=payload,
|
||||||
|
edge_bonus=edge_bonus,
|
||||||
|
cent_bonus=cent_bonus,
|
||||||
|
subgraph=subgraph,
|
||||||
|
node_key=payload.get("chunk_id") or payload.get("note_id")
|
||||||
|
)
|
||||||
|
|
||||||
|
text_content = payload.get("page_content") or payload.get("text") or payload.get("content")
|
||||||
|
|
||||||
|
results.append(QueryHit(
|
||||||
|
node_id=str(pid),
|
||||||
|
note_id=payload.get("note_id"),
|
||||||
|
semantic_score=float(semantic_score),
|
||||||
|
edge_bonus=edge_bonus,
|
||||||
|
centrality_bonus=cent_bonus,
|
||||||
|
total_score=total,
|
||||||
|
paths=None,
|
||||||
|
source={
|
||||||
|
"path": payload.get("path"),
|
||||||
|
"section": payload.get("section") or payload.get("section_title"),
|
||||||
|
"text": text_content
|
||||||
|
},
|
||||||
|
# --- FIX: Wir füllen das payload-Feld explizit ---
|
||||||
|
payload=payload,
|
||||||
|
explanation=explanation_obj
|
||||||
|
))
|
||||||
|
|
||||||
|
dt = int((time.time() - t0) * 1000)
|
||||||
|
return QueryResponse(results=results, used_mode=used_mode, latency_ms=dt)
|
||||||
|
|
||||||
|
|
||||||
|
def semantic_retrieve(req: QueryRequest) -> QueryResponse:
|
||||||
|
"""Reiner semantischer Retriever."""
|
||||||
|
client, prefix = _get_client_and_prefix()
|
||||||
|
vector = _get_query_vector(req)
|
||||||
|
top_k = req.top_k or get_settings().RETRIEVER_TOP_K
|
||||||
|
|
||||||
|
hits = _semantic_hits(client, prefix, vector, top_k=top_k, filters=req.filters)
|
||||||
|
return _build_hits_from_semantic(hits, top_k=top_k, used_mode="semantic", subgraph=None, explain=req.explain)
|
||||||
|
|
||||||
|
|
||||||
|
def hybrid_retrieve(req: QueryRequest) -> QueryResponse:
|
||||||
|
"""Hybrid-Retriever: semantische Suche + optionale Edge-Expansion."""
|
||||||
|
client, prefix = _get_client_and_prefix()
|
||||||
|
if req.query_vector:
|
||||||
|
vector = list(req.query_vector)
|
||||||
|
else:
|
||||||
|
vector = _get_query_vector(req)
|
||||||
|
|
||||||
|
top_k = req.top_k or get_settings().RETRIEVER_TOP_K
|
||||||
|
hits = _semantic_hits(client, prefix, vector, top_k=top_k, filters=req.filters)
|
||||||
|
|
||||||
|
depth, edge_types = _extract_expand_options(req)
|
||||||
|
subgraph: ga.Subgraph | None = None
|
||||||
|
if depth and depth > 0:
|
||||||
|
seed_ids: List[str] = []
|
||||||
|
for _pid, _score, payload in hits:
|
||||||
|
key = payload.get("chunk_id") or payload.get("note_id")
|
||||||
|
if key and key not in seed_ids:
|
||||||
|
seed_ids.append(key)
|
||||||
|
if seed_ids:
|
||||||
|
try:
|
||||||
|
subgraph = ga.expand(client, prefix, seed_ids, depth=depth, edge_types=edge_types)
|
||||||
|
except Exception:
|
||||||
|
subgraph = None
|
||||||
|
|
||||||
|
return _build_hits_from_semantic(hits, top_k=top_k, used_mode="hybrid", subgraph=subgraph, explain=req.explain)
|
||||||
|
|
||||||
|
|
||||||
|
class Retriever:
|
||||||
|
"""
|
||||||
|
Wrapper-Klasse für WP-05 (Chat).
|
||||||
|
"""
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def search(self, request: QueryRequest) -> QueryResponse:
|
||||||
|
return hybrid_retrieve(request)
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
from functools import lru_cache
|
|
||||||
from jsonschema import Draft202012Validator, RefResolver
|
|
||||||
|
|
||||||
SCHEMAS_DIR = os.getenv("SCHEMAS_DIR", os.path.join(os.path.dirname(os.path.dirname(__file__)), "..", "schemas"))
|
|
||||||
|
|
||||||
@lru_cache(maxsize=16)
|
|
||||||
def load_schema(name: str) -> dict:
|
|
||||||
# name: "note.schema.json" | "chunk.schema.json" | "edge.schema.json"
|
|
||||||
path = os.path.join(SCHEMAS_DIR, name)
|
|
||||||
if not os.path.isfile(path):
|
|
||||||
raise FileNotFoundError(f"Schema not found: {path}")
|
|
||||||
with open(path, "r", encoding="utf-8") as f:
|
|
||||||
return json.load(f)
|
|
||||||
|
|
||||||
@lru_cache(maxsize=16)
|
|
||||||
def get_validator(name: str) -> Draft202012Validator:
|
|
||||||
schema = load_schema(name)
|
|
||||||
resolver = RefResolver.from_schema(schema)
|
|
||||||
return Draft202012Validator(schema, resolver=resolver)
|
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/type_registry.py
|
||||||
|
DESCRIPTION: Loader für types.yaml. Achtung: Wird in der aktuellen Pipeline meist durch lokale Loader in 'ingestion.py' oder 'note_payload.py' umgangen.
|
||||||
|
VERSION: 1.0.0
|
||||||
|
STATUS: Deprecated (Redundant)
|
||||||
|
DEPENDENCIES: yaml, os, functools
|
||||||
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from functools import lru_cache
|
||||||
|
from typing import Dict, Any, Optional, Tuple
|
||||||
|
import os
|
||||||
|
|
||||||
|
try:
|
||||||
|
import yaml # PyYAML
|
||||||
|
except Exception:
|
||||||
|
yaml = None # wird erst benötigt, wenn eine Datei gelesen werden soll
|
||||||
|
|
||||||
|
# Konservativer Default – bewusst minimal
|
||||||
|
_DEFAULT_REGISTRY: Dict[str, Any] = {
|
||||||
|
"version": "1.0",
|
||||||
|
"types": {
|
||||||
|
"concept": {
|
||||||
|
"chunk_profile": "medium",
|
||||||
|
"edge_defaults": ["references", "related_to"],
|
||||||
|
"retriever_weight": 1.0,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"_using_defaults": True,
|
||||||
|
"_warning": "types.yaml missing or invalid – using built-in defaults (type=concept).",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Chunk-Profile → Overlap-Empfehlungen (nur für synthetische Fensterbildung)
|
||||||
|
# Die absoluten Chunk-Längen bleiben Aufgabe des Chunkers (assemble_chunks).
|
||||||
|
_PROFILE_TO_OVERLAP: Dict[str, Tuple[int, int]] = {
|
||||||
|
"short": (20, 30),
|
||||||
|
"medium": (40, 60),
|
||||||
|
"long": (60, 80),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def load_type_registry(path: str = "config/types.yaml") -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Lädt die Registry aus 'path'. Bei Fehlern wird ein konserviver Default geliefert.
|
||||||
|
Die Rückgabe ist *prozessweit* gecached.
|
||||||
|
"""
|
||||||
|
if not path:
|
||||||
|
return dict(_DEFAULT_REGISTRY)
|
||||||
|
|
||||||
|
if not os.path.isfile(path):
|
||||||
|
return dict(_DEFAULT_REGISTRY)
|
||||||
|
|
||||||
|
if yaml is None:
|
||||||
|
# PyYAML fehlt → auf Default zurückfallen
|
||||||
|
return dict(_DEFAULT_REGISTRY)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
data = yaml.safe_load(f) or {}
|
||||||
|
# Minimal validieren
|
||||||
|
if not isinstance(data, dict) or "types" not in data or not isinstance(data["types"], dict):
|
||||||
|
return dict(_DEFAULT_REGISTRY)
|
||||||
|
data.setdefault("version", "1.0")
|
||||||
|
data.setdefault("_using_defaults", False)
|
||||||
|
return data
|
||||||
|
except Exception:
|
||||||
|
return dict(_DEFAULT_REGISTRY)
|
||||||
|
|
||||||
|
|
||||||
|
def get_type_config(note_type: Optional[str], reg: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
t = (note_type or "concept").strip().lower()
|
||||||
|
types = (reg or {}).get("types", {}) if isinstance(reg, dict) else {}
|
||||||
|
return types.get(t) or types.get("concept") or _DEFAULT_REGISTRY["types"]["concept"]
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_note_type(fm_type: Optional[str], reg: Dict[str, Any]) -> str:
|
||||||
|
"""Liefert einen gültigen Typ (unbekannt → 'concept')."""
|
||||||
|
t = (fm_type or "concept").strip().lower()
|
||||||
|
types = (reg or {}).get("types", {}) if isinstance(reg, dict) else {}
|
||||||
|
return t if t in types else "concept"
|
||||||
|
|
||||||
|
|
||||||
|
def effective_chunk_profile(note_type: Optional[str], reg: Dict[str, Any]) -> Optional[str]:
|
||||||
|
cfg = get_type_config(note_type, reg)
|
||||||
|
prof = cfg.get("chunk_profile")
|
||||||
|
if isinstance(prof, str) and prof.strip():
|
||||||
|
return prof.strip().lower()
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def profile_overlap(profile: Optional[str]) -> Tuple[int, int]:
|
||||||
|
"""Gibt eine Overlap-Empfehlung (low, high) für das Profil zurück."""
|
||||||
|
if not profile:
|
||||||
|
return _PROFILE_TO_OVERLAP["medium"]
|
||||||
|
return _PROFILE_TO_OVERLAP.get(profile.strip().lower(), _PROFILE_TO_OVERLAP["medium"])
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
from typing import Dict
|
|
||||||
from jsonschema import ValidationError
|
|
||||||
from .schema_loader import get_validator
|
|
||||||
|
|
||||||
NOTE_SCHEMA_NAME = "note.schema.json"
|
|
||||||
|
|
||||||
def validate_note_payload(payload: Dict) -> None:
|
|
||||||
validator = get_validator(NOTE_SCHEMA_NAME)
|
|
||||||
errors = sorted(validator.iter_errors(payload), key=lambda e: e.path)
|
|
||||||
if errors:
|
|
||||||
msgs = []
|
|
||||||
for e in errors:
|
|
||||||
loc = ".".join([str(x) for x in e.path]) or "<root>"
|
|
||||||
msgs.append(f"{loc}: {e.message}")
|
|
||||||
raise ValidationError(" | ".join(msgs))
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
"""
|
|
||||||
Version 1
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
from fastapi import FastAPI, HTTPException
|
|
||||||
from pydantic import BaseModel
|
|
||||||
from typing import List, Optional
|
|
||||||
from sentence_transformers import SentenceTransformer
|
|
||||||
|
|
||||||
app = FastAPI(title="mindnet-embed", version="1.0")
|
|
||||||
|
|
||||||
MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2" # 384-dim
|
|
||||||
_model: SentenceTransformer | None = None
|
|
||||||
|
|
||||||
class EmbedIn(BaseModel):
|
|
||||||
model: Optional[str] = None
|
|
||||||
inputs: List[str]
|
|
||||||
|
|
||||||
class EmbedOut(BaseModel):
|
|
||||||
embeddings: List[List[float]]
|
|
||||||
|
|
||||||
@app.on_event("startup")
|
|
||||||
def _load_model():
|
|
||||||
global _model
|
|
||||||
_model = SentenceTransformer(MODEL_NAME)
|
|
||||||
|
|
||||||
@app.get("/health")
|
|
||||||
def health():
|
|
||||||
return {"ok": True, "model": MODEL_NAME, "dim": 384}
|
|
||||||
|
|
||||||
@app.post("/embed", response_model=EmbedOut)
|
|
||||||
def embed(payload: EmbedIn) -> EmbedOut:
|
|
||||||
if _model is None:
|
|
||||||
raise HTTPException(status_code=503, detail="Model not loaded")
|
|
||||||
if not payload.inputs:
|
|
||||||
return EmbedOut(embeddings=[])
|
|
||||||
vecs = _model.encode(payload.inputs, normalize_embeddings=False).tolist()
|
|
||||||
if any(len(v) != 384 for v in vecs):
|
|
||||||
raise HTTPException(status_code=500, detail="Embedding size mismatch (expected 384)")
|
|
||||||
return EmbedOut(embeddings=vecs)
|
|
||||||
+6
-2
@@ -1,6 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
Version 0.1
|
FILE: app/embeddings.py
|
||||||
|
DESCRIPTION: Lokaler Wrapper für SentenceTransformer Embeddings.
|
||||||
|
VERSION: 0.1.0
|
||||||
|
STATUS: Active (Bestätigung durch Aufrufer erforderlich)
|
||||||
|
DEPENDENCIES: app.config, sentence_transformers
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui.py
|
||||||
|
DESCRIPTION: Main Entrypoint für Streamlit. Router, der basierend auf Sidebar-Auswahl die Module (Chat, Editor, Graph) lädt.
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: streamlit, ui_config, ui_sidebar, ui_chat, ui_editor, ui_graph_service, ui_graph*, ui_graph_cytoscape
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import streamlit as st
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
# --- CONFIG & STYLING ---
|
||||||
|
st.set_page_config(page_title="mindnet v2.6", page_icon="🧠", layout="wide")
|
||||||
|
st.markdown("""
|
||||||
|
<style>
|
||||||
|
.block-container { padding-top: 2rem; max_width: 1200px; margin: auto; }
|
||||||
|
.intent-badge { background-color: #e8f0fe; color: #1a73e8; padding: 4px 10px; border-radius: 12px; font-size: 0.8rem; font-weight: 600; border: 1px solid #d2e3fc; display: inline-block; margin-bottom: 0.5rem; }
|
||||||
|
.draft-box { border: 1px solid #d0d7de; border-radius: 6px; padding: 16px; background-color: #f6f8fa; margin: 10px 0; }
|
||||||
|
.preview-box { border: 1px solid #e0e0e0; border-radius: 6px; padding: 24px; background-color: white; }
|
||||||
|
</style>
|
||||||
|
""", unsafe_allow_html=True)
|
||||||
|
|
||||||
|
# --- MODULE IMPORTS ---
|
||||||
|
try:
|
||||||
|
from ui_config import QDRANT_URL, QDRANT_KEY, COLLECTION_PREFIX
|
||||||
|
from ui_graph_service import GraphExplorerService
|
||||||
|
|
||||||
|
# Komponenten
|
||||||
|
from ui_sidebar import render_sidebar
|
||||||
|
from ui_chat import render_chat_interface
|
||||||
|
from ui_editor import render_manual_editor
|
||||||
|
|
||||||
|
# Die beiden Graph-Engines
|
||||||
|
from ui_graph import render_graph_explorer as render_graph_agraph
|
||||||
|
from ui_graph_cytoscape import render_graph_explorer_cytoscape # <-- Import
|
||||||
|
|
||||||
|
except ImportError as e:
|
||||||
|
st.error(f"Import Error: {e}. Bitte stelle sicher, dass alle UI-Dateien im Ordner liegen und 'streamlit-cytoscapejs' installiert ist.")
|
||||||
|
st.stop()
|
||||||
|
|
||||||
|
# --- SESSION STATE ---
|
||||||
|
if "messages" not in st.session_state: st.session_state.messages = []
|
||||||
|
if "user_id" not in st.session_state: st.session_state.user_id = str(uuid.uuid4())
|
||||||
|
|
||||||
|
# --- SERVICE INIT ---
|
||||||
|
graph_service = GraphExplorerService(QDRANT_URL, QDRANT_KEY, COLLECTION_PREFIX)
|
||||||
|
|
||||||
|
# --- MAIN ROUTING ---
|
||||||
|
mode, top_k, explain = render_sidebar()
|
||||||
|
|
||||||
|
if mode == "💬 Chat":
|
||||||
|
render_chat_interface(top_k, explain)
|
||||||
|
elif mode == "📝 Manueller Editor":
|
||||||
|
render_manual_editor()
|
||||||
|
elif mode == "🕸️ Graph (Agraph)":
|
||||||
|
render_graph_agraph(graph_service)
|
||||||
|
elif mode == "🕸️ Graph (Cytoscape)":
|
||||||
|
render_graph_explorer_cytoscape(graph_service)
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_api.py
|
||||||
|
DESCRIPTION: Wrapper für Backend-Calls (Chat, Ingest, Feedback). Kapselt requests und Error-Handling.
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: requests, streamlit, ui_config
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import requests
|
||||||
|
import streamlit as st
|
||||||
|
from ui_config import CHAT_ENDPOINT, INGEST_ANALYZE_ENDPOINT, INGEST_SAVE_ENDPOINT, FEEDBACK_ENDPOINT, API_TIMEOUT
|
||||||
|
|
||||||
|
def send_chat_message(message: str, top_k: int, explain: bool):
|
||||||
|
try:
|
||||||
|
response = requests.post(
|
||||||
|
CHAT_ENDPOINT,
|
||||||
|
json={"message": message, "top_k": top_k, "explain": explain},
|
||||||
|
timeout=API_TIMEOUT
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json()
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": str(e)}
|
||||||
|
|
||||||
|
def analyze_draft_text(text: str, n_type: str):
|
||||||
|
try:
|
||||||
|
response = requests.post(INGEST_ANALYZE_ENDPOINT, json={"text": text, "type": n_type}, timeout=15)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json()
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": str(e)}
|
||||||
|
|
||||||
|
def save_draft_to_vault(markdown_content: str, filename: str = None):
|
||||||
|
try:
|
||||||
|
response = requests.post(INGEST_SAVE_ENDPOINT, json={"markdown_content": markdown_content, "filename": filename}, timeout=API_TIMEOUT)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json()
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": str(e)}
|
||||||
|
|
||||||
|
def submit_feedback(query_id, node_id, score, comment=None):
|
||||||
|
try:
|
||||||
|
requests.post(FEEDBACK_ENDPOINT, json={"query_id": query_id, "node_id": node_id, "score": score, "comment": comment}, timeout=2)
|
||||||
|
st.toast(f"Feedback ({score}) gesendet!")
|
||||||
|
except: pass
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_callbacks.py
|
||||||
|
DESCRIPTION: Event-Handler für UI-Interaktionen. Implementiert den Übergang vom Graphen zum Editor (State Transfer).
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: streamlit, os, ui_utils
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import streamlit as st
|
||||||
|
import os
|
||||||
|
from ui_utils import build_markdown_doc
|
||||||
|
|
||||||
|
def switch_to_editor_callback(note_payload):
|
||||||
|
"""
|
||||||
|
Callback für den 'Bearbeiten'-Button im Graphen.
|
||||||
|
Versucht, die Datei direkt aus dem Vault (Dateisystem) zu lesen.
|
||||||
|
Das garantiert, dass Frontmatter und Inhalt vollständig sind (Single Source of Truth).
|
||||||
|
"""
|
||||||
|
# 1. Pfad ermitteln (Priorität auf 'path' aus Qdrant)
|
||||||
|
origin_fname = note_payload.get('path')
|
||||||
|
|
||||||
|
# Fallback für Legacy-Datenfelder
|
||||||
|
if not origin_fname:
|
||||||
|
origin_fname = note_payload.get('file_path') or note_payload.get('filename')
|
||||||
|
|
||||||
|
content = ""
|
||||||
|
file_loaded = False
|
||||||
|
|
||||||
|
# 2. Versuch: Direkt von der Festplatte lesen
|
||||||
|
# Wir prüfen, ob der Pfad existiert und lesen den aktuellen Stand der Datei.
|
||||||
|
if origin_fname and os.path.exists(origin_fname):
|
||||||
|
try:
|
||||||
|
with open(origin_fname, "r", encoding="utf-8") as f:
|
||||||
|
content = f.read()
|
||||||
|
file_loaded = True
|
||||||
|
except Exception as e:
|
||||||
|
# Fehler im Terminal loggen, aber UI nicht crashen lassen
|
||||||
|
print(f"Fehler beim Lesen von {origin_fname}: {e}")
|
||||||
|
|
||||||
|
# 3. Fallback: Inhalt aus Qdrant nehmen (wenn Datei nicht zugreifbar)
|
||||||
|
if not file_loaded:
|
||||||
|
# Wir nehmen 'fulltext' aus dem Payload
|
||||||
|
content = note_payload.get('fulltext', '')
|
||||||
|
|
||||||
|
if not content:
|
||||||
|
# Letzter Ausweg: Metadaten nehmen und Dummy-Content bauen
|
||||||
|
content = build_markdown_doc(note_payload, "Inhalt konnte nicht geladen werden (Datei nicht gefunden).")
|
||||||
|
else:
|
||||||
|
# Check: Hat der Text ein Frontmatter? Wenn nein, rekonstruieren wir es.
|
||||||
|
if not content.strip().startswith("---"):
|
||||||
|
content = build_markdown_doc(note_payload, content)
|
||||||
|
|
||||||
|
# Notfall-Pfad Konstruktion (falls gar kein Pfad im System ist)
|
||||||
|
if not origin_fname and 'note_id' in note_payload:
|
||||||
|
origin_fname = f"{note_payload['note_id']}.md"
|
||||||
|
|
||||||
|
# 4. Daten an den Editor übergeben
|
||||||
|
# Wir nutzen den Chat-Verlauf als Transportmittel für den State
|
||||||
|
st.session_state.messages.append({
|
||||||
|
"role": "assistant",
|
||||||
|
"intent": "INTERVIEW",
|
||||||
|
"content": content,
|
||||||
|
"query_id": f"edit_{note_payload.get('note_id', 'unknown')}", # Trigger für den Editor
|
||||||
|
"origin_filename": origin_fname,
|
||||||
|
"origin_note_id": note_payload.get('note_id')
|
||||||
|
})
|
||||||
|
|
||||||
|
# 5. Modus umschalten (wechselt den Tab beim nächsten Rerun)
|
||||||
|
st.session_state["sidebar_mode_selection"] = "📝 Manueller Editor"
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_chat.py
|
||||||
|
DESCRIPTION: Chat-UI. Rendert Nachrichtenverlauf, Quellen-Expanders mit Feedback-Buttons und delegiert bei Bedarf an den Editor.
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: streamlit, ui_api, ui_editor
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import streamlit as st
|
||||||
|
from ui_api import send_chat_message, submit_feedback
|
||||||
|
from ui_editor import render_draft_editor
|
||||||
|
|
||||||
|
def render_chat_interface(top_k, explain):
|
||||||
|
"""
|
||||||
|
Rendert das Chat-Interface.
|
||||||
|
Zeigt Nachrichten an und behandelt User-Input.
|
||||||
|
"""
|
||||||
|
# 1. Verlauf anzeigen
|
||||||
|
for idx, msg in enumerate(st.session_state.messages):
|
||||||
|
with st.chat_message(msg["role"]):
|
||||||
|
if msg["role"] == "assistant":
|
||||||
|
# Intent Badge
|
||||||
|
intent = msg.get("intent", "UNKNOWN")
|
||||||
|
st.markdown(f'<div class="intent-badge">Intent: {intent}</div>', unsafe_allow_html=True)
|
||||||
|
|
||||||
|
# Debugging (optional, gut für Entwicklung)
|
||||||
|
with st.expander("🐞 Payload", expanded=False):
|
||||||
|
st.json(msg)
|
||||||
|
|
||||||
|
# Unterscheidung: Normaler Text oder Editor-Modus (Interview)
|
||||||
|
if intent == "INTERVIEW":
|
||||||
|
render_draft_editor(msg)
|
||||||
|
else:
|
||||||
|
st.markdown(msg["content"])
|
||||||
|
|
||||||
|
# Quellen anzeigen
|
||||||
|
if "sources" in msg and msg["sources"]:
|
||||||
|
for hit in msg["sources"]:
|
||||||
|
score = hit.get('total_score', 0)
|
||||||
|
# Wenn score None ist, 0.0 annehmen
|
||||||
|
if score is None: score = 0.0
|
||||||
|
|
||||||
|
with st.expander(f"📄 {hit.get('note_id', '?')} ({score:.2f})"):
|
||||||
|
st.markdown(f"_{hit.get('source', {}).get('text', '')[:300]}..._")
|
||||||
|
|
||||||
|
# Explanation Layer
|
||||||
|
if hit.get('explanation'):
|
||||||
|
st.caption(f"Grund: {hit['explanation']['reasons'][0]['message']}")
|
||||||
|
|
||||||
|
# Feedback Buttons pro Source
|
||||||
|
def _cb(qid=msg.get("query_id"), nid=hit.get('node_id')):
|
||||||
|
val = st.session_state.get(f"fb_src_{qid}_{nid}")
|
||||||
|
if val is not None: submit_feedback(qid, nid, val+1)
|
||||||
|
|
||||||
|
st.feedback("faces", key=f"fb_src_{msg.get('query_id')}_{hit.get('node_id')}", on_change=_cb)
|
||||||
|
|
||||||
|
# Globales Feedback für die Antwort
|
||||||
|
if "query_id" in msg:
|
||||||
|
qid = msg["query_id"]
|
||||||
|
st.feedback("stars", key=f"fb_glob_{qid}", on_change=lambda: submit_feedback(qid, "generated_answer", st.session_state[f"fb_glob_{qid}"]+1))
|
||||||
|
else:
|
||||||
|
# User Nachricht
|
||||||
|
st.markdown(msg["content"])
|
||||||
|
|
||||||
|
# 2. Input Feld
|
||||||
|
if prompt := st.chat_input("Frage Mindnet..."):
|
||||||
|
st.session_state.messages.append({"role": "user", "content": prompt})
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
# 3. Antwort generieren (wenn letzte Nachricht vom User ist)
|
||||||
|
if len(st.session_state.messages) > 0 and st.session_state.messages[-1]["role"] == "user":
|
||||||
|
with st.chat_message("assistant"):
|
||||||
|
with st.spinner("Thinking..."):
|
||||||
|
resp = send_chat_message(st.session_state.messages[-1]["content"], top_k, explain)
|
||||||
|
|
||||||
|
if "error" in resp:
|
||||||
|
st.error(resp["error"])
|
||||||
|
else:
|
||||||
|
st.session_state.messages.append({
|
||||||
|
"role": "assistant",
|
||||||
|
"content": resp.get("answer"),
|
||||||
|
"intent": resp.get("intent", "FACT"),
|
||||||
|
"sources": resp.get("sources", []),
|
||||||
|
"query_id": resp.get("query_id")
|
||||||
|
})
|
||||||
|
st.rerun()
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_config.py
|
||||||
|
DESCRIPTION: Zentrale Konfiguration für das Frontend. Definiert API-Endpoints, Timeouts und Graph-Styles (Farben).
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: os, hashlib, dotenv, pathlib
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import hashlib
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
# --- API & PORTS ---
|
||||||
|
API_BASE_URL = os.getenv("MINDNET_API_URL", "http://localhost:8002")
|
||||||
|
CHAT_ENDPOINT = f"{API_BASE_URL}/chat"
|
||||||
|
FEEDBACK_ENDPOINT = f"{API_BASE_URL}/feedback"
|
||||||
|
INGEST_ANALYZE_ENDPOINT = f"{API_BASE_URL}/ingest/analyze"
|
||||||
|
INGEST_SAVE_ENDPOINT = f"{API_BASE_URL}/ingest/save"
|
||||||
|
|
||||||
|
# --- QDRANT ---
|
||||||
|
QDRANT_URL = os.getenv("QDRANT_URL", "http://localhost:6333")
|
||||||
|
QDRANT_KEY = os.getenv("QDRANT_API_KEY", None)
|
||||||
|
if QDRANT_KEY == "": QDRANT_KEY = None
|
||||||
|
COLLECTION_PREFIX = os.getenv("COLLECTION_PREFIX", "mindnet")
|
||||||
|
|
||||||
|
# --- FILES & TIMEOUTS ---
|
||||||
|
HISTORY_FILE = Path("data/logs/search_history.jsonl")
|
||||||
|
timeout_setting = os.getenv("MINDNET_API_TIMEOUT") or os.getenv("MINDNET_LLM_TIMEOUT")
|
||||||
|
API_TIMEOUT = float(timeout_setting) if timeout_setting else 300.0
|
||||||
|
|
||||||
|
# --- STYLING CONSTANTS ---
|
||||||
|
|
||||||
|
# Basierend auf types.yaml
|
||||||
|
GRAPH_COLORS = {
|
||||||
|
# Kerntypen
|
||||||
|
"experience": "#feca57", # Gelb/Orange
|
||||||
|
"project": "#ff9f43", # Dunkleres Orange
|
||||||
|
"decision": "#5f27cd", # Lila
|
||||||
|
|
||||||
|
# Persönlichkeit
|
||||||
|
"value": "#00d2d3", # Cyan
|
||||||
|
"principle": "#0abde3", # Dunkles Cyan
|
||||||
|
"belief": "#48dbfb", # Helles Blau
|
||||||
|
"profile": "#1dd1a1", # Grün
|
||||||
|
|
||||||
|
# Strategie & Risiko
|
||||||
|
"goal": "#ff9ff3", # Pink
|
||||||
|
"risk": "#ff6b6b", # Rot
|
||||||
|
|
||||||
|
# Basis
|
||||||
|
"concept": "#54a0ff", # Blau
|
||||||
|
"task": "#8395a7", # Grau-Blau
|
||||||
|
"journal": "#c8d6e5", # Hellgrau
|
||||||
|
"source": "#576574", # Dunkelgrau
|
||||||
|
"glossary": "#222f3e", # Sehr dunkel
|
||||||
|
|
||||||
|
"default": "#8395a7" # Fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
# System-Kanten, die wir NICHT im Graphen sehen wollen, um Rauschen zu reduzieren
|
||||||
|
SYSTEM_EDGES = ["prev", "next", "belongs_to"]
|
||||||
|
|
||||||
|
def get_edge_color(kind: str) -> str:
|
||||||
|
"""Generiert eine deterministische Farbe basierend auf dem Edge-Typ."""
|
||||||
|
if not kind: return "#bdc3c7"
|
||||||
|
|
||||||
|
# Einige feste Farben für wichtige semantische Typen
|
||||||
|
fixed_colors = {
|
||||||
|
"depends_on": "#ff6b6b", # Rot (Blocker/Abhängigkeit)
|
||||||
|
"blocks": "#ee5253", # Dunkelrot
|
||||||
|
"caused_by": "#ff9ff3", # Pink
|
||||||
|
"related_to": "#c8d6e5", # Hellgrau (Hintergrund)
|
||||||
|
"references": "#bdc3c7", # Grau
|
||||||
|
"derived_from": "#1dd1a1" # Grün
|
||||||
|
}
|
||||||
|
|
||||||
|
if kind in fixed_colors:
|
||||||
|
return fixed_colors[kind]
|
||||||
|
|
||||||
|
# Fallback: Hash-basierte Farbe für dynamische Typen
|
||||||
|
# Wir nutzen einen Pastell-Generator, damit es nicht zu grell wird
|
||||||
|
hash_obj = hashlib.md5(kind.encode())
|
||||||
|
hue = int(hash_obj.hexdigest(), 16) % 360
|
||||||
|
return f"hsl({hue}, 60%, 50%)"
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_editor.py
|
||||||
|
DESCRIPTION: Markdown-Editor mit Live-Vorschau.
|
||||||
|
Refactored für WP-14: Asynchrones Feedback-Handling (Queued State).
|
||||||
|
VERSION: 2.7.0 (Fix: Async Save UI)
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: streamlit, uuid, re, datetime, ui_utils, ui_api
|
||||||
|
"""
|
||||||
|
import streamlit as st
|
||||||
|
import uuid
|
||||||
|
import re
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from ui_utils import parse_markdown_draft, build_markdown_doc, slugify
|
||||||
|
from ui_api import save_draft_to_vault, analyze_draft_text
|
||||||
|
|
||||||
|
def render_draft_editor(msg):
|
||||||
|
"""
|
||||||
|
Rendert den Markdown-Editor.
|
||||||
|
Nutzt 'origin_filename' aus der Message, um zwischen Update und Neu zu unterscheiden.
|
||||||
|
"""
|
||||||
|
if "query_id" not in msg or not msg["query_id"]:
|
||||||
|
msg["query_id"] = str(uuid.uuid4())
|
||||||
|
|
||||||
|
qid = msg["query_id"]
|
||||||
|
key_base = f"draft_{qid}"
|
||||||
|
|
||||||
|
# State Keys
|
||||||
|
data_meta_key = f"{key_base}_data_meta"
|
||||||
|
data_sugg_key = f"{key_base}_data_suggestions"
|
||||||
|
widget_body_key = f"{key_base}_widget_body"
|
||||||
|
data_body_key = f"{key_base}_data_body"
|
||||||
|
|
||||||
|
# --- INIT STATE ---
|
||||||
|
if f"{key_base}_init" not in st.session_state:
|
||||||
|
meta, body = parse_markdown_draft(msg["content"])
|
||||||
|
if "type" not in meta: meta["type"] = "default"
|
||||||
|
if "title" not in meta: meta["title"] = ""
|
||||||
|
tags = meta.get("tags", [])
|
||||||
|
meta["tags_str"] = ", ".join(tags) if isinstance(tags, list) else str(tags)
|
||||||
|
|
||||||
|
st.session_state[data_meta_key] = meta
|
||||||
|
st.session_state[data_sugg_key] = []
|
||||||
|
st.session_state[data_body_key] = body.strip()
|
||||||
|
|
||||||
|
st.session_state[f"{key_base}_wdg_title"] = meta["title"]
|
||||||
|
st.session_state[f"{key_base}_wdg_type"] = meta["type"]
|
||||||
|
st.session_state[f"{key_base}_wdg_tags"] = meta["tags_str"]
|
||||||
|
|
||||||
|
# Pfad übernehmen (Source of Truth)
|
||||||
|
st.session_state[f"{key_base}_origin_filename"] = msg.get("origin_filename")
|
||||||
|
st.session_state[f"{key_base}_init"] = True
|
||||||
|
|
||||||
|
# --- RESURRECTION ---
|
||||||
|
if widget_body_key not in st.session_state and data_body_key in st.session_state:
|
||||||
|
st.session_state[widget_body_key] = st.session_state[data_body_key]
|
||||||
|
|
||||||
|
# --- SYNC HELPER ---
|
||||||
|
def _sync_meta():
|
||||||
|
meta = st.session_state[data_meta_key]
|
||||||
|
meta["title"] = st.session_state.get(f"{key_base}_wdg_title", "")
|
||||||
|
meta["type"] = st.session_state.get(f"{key_base}_wdg_type", "default")
|
||||||
|
meta["tags_str"] = st.session_state.get(f"{key_base}_wdg_tags", "")
|
||||||
|
st.session_state[data_meta_key] = meta
|
||||||
|
|
||||||
|
def _sync_body():
|
||||||
|
st.session_state[data_body_key] = st.session_state[widget_body_key]
|
||||||
|
|
||||||
|
def _insert_text(t):
|
||||||
|
st.session_state[widget_body_key] = f"{st.session_state.get(widget_body_key, '')}\n\n{t}"
|
||||||
|
st.session_state[data_body_key] = st.session_state[widget_body_key]
|
||||||
|
|
||||||
|
def _remove_text(t):
|
||||||
|
st.session_state[widget_body_key] = st.session_state.get(widget_body_key, '').replace(t, "").strip()
|
||||||
|
st.session_state[data_body_key] = st.session_state[widget_body_key]
|
||||||
|
|
||||||
|
# --- UI LAYOUT ---
|
||||||
|
|
||||||
|
origin_fname = st.session_state.get(f"{key_base}_origin_filename")
|
||||||
|
|
||||||
|
if origin_fname:
|
||||||
|
display_name = str(origin_fname).split("/")[-1]
|
||||||
|
st.success(f"📂 **Update-Modus**: `{display_name}`")
|
||||||
|
with st.expander("Dateipfad Details", expanded=False):
|
||||||
|
st.code(origin_fname)
|
||||||
|
st.markdown(f'<div class="draft-box" style="border-left: 5px solid #ff9f43;">', unsafe_allow_html=True)
|
||||||
|
else:
|
||||||
|
st.info("✨ **Erstell-Modus**: Neue Datei wird angelegt.")
|
||||||
|
st.markdown(f'<div class="draft-box">', unsafe_allow_html=True)
|
||||||
|
|
||||||
|
st.markdown("### Editor")
|
||||||
|
|
||||||
|
# Meta Felder
|
||||||
|
meta_ref = st.session_state[data_meta_key]
|
||||||
|
c1, c2 = st.columns([2, 1])
|
||||||
|
with c1:
|
||||||
|
st.text_input("Titel", key=f"{key_base}_wdg_title", on_change=_sync_meta)
|
||||||
|
with c2:
|
||||||
|
known_types = ["concept", "project", "decision", "experience", "journal", "value", "goal", "principle", "risk", "belief"]
|
||||||
|
curr_type = st.session_state.get(f"{key_base}_wdg_type", meta_ref["type"])
|
||||||
|
if curr_type not in known_types: known_types.append(curr_type)
|
||||||
|
st.selectbox("Typ", known_types, key=f"{key_base}_wdg_type", on_change=_sync_meta)
|
||||||
|
|
||||||
|
st.text_input("Tags", key=f"{key_base}_wdg_tags", on_change=_sync_meta)
|
||||||
|
|
||||||
|
# Tabs
|
||||||
|
tab_edit, tab_intel, tab_view = st.tabs(["✏️ Inhalt", "🧠 Intelligence", "👁️ Vorschau"])
|
||||||
|
|
||||||
|
with tab_edit:
|
||||||
|
st.text_area("Body", key=widget_body_key, height=600, on_change=_sync_body, label_visibility="collapsed")
|
||||||
|
|
||||||
|
with tab_intel:
|
||||||
|
st.info("Analysiert den Text auf Verknüpfungsmöglichkeiten.")
|
||||||
|
if st.button("🔍 Analyse starten", key=f"{key_base}_analyze"):
|
||||||
|
st.session_state[data_sugg_key] = []
|
||||||
|
text_to_analyze = st.session_state.get(widget_body_key, st.session_state.get(data_body_key, ""))
|
||||||
|
with st.spinner("Analysiere..."):
|
||||||
|
analysis = analyze_draft_text(text_to_analyze, st.session_state.get(f"{key_base}_wdg_type", "concept"))
|
||||||
|
if "error" in analysis:
|
||||||
|
st.error(f"Fehler: {analysis['error']}")
|
||||||
|
else:
|
||||||
|
suggestions = analysis.get("suggestions", [])
|
||||||
|
st.session_state[data_sugg_key] = suggestions
|
||||||
|
if not suggestions: st.warning("Keine Vorschläge.")
|
||||||
|
else: st.success(f"{len(suggestions)} Vorschläge gefunden.")
|
||||||
|
|
||||||
|
suggestions = st.session_state[data_sugg_key]
|
||||||
|
if suggestions:
|
||||||
|
current_text = st.session_state.get(widget_body_key, "")
|
||||||
|
for idx, sugg in enumerate(suggestions):
|
||||||
|
link_text = sugg.get('suggested_markdown', '')
|
||||||
|
is_inserted = link_text in current_text
|
||||||
|
bg_color = "#e6fffa" if is_inserted else "#ffffff"
|
||||||
|
border = "3px solid #28a745" if is_inserted else "3px solid #1a73e8"
|
||||||
|
st.markdown(f"<div style='border-left: {border}; background-color: {bg_color}; padding: 10px; margin-bottom: 8px;'><b>{sugg.get('target_title')}</b> <small>({sugg.get('type')})</small><br><i>{sugg.get('reason')}</i><br><code>{link_text}</code></div>", unsafe_allow_html=True)
|
||||||
|
if is_inserted:
|
||||||
|
st.button("❌ Entfernen", key=f"del_{idx}_{key_base}", on_click=_remove_text, args=(link_text,))
|
||||||
|
else:
|
||||||
|
st.button("➕ Einfügen", key=f"add_{idx}_{key_base}", on_click=_insert_text, args=(link_text,))
|
||||||
|
|
||||||
|
# Save Logic Preparation
|
||||||
|
final_tags = [t.strip() for t in st.session_state.get(f"{key_base}_wdg_tags", "").split(",") if t.strip()]
|
||||||
|
final_meta = {
|
||||||
|
"id": "generated_on_save",
|
||||||
|
"type": st.session_state.get(f"{key_base}_wdg_type", "default"),
|
||||||
|
"title": st.session_state.get(f"{key_base}_wdg_title", "").strip(),
|
||||||
|
"status": "draft",
|
||||||
|
"tags": final_tags
|
||||||
|
}
|
||||||
|
if "origin_note_id" in msg:
|
||||||
|
final_meta["id"] = msg["origin_note_id"]
|
||||||
|
|
||||||
|
final_body = st.session_state.get(widget_body_key, st.session_state[data_body_key])
|
||||||
|
if not final_meta["title"]:
|
||||||
|
h1_match = re.search(r"^#\s+(.*)$", final_body, re.MULTILINE)
|
||||||
|
if h1_match: final_meta["title"] = h1_match.group(1).strip()
|
||||||
|
|
||||||
|
final_doc = build_markdown_doc(final_meta, final_body)
|
||||||
|
|
||||||
|
with tab_view:
|
||||||
|
st.markdown('<div class="preview-box">', unsafe_allow_html=True)
|
||||||
|
st.markdown(final_doc)
|
||||||
|
st.markdown('</div>', unsafe_allow_html=True)
|
||||||
|
|
||||||
|
st.markdown("---")
|
||||||
|
|
||||||
|
# Save Actions
|
||||||
|
b1, b2 = st.columns([1, 1])
|
||||||
|
with b1:
|
||||||
|
save_label = "💾 Update speichern" if origin_fname else "💾 Neu anlegen & Indizieren"
|
||||||
|
|
||||||
|
if st.button(save_label, type="primary", key=f"{key_base}_save"):
|
||||||
|
with st.spinner("Sende an Backend..."):
|
||||||
|
if origin_fname:
|
||||||
|
target_file = origin_fname
|
||||||
|
else:
|
||||||
|
raw_title = final_meta.get("title", "draft")
|
||||||
|
target_file = f"{datetime.now().strftime('%Y%m%d')}-{slugify(raw_title)[:60]}.md"
|
||||||
|
|
||||||
|
result = save_draft_to_vault(final_doc, filename=target_file)
|
||||||
|
|
||||||
|
# --- WP-14 CHANGE START: Handling Async Response ---
|
||||||
|
if "error" in result:
|
||||||
|
st.error(f"Fehler: {result['error']}")
|
||||||
|
else:
|
||||||
|
status = result.get("status", "success")
|
||||||
|
file_path = result.get("file_path", "unbekannt")
|
||||||
|
|
||||||
|
if status == "queued":
|
||||||
|
# Neuer Status für Async Processing
|
||||||
|
st.info(f"✅ **Eingereiht:** Datei `{file_path}` wurde gespeichert.")
|
||||||
|
st.caption("Die KI-Analyse und Indizierung läuft im Hintergrund. Du kannst weiterarbeiten.")
|
||||||
|
else:
|
||||||
|
# Legacy / Synchroner Fall
|
||||||
|
st.success(f"Gespeichert: {file_path}")
|
||||||
|
|
||||||
|
st.balloons()
|
||||||
|
# --- WP-14 CHANGE END ---
|
||||||
|
|
||||||
|
with b2:
|
||||||
|
if st.button("📋 Code anzeigen", key=f"{key_base}_btn_copy"):
|
||||||
|
st.code(final_doc, language="markdown")
|
||||||
|
|
||||||
|
st.markdown("</div>", unsafe_allow_html=True)
|
||||||
|
|
||||||
|
def render_manual_editor():
|
||||||
|
"""
|
||||||
|
Rendert den manuellen Editor.
|
||||||
|
"""
|
||||||
|
target_msg = None
|
||||||
|
if st.session_state.messages:
|
||||||
|
last_msg = st.session_state.messages[-1]
|
||||||
|
qid = str(last_msg.get("query_id", ""))
|
||||||
|
if qid.startswith("edit_"):
|
||||||
|
target_msg = last_msg
|
||||||
|
|
||||||
|
if not target_msg:
|
||||||
|
target_msg = {
|
||||||
|
"content": "---\ntype: concept\ntitle: Neue Notiz\nstatus: draft\ntags: []\n---\n# Titel\n",
|
||||||
|
"query_id": f"manual_{uuid.uuid4()}"
|
||||||
|
}
|
||||||
|
|
||||||
|
render_draft_editor(target_msg)
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_graph.py
|
||||||
|
DESCRIPTION: Legacy Graph-Explorer (Streamlit-Agraph). Implementiert Physik-Simulation (BarnesHut) und direkten Editor-Sprung.
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Maintenance (Active Fallback)
|
||||||
|
DEPENDENCIES: streamlit, streamlit_agraph, qdrant_client, ui_config, ui_callbacks
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import streamlit as st
|
||||||
|
from streamlit_agraph import agraph, Config
|
||||||
|
from qdrant_client import models
|
||||||
|
from ui_config import COLLECTION_PREFIX, GRAPH_COLORS
|
||||||
|
from ui_callbacks import switch_to_editor_callback
|
||||||
|
|
||||||
|
def render_graph_explorer(graph_service):
|
||||||
|
st.header("🕸️ Graph Explorer")
|
||||||
|
|
||||||
|
# Session State initialisieren
|
||||||
|
if "graph_center_id" not in st.session_state:
|
||||||
|
st.session_state.graph_center_id = None
|
||||||
|
|
||||||
|
# Defaults für View & Physik setzen
|
||||||
|
st.session_state.setdefault("graph_depth", 2)
|
||||||
|
st.session_state.setdefault("graph_show_labels", True)
|
||||||
|
# Höhere Default-Werte für Abstand
|
||||||
|
st.session_state.setdefault("graph_spacing", 250)
|
||||||
|
st.session_state.setdefault("graph_gravity", -4000)
|
||||||
|
|
||||||
|
col_ctrl, col_graph = st.columns([1, 4])
|
||||||
|
|
||||||
|
# --- LINKE SPALTE: CONTROLS ---
|
||||||
|
with col_ctrl:
|
||||||
|
st.subheader("Fokus")
|
||||||
|
|
||||||
|
# Sucheingabe
|
||||||
|
search_term = st.text_input("Suche Notiz", placeholder="Titel eingeben...")
|
||||||
|
|
||||||
|
# Suchlogik Qdrant
|
||||||
|
if search_term:
|
||||||
|
hits, _ = graph_service.client.scroll(
|
||||||
|
collection_name=f"{COLLECTION_PREFIX}_notes",
|
||||||
|
scroll_filter=models.Filter(must=[models.FieldCondition(key="title", match=models.MatchText(text=search_term))]),
|
||||||
|
limit=10
|
||||||
|
)
|
||||||
|
options = {h.payload['title']: h.payload['note_id'] for h in hits}
|
||||||
|
|
||||||
|
if options:
|
||||||
|
selected_title = st.selectbox("Ergebnisse:", list(options.keys()))
|
||||||
|
if st.button("Laden", use_container_width=True):
|
||||||
|
st.session_state.graph_center_id = options[selected_title]
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
st.divider()
|
||||||
|
|
||||||
|
# Layout & Physik Einstellungen
|
||||||
|
with st.expander("👁️ Ansicht & Layout", expanded=True):
|
||||||
|
st.session_state.graph_depth = st.slider("Tiefe (Tier)", 1, 3, st.session_state.graph_depth)
|
||||||
|
st.session_state.graph_show_labels = st.checkbox("Kanten-Beschriftung", st.session_state.graph_show_labels)
|
||||||
|
|
||||||
|
st.markdown("**Physik (BarnesHut)**")
|
||||||
|
st.session_state.graph_spacing = st.slider("Federlänge (Abstand)", 50, 800, st.session_state.graph_spacing)
|
||||||
|
st.session_state.graph_gravity = st.slider("Abstoßung (Gravity)", -20000, -500, st.session_state.graph_gravity)
|
||||||
|
|
||||||
|
if st.button("Reset Layout"):
|
||||||
|
st.session_state.graph_spacing = 250
|
||||||
|
st.session_state.graph_gravity = -4000
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
st.divider()
|
||||||
|
st.caption("Legende (Top Typen)")
|
||||||
|
for k, v in list(GRAPH_COLORS.items())[:8]:
|
||||||
|
st.markdown(f"<span style='color:{v}'>●</span> {k}", unsafe_allow_html=True)
|
||||||
|
|
||||||
|
# --- RECHTE SPALTE: GRAPH & ACTION BAR ---
|
||||||
|
with col_graph:
|
||||||
|
center_id = st.session_state.graph_center_id
|
||||||
|
|
||||||
|
if center_id:
|
||||||
|
# Action Container oben fixieren (Layout Fix)
|
||||||
|
action_container = st.container()
|
||||||
|
|
||||||
|
# Graph und Daten laden
|
||||||
|
with st.spinner(f"Lade Graph..."):
|
||||||
|
nodes, edges = graph_service.get_ego_graph(
|
||||||
|
center_id,
|
||||||
|
depth=st.session_state.graph_depth,
|
||||||
|
show_labels=st.session_state.graph_show_labels
|
||||||
|
)
|
||||||
|
|
||||||
|
# WICHTIG: Daten für Editor holen (inkl. Pfad)
|
||||||
|
note_data = graph_service.get_note_with_full_content(center_id)
|
||||||
|
|
||||||
|
# Action Bar rendern
|
||||||
|
with action_container:
|
||||||
|
c1, c2 = st.columns([3, 1])
|
||||||
|
with c1:
|
||||||
|
st.caption(f"Aktives Zentrum: **{center_id}**")
|
||||||
|
with c2:
|
||||||
|
if note_data:
|
||||||
|
st.button("📝 Bearbeiten",
|
||||||
|
use_container_width=True,
|
||||||
|
on_click=switch_to_editor_callback,
|
||||||
|
args=(note_data,))
|
||||||
|
else:
|
||||||
|
st.error("Datenfehler: Note nicht gefunden")
|
||||||
|
|
||||||
|
# Debug Inspector
|
||||||
|
with st.expander("🕵️ Data Inspector", expanded=False):
|
||||||
|
if note_data:
|
||||||
|
st.json(note_data)
|
||||||
|
if 'path' in note_data:
|
||||||
|
st.success(f"Pfad OK: {note_data['path']}")
|
||||||
|
else:
|
||||||
|
st.error("Pfad fehlt!")
|
||||||
|
else:
|
||||||
|
st.info("Leer.")
|
||||||
|
|
||||||
|
if not nodes:
|
||||||
|
st.warning("Keine Daten gefunden.")
|
||||||
|
else:
|
||||||
|
# --- CONFIGURATION (BarnesHut) ---
|
||||||
|
# Height-Trick für Re-Render (da key-Parameter manchmal crasht)
|
||||||
|
dyn_height = 800 + (abs(st.session_state.graph_gravity) % 5)
|
||||||
|
|
||||||
|
config = Config(
|
||||||
|
width=1000,
|
||||||
|
height=dyn_height,
|
||||||
|
directed=True,
|
||||||
|
physics={
|
||||||
|
"enabled": True,
|
||||||
|
"solver": "barnesHut",
|
||||||
|
"barnesHut": {
|
||||||
|
"gravitationalConstant": st.session_state.graph_gravity,
|
||||||
|
"centralGravity": 0.005, # Extrem wichtig für die Ausbreitung!
|
||||||
|
"springLength": st.session_state.graph_spacing,
|
||||||
|
"springConstant": 0.04,
|
||||||
|
"damping": 0.09,
|
||||||
|
"avoidOverlap": 0.1
|
||||||
|
},
|
||||||
|
"stabilization": {"enabled": True, "iterations": 600}
|
||||||
|
},
|
||||||
|
hierarchical=False,
|
||||||
|
nodeHighlightBehavior=True,
|
||||||
|
highlightColor="#F7A7A6",
|
||||||
|
collapsible=False
|
||||||
|
)
|
||||||
|
|
||||||
|
return_value = agraph(nodes=nodes, edges=edges, config=config)
|
||||||
|
|
||||||
|
# Interaktions-Logik (Klick auf Node)
|
||||||
|
if return_value:
|
||||||
|
if return_value != center_id:
|
||||||
|
# Navigation: Neues Zentrum setzen
|
||||||
|
st.session_state.graph_center_id = return_value
|
||||||
|
st.rerun()
|
||||||
|
else:
|
||||||
|
# Klick auf das Zentrum selbst
|
||||||
|
st.toast(f"Zentrum: {return_value}")
|
||||||
|
|
||||||
|
else:
|
||||||
|
st.info("👈 Bitte wähle links eine Notiz aus, um den Graphen zu starten.")
|
||||||
@@ -0,0 +1,334 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_graph_cytoscape.py
|
||||||
|
DESCRIPTION: Moderner Graph-Explorer (Cytoscape.js). Features: COSE-Layout, Deep-Linking (URL Params), Active Inspector Pattern (CSS-Styling ohne Re-Render).
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: streamlit, st_cytoscape, qdrant_client, ui_config, ui_callbacks
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import streamlit as st
|
||||||
|
from st_cytoscape import cytoscape
|
||||||
|
from qdrant_client import models
|
||||||
|
from ui_config import COLLECTION_PREFIX, GRAPH_COLORS
|
||||||
|
from ui_callbacks import switch_to_editor_callback
|
||||||
|
|
||||||
|
def update_url_params():
|
||||||
|
"""Callback: Schreibt Slider-Werte in die URL und synchronisiert den State."""
|
||||||
|
# Werte aus den Slider-Keys in die Logik-Variablen übertragen
|
||||||
|
if "cy_depth_slider" in st.session_state:
|
||||||
|
st.session_state.cy_depth = st.session_state.cy_depth_slider
|
||||||
|
if "cy_len_slider" in st.session_state:
|
||||||
|
st.session_state.cy_ideal_edge_len = st.session_state.cy_len_slider
|
||||||
|
if "cy_rep_slider" in st.session_state:
|
||||||
|
st.session_state.cy_node_repulsion = st.session_state.cy_rep_slider
|
||||||
|
|
||||||
|
# In URL schreiben
|
||||||
|
st.query_params["depth"] = st.session_state.cy_depth
|
||||||
|
st.query_params["len"] = st.session_state.cy_ideal_edge_len
|
||||||
|
st.query_params["rep"] = st.session_state.cy_node_repulsion
|
||||||
|
|
||||||
|
def render_graph_explorer_cytoscape(graph_service):
|
||||||
|
st.header("🕸️ Graph Explorer (Cytoscape)")
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 1. STATE & PERSISTENZ
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
if "graph_center_id" not in st.session_state:
|
||||||
|
st.session_state.graph_center_id = None
|
||||||
|
|
||||||
|
if "graph_inspected_id" not in st.session_state:
|
||||||
|
st.session_state.graph_inspected_id = None
|
||||||
|
|
||||||
|
# Lade Einstellungen aus der URL (falls vorhanden), sonst Defaults
|
||||||
|
params = st.query_params
|
||||||
|
|
||||||
|
# Helper um sicher int zu parsen
|
||||||
|
def get_param(key, default):
|
||||||
|
try: return int(params.get(key, default))
|
||||||
|
except: return default
|
||||||
|
|
||||||
|
# Initialisiere Session State Variablen, falls noch nicht vorhanden
|
||||||
|
if "cy_depth" not in st.session_state:
|
||||||
|
st.session_state.cy_depth = get_param("depth", 2)
|
||||||
|
|
||||||
|
if "cy_ideal_edge_len" not in st.session_state:
|
||||||
|
st.session_state.cy_ideal_edge_len = get_param("len", 150)
|
||||||
|
|
||||||
|
if "cy_node_repulsion" not in st.session_state:
|
||||||
|
st.session_state.cy_node_repulsion = get_param("rep", 1000000)
|
||||||
|
|
||||||
|
col_ctrl, col_graph = st.columns([1, 4])
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 2. LINKES PANEL (Steuerung)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
with col_ctrl:
|
||||||
|
st.subheader("Fokus")
|
||||||
|
|
||||||
|
search_term = st.text_input("Suche Notiz", placeholder="Titel eingeben...", key="cy_search")
|
||||||
|
|
||||||
|
if search_term:
|
||||||
|
hits, _ = graph_service.client.scroll(
|
||||||
|
collection_name=f"{COLLECTION_PREFIX}_notes",
|
||||||
|
limit=10,
|
||||||
|
scroll_filter=models.Filter(must=[models.FieldCondition(key="title", match=models.MatchText(text=search_term))])
|
||||||
|
)
|
||||||
|
options = {h.payload['title']: h.payload['note_id'] for h in hits}
|
||||||
|
|
||||||
|
if options:
|
||||||
|
selected_title = st.selectbox("Ergebnisse:", list(options.keys()), key="cy_select")
|
||||||
|
if st.button("Laden", use_container_width=True, key="cy_load"):
|
||||||
|
new_id = options[selected_title]
|
||||||
|
st.session_state.graph_center_id = new_id
|
||||||
|
st.session_state.graph_inspected_id = new_id
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
st.divider()
|
||||||
|
|
||||||
|
# LAYOUT EINSTELLUNGEN (Mit URL Sync)
|
||||||
|
with st.expander("👁️ Layout Einstellungen", expanded=True):
|
||||||
|
st.slider("Tiefe (Tier)", 1, 3,
|
||||||
|
value=st.session_state.cy_depth,
|
||||||
|
key="cy_depth_slider",
|
||||||
|
on_change=update_url_params)
|
||||||
|
|
||||||
|
st.markdown("**COSE Layout**")
|
||||||
|
st.slider("Kantenlänge", 50, 600,
|
||||||
|
value=st.session_state.cy_ideal_edge_len,
|
||||||
|
key="cy_len_slider",
|
||||||
|
on_change=update_url_params)
|
||||||
|
|
||||||
|
st.slider("Knoten-Abstoßung", 100000, 5000000, step=100000,
|
||||||
|
value=st.session_state.cy_node_repulsion,
|
||||||
|
key="cy_rep_slider",
|
||||||
|
on_change=update_url_params)
|
||||||
|
|
||||||
|
if st.button("Neu berechnen", key="cy_rerun"):
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
st.divider()
|
||||||
|
st.caption("Legende")
|
||||||
|
for k, v in list(GRAPH_COLORS.items())[:8]:
|
||||||
|
st.markdown(f"<span style='color:{v}'>●</span> {k}", unsafe_allow_html=True)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 3. RECHTES PANEL (GRAPH & INSPECTOR)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
with col_graph:
|
||||||
|
center_id = st.session_state.graph_center_id
|
||||||
|
|
||||||
|
# Fallback Init
|
||||||
|
if not center_id and st.session_state.graph_inspected_id:
|
||||||
|
center_id = st.session_state.graph_inspected_id
|
||||||
|
st.session_state.graph_center_id = center_id
|
||||||
|
|
||||||
|
if center_id:
|
||||||
|
# Sync Inspection
|
||||||
|
if not st.session_state.graph_inspected_id:
|
||||||
|
st.session_state.graph_inspected_id = center_id
|
||||||
|
|
||||||
|
inspected_id = st.session_state.graph_inspected_id
|
||||||
|
|
||||||
|
# --- DATEN LADEN ---
|
||||||
|
with st.spinner(f"Lade Graph (Tiefe {st.session_state.cy_depth})..."):
|
||||||
|
# 1. Graph Daten
|
||||||
|
nodes_data, edges_data = graph_service.get_ego_graph(
|
||||||
|
center_id,
|
||||||
|
depth=st.session_state.cy_depth
|
||||||
|
)
|
||||||
|
# 2. Detail Daten (Inspector)
|
||||||
|
inspected_data = graph_service.get_note_with_full_content(inspected_id)
|
||||||
|
|
||||||
|
# --- ACTION BAR ---
|
||||||
|
action_container = st.container()
|
||||||
|
with action_container:
|
||||||
|
c1, c2, c3 = st.columns([2, 1, 1])
|
||||||
|
|
||||||
|
with c1:
|
||||||
|
title_show = inspected_data.get('title', inspected_id) if inspected_data else inspected_id
|
||||||
|
st.info(f"**Ausgewählt:** {title_show}")
|
||||||
|
|
||||||
|
with c2:
|
||||||
|
# NAVIGATION
|
||||||
|
if inspected_id != center_id:
|
||||||
|
if st.button("🎯 Als Zentrum setzen", use_container_width=True, key="cy_nav_btn"):
|
||||||
|
st.session_state.graph_center_id = inspected_id
|
||||||
|
st.rerun()
|
||||||
|
else:
|
||||||
|
st.caption("_(Ist aktuelles Zentrum)_")
|
||||||
|
|
||||||
|
with c3:
|
||||||
|
# EDITIEREN
|
||||||
|
if inspected_data:
|
||||||
|
st.button("📝 Bearbeiten",
|
||||||
|
use_container_width=True,
|
||||||
|
on_click=switch_to_editor_callback,
|
||||||
|
args=(inspected_data,),
|
||||||
|
key="cy_edit_btn")
|
||||||
|
|
||||||
|
# --- DATA INSPECTOR ---
|
||||||
|
with st.expander("🕵️ Data Inspector (Details)", expanded=False):
|
||||||
|
if inspected_data:
|
||||||
|
col_i1, col_i2 = st.columns(2)
|
||||||
|
with col_i1:
|
||||||
|
st.markdown(f"**ID:** `{inspected_data.get('note_id')}`")
|
||||||
|
st.markdown(f"**Typ:** `{inspected_data.get('type')}`")
|
||||||
|
with col_i2:
|
||||||
|
st.markdown(f"**Tags:** {', '.join(inspected_data.get('tags', []))}")
|
||||||
|
path_check = "✅" if inspected_data.get('path') else "❌"
|
||||||
|
st.markdown(f"**Pfad:** {path_check}")
|
||||||
|
|
||||||
|
st.caption("Inhalt (Vorschau):")
|
||||||
|
st.text_area("Content Preview", inspected_data.get('fulltext', '')[:1000], height=200, disabled=True, label_visibility="collapsed")
|
||||||
|
|
||||||
|
with st.expander("📄 Raw JSON anzeigen"):
|
||||||
|
st.json(inspected_data)
|
||||||
|
else:
|
||||||
|
st.warning("Keine Daten geladen.")
|
||||||
|
|
||||||
|
# --- GRAPH ELEMENTS ---
|
||||||
|
cy_elements = []
|
||||||
|
|
||||||
|
for n in nodes_data:
|
||||||
|
is_center = (n.id == center_id)
|
||||||
|
is_inspected = (n.id == inspected_id)
|
||||||
|
|
||||||
|
tooltip_text = n.title if n.title else n.label
|
||||||
|
display_label = n.label
|
||||||
|
if len(display_label) > 15 and " " in display_label:
|
||||||
|
display_label = display_label.replace(" ", "\n", 1)
|
||||||
|
|
||||||
|
cy_node = {
|
||||||
|
"data": {
|
||||||
|
"id": n.id,
|
||||||
|
"label": display_label,
|
||||||
|
"bg_color": n.color,
|
||||||
|
"tooltip": tooltip_text
|
||||||
|
},
|
||||||
|
# Wir steuern das Aussehen rein über Klassen (.inspected / .center)
|
||||||
|
"classes": " ".join([c for c in ["center" if is_center else "", "inspected" if is_inspected else ""] if c]),
|
||||||
|
"selected": False
|
||||||
|
}
|
||||||
|
cy_elements.append(cy_node)
|
||||||
|
|
||||||
|
for e in edges_data:
|
||||||
|
target_id = getattr(e, "to", getattr(e, "target", None))
|
||||||
|
if target_id:
|
||||||
|
cy_edge = {
|
||||||
|
"data": {
|
||||||
|
"source": e.source,
|
||||||
|
"target": target_id,
|
||||||
|
"label": e.label,
|
||||||
|
"line_color": e.color
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cy_elements.append(cy_edge)
|
||||||
|
|
||||||
|
# --- STYLESHEET ---
|
||||||
|
stylesheet = [
|
||||||
|
{
|
||||||
|
"selector": "node",
|
||||||
|
"style": {
|
||||||
|
"label": "data(label)",
|
||||||
|
"width": "30px", "height": "30px",
|
||||||
|
"background-color": "data(bg_color)",
|
||||||
|
"color": "#333", "font-size": "12px",
|
||||||
|
"text-valign": "center", "text-halign": "center",
|
||||||
|
"text-wrap": "wrap", "text-max-width": "90px",
|
||||||
|
"border-width": 2, "border-color": "#fff",
|
||||||
|
"title": "data(tooltip)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
# Inspiziert (Gelber Rahmen)
|
||||||
|
{
|
||||||
|
"selector": ".inspected",
|
||||||
|
"style": {
|
||||||
|
"border-width": 6,
|
||||||
|
"border-color": "#FFC300",
|
||||||
|
"width": "50px", "height": "50px",
|
||||||
|
"font-weight": "bold",
|
||||||
|
"z-index": 999
|
||||||
|
}
|
||||||
|
},
|
||||||
|
# Zentrum (Roter Rahmen)
|
||||||
|
{
|
||||||
|
"selector": ".center",
|
||||||
|
"style": {
|
||||||
|
"border-width": 4,
|
||||||
|
"border-color": "#FF5733",
|
||||||
|
"width": "40px", "height": "40px"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
# Mix
|
||||||
|
{
|
||||||
|
"selector": ".center.inspected",
|
||||||
|
"style": {
|
||||||
|
"border-width": 6,
|
||||||
|
"border-color": "#FF5733",
|
||||||
|
"width": "55px", "height": "55px"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
# Default Selection unterdrücken
|
||||||
|
{
|
||||||
|
"selector": "node:selected",
|
||||||
|
"style": {
|
||||||
|
"border-width": 0,
|
||||||
|
"overlay-opacity": 0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"selector": "edge",
|
||||||
|
"style": {
|
||||||
|
"width": 2,
|
||||||
|
"line-color": "data(line_color)",
|
||||||
|
"target-arrow-color": "data(line_color)",
|
||||||
|
"target-arrow-shape": "triangle",
|
||||||
|
"curve-style": "bezier",
|
||||||
|
"label": "data(label)",
|
||||||
|
"font-size": "10px", "color": "#666",
|
||||||
|
"text-background-opacity": 0.8, "text-background-color": "#fff"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
# --- RENDER ---
|
||||||
|
graph_key = f"cy_{center_id}_{st.session_state.cy_depth}_{st.session_state.cy_ideal_edge_len}"
|
||||||
|
|
||||||
|
clicked_elements = cytoscape(
|
||||||
|
elements=cy_elements,
|
||||||
|
stylesheet=stylesheet,
|
||||||
|
layout={
|
||||||
|
"name": "cose",
|
||||||
|
"idealEdgeLength": st.session_state.cy_ideal_edge_len,
|
||||||
|
"nodeOverlap": 20,
|
||||||
|
"refresh": 20,
|
||||||
|
"fit": True,
|
||||||
|
"padding": 50,
|
||||||
|
"randomize": False,
|
||||||
|
"componentSpacing": 100,
|
||||||
|
"nodeRepulsion": st.session_state.cy_node_repulsion,
|
||||||
|
"edgeElasticity": 100,
|
||||||
|
"nestingFactor": 5,
|
||||||
|
"gravity": 80,
|
||||||
|
"numIter": 1000,
|
||||||
|
"initialTemp": 200,
|
||||||
|
"coolingFactor": 0.95,
|
||||||
|
"minTemp": 1.0,
|
||||||
|
"animate": False
|
||||||
|
},
|
||||||
|
key=graph_key,
|
||||||
|
height="700px"
|
||||||
|
)
|
||||||
|
|
||||||
|
# --- EVENT HANDLING ---
|
||||||
|
if clicked_elements:
|
||||||
|
clicked_nodes = clicked_elements.get("nodes", [])
|
||||||
|
if clicked_nodes:
|
||||||
|
clicked_id = clicked_nodes[0]
|
||||||
|
|
||||||
|
if clicked_id != st.session_state.graph_inspected_id:
|
||||||
|
st.session_state.graph_inspected_id = clicked_id
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
else:
|
||||||
|
st.info("👈 Bitte wähle links eine Notiz aus.")
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_graph_service.py
|
||||||
|
DESCRIPTION: Data Layer für den Graphen. Greift direkt auf Qdrant zu (Performance), um Knoten/Kanten zu laden und Texte zu rekonstruieren ("Stitching").
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: qdrant_client, streamlit_agraph, ui_config, re
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
from qdrant_client import QdrantClient, models
|
||||||
|
from streamlit_agraph import Node, Edge
|
||||||
|
from ui_config import GRAPH_COLORS, get_edge_color, SYSTEM_EDGES
|
||||||
|
|
||||||
|
class GraphExplorerService:
|
||||||
|
def __init__(self, url, api_key=None, prefix="mindnet"):
|
||||||
|
self.client = QdrantClient(url=url, api_key=api_key)
|
||||||
|
self.prefix = prefix
|
||||||
|
self.notes_col = f"{prefix}_notes"
|
||||||
|
self.chunks_col = f"{prefix}_chunks"
|
||||||
|
self.edges_col = f"{prefix}_edges"
|
||||||
|
self._note_cache = {}
|
||||||
|
|
||||||
|
def get_note_with_full_content(self, note_id):
|
||||||
|
"""
|
||||||
|
Lädt die Metadaten der Note und rekonstruiert den gesamten Text
|
||||||
|
aus den Chunks (Stitching). Wichtig für den Editor-Fallback.
|
||||||
|
"""
|
||||||
|
# 1. Metadaten holen
|
||||||
|
meta = self._fetch_note_cached(note_id)
|
||||||
|
if not meta: return None
|
||||||
|
|
||||||
|
# 2. Volltext aus Chunks bauen
|
||||||
|
full_text = self._fetch_full_text_stitched(note_id)
|
||||||
|
|
||||||
|
# 3. Ergebnis kombinieren (Wir überschreiben das 'fulltext' Feld mit dem frischen Stitching)
|
||||||
|
# Wir geben eine Kopie zurück, um den Cache nicht zu verfälschen
|
||||||
|
complete_note = meta.copy()
|
||||||
|
if full_text:
|
||||||
|
complete_note['fulltext'] = full_text
|
||||||
|
|
||||||
|
return complete_note
|
||||||
|
|
||||||
|
def get_ego_graph(self, center_note_id: str, depth=2, show_labels=True):
|
||||||
|
"""
|
||||||
|
Erstellt den Ego-Graphen um eine zentrale Notiz.
|
||||||
|
Lädt Volltext für das Zentrum und Snippets für Nachbarn.
|
||||||
|
"""
|
||||||
|
nodes_dict = {}
|
||||||
|
unique_edges = {}
|
||||||
|
|
||||||
|
# 1. Center Note laden
|
||||||
|
center_note = self._fetch_note_cached(center_note_id)
|
||||||
|
if not center_note: return [], []
|
||||||
|
self._add_node_to_dict(nodes_dict, center_note, level=0)
|
||||||
|
|
||||||
|
# Initialset für Suche
|
||||||
|
level_1_ids = {center_note_id}
|
||||||
|
|
||||||
|
# Suche Kanten für Center (L1)
|
||||||
|
l1_edges = self._find_connected_edges([center_note_id], center_note.get("title"))
|
||||||
|
|
||||||
|
for edge_data in l1_edges:
|
||||||
|
src_id, tgt_id = self._process_edge(edge_data, nodes_dict, unique_edges, current_depth=1)
|
||||||
|
if src_id: level_1_ids.add(src_id)
|
||||||
|
if tgt_id: level_1_ids.add(tgt_id)
|
||||||
|
|
||||||
|
# Level 2 Suche (begrenzt für Performance)
|
||||||
|
if depth > 1 and len(level_1_ids) > 1 and len(level_1_ids) < 80:
|
||||||
|
l1_subset = list(level_1_ids - {center_note_id})
|
||||||
|
if l1_subset:
|
||||||
|
l2_edges = self._find_connected_edges_batch(l1_subset)
|
||||||
|
for edge_data in l2_edges:
|
||||||
|
self._process_edge(edge_data, nodes_dict, unique_edges, current_depth=2)
|
||||||
|
|
||||||
|
# --- SMART CONTENT LOADING ---
|
||||||
|
|
||||||
|
# A. Fulltext für Center Node holen (Chunks zusammenfügen)
|
||||||
|
center_text = self._fetch_full_text_stitched(center_note_id)
|
||||||
|
if center_note_id in nodes_dict:
|
||||||
|
orig_title = nodes_dict[center_note_id].title
|
||||||
|
clean_full = self._clean_markdown(center_text[:2000])
|
||||||
|
# Wir packen den Text in den Tooltip (title attribute)
|
||||||
|
nodes_dict[center_note_id].title = f"{orig_title}\n\n📄 INHALT:\n{clean_full}..."
|
||||||
|
|
||||||
|
# B. Previews für alle Nachbarn holen (Batch)
|
||||||
|
all_ids = list(nodes_dict.keys())
|
||||||
|
previews = self._fetch_previews_for_nodes(all_ids)
|
||||||
|
|
||||||
|
for nid, node_obj in nodes_dict.items():
|
||||||
|
if nid != center_note_id:
|
||||||
|
prev_raw = previews.get(nid, "Kein Vorschau-Text.")
|
||||||
|
clean_prev = self._clean_markdown(prev_raw[:600])
|
||||||
|
node_obj.title = f"{node_obj.title}\n\n🔍 VORSCHAU:\n{clean_prev}..."
|
||||||
|
|
||||||
|
# Graphen bauen (Nodes & Edges finalisieren)
|
||||||
|
final_edges = []
|
||||||
|
for (src, tgt), data in unique_edges.items():
|
||||||
|
kind = data['kind']
|
||||||
|
prov = data['provenance']
|
||||||
|
color = get_edge_color(kind)
|
||||||
|
is_smart = (prov != "explicit" and prov != "rule")
|
||||||
|
|
||||||
|
# Label Logik
|
||||||
|
label_text = kind if show_labels else " "
|
||||||
|
|
||||||
|
final_edges.append(Edge(
|
||||||
|
source=src, target=tgt, label=label_text, color=color, dashes=is_smart,
|
||||||
|
title=f"Relation: {kind}\nProvenance: {prov}"
|
||||||
|
))
|
||||||
|
|
||||||
|
return list(nodes_dict.values()), final_edges
|
||||||
|
|
||||||
|
def _clean_markdown(self, text):
|
||||||
|
"""Entfernt Markdown-Sonderzeichen für saubere Tooltips im Browser."""
|
||||||
|
if not text: return ""
|
||||||
|
# Entferne Header Marker (## )
|
||||||
|
text = re.sub(r'#+\s', '', text)
|
||||||
|
# Entferne Bold/Italic (** oder *)
|
||||||
|
text = re.sub(r'\*\*|__|\*|_', '', text)
|
||||||
|
# Entferne Links [Text](Url) -> Text
|
||||||
|
text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text)
|
||||||
|
# Entferne Wikilinks [[Link]] -> Link
|
||||||
|
text = re.sub(r'\[\[([^\]]+)\]\]', r'\1', text)
|
||||||
|
return text
|
||||||
|
|
||||||
|
def _fetch_full_text_stitched(self, note_id):
|
||||||
|
"""Lädt alle Chunks einer Note und baut den Text zusammen."""
|
||||||
|
try:
|
||||||
|
scroll_filter = models.Filter(
|
||||||
|
must=[models.FieldCondition(key="note_id", match=models.MatchValue(value=note_id))]
|
||||||
|
)
|
||||||
|
# Limit hoch genug setzen
|
||||||
|
chunks, _ = self.client.scroll(self.chunks_col, scroll_filter=scroll_filter, limit=100, with_payload=True)
|
||||||
|
# Sortieren nach 'ord' (Reihenfolge im Dokument)
|
||||||
|
chunks.sort(key=lambda x: x.payload.get('ord', 999))
|
||||||
|
|
||||||
|
full_text = []
|
||||||
|
for c in chunks:
|
||||||
|
# 'text' ist der reine Inhalt ohne Overlap
|
||||||
|
txt = c.payload.get('text', '')
|
||||||
|
if txt: full_text.append(txt)
|
||||||
|
|
||||||
|
return "\n\n".join(full_text)
|
||||||
|
except:
|
||||||
|
return "Fehler beim Laden des Volltexts."
|
||||||
|
|
||||||
|
def _fetch_previews_for_nodes(self, node_ids):
|
||||||
|
"""Holt Batch-weise den ersten Chunk für eine Liste von Nodes."""
|
||||||
|
if not node_ids: return {}
|
||||||
|
previews = {}
|
||||||
|
try:
|
||||||
|
scroll_filter = models.Filter(must=[models.FieldCondition(key="note_id", match=models.MatchAny(any=node_ids))])
|
||||||
|
# Limit = Anzahl Nodes * 3 (Puffer)
|
||||||
|
chunks, _ = self.client.scroll(self.chunks_col, scroll_filter=scroll_filter, limit=len(node_ids)*3, with_payload=True)
|
||||||
|
|
||||||
|
for c in chunks:
|
||||||
|
nid = c.payload.get("note_id")
|
||||||
|
# Nur den ersten gefundenen Chunk pro Note nehmen
|
||||||
|
if nid and nid not in previews:
|
||||||
|
previews[nid] = c.payload.get("window") or c.payload.get("text") or ""
|
||||||
|
except: pass
|
||||||
|
return previews
|
||||||
|
|
||||||
|
def _find_connected_edges(self, note_ids, note_title=None):
|
||||||
|
"""Findet eingehende und ausgehende Kanten."""
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
# 1. OUTGOING EDGES (Der "Owner"-Fix)
|
||||||
|
# Wir suchen Kanten, die im Feld 'note_id' (Owner) eine unserer Notizen haben.
|
||||||
|
# Das findet ALLE ausgehenden Kanten, egal ob sie an einem Chunk oder der Note hängen.
|
||||||
|
if note_ids:
|
||||||
|
out_filter = models.Filter(must=[
|
||||||
|
models.FieldCondition(key="note_id", match=models.MatchAny(any=note_ids)),
|
||||||
|
models.FieldCondition(key="kind", match=models.MatchExcept(**{"except": SYSTEM_EDGES}))
|
||||||
|
])
|
||||||
|
# Limit hoch, um alles zu finden
|
||||||
|
res_out, _ = self.client.scroll(self.edges_col, scroll_filter=out_filter, limit=500, with_payload=True)
|
||||||
|
results.extend(res_out)
|
||||||
|
|
||||||
|
# 2. INCOMING EDGES (Ziel = Chunk ID oder Titel oder Note ID)
|
||||||
|
# Hier müssen wir Chunks auflösen, um Treffer auf Chunks zu finden.
|
||||||
|
|
||||||
|
# Chunk IDs der aktuellen Notes holen
|
||||||
|
chunk_ids = []
|
||||||
|
if note_ids:
|
||||||
|
c_filter = models.Filter(must=[models.FieldCondition(key="note_id", match=models.MatchAny(any=note_ids))])
|
||||||
|
chunks, _ = self.client.scroll(self.chunks_col, scroll_filter=c_filter, limit=300)
|
||||||
|
chunk_ids = [c.id for c in chunks]
|
||||||
|
|
||||||
|
shoulds = []
|
||||||
|
# Case A: Edge zeigt auf einen unserer Chunks
|
||||||
|
if chunk_ids:
|
||||||
|
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchAny(any=chunk_ids)))
|
||||||
|
|
||||||
|
# Case B: Edge zeigt direkt auf unsere Note ID
|
||||||
|
if note_ids:
|
||||||
|
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchAny(any=note_ids)))
|
||||||
|
|
||||||
|
# Case C: Edge zeigt auf unseren Titel (Wikilinks)
|
||||||
|
if note_title:
|
||||||
|
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchValue(value=note_title)))
|
||||||
|
|
||||||
|
if shoulds:
|
||||||
|
in_filter = models.Filter(
|
||||||
|
must=[models.FieldCondition(key="kind", match=models.MatchExcept(**{"except": SYSTEM_EDGES}))],
|
||||||
|
should=shoulds
|
||||||
|
)
|
||||||
|
res_in, _ = self.client.scroll(self.edges_col, scroll_filter=in_filter, limit=500, with_payload=True)
|
||||||
|
results.extend(res_in)
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
def _find_connected_edges_batch(self, note_ids):
|
||||||
|
# Wrapper für Level 2 Suche
|
||||||
|
return self._find_connected_edges(note_ids)
|
||||||
|
|
||||||
|
def _process_edge(self, record, nodes_dict, unique_edges, current_depth):
|
||||||
|
"""Verarbeitet eine rohe Edge, löst IDs auf und fügt sie den Dictionaries hinzu."""
|
||||||
|
payload = record.payload
|
||||||
|
src_ref = payload.get("source_id")
|
||||||
|
tgt_ref = payload.get("target_id")
|
||||||
|
kind = payload.get("kind")
|
||||||
|
provenance = payload.get("provenance", "explicit")
|
||||||
|
|
||||||
|
# IDs zu Notes auflösen
|
||||||
|
src_note = self._resolve_note_from_ref(src_ref)
|
||||||
|
tgt_note = self._resolve_note_from_ref(tgt_ref)
|
||||||
|
|
||||||
|
if src_note and tgt_note:
|
||||||
|
src_id = src_note['note_id']
|
||||||
|
tgt_id = tgt_note['note_id']
|
||||||
|
|
||||||
|
if src_id != tgt_id:
|
||||||
|
# Nodes hinzufügen
|
||||||
|
self._add_node_to_dict(nodes_dict, src_note, level=current_depth)
|
||||||
|
self._add_node_to_dict(nodes_dict, tgt_note, level=current_depth)
|
||||||
|
|
||||||
|
# Kante hinzufügen (mit Deduplizierung)
|
||||||
|
key = (src_id, tgt_id)
|
||||||
|
existing = unique_edges.get(key)
|
||||||
|
|
||||||
|
should_update = True
|
||||||
|
# Bevorzuge explizite Kanten vor Smart Kanten
|
||||||
|
is_current_explicit = (provenance in ["explicit", "rule"])
|
||||||
|
if existing:
|
||||||
|
is_existing_explicit = (existing['provenance'] in ["explicit", "rule"])
|
||||||
|
if is_existing_explicit and not is_current_explicit:
|
||||||
|
should_update = False
|
||||||
|
|
||||||
|
if should_update:
|
||||||
|
unique_edges[key] = {"source": src_id, "target": tgt_id, "kind": kind, "provenance": provenance}
|
||||||
|
return src_id, tgt_id
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
def _fetch_note_cached(self, note_id):
|
||||||
|
if note_id in self._note_cache: return self._note_cache[note_id]
|
||||||
|
res, _ = self.client.scroll(
|
||||||
|
collection_name=self.notes_col,
|
||||||
|
scroll_filter=models.Filter(must=[models.FieldCondition(key="note_id", match=models.MatchValue(value=note_id))]),
|
||||||
|
limit=1, with_payload=True
|
||||||
|
)
|
||||||
|
if res:
|
||||||
|
self._note_cache[note_id] = res[0].payload
|
||||||
|
return res[0].payload
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _resolve_note_from_ref(self, ref_str):
|
||||||
|
"""Löst eine ID (Chunk, Note oder Titel) zu einer Note Payload auf."""
|
||||||
|
if not ref_str: return None
|
||||||
|
|
||||||
|
# Fall A: Chunk ID (enthält #)
|
||||||
|
if "#" in ref_str:
|
||||||
|
try:
|
||||||
|
# Versuch 1: Chunk ID direkt
|
||||||
|
res = self.client.retrieve(self.chunks_col, ids=[ref_str], with_payload=True)
|
||||||
|
if res: return self._fetch_note_cached(res[0].payload.get("note_id"))
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
# Versuch 2: NoteID#Section (Hash abtrennen)
|
||||||
|
possible_note_id = ref_str.split("#")[0]
|
||||||
|
if self._fetch_note_cached(possible_note_id): return self._fetch_note_cached(possible_note_id)
|
||||||
|
|
||||||
|
# Fall B: Note ID direkt
|
||||||
|
if self._fetch_note_cached(ref_str): return self._fetch_note_cached(ref_str)
|
||||||
|
|
||||||
|
# Fall C: Titel
|
||||||
|
res, _ = self.client.scroll(
|
||||||
|
collection_name=self.notes_col,
|
||||||
|
scroll_filter=models.Filter(must=[models.FieldCondition(key="title", match=models.MatchValue(value=ref_str))]),
|
||||||
|
limit=1, with_payload=True
|
||||||
|
)
|
||||||
|
if res:
|
||||||
|
self._note_cache[res[0].payload['note_id']] = res[0].payload
|
||||||
|
return res[0].payload
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _add_node_to_dict(self, node_dict, note_payload, level=1):
|
||||||
|
nid = note_payload.get("note_id")
|
||||||
|
if nid in node_dict: return
|
||||||
|
|
||||||
|
ntype = note_payload.get("type", "default")
|
||||||
|
color = GRAPH_COLORS.get(ntype, GRAPH_COLORS["default"])
|
||||||
|
|
||||||
|
# Basis-Tooltip (wird später erweitert)
|
||||||
|
tooltip = f"Titel: {note_payload.get('title')}\nTyp: {ntype}"
|
||||||
|
|
||||||
|
if level == 0: size = 45
|
||||||
|
elif level == 1: size = 25
|
||||||
|
else: size = 15
|
||||||
|
|
||||||
|
node_dict[nid] = Node(
|
||||||
|
id=nid,
|
||||||
|
label=note_payload.get('title', nid),
|
||||||
|
size=size,
|
||||||
|
color=color,
|
||||||
|
shape="dot" if level > 0 else "diamond",
|
||||||
|
title=tooltip,
|
||||||
|
font={'color': 'black', 'face': 'arial', 'size': 14 if level < 2 else 0}
|
||||||
|
)
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_sidebar.py
|
||||||
|
DESCRIPTION: Rendert die Sidebar. Steuert den Modus-Wechsel (Chat/Editor/Graph) und globale Settings (Top-K).
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: streamlit, ui_utils, ui_config
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import streamlit as st
|
||||||
|
from ui_utils import load_history_from_logs
|
||||||
|
from ui_config import HISTORY_FILE
|
||||||
|
|
||||||
|
def render_sidebar():
|
||||||
|
with st.sidebar:
|
||||||
|
st.title("🧠 mindnet")
|
||||||
|
st.caption("v2.6 | WP-19 Graph View")
|
||||||
|
|
||||||
|
if "sidebar_mode_selection" not in st.session_state:
|
||||||
|
st.session_state["sidebar_mode_selection"] = "💬 Chat"
|
||||||
|
|
||||||
|
mode = st.radio(
|
||||||
|
"Modus",
|
||||||
|
[
|
||||||
|
"💬 Chat",
|
||||||
|
"📝 Manueller Editor",
|
||||||
|
"🕸️ Graph (Agraph)",
|
||||||
|
"🕸️ Graph (Cytoscape)" # <-- Neuer Punkt
|
||||||
|
],
|
||||||
|
key="sidebar_mode_selection"
|
||||||
|
)
|
||||||
|
|
||||||
|
st.divider()
|
||||||
|
st.subheader("⚙️ Settings")
|
||||||
|
top_k = st.slider("Quellen (Top-K)", 1, 10, 5)
|
||||||
|
explain = st.toggle("Explanation Layer", True)
|
||||||
|
|
||||||
|
st.divider()
|
||||||
|
st.subheader("🕒 Verlauf")
|
||||||
|
for q in load_history_from_logs(HISTORY_FILE, 8):
|
||||||
|
if st.button(f"🔎 {q[:25]}...", key=f"hist_{q}", use_container_width=True):
|
||||||
|
st.session_state.messages.append({"role": "user", "content": q})
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
return mode, top_k, explain
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/frontend/ui_utils.py
|
||||||
|
DESCRIPTION: String-Utilities. Parser für Markdown/YAML (LLM-Healing) und Helper für History-Loading.
|
||||||
|
VERSION: 2.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: re, yaml, unicodedata, json, datetime
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import yaml
|
||||||
|
import unicodedata
|
||||||
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
def slugify(value):
|
||||||
|
if not value: return ""
|
||||||
|
value = str(value).lower()
|
||||||
|
replacements = {'ä': 'ae', 'ö': 'oe', 'ü': 'ue', 'ß': 'ss', '&': 'und', '+': 'und'}
|
||||||
|
for k, v in replacements.items():
|
||||||
|
value = value.replace(k, v)
|
||||||
|
|
||||||
|
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
|
||||||
|
value = re.sub(r'[^\w\s-]', '', value).strip()
|
||||||
|
return re.sub(r'[-\s]+', '-', value)
|
||||||
|
|
||||||
|
def normalize_meta_and_body(meta, body):
|
||||||
|
ALLOWED_KEYS = {"title", "type", "status", "tags", "id", "created", "updated", "aliases", "lang"}
|
||||||
|
clean_meta = {}
|
||||||
|
extra_content = []
|
||||||
|
|
||||||
|
if "titel" in meta and "title" not in meta:
|
||||||
|
meta["title"] = meta.pop("titel")
|
||||||
|
|
||||||
|
tag_candidates = ["tags", "emotionale_keywords", "keywords", "schluesselwoerter"]
|
||||||
|
all_tags = []
|
||||||
|
for key in tag_candidates:
|
||||||
|
if key in meta:
|
||||||
|
val = meta[key]
|
||||||
|
if isinstance(val, list): all_tags.extend(val)
|
||||||
|
elif isinstance(val, str): all_tags.extend([t.strip() for t in val.split(",")])
|
||||||
|
|
||||||
|
for key, val in meta.items():
|
||||||
|
if key in ALLOWED_KEYS:
|
||||||
|
clean_meta[key] = val
|
||||||
|
elif key in tag_candidates:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
if val and isinstance(val, str):
|
||||||
|
header = key.replace("_", " ").title()
|
||||||
|
extra_content.append(f"## {header}\n{val}\n")
|
||||||
|
|
||||||
|
if all_tags:
|
||||||
|
clean_tags = []
|
||||||
|
for t in all_tags:
|
||||||
|
t_clean = str(t).replace("#", "").strip()
|
||||||
|
if t_clean: clean_tags.append(t_clean)
|
||||||
|
clean_meta["tags"] = list(set(clean_tags))
|
||||||
|
|
||||||
|
if extra_content:
|
||||||
|
new_section = "\n".join(extra_content)
|
||||||
|
final_body = f"{new_section}\n{body}"
|
||||||
|
else:
|
||||||
|
final_body = body
|
||||||
|
|
||||||
|
return clean_meta, final_body
|
||||||
|
|
||||||
|
def parse_markdown_draft(full_text):
|
||||||
|
clean_text = full_text.strip()
|
||||||
|
pattern_block = r"```(?:markdown|md|yaml)?\s*(.*?)\s*```"
|
||||||
|
match_block = re.search(pattern_block, clean_text, re.DOTALL | re.IGNORECASE)
|
||||||
|
if match_block:
|
||||||
|
clean_text = match_block.group(1).strip()
|
||||||
|
|
||||||
|
meta = {}
|
||||||
|
body = clean_text
|
||||||
|
yaml_str = ""
|
||||||
|
|
||||||
|
parts = re.split(r"^---+\s*$", clean_text, maxsplit=2, flags=re.MULTILINE)
|
||||||
|
|
||||||
|
if len(parts) >= 3:
|
||||||
|
yaml_str = parts[1]
|
||||||
|
body = parts[2]
|
||||||
|
elif clean_text.startswith("---"):
|
||||||
|
fallback_match = re.search(r"^---\s*(.*?)(?=\n#)", clean_text, re.DOTALL | re.MULTILINE)
|
||||||
|
if fallback_match:
|
||||||
|
yaml_str = fallback_match.group(1)
|
||||||
|
body = clean_text.replace(f"---{yaml_str}", "", 1).strip()
|
||||||
|
|
||||||
|
if yaml_str:
|
||||||
|
yaml_str_clean = yaml_str.replace("#", "")
|
||||||
|
try:
|
||||||
|
parsed = yaml.safe_load(yaml_str_clean)
|
||||||
|
if isinstance(parsed, dict):
|
||||||
|
meta = parsed
|
||||||
|
except Exception as e:
|
||||||
|
print(f"YAML Parsing Warning: {e}")
|
||||||
|
|
||||||
|
if not meta.get("title"):
|
||||||
|
h1_match = re.search(r"^#\s+(.*)$", body, re.MULTILINE)
|
||||||
|
if h1_match:
|
||||||
|
meta["title"] = h1_match.group(1).strip()
|
||||||
|
|
||||||
|
if meta.get("type") == "draft":
|
||||||
|
meta["status"] = "draft"
|
||||||
|
meta["type"] = "experience"
|
||||||
|
|
||||||
|
return normalize_meta_and_body(meta, body)
|
||||||
|
|
||||||
|
def build_markdown_doc(meta, body):
|
||||||
|
if "id" not in meta or meta["id"] == "generated_on_save":
|
||||||
|
raw_title = meta.get('title', 'note')
|
||||||
|
clean_slug = slugify(raw_title)[:50] or "note"
|
||||||
|
meta["id"] = f"{datetime.now().strftime('%Y%m%d')}-{clean_slug}"
|
||||||
|
|
||||||
|
meta["updated"] = datetime.now().strftime("%Y-%m-%d")
|
||||||
|
|
||||||
|
ordered_meta = {}
|
||||||
|
prio_keys = ["id", "type", "title", "status", "tags"]
|
||||||
|
for k in prio_keys:
|
||||||
|
if k in meta: ordered_meta[k] = meta.pop(k)
|
||||||
|
ordered_meta.update(meta)
|
||||||
|
|
||||||
|
try:
|
||||||
|
yaml_str = yaml.dump(ordered_meta, default_flow_style=None, sort_keys=False, allow_unicode=True).strip()
|
||||||
|
except:
|
||||||
|
yaml_str = "error: generating_yaml"
|
||||||
|
|
||||||
|
return f"---\n{yaml_str}\n---\n\n{body}"
|
||||||
|
|
||||||
|
def load_history_from_logs(filepath, limit=10):
|
||||||
|
queries = []
|
||||||
|
if filepath.exists():
|
||||||
|
try:
|
||||||
|
with open(filepath, "r", encoding="utf-8") as f:
|
||||||
|
lines = f.readlines()
|
||||||
|
for line in reversed(lines):
|
||||||
|
try:
|
||||||
|
entry = json.loads(line)
|
||||||
|
q = entry.get("query_text")
|
||||||
|
if q and q not in queries:
|
||||||
|
queries.append(q)
|
||||||
|
if len(queries) >= limit: break
|
||||||
|
except: continue
|
||||||
|
except: pass
|
||||||
|
return queries
|
||||||
+41
-9
@@ -1,25 +1,57 @@
|
|||||||
"""
|
"""
|
||||||
Version 0.3
|
FILE: app/main.py
|
||||||
|
DESCRIPTION: Bootstrap der FastAPI Anwendung. Inkludiert Router und Middleware.
|
||||||
|
VERSION: 0.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.config, app.routers.* (embed, qdrant, query, graph, tools, feedback, chat, ingest, admin)
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from .config import get_settings
|
from .config import get_settings
|
||||||
from .routers.embed_router import router as embed_router
|
#from .routers.embed_router import router as embed_router
|
||||||
from .routers.qdrant_router import router as qdrant_router
|
#from .routers.qdrant_router import router as qdrant_router
|
||||||
|
|
||||||
|
from .routers.query import router as query_router
|
||||||
|
from .routers.graph import router as graph_router
|
||||||
|
from .routers.tools import router as tools_router
|
||||||
|
from .routers.feedback import router as feedback_router
|
||||||
|
# NEU: Chat Router (WP-05)
|
||||||
|
from .routers.chat import router as chat_router
|
||||||
|
# NEU: Ingest Router (WP-11)
|
||||||
|
from .routers.ingest import router as ingest_router
|
||||||
|
|
||||||
|
try:
|
||||||
|
from .routers.admin import router as admin_router
|
||||||
|
except Exception:
|
||||||
|
admin_router = None
|
||||||
|
|
||||||
def create_app() -> FastAPI:
|
def create_app() -> FastAPI:
|
||||||
app = FastAPI(title="mindnet API", version="0.1.0")
|
app = FastAPI(title="mindnet API", version="0.6.0") # Version bump WP-11
|
||||||
s = get_settings()
|
s = get_settings()
|
||||||
|
|
||||||
@app.get("/healthz")
|
@app.get("/healthz")
|
||||||
def healthz():
|
def healthz():
|
||||||
return {"status": "ok", "qdrant": s.QDRANT_URL, "prefix": s.COLLECTION_PREFIX}
|
return {"status": "ok", "qdrant": s.QDRANT_URL, "prefix": s.COLLECTION_PREFIX}
|
||||||
|
|
||||||
app.include_router(embed_router)
|
# app.include_router(embed_router)
|
||||||
app.include_router(qdrant_router)
|
# app.include_router(qdrant_router)
|
||||||
|
|
||||||
|
app.include_router(query_router, prefix="/query", tags=["query"])
|
||||||
|
app.include_router(graph_router, prefix="/graph", tags=["graph"])
|
||||||
|
app.include_router(tools_router, prefix="/tools", tags=["tools"])
|
||||||
|
app.include_router(feedback_router, prefix="/feedback", tags=["feedback"])
|
||||||
|
|
||||||
|
# NEU: Chat Endpoint
|
||||||
|
app.include_router(chat_router, prefix="/chat", tags=["chat"])
|
||||||
|
|
||||||
|
# NEU: Ingest Endpoint
|
||||||
|
app.include_router(ingest_router, prefix="/ingest", tags=["ingest"])
|
||||||
|
|
||||||
|
if admin_router:
|
||||||
|
app.include_router(admin_router, prefix="/admin", tags=["admin"])
|
||||||
|
|
||||||
return app
|
return app
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
app = create_app()
|
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""
|
||||||
|
app/models/__init__.py — Package-Init für mindnet DTOs (WP-04)
|
||||||
|
Version: 0.1.0 • Stand: 2025-10-07
|
||||||
|
"""
|
||||||
|
|
||||||
|
from .dto import (
|
||||||
|
EdgeKind,
|
||||||
|
NodeDTO,
|
||||||
|
EdgeDTO,
|
||||||
|
QueryRequest,
|
||||||
|
QueryHit,
|
||||||
|
QueryResponse,
|
||||||
|
GraphResponse,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"EdgeKind",
|
||||||
|
"NodeDTO",
|
||||||
|
"EdgeDTO",
|
||||||
|
"QueryRequest",
|
||||||
|
"QueryHit",
|
||||||
|
"QueryResponse",
|
||||||
|
"GraphResponse",
|
||||||
|
]
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/models/dto.py
|
||||||
|
DESCRIPTION: Pydantic-Modelle (DTOs) für Request/Response Bodies. Definiert das API-Schema.
|
||||||
|
VERSION: 0.6.2
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: pydantic, typing, uuid
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
from typing import List, Literal, Optional, Dict, Any
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
EdgeKind = Literal["references", "references_at", "backlink", "next", "prev", "belongs_to", "depends_on", "related_to", "similar_to"]
|
||||||
|
|
||||||
|
|
||||||
|
# --- Basis-DTOs ---
|
||||||
|
|
||||||
|
class NodeDTO(BaseModel):
|
||||||
|
"""Darstellung eines Knotens (Note oder Chunk) im API-Graph."""
|
||||||
|
id: str
|
||||||
|
type: Literal["note", "chunk"]
|
||||||
|
title: Optional[str] = None
|
||||||
|
note_id: Optional[str] = None
|
||||||
|
tags: Optional[List[str]] = None
|
||||||
|
in_degree: Optional[int] = None
|
||||||
|
out_degree: Optional[int] = None
|
||||||
|
score: Optional[float] = None
|
||||||
|
section_title: Optional[str] = None
|
||||||
|
section_path: Optional[str] = None
|
||||||
|
path: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class EdgeDTO(BaseModel):
|
||||||
|
"""Darstellung einer Kante im API-Graph."""
|
||||||
|
id: str
|
||||||
|
kind: str
|
||||||
|
source: str
|
||||||
|
target: str
|
||||||
|
weight: float
|
||||||
|
direction: Literal["out", "in", "undirected"] = "out"
|
||||||
|
|
||||||
|
|
||||||
|
# --- Request Models ---
|
||||||
|
|
||||||
|
class QueryRequest(BaseModel):
|
||||||
|
"""
|
||||||
|
Request für /query.
|
||||||
|
"""
|
||||||
|
mode: Literal["semantic", "edge", "hybrid"] = "hybrid"
|
||||||
|
query: Optional[str] = None
|
||||||
|
query_vector: Optional[List[float]] = None
|
||||||
|
top_k: int = 10
|
||||||
|
expand: Dict = {"depth": 1, "edge_types": ["references", "belongs_to", "prev", "next", "depends_on", "related_to"]}
|
||||||
|
filters: Optional[Dict] = None
|
||||||
|
ret: Dict = {"with_paths": True, "with_notes": True, "with_chunks": True}
|
||||||
|
explain: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class FeedbackRequest(BaseModel):
|
||||||
|
"""
|
||||||
|
User-Feedback zu einem spezifischen Treffer oder der Gesamtantwort.
|
||||||
|
"""
|
||||||
|
query_id: str = Field(..., description="ID der ursprünglichen Suche")
|
||||||
|
# node_id ist optional: Wenn leer oder "generated_answer", gilt es für die Antwort.
|
||||||
|
# Wenn eine echte Chunk-ID, gilt es für die Quelle.
|
||||||
|
node_id: str = Field(..., description="ID des bewerteten Treffers oder 'generated_answer'")
|
||||||
|
# Update: Range auf 1-5 erweitert für differenziertes Tuning
|
||||||
|
score: int = Field(..., ge=1, le=5, description="1 (Irrelevant/Falsch) bis 5 (Perfekt)")
|
||||||
|
comment: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ChatRequest(BaseModel):
|
||||||
|
"""
|
||||||
|
WP-05: Request für /chat.
|
||||||
|
"""
|
||||||
|
message: str = Field(..., description="Die Nachricht des Users")
|
||||||
|
conversation_id: Optional[str] = Field(None, description="Optional: ID für Chat-Verlauf (noch nicht implementiert)")
|
||||||
|
# RAG Parameter (Override defaults)
|
||||||
|
top_k: int = 5
|
||||||
|
explain: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
# --- WP-04b Explanation Models ---
|
||||||
|
|
||||||
|
class ScoreBreakdown(BaseModel):
|
||||||
|
"""Aufschlüsselung der Score-Komponenten."""
|
||||||
|
semantic_contribution: float
|
||||||
|
edge_contribution: float
|
||||||
|
centrality_contribution: float
|
||||||
|
raw_semantic: float
|
||||||
|
raw_edge_bonus: float
|
||||||
|
raw_centrality: float
|
||||||
|
node_weight: float
|
||||||
|
|
||||||
|
|
||||||
|
class Reason(BaseModel):
|
||||||
|
"""Ein semantischer Grund für das Ranking."""
|
||||||
|
kind: Literal["semantic", "edge", "type", "centrality"]
|
||||||
|
message: str
|
||||||
|
score_impact: Optional[float] = None
|
||||||
|
details: Optional[Dict[str, Any]] = None
|
||||||
|
|
||||||
|
|
||||||
|
class Explanation(BaseModel):
|
||||||
|
"""Container für alle Erklärungsdaten eines Treffers."""
|
||||||
|
breakdown: ScoreBreakdown
|
||||||
|
reasons: List[Reason]
|
||||||
|
related_edges: Optional[List[EdgeDTO]] = None
|
||||||
|
|
||||||
|
|
||||||
|
# --- Response Models ---
|
||||||
|
|
||||||
|
class QueryHit(BaseModel):
|
||||||
|
"""Einzelnes Trefferobjekt für /query."""
|
||||||
|
node_id: str
|
||||||
|
note_id: Optional[str]
|
||||||
|
semantic_score: float
|
||||||
|
edge_bonus: float
|
||||||
|
centrality_bonus: float
|
||||||
|
total_score: float
|
||||||
|
paths: Optional[List[List[Dict]]] = None
|
||||||
|
source: Optional[Dict] = None
|
||||||
|
payload: Optional[Dict] = None # Added for flexibility & WP-06 meta-data
|
||||||
|
explanation: Optional[Explanation] = None
|
||||||
|
|
||||||
|
|
||||||
|
class QueryResponse(BaseModel):
|
||||||
|
"""Antwortstruktur für /query."""
|
||||||
|
query_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
|
||||||
|
results: List[QueryHit]
|
||||||
|
used_mode: str
|
||||||
|
latency_ms: int
|
||||||
|
|
||||||
|
|
||||||
|
class GraphResponse(BaseModel):
|
||||||
|
"""Antwortstruktur für /graph/{note_id}."""
|
||||||
|
center_note_id: str
|
||||||
|
nodes: List[NodeDTO]
|
||||||
|
edges: List[EdgeDTO]
|
||||||
|
stats: Dict[str, int]
|
||||||
|
|
||||||
|
|
||||||
|
class ChatResponse(BaseModel):
|
||||||
|
"""
|
||||||
|
WP-05/06: Antwortstruktur für /chat.
|
||||||
|
"""
|
||||||
|
query_id: str = Field(..., description="Traceability ID (dieselbe wie für Search)")
|
||||||
|
answer: str = Field(..., description="Generierte Antwort vom LLM")
|
||||||
|
sources: List[QueryHit] = Field(..., description="Die für die Antwort genutzten Quellen")
|
||||||
|
latency_ms: int
|
||||||
|
intent: Optional[str] = Field("FACT", description="WP-06: Erkannter Intent (FACT/DECISION)")
|
||||||
|
intent_source: Optional[str] = Field("Unknown", description="WP-06: Quelle der Intent-Erkennung (Keyword vs. LLM)")
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""
|
||||||
|
app/models/__init__.py — Package-Init für mindnet DTOs
|
||||||
|
|
||||||
|
Zweck:
|
||||||
|
Stellt zentrale API-/DTO-Modelle als Import-Fassade bereit.
|
||||||
|
Kompatibilität:
|
||||||
|
Python 3.12+, Pydantic 2.x
|
||||||
|
Version:
|
||||||
|
0.1.0 (Erstanlage für WP-04)
|
||||||
|
Stand:
|
||||||
|
2025-10-07
|
||||||
|
Bezug:
|
||||||
|
Handbuch / Knowledge Design (WP-03/04)
|
||||||
|
Nutzung:
|
||||||
|
from app.models import QueryRequest, QueryResponse, GraphResponse
|
||||||
|
Änderungsverlauf:
|
||||||
|
0.1.0 (2025-10-07) – Erstanlage.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from .dto import (
|
||||||
|
EdgeKind,
|
||||||
|
NodeDTO,
|
||||||
|
EdgeDTO,
|
||||||
|
QueryRequest,
|
||||||
|
QueryHit,
|
||||||
|
QueryResponse,
|
||||||
|
GraphResponse,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"EdgeKind",
|
||||||
|
"NodeDTO",
|
||||||
|
"EdgeDTO",
|
||||||
|
"QueryRequest",
|
||||||
|
"QueryHit",
|
||||||
|
"QueryResponse",
|
||||||
|
"GraphResponse",
|
||||||
|
]
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/routers/admin.py
|
||||||
|
DESCRIPTION: Monitoring-Endpunkt. Zeigt Qdrant-Collection-Counts und geladene Config.
|
||||||
|
VERSION: 0.1.0
|
||||||
|
STATUS: Active (Optional)
|
||||||
|
DEPENDENCIES: qdrant_client, app.config
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
from fastapi import APIRouter
|
||||||
|
from qdrant_client import QdrantClient
|
||||||
|
from app.config import get_settings
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.get("/stats")
|
||||||
|
def stats():
|
||||||
|
s = get_settings()
|
||||||
|
client = QdrantClient(url=s.QDRANT_URL, api_key=s.QDRANT_API_KEY)
|
||||||
|
notes = f"{s.COLLECTION_PREFIX}_notes"
|
||||||
|
chunks = f"{s.COLLECTION_PREFIX}_chunks"
|
||||||
|
edges = f"{s.COLLECTION_PREFIX}_edges"
|
||||||
|
|
||||||
|
def _count(col: str) -> int:
|
||||||
|
try:
|
||||||
|
return client.count(collection_name=col, exact=True).count
|
||||||
|
except Exception:
|
||||||
|
return -1
|
||||||
|
|
||||||
|
return {
|
||||||
|
"collections": {
|
||||||
|
"notes": {"name": notes, "count": _count(notes)},
|
||||||
|
"chunks": {"name": chunks, "count": _count(chunks)},
|
||||||
|
"edges": {"name": edges, "count": _count(edges)},
|
||||||
|
},
|
||||||
|
"config": {
|
||||||
|
"qdrant": s.QDRANT_URL,
|
||||||
|
"prefix": s.COLLECTION_PREFIX,
|
||||||
|
"vector_size": s.VECTOR_SIZE,
|
||||||
|
"distance": s.DISTANCE,
|
||||||
|
"retriever": {
|
||||||
|
"w_sem": s.RETRIEVER_W_SEM,
|
||||||
|
"w_edge": s.RETRIEVER_W_EDGE,
|
||||||
|
"w_cent": s.RETRIEVER_W_CENT,
|
||||||
|
"top_k": s.RETRIEVER_TOP_K,
|
||||||
|
"expand_depth": s.RETRIEVER_EXPAND_DEPTH,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -0,0 +1,355 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/routers/chat.py
|
||||||
|
DESCRIPTION: Haupt-Chat-Interface (RAG & Interview). Enthält Intent-Router (Keywords/LLM) und Prompt-Construction.
|
||||||
|
VERSION: 2.5.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.config, app.models.dto, app.services.llm_service, app.core.retriever, app.services.feedback_service
|
||||||
|
EXTERNAL_CONFIG: config/decision_engine.yaml, config/types.yaml
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
|
from typing import List, Dict, Any, Optional
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
import logging
|
||||||
|
import yaml
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.config import get_settings
|
||||||
|
from app.models.dto import ChatRequest, ChatResponse, QueryRequest, QueryHit
|
||||||
|
from app.services.llm_service import LLMService
|
||||||
|
from app.core.retriever import Retriever
|
||||||
|
from app.services.feedback_service import log_search
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# --- Helper: Config Loader ---
|
||||||
|
|
||||||
|
_DECISION_CONFIG_CACHE = None
|
||||||
|
_TYPES_CONFIG_CACHE = None
|
||||||
|
|
||||||
|
def _load_decision_config() -> Dict[str, Any]:
|
||||||
|
settings = get_settings()
|
||||||
|
path = Path(settings.DECISION_CONFIG_PATH)
|
||||||
|
default_config = {
|
||||||
|
"strategies": {
|
||||||
|
"FACT": {"trigger_keywords": []}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if not path.exists():
|
||||||
|
logger.warning(f"Decision config not found at {path}, using defaults.")
|
||||||
|
return default_config
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
return yaml.safe_load(f)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to load decision config: {e}")
|
||||||
|
return default_config
|
||||||
|
|
||||||
|
def _load_types_config() -> Dict[str, Any]:
|
||||||
|
"""Lädt die types.yaml für Keyword-Erkennung."""
|
||||||
|
path = os.getenv("MINDNET_TYPES_FILE", "config/types.yaml")
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
return yaml.safe_load(f) or {}
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def get_full_config() -> Dict[str, Any]:
|
||||||
|
global _DECISION_CONFIG_CACHE
|
||||||
|
if _DECISION_CONFIG_CACHE is None:
|
||||||
|
_DECISION_CONFIG_CACHE = _load_decision_config()
|
||||||
|
return _DECISION_CONFIG_CACHE
|
||||||
|
|
||||||
|
def get_types_config() -> Dict[str, Any]:
|
||||||
|
global _TYPES_CONFIG_CACHE
|
||||||
|
if _TYPES_CONFIG_CACHE is None:
|
||||||
|
_TYPES_CONFIG_CACHE = _load_types_config()
|
||||||
|
return _TYPES_CONFIG_CACHE
|
||||||
|
|
||||||
|
def get_decision_strategy(intent: str) -> Dict[str, Any]:
|
||||||
|
config = get_full_config()
|
||||||
|
strategies = config.get("strategies", {})
|
||||||
|
return strategies.get(intent, strategies.get("FACT", {}))
|
||||||
|
|
||||||
|
# --- Helper: Target Type Detection (WP-07) ---
|
||||||
|
|
||||||
|
def _detect_target_type(message: str, configured_schemas: Dict[str, Any]) -> str:
|
||||||
|
"""
|
||||||
|
Versucht zu erraten, welchen Notiz-Typ der User erstellen will.
|
||||||
|
Nutzt Keywords aus types.yaml UND Mappings.
|
||||||
|
"""
|
||||||
|
message_lower = message.lower()
|
||||||
|
|
||||||
|
# 1. Check types.yaml detection_keywords (Priority!)
|
||||||
|
types_cfg = get_types_config()
|
||||||
|
types_def = types_cfg.get("types", {})
|
||||||
|
|
||||||
|
for type_name, type_data in types_def.items():
|
||||||
|
keywords = type_data.get("detection_keywords", [])
|
||||||
|
for kw in keywords:
|
||||||
|
if kw.lower() in message_lower:
|
||||||
|
return type_name
|
||||||
|
|
||||||
|
# 2. Direkter Match mit Schema-Keys
|
||||||
|
for type_key in configured_schemas.keys():
|
||||||
|
if type_key == "default": continue
|
||||||
|
if type_key in message_lower:
|
||||||
|
return type_key
|
||||||
|
|
||||||
|
# 3. Synonym-Mapping (Legacy Fallback)
|
||||||
|
synonyms = {
|
||||||
|
"projekt": "project", "vorhaben": "project",
|
||||||
|
"entscheidung": "decision", "beschluss": "decision",
|
||||||
|
"ziel": "goal",
|
||||||
|
"erfahrung": "experience", "lektion": "experience",
|
||||||
|
"wert": "value",
|
||||||
|
"prinzip": "principle",
|
||||||
|
"notiz": "default", "idee": "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
for term, schema_key in synonyms.items():
|
||||||
|
if term in message_lower:
|
||||||
|
return schema_key
|
||||||
|
|
||||||
|
return "default"
|
||||||
|
|
||||||
|
# --- Dependencies ---
|
||||||
|
|
||||||
|
def get_llm_service():
|
||||||
|
return LLMService()
|
||||||
|
|
||||||
|
def get_retriever():
|
||||||
|
return Retriever()
|
||||||
|
|
||||||
|
|
||||||
|
# --- Logic ---
|
||||||
|
|
||||||
|
def _build_enriched_context(hits: List[QueryHit]) -> str:
|
||||||
|
context_parts = []
|
||||||
|
for i, hit in enumerate(hits, 1):
|
||||||
|
source = hit.source or {}
|
||||||
|
content = (
|
||||||
|
source.get("text") or source.get("content") or
|
||||||
|
source.get("page_content") or source.get("chunk_text") or
|
||||||
|
"[Kein Text]"
|
||||||
|
)
|
||||||
|
title = hit.note_id or "Unbekannt"
|
||||||
|
|
||||||
|
payload = hit.payload or {}
|
||||||
|
note_type = payload.get("type") or source.get("type", "unknown")
|
||||||
|
note_type = str(note_type).upper()
|
||||||
|
|
||||||
|
entry = (
|
||||||
|
f"### QUELLE {i}: {title}\n"
|
||||||
|
f"TYP: [{note_type}] (Score: {hit.total_score:.2f})\n"
|
||||||
|
f"INHALT:\n{content}\n"
|
||||||
|
)
|
||||||
|
context_parts.append(entry)
|
||||||
|
|
||||||
|
return "\n\n".join(context_parts)
|
||||||
|
|
||||||
|
def _is_question(query: str) -> bool:
|
||||||
|
"""Prüft, ob der Input wahrscheinlich eine Frage ist."""
|
||||||
|
q = query.strip().lower()
|
||||||
|
if "?" in q: return True
|
||||||
|
|
||||||
|
# W-Fragen Indikatoren (falls User das ? vergisst)
|
||||||
|
starters = ["wer", "wie", "was", "wo", "wann", "warum", "weshalb", "wozu", "welche", "bist du", "entspricht"]
|
||||||
|
if any(q.startswith(s + " ") for s in starters):
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def _classify_intent(query: str, llm: LLMService) -> tuple[str, str]:
|
||||||
|
"""
|
||||||
|
Hybrid Router v5:
|
||||||
|
1. Decision Keywords (Strategie) -> Prio 1
|
||||||
|
2. Type Keywords (Interview Trigger) -> Prio 2, ABER NUR WENN KEINE FRAGE!
|
||||||
|
3. LLM (Fallback) -> Prio 3
|
||||||
|
"""
|
||||||
|
config = get_full_config()
|
||||||
|
strategies = config.get("strategies", {})
|
||||||
|
settings = config.get("settings", {})
|
||||||
|
|
||||||
|
query_lower = query.lower()
|
||||||
|
|
||||||
|
# 1. FAST PATH A: Strategie Keywords (z.B. "Soll ich...")
|
||||||
|
for intent_name, strategy in strategies.items():
|
||||||
|
if intent_name == "FACT": continue
|
||||||
|
keywords = strategy.get("trigger_keywords", [])
|
||||||
|
for k in keywords:
|
||||||
|
if k.lower() in query_lower:
|
||||||
|
return intent_name, "Keyword (Strategy)"
|
||||||
|
|
||||||
|
# 2. FAST PATH B: Type Keywords (z.B. "Projekt", "Werte") -> INTERVIEW
|
||||||
|
# FIX: Wir prüfen, ob es eine Frage ist. Fragen zu Typen sollen RAG (FACT/DECISION) sein,
|
||||||
|
# keine Interviews. Wir überlassen das dann dem LLM Router (Slow Path).
|
||||||
|
|
||||||
|
if not _is_question(query_lower):
|
||||||
|
types_cfg = get_types_config()
|
||||||
|
types_def = types_cfg.get("types", {})
|
||||||
|
|
||||||
|
for type_name, type_data in types_def.items():
|
||||||
|
keywords = type_data.get("detection_keywords", [])
|
||||||
|
for kw in keywords:
|
||||||
|
if kw.lower() in query_lower:
|
||||||
|
return "INTERVIEW", f"Keyword (Type: {type_name})"
|
||||||
|
|
||||||
|
# 3. SLOW PATH: LLM Router
|
||||||
|
if settings.get("llm_fallback_enabled", False):
|
||||||
|
# Nutze Prompts aus prompts.yaml (via LLM Service)
|
||||||
|
router_prompt_template = llm.prompts.get("router_prompt", "")
|
||||||
|
|
||||||
|
if router_prompt_template:
|
||||||
|
prompt = router_prompt_template.replace("{query}", query)
|
||||||
|
logger.info("Keywords failed (or Question detected). Asking LLM for Intent...")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Nutze priority="realtime" für den Router, damit er nicht wartet
|
||||||
|
raw_response = await llm.generate_raw_response(prompt, priority="realtime")
|
||||||
|
llm_output_upper = raw_response.upper()
|
||||||
|
|
||||||
|
# Zuerst INTERVIEW prüfen
|
||||||
|
if "INTERVIEW" in llm_output_upper or "CREATE" in llm_output_upper:
|
||||||
|
return "INTERVIEW", "LLM Router"
|
||||||
|
|
||||||
|
for strat_key in strategies.keys():
|
||||||
|
if strat_key in llm_output_upper:
|
||||||
|
return strat_key, "LLM Router"
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Router LLM failed: {e}")
|
||||||
|
|
||||||
|
return "FACT", "Default (No Match)"
|
||||||
|
|
||||||
|
@router.post("/", response_model=ChatResponse)
|
||||||
|
async def chat_endpoint(
|
||||||
|
request: ChatRequest,
|
||||||
|
llm: LLMService = Depends(get_llm_service),
|
||||||
|
retriever: Retriever = Depends(get_retriever)
|
||||||
|
):
|
||||||
|
start_time = time.time()
|
||||||
|
query_id = str(uuid.uuid4())
|
||||||
|
logger.info(f"Chat request [{query_id}]: {request.message[:50]}...")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 1. Intent Detection
|
||||||
|
intent, intent_source = await _classify_intent(request.message, llm)
|
||||||
|
logger.info(f"[{query_id}] Final Intent: {intent} via {intent_source}")
|
||||||
|
|
||||||
|
# Strategy Load
|
||||||
|
strategy = get_decision_strategy(intent)
|
||||||
|
prompt_key = strategy.get("prompt_template", "rag_template")
|
||||||
|
|
||||||
|
sources_hits = []
|
||||||
|
final_prompt = ""
|
||||||
|
|
||||||
|
if intent == "INTERVIEW":
|
||||||
|
# --- INTERVIEW MODE ---
|
||||||
|
target_type = _detect_target_type(request.message, strategy.get("schemas", {}))
|
||||||
|
|
||||||
|
types_cfg = get_types_config()
|
||||||
|
type_def = types_cfg.get("types", {}).get(target_type, {})
|
||||||
|
fields_list = type_def.get("schema", [])
|
||||||
|
|
||||||
|
if not fields_list:
|
||||||
|
configured_schemas = strategy.get("schemas", {})
|
||||||
|
fallback_schema = configured_schemas.get(target_type, configured_schemas.get("default"))
|
||||||
|
if isinstance(fallback_schema, dict):
|
||||||
|
fields_list = fallback_schema.get("fields", [])
|
||||||
|
else:
|
||||||
|
fields_list = fallback_schema or []
|
||||||
|
|
||||||
|
logger.info(f"[{query_id}] Interview Type: {target_type}. Fields: {len(fields_list)}")
|
||||||
|
fields_str = "\n- " + "\n- ".join(fields_list)
|
||||||
|
|
||||||
|
template = llm.prompts.get(prompt_key, "")
|
||||||
|
final_prompt = template.replace("{context_str}", "Dialogverlauf...") \
|
||||||
|
.replace("{query}", request.message) \
|
||||||
|
.replace("{target_type}", target_type) \
|
||||||
|
.replace("{schema_fields}", fields_str) \
|
||||||
|
.replace("{schema_hint}", "")
|
||||||
|
sources_hits = []
|
||||||
|
|
||||||
|
else:
|
||||||
|
# --- RAG MODE ---
|
||||||
|
inject_types = strategy.get("inject_types", [])
|
||||||
|
prepend_instr = strategy.get("prepend_instruction", "")
|
||||||
|
|
||||||
|
query_req = QueryRequest(
|
||||||
|
query=request.message,
|
||||||
|
mode="hybrid",
|
||||||
|
top_k=request.top_k,
|
||||||
|
explain=request.explain
|
||||||
|
)
|
||||||
|
retrieve_result = await retriever.search(query_req)
|
||||||
|
hits = retrieve_result.results
|
||||||
|
|
||||||
|
if inject_types:
|
||||||
|
strategy_req = QueryRequest(
|
||||||
|
query=request.message,
|
||||||
|
mode="hybrid",
|
||||||
|
top_k=3,
|
||||||
|
filters={"type": inject_types},
|
||||||
|
explain=False
|
||||||
|
)
|
||||||
|
strategy_result = await retriever.search(strategy_req)
|
||||||
|
existing_ids = {h.node_id for h in hits}
|
||||||
|
for strat_hit in strategy_result.results:
|
||||||
|
if strat_hit.node_id not in existing_ids:
|
||||||
|
hits.append(strat_hit)
|
||||||
|
|
||||||
|
if not hits:
|
||||||
|
context_str = "Keine relevanten Notizen gefunden."
|
||||||
|
else:
|
||||||
|
context_str = _build_enriched_context(hits)
|
||||||
|
|
||||||
|
template = llm.prompts.get(prompt_key, "{context_str}\n\n{query}")
|
||||||
|
|
||||||
|
if prepend_instr:
|
||||||
|
context_str = f"{prepend_instr}\n\n{context_str}"
|
||||||
|
|
||||||
|
final_prompt = template.replace("{context_str}", context_str).replace("{query}", request.message)
|
||||||
|
sources_hits = hits
|
||||||
|
|
||||||
|
# --- GENERATION ---
|
||||||
|
system_prompt = llm.prompts.get("system_prompt", "")
|
||||||
|
|
||||||
|
# Chat nutzt IMMER realtime priority
|
||||||
|
answer_text = await llm.generate_raw_response(
|
||||||
|
prompt=final_prompt,
|
||||||
|
system=system_prompt,
|
||||||
|
priority="realtime"
|
||||||
|
)
|
||||||
|
|
||||||
|
duration_ms = int((time.time() - start_time) * 1000)
|
||||||
|
|
||||||
|
# Logging
|
||||||
|
try:
|
||||||
|
log_search(
|
||||||
|
query_id=query_id,
|
||||||
|
query_text=request.message,
|
||||||
|
results=sources_hits,
|
||||||
|
mode="interview" if intent == "INTERVIEW" else "chat_rag",
|
||||||
|
metadata={"intent": intent, "source": intent_source}
|
||||||
|
)
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
return ChatResponse(
|
||||||
|
query_id=query_id,
|
||||||
|
answer=answer_text,
|
||||||
|
sources=sources_hits,
|
||||||
|
latency_ms=duration_ms,
|
||||||
|
intent=intent,
|
||||||
|
intent_source=intent_source
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error in chat endpoint: {e}", exc_info=True)
|
||||||
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
Version 0.1
|
FILE: app/routers/embed_router.py
|
||||||
|
DESCRIPTION: Exponiert die lokale Embedding-Funktion als API-Endpunkt.
|
||||||
|
VERSION: 0.1.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.embeddings, pydantic
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/routers/feedback.py
|
||||||
|
DESCRIPTION: Endpunkt für explizites User-Feedback (WP-04c).
|
||||||
|
VERSION: 0.1.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.models.dto, app.services.feedback_service
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, HTTPException
|
||||||
|
from app.models.dto import FeedbackRequest
|
||||||
|
from app.services.feedback_service import log_feedback
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.post("", status_code=201)
|
||||||
|
def post_feedback(fb: FeedbackRequest):
|
||||||
|
"""
|
||||||
|
Nimmt Feedback entgegen (z.B. Daumen hoch für einen Treffer).
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
log_feedback(fb)
|
||||||
|
return {"status": "recorded", "query_id": fb.query_id}
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/routers/graph.py
|
||||||
|
DESCRIPTION: Liefert Graph-Daten (Knoten/Kanten) für UI-Visualisierungen basierend auf einer Seed-ID. (WP4)
|
||||||
|
VERSION: 0.1.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: qdrant_client, app.models.dto, app.core.graph_adapter, app.config
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
from typing import List, Optional
|
||||||
|
from fastapi import APIRouter, Query
|
||||||
|
from qdrant_client import QdrantClient
|
||||||
|
from app.models.dto import GraphResponse, NodeDTO, EdgeDTO
|
||||||
|
from app.core.graph_adapter import expand
|
||||||
|
from app.config import get_settings
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.get("/{note_id}", response_model=GraphResponse)
|
||||||
|
def get_graph(note_id: str, depth: int = 1, edge_types: Optional[List[str]] = Query(None)) -> GraphResponse:
|
||||||
|
s = get_settings()
|
||||||
|
client = QdrantClient(url=s.QDRANT_URL, api_key=s.QDRANT_API_KEY)
|
||||||
|
|
||||||
|
sg = expand(client, s.COLLECTION_PREFIX, [note_id], depth=depth, edge_types=edge_types)
|
||||||
|
|
||||||
|
# Seed-Node (Payload optional später ergänzen über get_note_payload)
|
||||||
|
nodes = [NodeDTO(id=note_id, type="note",
|
||||||
|
title=None, tags=[],
|
||||||
|
in_degree=sg.in_degree.get(note_id, 0),
|
||||||
|
out_degree=sg.out_degree.get(note_id, 0))]
|
||||||
|
|
||||||
|
# direkte Out-Kanten des Seeds
|
||||||
|
edges = []
|
||||||
|
for e in sg.adj.get(note_id, []):
|
||||||
|
edges.append(EdgeDTO(
|
||||||
|
id=f"{note_id}->{e['target']}:{e['kind']}",
|
||||||
|
kind=e["kind"], source=note_id, target=e["target"],
|
||||||
|
weight=float(e["weight"]), direction="out"
|
||||||
|
))
|
||||||
|
|
||||||
|
return GraphResponse(center_note_id=note_id, nodes=nodes, edges=edges,
|
||||||
|
stats={"node_count": len(nodes), "edge_count": len(edges)})
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/routers/ingest.py
|
||||||
|
DESCRIPTION: Endpunkte für WP-11. Nimmt Markdown entgegen.
|
||||||
|
Refactored für WP-14: Nutzt BackgroundTasks für non-blocking Save.
|
||||||
|
VERSION: 0.7.0 (Fix: Timeout WP-14)
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.core.ingestion, app.services.discovery, fastapi, pydantic
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import logging
|
||||||
|
import asyncio
|
||||||
|
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import Optional, Dict, Any
|
||||||
|
|
||||||
|
from app.core.ingestion import IngestionService
|
||||||
|
from app.services.discovery import DiscoveryService
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
# Services Init
|
||||||
|
discovery_service = DiscoveryService()
|
||||||
|
|
||||||
|
class AnalyzeRequest(BaseModel):
|
||||||
|
text: str
|
||||||
|
type: str = "concept"
|
||||||
|
|
||||||
|
class SaveRequest(BaseModel):
|
||||||
|
markdown_content: str
|
||||||
|
filename: Optional[str] = None
|
||||||
|
folder: str = "00_Inbox"
|
||||||
|
|
||||||
|
class SaveResponse(BaseModel):
|
||||||
|
status: str
|
||||||
|
file_path: str
|
||||||
|
note_id: str
|
||||||
|
message: str # Neu für UX Feedback
|
||||||
|
stats: Dict[str, Any] # Kann leer sein bei async processing
|
||||||
|
|
||||||
|
# --- Background Task Wrapper ---
|
||||||
|
async def run_ingestion_task(markdown_content: str, filename: str, vault_root: str, folder: str):
|
||||||
|
"""
|
||||||
|
Führt die Ingestion im Hintergrund aus, damit der Request nicht blockiert.
|
||||||
|
"""
|
||||||
|
logger.info(f"🔄 Background Task started: Ingesting {filename}...")
|
||||||
|
try:
|
||||||
|
ingest_service = IngestionService()
|
||||||
|
result = await ingest_service.create_from_text(
|
||||||
|
markdown_content=markdown_content,
|
||||||
|
filename=filename,
|
||||||
|
vault_root=vault_root,
|
||||||
|
folder=folder
|
||||||
|
)
|
||||||
|
# Hier könnte man später Notification-Services (Websockets) triggern
|
||||||
|
if result.get("status") == "error":
|
||||||
|
logger.error(f"❌ Background Ingestion Error for {filename}: {result.get('error')}")
|
||||||
|
else:
|
||||||
|
logger.info(f"✅ Background Task finished: {filename} ({result.get('chunks_count')} Chunks)")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ Critical Background Task Failure: {e}", exc_info=True)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/analyze")
|
||||||
|
async def analyze_draft(req: AnalyzeRequest):
|
||||||
|
"""
|
||||||
|
WP-11 Intelligence: Liefert Link-Vorschläge via DiscoveryService.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
result = await discovery_service.analyze_draft(req.text, req.type)
|
||||||
|
return result
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Analyze failed: {e}", exc_info=True)
|
||||||
|
return {"suggestions": [], "error": str(e)}
|
||||||
|
|
||||||
|
@router.post("/save", response_model=SaveResponse)
|
||||||
|
async def save_note(req: SaveRequest, background_tasks: BackgroundTasks):
|
||||||
|
"""
|
||||||
|
WP-14 Fix: Startet Ingestion im Hintergrund (Fire & Forget).
|
||||||
|
Verhindert Timeouts bei aktiver Smart-Edge-Allocation (WP-15).
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
vault_root = os.getenv("MINDNET_VAULT_ROOT", "./vault")
|
||||||
|
abs_vault_root = os.path.abspath(vault_root)
|
||||||
|
|
||||||
|
if not os.path.exists(abs_vault_root):
|
||||||
|
try: os.makedirs(abs_vault_root, exist_ok=True)
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
final_filename = req.filename or f"draft_{int(time.time())}.md"
|
||||||
|
|
||||||
|
# Wir geben sofort eine ID zurück (optimistisch),
|
||||||
|
# auch wenn die echte ID erst nach dem Parsing feststeht.
|
||||||
|
# Für UI-Feedback nutzen wir den Filename.
|
||||||
|
|
||||||
|
# Task in die Queue schieben
|
||||||
|
background_tasks.add_task(
|
||||||
|
run_ingestion_task,
|
||||||
|
markdown_content=req.markdown_content,
|
||||||
|
filename=final_filename,
|
||||||
|
vault_root=abs_vault_root,
|
||||||
|
folder=req.folder
|
||||||
|
)
|
||||||
|
|
||||||
|
return SaveResponse(
|
||||||
|
status="queued",
|
||||||
|
file_path=os.path.join(req.folder, final_filename),
|
||||||
|
note_id="pending",
|
||||||
|
message="Speicherung & KI-Analyse im Hintergrund gestartet.",
|
||||||
|
stats={
|
||||||
|
"chunks": -1, # Indikator für Async
|
||||||
|
"edges": -1
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Save dispatch failed: {e}", exc_info=True)
|
||||||
|
raise HTTPException(status_code=500, detail=f"Save dispatch failed: {str(e)}")
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
"""
|
|
||||||
Version 0.1
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from typing import Any, Optional, List
|
|
||||||
import uuid
|
|
||||||
|
|
||||||
from fastapi import APIRouter
|
|
||||||
from pydantic import BaseModel, Field
|
|
||||||
from qdrant_client import QdrantClient
|
|
||||||
from qdrant_client.http.models import (
|
|
||||||
Distance,
|
|
||||||
VectorParams,
|
|
||||||
PointStruct,
|
|
||||||
Filter,
|
|
||||||
FieldCondition,
|
|
||||||
MatchValue,
|
|
||||||
)
|
|
||||||
|
|
||||||
from ..config import get_settings
|
|
||||||
from ..embeddings import embed_texts
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/qdrant", tags=["qdrant"])
|
|
||||||
|
|
||||||
def _client() -> QdrantClient:
|
|
||||||
s = get_settings()
|
|
||||||
return QdrantClient(url=s.QDRANT_URL, api_key=s.QDRANT_API_KEY)
|
|
||||||
|
|
||||||
def _col(name: str) -> str:
|
|
||||||
return f"{get_settings().COLLECTION_PREFIX}_{name}"
|
|
||||||
|
|
||||||
def _uuid5(s: str) -> str:
|
|
||||||
"""Deterministic UUIDv5 from arbitrary string (server-side point id)."""
|
|
||||||
return str(uuid.uuid5(uuid.NAMESPACE_URL, s))
|
|
||||||
|
|
||||||
# --- Models ---
|
|
||||||
class BaseMeta(BaseModel):
|
|
||||||
note_id: str = Field(..., description="Stable ID of the note (e.g., hash of vault-relative path)")
|
|
||||||
title: Optional[str] = Field(None, description="Note or chunk title")
|
|
||||||
path: Optional[str] = Field(None, description="Vault-relative path to the .md file")
|
|
||||||
Typ: Optional[str] = None
|
|
||||||
Status: Optional[str] = None
|
|
||||||
tags: Optional[List[str]] = None
|
|
||||||
Rolle: Optional[List[str]] = None # allow list
|
|
||||||
|
|
||||||
class UpsertChunkRequest(BaseMeta):
|
|
||||||
chunk_id: str = Field(..., description="Stable ID of the chunk within the note")
|
|
||||||
text: str = Field(..., description="Chunk text content")
|
|
||||||
links: Optional[List[str]] = Field(default=None, description="Outbound links detected in the chunk")
|
|
||||||
|
|
||||||
class UpsertNoteRequest(BaseMeta):
|
|
||||||
text: Optional[str] = Field(None, description="Full note text (optional)")
|
|
||||||
|
|
||||||
class UpsertEdgeRequest(BaseModel):
|
|
||||||
src_note_id: str
|
|
||||||
dst_note_id: Optional[str] = None
|
|
||||||
src_chunk_id: Optional[str] = None
|
|
||||||
dst_chunk_id: Optional[str] = None
|
|
||||||
relation: str = Field(default="links_to")
|
|
||||||
link_text: Optional[str] = None
|
|
||||||
|
|
||||||
class QueryRequest(BaseModel):
|
|
||||||
query: str
|
|
||||||
limit: int = 5
|
|
||||||
note_id: Optional[str] = None
|
|
||||||
path: Optional[str] = None
|
|
||||||
tags: Optional[List[str]] = None
|
|
||||||
|
|
||||||
# --- Helpers ---
|
|
||||||
def _ensure_collections():
|
|
||||||
s = get_settings()
|
|
||||||
cli = _client()
|
|
||||||
# chunks
|
|
||||||
try:
|
|
||||||
cli.get_collection(_col("chunks"))
|
|
||||||
except Exception:
|
|
||||||
cli.recreate_collection(_col("chunks"), vectors_config=VectorParams(size=s.VECTOR_SIZE, distance=Distance.COSINE))
|
|
||||||
# notes
|
|
||||||
try:
|
|
||||||
cli.get_collection(_col("notes"))
|
|
||||||
except Exception:
|
|
||||||
cli.recreate_collection(_col("notes"), vectors_config=VectorParams(size=s.VECTOR_SIZE, distance=Distance.COSINE))
|
|
||||||
# edges (dummy vector of size 1)
|
|
||||||
try:
|
|
||||||
cli.get_collection(_col("edges"))
|
|
||||||
except Exception:
|
|
||||||
cli.recreate_collection(_col("edges"), vectors_config=VectorParams(size=1, distance=Distance.COSINE))
|
|
||||||
|
|
||||||
@router.post("/upsert_chunk", summary="Upsert a chunk into mindnet_chunks")
|
|
||||||
def upsert_chunk(req: UpsertChunkRequest) -> dict:
|
|
||||||
_ensure_collections()
|
|
||||||
cli = _client()
|
|
||||||
vec = embed_texts([req.text])[0]
|
|
||||||
payload: dict[str, Any] = req.model_dump()
|
|
||||||
payload.pop("text", None)
|
|
||||||
payload["preview"] = (req.text[:240] + "…") if len(req.text) > 240 else req.text
|
|
||||||
qdrant_id = _uuid5(f"chunk:{req.chunk_id}")
|
|
||||||
pt = PointStruct(id=qdrant_id, vector=vec, payload=payload)
|
|
||||||
cli.upsert(collection_name=_col("chunks"), points=[pt])
|
|
||||||
return {"status": "ok", "id": qdrant_id}
|
|
||||||
|
|
||||||
@router.post("/upsert_note", summary="Upsert a note into mindnet_notes")
|
|
||||||
def upsert_note(req: UpsertNoteRequest) -> dict:
|
|
||||||
_ensure_collections()
|
|
||||||
cli = _client()
|
|
||||||
text_for_embedding = req.text if req.text else (req.title or req.note_id)
|
|
||||||
vec = embed_texts([text_for_embedding])[0]
|
|
||||||
payload: dict[str, Any] = req.model_dump()
|
|
||||||
payload.pop("text", None)
|
|
||||||
qdrant_id = _uuid5(f"note:{req.note_id}")
|
|
||||||
pt = PointStruct(id=qdrant_id, vector=vec, payload=payload)
|
|
||||||
cli.upsert(collection_name=_col("notes"), points=[pt])
|
|
||||||
return {"status": "ok", "id": qdrant_id}
|
|
||||||
|
|
||||||
@router.post("/upsert_edge", summary="Upsert a graph edge into mindnet_edges")
|
|
||||||
def upsert_edge(req: UpsertEdgeRequest) -> dict:
|
|
||||||
_ensure_collections()
|
|
||||||
cli = _client()
|
|
||||||
payload = req.model_dump()
|
|
||||||
vec = [0.0]
|
|
||||||
raw_edge_id = f"{req.src_note_id}|{req.src_chunk_id or ''}->{req.dst_note_id or ''}|{req.dst_chunk_id or ''}|{req.relation}"
|
|
||||||
qdrant_id = _uuid5(f"edge:{raw_edge_id}")
|
|
||||||
pt = PointStruct(id=qdrant_id, vector=vec, payload=payload)
|
|
||||||
cli.upsert(collection_name=_col("edges"), points=[pt])
|
|
||||||
return {"status": "ok", "id": qdrant_id}
|
|
||||||
|
|
||||||
@router.post("/query", summary="Vector query over mindnet_chunks with optional filters")
|
|
||||||
def query(req: QueryRequest) -> dict:
|
|
||||||
_ensure_collections()
|
|
||||||
cli = _client()
|
|
||||||
vec = embed_texts([req.query])[0]
|
|
||||||
|
|
||||||
flt: Optional[Filter] = None
|
|
||||||
conds = []
|
|
||||||
if req.note_id:
|
|
||||||
conds.append(FieldCondition(key="note_id", match=MatchValue(value=req.note_id)))
|
|
||||||
if req.path:
|
|
||||||
conds.append(FieldCondition(key="path", match=MatchValue(value=req.path)))
|
|
||||||
if req.tags:
|
|
||||||
for t in req.tags:
|
|
||||||
conds.append(FieldCondition(key="tags", match=MatchValue(value=t)))
|
|
||||||
if conds:
|
|
||||||
flt = Filter(must=conds)
|
|
||||||
|
|
||||||
res = cli.search(collection_name=_col("chunks"), query_vector=vec, limit=req.limit, with_payload=True, with_vectors=False, query_filter=flt)
|
|
||||||
hits = []
|
|
||||||
for p in res:
|
|
||||||
pl = p.payload or {}
|
|
||||||
hits.append({
|
|
||||||
"chunk_id": p.id,
|
|
||||||
"score": p.score,
|
|
||||||
"note_id": pl.get("note_id"),
|
|
||||||
"title": pl.get("title"),
|
|
||||||
"path": pl.get("path"),
|
|
||||||
"preview": pl.get("preview"),
|
|
||||||
"tags": pl.get("tags"),
|
|
||||||
})
|
|
||||||
return {"results": hits}
|
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/routers/query.py
|
||||||
|
DESCRIPTION: Klassische Such-Endpunkte (Semantic & Hybrid). Initiiert asynchrones Feedback-Logging und ruft den richtigen Retriever Modus auf
|
||||||
|
VERSION: 0.2.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.models.dto, app.core.retriever, app.services.feedback_service
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
||||||
|
from app.models.dto import QueryRequest, QueryResponse
|
||||||
|
from app.core.retriever import hybrid_retrieve, semantic_retrieve
|
||||||
|
# NEU:
|
||||||
|
from app.services.feedback_service import log_search
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.post("", response_model=QueryResponse)
|
||||||
|
def post_query(req: QueryRequest, background_tasks: BackgroundTasks) -> QueryResponse:
|
||||||
|
try:
|
||||||
|
if req.mode == "semantic":
|
||||||
|
res = semantic_retrieve(req)
|
||||||
|
else:
|
||||||
|
res = hybrid_retrieve(req)
|
||||||
|
|
||||||
|
# WP-04c: Logging im Hintergrund (bremst Antwort nicht)
|
||||||
|
background_tasks.add_task(log_search, req, res)
|
||||||
|
|
||||||
|
return res
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=500, detail=f"query failed: {e}")
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/routers/tools.py
|
||||||
|
DESCRIPTION: Liefert JSON-Schemas für die Integration als 'Tools' in Agents (Ollama/OpenAI). Read-Only.
|
||||||
|
VERSION: 0.1.1
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: fastapi
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
TOOLS = {
|
||||||
|
"tools": [
|
||||||
|
{
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "mindnet_query",
|
||||||
|
"description": "Hybrid-Retrieval über mindnet (Semantik + Edges).",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"oneOf": [
|
||||||
|
{"required": ["query"]},
|
||||||
|
{"required": ["query_vector"]}
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"query": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Freitext-Query; wird serverseitig in 384-d Embedding konvertiert."
|
||||||
|
},
|
||||||
|
"query_vector": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {"type": "number"},
|
||||||
|
"description": "Direkter 384-d Query-Vektor (optional)."
|
||||||
|
},
|
||||||
|
"top_k": {"type":"integer","default":10,"minimum":1,"maximum":50},
|
||||||
|
"expand_depth": {"type":"integer","default":1,"minimum":0,"maximum":3},
|
||||||
|
"edge_types": {
|
||||||
|
"type":"array","items":{"type":"string"},
|
||||||
|
"default": ["references","belongs_to","prev","next"]
|
||||||
|
},
|
||||||
|
"filters": {"type":"object","description":"payload-Filter (tags etc.)"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "mindnet_subgraph",
|
||||||
|
"description": "Gibt die Nachbarschaft (Edges) einer Note/Seed-ID zurück.",
|
||||||
|
"parameters": {
|
||||||
|
"type":"object",
|
||||||
|
"properties": {
|
||||||
|
"note_id":{"type":"string"},
|
||||||
|
"depth":{"type":"integer","default":1,"minimum":0,"maximum":3},
|
||||||
|
"edge_types":{
|
||||||
|
"type":"array","items":{"type":"string"},
|
||||||
|
"default":["references","belongs_to","prev","next","backlink"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required":["note_id"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
@router.get("/ollama")
|
||||||
|
def get_ollama_tools():
|
||||||
|
return TOOLS
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/services/discovery.py
|
||||||
|
DESCRIPTION: Service für WP-11. Analysiert Texte, findet Entitäten und schlägt typisierte Verbindungen vor ("Matrix-Logic").
|
||||||
|
VERSION: 0.6.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.core.qdrant, app.models.dto, app.core.retriever
|
||||||
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
from typing import List, Dict, Any, Optional, Set
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from app.core.qdrant import QdrantConfig, get_client
|
||||||
|
from app.models.dto import QueryRequest
|
||||||
|
from app.core.retriever import hybrid_retrieve
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class DiscoveryService:
|
||||||
|
def __init__(self, collection_prefix: str = None):
|
||||||
|
self.cfg = QdrantConfig.from_env()
|
||||||
|
self.prefix = collection_prefix or self.cfg.prefix or "mindnet"
|
||||||
|
self.client = get_client(self.cfg)
|
||||||
|
self.registry = self._load_type_registry()
|
||||||
|
|
||||||
|
async def analyze_draft(self, text: str, current_type: str) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Analysiert den Text und liefert Vorschläge mit kontext-sensitiven Kanten-Typen.
|
||||||
|
"""
|
||||||
|
suggestions = []
|
||||||
|
|
||||||
|
# Fallback, falls keine spezielle Regel greift
|
||||||
|
default_edge_type = self._get_default_edge_type(current_type)
|
||||||
|
|
||||||
|
# Tracking-Sets für Deduplizierung (Wir merken uns NOTE-IDs)
|
||||||
|
seen_target_note_ids = set()
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 1. Exact Match: Titel/Aliases
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# Holt Titel, Aliases UND Typen aus dem Index
|
||||||
|
known_entities = self._fetch_all_titles_and_aliases()
|
||||||
|
found_entities = self._find_entities_in_text(text, known_entities)
|
||||||
|
|
||||||
|
for entity in found_entities:
|
||||||
|
if entity["id"] in seen_target_note_ids:
|
||||||
|
continue
|
||||||
|
seen_target_note_ids.add(entity["id"])
|
||||||
|
|
||||||
|
# INTELLIGENTE KANTEN-LOGIK (MATRIX)
|
||||||
|
target_type = entity.get("type", "concept")
|
||||||
|
smart_edge = self._resolve_edge_type(current_type, target_type)
|
||||||
|
|
||||||
|
suggestions.append({
|
||||||
|
"type": "exact_match",
|
||||||
|
"text_found": entity["match"],
|
||||||
|
"target_title": entity["title"],
|
||||||
|
"target_id": entity["id"],
|
||||||
|
"suggested_edge_type": smart_edge,
|
||||||
|
"suggested_markdown": f"[[rel:{smart_edge} {entity['title']}]]",
|
||||||
|
"confidence": 1.0,
|
||||||
|
"reason": f"Exakter Treffer: '{entity['match']}' ({target_type})"
|
||||||
|
})
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 2. Semantic Match: Sliding Window & Footer Focus
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
search_queries = self._generate_search_queries(text)
|
||||||
|
|
||||||
|
# Async parallel abfragen
|
||||||
|
tasks = [self._get_semantic_suggestions_async(q) for q in search_queries]
|
||||||
|
results_list = await asyncio.gather(*tasks)
|
||||||
|
|
||||||
|
# Ergebnisse verarbeiten
|
||||||
|
for hits in results_list:
|
||||||
|
for hit in hits:
|
||||||
|
note_id = hit.payload.get("note_id")
|
||||||
|
if not note_id: continue
|
||||||
|
|
||||||
|
# Deduplizierung (Notiz-Ebene)
|
||||||
|
if note_id in seen_target_note_ids:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Score Check (Threshold 0.50 für nomic-embed-text)
|
||||||
|
if hit.total_score > 0.50:
|
||||||
|
seen_target_note_ids.add(note_id)
|
||||||
|
|
||||||
|
target_title = hit.payload.get("title") or "Unbekannt"
|
||||||
|
|
||||||
|
# INTELLIGENTE KANTEN-LOGIK (MATRIX)
|
||||||
|
# Den Typ der gefundenen Notiz aus dem Payload lesen
|
||||||
|
target_type = hit.payload.get("type", "concept")
|
||||||
|
smart_edge = self._resolve_edge_type(current_type, target_type)
|
||||||
|
|
||||||
|
suggestions.append({
|
||||||
|
"type": "semantic_match",
|
||||||
|
"text_found": (hit.source.get("text") or "")[:60] + "...",
|
||||||
|
"target_title": target_title,
|
||||||
|
"target_id": note_id,
|
||||||
|
"suggested_edge_type": smart_edge,
|
||||||
|
"suggested_markdown": f"[[rel:{smart_edge} {target_title}]]",
|
||||||
|
"confidence": round(hit.total_score, 2),
|
||||||
|
"reason": f"Semantisch ähnlich zu {target_type} ({hit.total_score:.2f})"
|
||||||
|
})
|
||||||
|
|
||||||
|
# Sortieren nach Confidence
|
||||||
|
suggestions.sort(key=lambda x: x["confidence"], reverse=True)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"draft_length": len(text),
|
||||||
|
"analyzed_windows": len(search_queries),
|
||||||
|
"suggestions_count": len(suggestions),
|
||||||
|
"suggestions": suggestions[:10]
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# Core Logic: Die Matrix
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
|
||||||
|
def _resolve_edge_type(self, source_type: str, target_type: str) -> str:
|
||||||
|
"""
|
||||||
|
Entscheidungsmatrix für komplexe Verbindungen.
|
||||||
|
Definiert, wie Typ A auf Typ B verlinken sollte.
|
||||||
|
"""
|
||||||
|
st = source_type.lower()
|
||||||
|
tt = target_type.lower()
|
||||||
|
|
||||||
|
# Regeln für 'experience' (Erfahrungen)
|
||||||
|
if st == "experience":
|
||||||
|
if tt == "value": return "based_on"
|
||||||
|
if tt == "principle": return "derived_from"
|
||||||
|
if tt == "trip": return "part_of"
|
||||||
|
if tt == "lesson": return "learned"
|
||||||
|
if tt == "project": return "related_to" # oder belongs_to
|
||||||
|
|
||||||
|
# Regeln für 'project'
|
||||||
|
if st == "project":
|
||||||
|
if tt == "decision": return "depends_on"
|
||||||
|
if tt == "concept": return "uses"
|
||||||
|
if tt == "person": return "managed_by"
|
||||||
|
|
||||||
|
# Regeln für 'decision' (ADR)
|
||||||
|
if st == "decision":
|
||||||
|
if tt == "principle": return "compliant_with"
|
||||||
|
if tt == "requirement": return "addresses"
|
||||||
|
|
||||||
|
# Fallback: Standard aus der types.yaml für den Source-Typ
|
||||||
|
return self._get_default_edge_type(st)
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# Sliding Windows
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
|
||||||
|
def _generate_search_queries(self, text: str) -> List[str]:
|
||||||
|
"""
|
||||||
|
Erzeugt intelligente Fenster + Footer Scan.
|
||||||
|
"""
|
||||||
|
text_len = len(text)
|
||||||
|
if not text: return []
|
||||||
|
|
||||||
|
queries = []
|
||||||
|
|
||||||
|
# 1. Start / Gesamtkontext
|
||||||
|
queries.append(text[:600])
|
||||||
|
|
||||||
|
# 2. Footer-Scan (Wichtig für "Projekt"-Referenzen am Ende)
|
||||||
|
if text_len > 150:
|
||||||
|
footer = text[-250:]
|
||||||
|
if footer not in queries:
|
||||||
|
queries.append(footer)
|
||||||
|
|
||||||
|
# 3. Sliding Window für lange Texte
|
||||||
|
if text_len > 800:
|
||||||
|
window_size = 500
|
||||||
|
step = 1500
|
||||||
|
for i in range(window_size, text_len - window_size, step):
|
||||||
|
end_pos = min(i + window_size, text_len)
|
||||||
|
chunk = text[i:end_pos]
|
||||||
|
if len(chunk) > 100:
|
||||||
|
queries.append(chunk)
|
||||||
|
|
||||||
|
return queries
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# Standard Helpers
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
|
||||||
|
async def _get_semantic_suggestions_async(self, text: str):
|
||||||
|
req = QueryRequest(query=text, top_k=5, explain=False)
|
||||||
|
try:
|
||||||
|
res = hybrid_retrieve(req)
|
||||||
|
return res.results
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Semantic suggestion error: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
def _load_type_registry(self) -> dict:
|
||||||
|
path = os.getenv("MINDNET_TYPES_FILE", "config/types.yaml")
|
||||||
|
if not os.path.exists(path):
|
||||||
|
if os.path.exists("types.yaml"): path = "types.yaml"
|
||||||
|
else: return {}
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f: return yaml.safe_load(f) or {}
|
||||||
|
except Exception: return {}
|
||||||
|
|
||||||
|
def _get_default_edge_type(self, note_type: str) -> str:
|
||||||
|
types_cfg = self.registry.get("types", {})
|
||||||
|
type_def = types_cfg.get(note_type, {})
|
||||||
|
defaults = type_def.get("edge_defaults")
|
||||||
|
return defaults[0] if defaults else "related_to"
|
||||||
|
|
||||||
|
def _fetch_all_titles_and_aliases(self) -> List[Dict]:
|
||||||
|
notes = []
|
||||||
|
next_page = None
|
||||||
|
col = f"{self.prefix}_notes"
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
res, next_page = self.client.scroll(
|
||||||
|
collection_name=col, limit=1000, offset=next_page,
|
||||||
|
with_payload=True, with_vectors=False
|
||||||
|
)
|
||||||
|
for point in res:
|
||||||
|
pl = point.payload or {}
|
||||||
|
aliases = pl.get("aliases") or []
|
||||||
|
if isinstance(aliases, str): aliases = [aliases]
|
||||||
|
|
||||||
|
notes.append({
|
||||||
|
"id": pl.get("note_id"),
|
||||||
|
"title": pl.get("title"),
|
||||||
|
"aliases": aliases,
|
||||||
|
"type": pl.get("type", "concept") # WICHTIG: Typ laden für Matrix
|
||||||
|
})
|
||||||
|
if next_page is None: break
|
||||||
|
except Exception: pass
|
||||||
|
return notes
|
||||||
|
|
||||||
|
def _find_entities_in_text(self, text: str, entities: List[Dict]) -> List[Dict]:
|
||||||
|
found = []
|
||||||
|
text_lower = text.lower()
|
||||||
|
for entity in entities:
|
||||||
|
# Title Check
|
||||||
|
title = entity.get("title")
|
||||||
|
if title and title.lower() in text_lower:
|
||||||
|
found.append({"match": title, "title": title, "id": entity["id"], "type": entity["type"]})
|
||||||
|
continue
|
||||||
|
# Alias Check
|
||||||
|
for alias in entity.get("aliases", []):
|
||||||
|
if str(alias).lower() in text_lower:
|
||||||
|
found.append({"match": alias, "title": title, "id": entity["id"], "type": entity["type"]})
|
||||||
|
break
|
||||||
|
return found
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/services/embeddings_client.py
|
||||||
|
DESCRIPTION: Unified Embedding Client. Nutzt Ollama API (HTTP). Ersetzt lokale sentence-transformers.
|
||||||
|
VERSION: 2.5.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: httpx, requests, app.config
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
import httpx
|
||||||
|
import requests # Für den synchronen Fallback
|
||||||
|
from typing import List
|
||||||
|
from app.config import get_settings
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class EmbeddingsClient:
|
||||||
|
"""
|
||||||
|
Async Client für Embeddings via Ollama.
|
||||||
|
"""
|
||||||
|
def __init__(self):
|
||||||
|
self.settings = get_settings()
|
||||||
|
self.base_url = os.getenv("MINDNET_OLLAMA_URL", "http://127.0.0.1:11434")
|
||||||
|
self.model = os.getenv("MINDNET_EMBEDDING_MODEL")
|
||||||
|
|
||||||
|
if not self.model:
|
||||||
|
self.model = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
||||||
|
logger.warning(f"No MINDNET_EMBEDDING_MODEL set. Fallback to '{self.model}'.")
|
||||||
|
|
||||||
|
async def embed_query(self, text: str) -> List[float]:
|
||||||
|
return await self._request_embedding(text)
|
||||||
|
|
||||||
|
async def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
||||||
|
vectors = []
|
||||||
|
# Längeres Timeout für Batches
|
||||||
|
async with httpx.AsyncClient(timeout=120.0) as client:
|
||||||
|
for text in texts:
|
||||||
|
vec = await self._request_embedding_with_client(client, text)
|
||||||
|
vectors.append(vec)
|
||||||
|
return vectors
|
||||||
|
|
||||||
|
async def _request_embedding(self, text: str) -> List[float]:
|
||||||
|
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||||
|
return await self._request_embedding_with_client(client, text)
|
||||||
|
|
||||||
|
async def _request_embedding_with_client(self, client: httpx.AsyncClient, text: str) -> List[float]:
|
||||||
|
if not text or not text.strip(): return []
|
||||||
|
url = f"{self.base_url}/api/embeddings"
|
||||||
|
try:
|
||||||
|
response = await client.post(url, json={"model": self.model, "prompt": text})
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json().get("embedding", [])
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Async embedding failed: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# TEIL 2: SYNCHRONER FALLBACK (Unified)
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
|
def embed_text(text: str) -> List[float]:
|
||||||
|
"""
|
||||||
|
LEGACY/SYNC: Nutzt jetzt ebenfalls OLLAMA via 'requests'.
|
||||||
|
Ersetzt SentenceTransformers, um Dimensionskonflikte (768 vs 384) zu lösen.
|
||||||
|
"""
|
||||||
|
if not text or not text.strip():
|
||||||
|
return []
|
||||||
|
|
||||||
|
base_url = os.getenv("MINDNET_OLLAMA_URL", "http://127.0.0.1:11434")
|
||||||
|
model = os.getenv("MINDNET_EMBEDDING_MODEL")
|
||||||
|
|
||||||
|
# Fallback logik identisch zur Klasse
|
||||||
|
if not model:
|
||||||
|
model = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
||||||
|
|
||||||
|
url = f"{base_url}/api/embeddings"
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Synchroner Request (blockierend)
|
||||||
|
response = requests.post(url, json={"model": model, "prompt": text}, timeout=30)
|
||||||
|
response.raise_for_status()
|
||||||
|
data = response.json()
|
||||||
|
return data.get("embedding", [])
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Sync embedding (Ollama) failed: {e}")
|
||||||
|
return []
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/services/feedback_service.py
|
||||||
|
DESCRIPTION: Schreibt Search- und Feedback-Logs in JSONL-Dateien.
|
||||||
|
VERSION: 1.1
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.models.dto
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Dict, Any, List, Union
|
||||||
|
from app.models.dto import QueryRequest, QueryResponse, FeedbackRequest, QueryHit
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Pfad für Logs (lokal auf dem Beelink/PC)
|
||||||
|
LOG_DIR = Path("data/logs")
|
||||||
|
SEARCH_LOG_FILE = LOG_DIR / "search_history.jsonl"
|
||||||
|
FEEDBACK_LOG_FILE = LOG_DIR / "feedback.jsonl"
|
||||||
|
|
||||||
|
def _ensure_log_dir():
|
||||||
|
if not LOG_DIR.exists():
|
||||||
|
os.makedirs(LOG_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
def _append_jsonl(file_path: Path, data: dict):
|
||||||
|
try:
|
||||||
|
with open(file_path, "a", encoding="utf-8") as f:
|
||||||
|
f.write(json.dumps(data, ensure_ascii=False) + "\n")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to write log: {e}")
|
||||||
|
|
||||||
|
def log_search(
|
||||||
|
query_id: str,
|
||||||
|
query_text: str,
|
||||||
|
results: List[QueryHit],
|
||||||
|
mode: str = "unknown",
|
||||||
|
metadata: Dict[str, Any] = None
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Generische Logging-Funktion für Suche UND Chat.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
query_id: UUID der Anfrage.
|
||||||
|
query_text: User-Eingabe.
|
||||||
|
results: Liste der Treffer (QueryHit Objekte).
|
||||||
|
mode: z.B. "semantic", "hybrid", "chat_rag".
|
||||||
|
metadata: Zusätzliche Infos (z.B. generierte Antwort, Intent).
|
||||||
|
"""
|
||||||
|
_ensure_log_dir()
|
||||||
|
|
||||||
|
hits_summary = []
|
||||||
|
for hit in results:
|
||||||
|
# Pydantic Model Dump für saubere Serialisierung
|
||||||
|
breakdown = None
|
||||||
|
if hit.explanation and hit.explanation.breakdown:
|
||||||
|
breakdown = hit.explanation.breakdown.model_dump()
|
||||||
|
|
||||||
|
hits_summary.append({
|
||||||
|
"node_id": hit.node_id,
|
||||||
|
"note_id": hit.note_id,
|
||||||
|
"total_score": hit.total_score,
|
||||||
|
"breakdown": breakdown,
|
||||||
|
"rank_semantic": hit.semantic_score,
|
||||||
|
"rank_edge": hit.edge_bonus,
|
||||||
|
"type": hit.source.get("type") if hit.source else "unknown"
|
||||||
|
})
|
||||||
|
|
||||||
|
entry = {
|
||||||
|
"timestamp": time.time(),
|
||||||
|
"query_id": query_id,
|
||||||
|
"query_text": query_text,
|
||||||
|
"mode": mode,
|
||||||
|
"hits_count": len(hits_summary),
|
||||||
|
"hits": hits_summary,
|
||||||
|
"metadata": metadata or {}
|
||||||
|
}
|
||||||
|
|
||||||
|
_append_jsonl(SEARCH_LOG_FILE, entry)
|
||||||
|
logger.info(f"Logged search/chat interaction {query_id}")
|
||||||
|
|
||||||
|
def log_feedback(fb: FeedbackRequest):
|
||||||
|
"""
|
||||||
|
Speichert das User-Feedback.
|
||||||
|
"""
|
||||||
|
_ensure_log_dir()
|
||||||
|
|
||||||
|
entry = {
|
||||||
|
"timestamp": time.time(),
|
||||||
|
"query_id": fb.query_id,
|
||||||
|
"node_id": fb.node_id,
|
||||||
|
"score": fb.score,
|
||||||
|
"comment": fb.comment
|
||||||
|
}
|
||||||
|
|
||||||
|
_append_jsonl(FEEDBACK_LOG_FILE, entry)
|
||||||
|
logger.info(f"Logged feedback for {fb.query_id}")
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/services/llm_service.py
|
||||||
|
DESCRIPTION: Asynchroner Client für Ollama. Verwaltet Prompts und Background-Last (Semaphore).
|
||||||
|
VERSION: 2.8.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: httpx, yaml, asyncio, app.config
|
||||||
|
EXTERNAL_CONFIG: config/prompts.yaml
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
"""
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import yaml
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import asyncio
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional, Dict, Any, Literal
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class Settings:
|
||||||
|
OLLAMA_URL = os.getenv("MINDNET_OLLAMA_URL", "http://127.0.0.1:11434")
|
||||||
|
LLM_TIMEOUT = float(os.getenv("MINDNET_LLM_TIMEOUT", 300.0))
|
||||||
|
LLM_MODEL = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
||||||
|
PROMPTS_PATH = os.getenv("MINDNET_PROMPTS_PATH", "./config/prompts.yaml")
|
||||||
|
|
||||||
|
# NEU: Konfigurierbares Limit für Hintergrund-Last
|
||||||
|
# Default auf 2 (konservativ), kann in .env erhöht werden.
|
||||||
|
BACKGROUND_LIMIT = int(os.getenv("MINDNET_LLM_BACKGROUND_LIMIT", "2"))
|
||||||
|
|
||||||
|
def get_settings():
|
||||||
|
return Settings()
|
||||||
|
|
||||||
|
class LLMService:
|
||||||
|
# GLOBALER SEMAPHOR (Lazy Initialization)
|
||||||
|
# Wir initialisieren ihn erst, wenn wir die Settings kennen.
|
||||||
|
_background_semaphore = None
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.settings = get_settings()
|
||||||
|
self.prompts = self._load_prompts()
|
||||||
|
|
||||||
|
# Initialisiere Semaphore einmalig auf Klassen-Ebene basierend auf Config
|
||||||
|
if LLMService._background_semaphore is None:
|
||||||
|
limit = self.settings.BACKGROUND_LIMIT
|
||||||
|
logger.info(f"🚦 LLMService: Initializing Background Semaphore with limit: {limit}")
|
||||||
|
LLMService._background_semaphore = asyncio.Semaphore(limit)
|
||||||
|
|
||||||
|
self.timeout = httpx.Timeout(self.settings.LLM_TIMEOUT, connect=10.0)
|
||||||
|
|
||||||
|
self.client = httpx.AsyncClient(
|
||||||
|
base_url=self.settings.OLLAMA_URL,
|
||||||
|
timeout=self.timeout
|
||||||
|
)
|
||||||
|
|
||||||
|
def _load_prompts(self) -> dict:
|
||||||
|
path = Path(self.settings.PROMPTS_PATH)
|
||||||
|
if not path.exists(): return {}
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f: return yaml.safe_load(f)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to load prompts: {e}")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
async def generate_raw_response(
|
||||||
|
self,
|
||||||
|
prompt: str,
|
||||||
|
system: str = None,
|
||||||
|
force_json: bool = False,
|
||||||
|
max_retries: int = 0,
|
||||||
|
base_delay: float = 2.0,
|
||||||
|
priority: Literal["realtime", "background"] = "realtime"
|
||||||
|
) -> str:
|
||||||
|
"""
|
||||||
|
Führt einen LLM Call aus.
|
||||||
|
priority="realtime": Chat (Sofort, keine Bremse).
|
||||||
|
priority="background": Import/Analyse (Gedrosselt durch Semaphore).
|
||||||
|
"""
|
||||||
|
|
||||||
|
use_semaphore = (priority == "background")
|
||||||
|
|
||||||
|
if use_semaphore and LLMService._background_semaphore:
|
||||||
|
async with LLMService._background_semaphore:
|
||||||
|
return await self._execute_request(prompt, system, force_json, max_retries, base_delay)
|
||||||
|
else:
|
||||||
|
# Realtime oder Fallback (falls Semaphore Init fehlschlug)
|
||||||
|
return await self._execute_request(prompt, system, force_json, max_retries, base_delay)
|
||||||
|
|
||||||
|
async def _execute_request(self, prompt, system, force_json, max_retries, base_delay):
|
||||||
|
payload: Dict[str, Any] = {
|
||||||
|
"model": self.settings.LLM_MODEL,
|
||||||
|
"prompt": prompt,
|
||||||
|
"stream": False,
|
||||||
|
"options": {
|
||||||
|
"temperature": 0.1 if force_json else 0.7,
|
||||||
|
"num_ctx": 8192
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if force_json:
|
||||||
|
payload["format"] = "json"
|
||||||
|
|
||||||
|
if system:
|
||||||
|
payload["system"] = system
|
||||||
|
|
||||||
|
attempt = 0
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
response = await self.client.post("/api/generate", json=payload)
|
||||||
|
|
||||||
|
if response.status_code == 200:
|
||||||
|
data = response.json()
|
||||||
|
return data.get("response", "").strip()
|
||||||
|
else:
|
||||||
|
response.raise_for_status()
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
attempt += 1
|
||||||
|
if attempt > max_retries:
|
||||||
|
logger.error(f"LLM Final Error (Versuch {attempt}): {e}")
|
||||||
|
raise e
|
||||||
|
|
||||||
|
wait_time = base_delay * (2 ** (attempt - 1))
|
||||||
|
logger.warning(f"⚠️ LLM Retry ({attempt}/{max_retries}) in {wait_time}s: {e}")
|
||||||
|
await asyncio.sleep(wait_time)
|
||||||
|
|
||||||
|
async def generate_rag_response(self, query: str, context_str: str) -> str:
|
||||||
|
"""
|
||||||
|
Chat-Wrapper: Immer Realtime.
|
||||||
|
"""
|
||||||
|
system_prompt = self.prompts.get("system_prompt", "")
|
||||||
|
rag_template = self.prompts.get("rag_template", "{context_str}\n\n{query}")
|
||||||
|
|
||||||
|
final_prompt = rag_template.format(context_str=context_str, query=query)
|
||||||
|
|
||||||
|
return await self.generate_raw_response(
|
||||||
|
final_prompt,
|
||||||
|
system=system_prompt,
|
||||||
|
max_retries=0,
|
||||||
|
force_json=False,
|
||||||
|
priority="realtime"
|
||||||
|
)
|
||||||
|
|
||||||
|
async def close(self):
|
||||||
|
if self.client:
|
||||||
|
await self.client.aclose()
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/services/semantic_analyzer.py
|
||||||
|
DESCRIPTION: KI-gestützte Kanten-Validierung. Nutzt LLM (Background-Priority), um Kanten präzise einem Chunk zuzuordnen.
|
||||||
|
VERSION: 2.1.0 (Fix: Strict Edge String Validation against LLM Hallucinations)
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.services.llm_service, json, logging
|
||||||
|
LAST_ANALYSIS: 2025-12-16
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from typing import List, Optional
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
# Importe
|
||||||
|
from app.services.llm_service import LLMService
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class SemanticAnalyzer:
|
||||||
|
def __init__(self):
|
||||||
|
self.llm = LLMService()
|
||||||
|
|
||||||
|
def _is_valid_edge_string(self, edge_str: str) -> bool:
|
||||||
|
"""
|
||||||
|
Prüft, ob ein String eine valide Kante im Format 'kind:target' ist.
|
||||||
|
Verhindert, dass LLM-Geschwätz ("Here is the list: ...") als Kante durchrutscht.
|
||||||
|
"""
|
||||||
|
if not isinstance(edge_str, str) or ":" not in edge_str:
|
||||||
|
return False
|
||||||
|
|
||||||
|
parts = edge_str.split(":", 1)
|
||||||
|
kind = parts[0].strip()
|
||||||
|
target = parts[1].strip()
|
||||||
|
|
||||||
|
# Regel 1: Ein 'kind' (Beziehungstyp) darf keine Leerzeichen enthalten.
|
||||||
|
# Erlaubt: "derived_from", "related_to"
|
||||||
|
# Verboten: "derived end of instruction", "Here is the list"
|
||||||
|
if " " in kind:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Regel 2: Plausible Länge für den Typ
|
||||||
|
if len(kind) > 40 or len(kind) < 2:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Regel 3: Target darf nicht leer sein
|
||||||
|
if not target:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def assign_edges_to_chunk(self, chunk_text: str, all_edges: List[str], note_type: str) -> List[str]:
|
||||||
|
"""
|
||||||
|
Sendet einen Chunk und eine Liste potenzieller Kanten an das LLM.
|
||||||
|
Das LLM filtert heraus, welche Kanten für diesen Chunk relevant sind.
|
||||||
|
|
||||||
|
Features:
|
||||||
|
- Retry Strategy: Wartet bei Überlastung (max_retries=5).
|
||||||
|
- Priority Queue: Läuft als "background" Task, um den Chat nicht zu blockieren.
|
||||||
|
- Observability: Loggt Input-Größe, Raw-Response und Parsing-Details.
|
||||||
|
"""
|
||||||
|
if not all_edges:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# 1. Prompt laden
|
||||||
|
prompt_template = self.llm.prompts.get("edge_allocation_template")
|
||||||
|
|
||||||
|
if not prompt_template:
|
||||||
|
logger.warning("⚠️ [SemanticAnalyzer] Prompt 'edge_allocation_template' fehlt. Nutze Fallback.")
|
||||||
|
prompt_template = (
|
||||||
|
"TASK: Wähle aus den Kandidaten die relevanten Kanten für den Text.\n"
|
||||||
|
"TEXT: {chunk_text}\n"
|
||||||
|
"KANDIDATEN: {edge_list}\n"
|
||||||
|
"OUTPUT: JSON Liste von Strings [\"kind:target\"]."
|
||||||
|
)
|
||||||
|
|
||||||
|
# 2. Kandidaten-Liste formatieren
|
||||||
|
edges_str = "\n".join([f"- {e}" for e in all_edges])
|
||||||
|
|
||||||
|
# LOG: Request Info
|
||||||
|
logger.debug(f"🔍 [SemanticAnalyzer] Request: {len(chunk_text)} chars Text, {len(all_edges)} Candidates.")
|
||||||
|
|
||||||
|
# 3. Prompt füllen
|
||||||
|
final_prompt = prompt_template.format(
|
||||||
|
chunk_text=chunk_text[:3500],
|
||||||
|
edge_list=edges_str
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 4. LLM Call mit Traffic Control
|
||||||
|
response_json = await self.llm.generate_raw_response(
|
||||||
|
prompt=final_prompt,
|
||||||
|
force_json=True,
|
||||||
|
max_retries=5,
|
||||||
|
base_delay=5.0,
|
||||||
|
priority="background"
|
||||||
|
)
|
||||||
|
|
||||||
|
# LOG: Raw Response Preview
|
||||||
|
logger.debug(f"📥 [SemanticAnalyzer] Raw Response (Preview): {response_json[:200]}...")
|
||||||
|
|
||||||
|
# 5. Parsing & Cleaning
|
||||||
|
clean_json = response_json.replace("```json", "").replace("```", "").strip()
|
||||||
|
|
||||||
|
if not clean_json:
|
||||||
|
logger.warning("⚠️ [SemanticAnalyzer] Leere Antwort vom LLM erhalten. Trigger Fallback.")
|
||||||
|
return []
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = json.loads(clean_json)
|
||||||
|
except json.JSONDecodeError as json_err:
|
||||||
|
logger.error(f"❌ [SemanticAnalyzer] JSON Decode Error.")
|
||||||
|
logger.error(f" Grund: {json_err}")
|
||||||
|
logger.error(f" Empfangener String: {clean_json[:500]}")
|
||||||
|
logger.info(" -> Workaround: Fallback auf 'Alle Kanten' (durch Chunker).")
|
||||||
|
return []
|
||||||
|
|
||||||
|
valid_edges = []
|
||||||
|
|
||||||
|
# 6. Robuste Validierung (List vs Dict)
|
||||||
|
# Wir sammeln erst alle Strings ein
|
||||||
|
raw_candidates = []
|
||||||
|
|
||||||
|
if isinstance(data, list):
|
||||||
|
raw_candidates = data
|
||||||
|
|
||||||
|
elif isinstance(data, dict):
|
||||||
|
logger.info(f"ℹ️ [SemanticAnalyzer] LLM lieferte Dict statt Liste. Versuche Reparatur. Keys: {list(data.keys())}")
|
||||||
|
for key, val in data.items():
|
||||||
|
# Fall A: {"edges": ["kind:target"]}
|
||||||
|
if key.lower() in ["edges", "results", "kanten", "matches"] and isinstance(val, list):
|
||||||
|
raw_candidates.extend(val)
|
||||||
|
|
||||||
|
# Fall B: {"kind": "target"} (Beziehung als Key)
|
||||||
|
elif isinstance(val, str):
|
||||||
|
raw_candidates.append(f"{key}:{val}")
|
||||||
|
|
||||||
|
# Fall C: {"kind": ["target1", "target2"]}
|
||||||
|
elif isinstance(val, list):
|
||||||
|
for target in val:
|
||||||
|
if isinstance(target, str):
|
||||||
|
raw_candidates.append(f"{key}:{target}")
|
||||||
|
|
||||||
|
# 7. Strict Validation Loop
|
||||||
|
for e in raw_candidates:
|
||||||
|
e_str = str(e)
|
||||||
|
if self._is_valid_edge_string(e_str):
|
||||||
|
valid_edges.append(e_str)
|
||||||
|
else:
|
||||||
|
logger.debug(f" [SemanticAnalyzer] Invalid edge format rejected: '{e_str}'")
|
||||||
|
|
||||||
|
# Safety: Filtere nur Kanten, die halbwegs valide aussehen (Doppelcheck)
|
||||||
|
final_result = [e for e in valid_edges if ":" in e]
|
||||||
|
|
||||||
|
# LOG: Ergebnis
|
||||||
|
if final_result:
|
||||||
|
logger.info(f"✅ [SemanticAnalyzer] Success. {len(final_result)} Kanten zugewiesen.")
|
||||||
|
else:
|
||||||
|
logger.debug(" [SemanticAnalyzer] Keine spezifischen Kanten erkannt (Empty Result).")
|
||||||
|
|
||||||
|
return final_result
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"💥 [SemanticAnalyzer] Kritischer Fehler: {e}", exc_info=True)
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def close(self):
|
||||||
|
if self.llm:
|
||||||
|
await self.llm.close()
|
||||||
|
|
||||||
|
# Singleton Helper
|
||||||
|
_analyzer_instance = None
|
||||||
|
def get_semantic_analyzer():
|
||||||
|
global _analyzer_instance
|
||||||
|
if _analyzer_instance is None:
|
||||||
|
_analyzer_instance = SemanticAnalyzer()
|
||||||
|
return _analyzer_instance
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
# config/decision_engine.yaml
|
||||||
|
# Steuerung der Decision Engine (Intent Recognition)
|
||||||
|
# Version: 2.4.0 (Clean Architecture: Generic Intents only)
|
||||||
|
|
||||||
|
version: 1.4
|
||||||
|
|
||||||
|
settings:
|
||||||
|
llm_fallback_enabled: true
|
||||||
|
|
||||||
|
# Few-Shot Prompting für den LLM-Router (Slow Path)
|
||||||
|
llm_router_prompt: |
|
||||||
|
Du bist ein Klassifikator. Analysiere die Nachricht und wähle die passende Strategie.
|
||||||
|
Antworte NUR mit dem Namen der Strategie.
|
||||||
|
|
||||||
|
STRATEGIEN:
|
||||||
|
- INTERVIEW: User will Wissen erfassen, Notizen anlegen oder Dinge festhalten.
|
||||||
|
- DECISION: Rat, Strategie, Vor/Nachteile, "Soll ich".
|
||||||
|
- EMPATHY: Gefühle, Frust, Freude, Probleme.
|
||||||
|
- CODING: Code, Syntax, Programmierung.
|
||||||
|
- FACT: Wissen, Fakten, Definitionen.
|
||||||
|
|
||||||
|
BEISPIELE:
|
||||||
|
User: "Wie funktioniert Qdrant?" -> FACT
|
||||||
|
User: "Soll ich Qdrant nutzen?" -> DECISION
|
||||||
|
User: "Ich möchte etwas notieren" -> INTERVIEW
|
||||||
|
User: "Lass uns das festhalten" -> INTERVIEW
|
||||||
|
User: "Schreibe ein Python Script" -> CODING
|
||||||
|
User: "Alles ist grau und sinnlos" -> EMPATHY
|
||||||
|
|
||||||
|
NACHRICHT: "{query}"
|
||||||
|
|
||||||
|
STRATEGIE:
|
||||||
|
|
||||||
|
strategies:
|
||||||
|
# 1. Fakten-Abfrage (Fallback & Default)
|
||||||
|
FACT:
|
||||||
|
description: "Reine Wissensabfrage."
|
||||||
|
trigger_keywords: []
|
||||||
|
inject_types: []
|
||||||
|
prompt_template: "rag_template"
|
||||||
|
prepend_instruction: null
|
||||||
|
|
||||||
|
# 2. Entscheidungs-Frage
|
||||||
|
DECISION:
|
||||||
|
description: "Der User sucht Rat, Strategie oder Abwägung."
|
||||||
|
trigger_keywords:
|
||||||
|
- "soll ich"
|
||||||
|
- "meinung"
|
||||||
|
- "besser"
|
||||||
|
- "empfehlung"
|
||||||
|
- "strategie"
|
||||||
|
- "entscheidung"
|
||||||
|
- "abwägung"
|
||||||
|
- "vergleich"
|
||||||
|
inject_types: ["value", "principle", "goal", "risk"]
|
||||||
|
prompt_template: "decision_template"
|
||||||
|
prepend_instruction: |
|
||||||
|
!!! ENTSCHEIDUNGS-MODUS !!!
|
||||||
|
BITTE WÄGE FAKTEN GEGEN FOLGENDE WERTE, PRINZIPIEN UND ZIELE AB:
|
||||||
|
|
||||||
|
# 3. Empathie / "Ich"-Modus
|
||||||
|
EMPATHY:
|
||||||
|
description: "Reaktion auf emotionale Zustände."
|
||||||
|
trigger_keywords:
|
||||||
|
- "ich fühle"
|
||||||
|
- "traurig"
|
||||||
|
- "glücklich"
|
||||||
|
- "gestresst"
|
||||||
|
- "angst"
|
||||||
|
- "nervt"
|
||||||
|
- "überfordert"
|
||||||
|
- "müde"
|
||||||
|
inject_types: ["experience", "belief", "profile"]
|
||||||
|
prompt_template: "empathy_template"
|
||||||
|
prepend_instruction: null
|
||||||
|
|
||||||
|
# 4. Coding / Technical
|
||||||
|
CODING:
|
||||||
|
description: "Technische Anfragen und Programmierung."
|
||||||
|
trigger_keywords:
|
||||||
|
- "code"
|
||||||
|
- "python"
|
||||||
|
- "script"
|
||||||
|
- "funktion"
|
||||||
|
- "bug"
|
||||||
|
- "syntax"
|
||||||
|
- "json"
|
||||||
|
- "yaml"
|
||||||
|
- "bash"
|
||||||
|
inject_types: ["snippet", "reference", "source"]
|
||||||
|
prompt_template: "technical_template"
|
||||||
|
prepend_instruction: null
|
||||||
|
|
||||||
|
# 5. Interview / Datenerfassung
|
||||||
|
# HINWEIS: Spezifische Typen (Projekt, Ziel etc.) werden automatisch
|
||||||
|
# über die types.yaml erkannt. Hier stehen nur generische Trigger.
|
||||||
|
INTERVIEW:
|
||||||
|
description: "Der User möchte Wissen erfassen."
|
||||||
|
trigger_keywords:
|
||||||
|
- "neue notiz"
|
||||||
|
- "etwas notieren"
|
||||||
|
- "festhalten"
|
||||||
|
- "erstellen"
|
||||||
|
- "dokumentieren"
|
||||||
|
- "anlegen"
|
||||||
|
- "interview"
|
||||||
|
- "erfassen"
|
||||||
|
- "idee speichern"
|
||||||
|
- "draft"
|
||||||
|
inject_types: []
|
||||||
|
prompt_template: "interview_template"
|
||||||
|
prepend_instruction: null
|
||||||
|
|
||||||
|
# Schemas: Hier nur der Fallback.
|
||||||
|
# Spezifische Schemas (Project, Experience) kommen jetzt aus types.yaml!
|
||||||
|
schemas:
|
||||||
|
default:
|
||||||
|
fields:
|
||||||
|
- "Titel"
|
||||||
|
- "Thema/Inhalt"
|
||||||
|
- "Tags"
|
||||||
|
hint: "Halte es einfach und übersichtlich."
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
# config/prompts.yaml — Final V2.3.1 (Multi-Personality Support)
|
||||||
|
|
||||||
|
system_prompt: |
|
||||||
|
Du bist 'mindnet', mein digitaler Zwilling und strategischer Partner.
|
||||||
|
|
||||||
|
DEINE IDENTITÄT:
|
||||||
|
- Du bist nicht nur eine Datenbank, sondern handelst nach MEINEN Werten und Zielen.
|
||||||
|
- Du passt deinen Stil dynamisch an die Situation an (Analytisch, Empathisch oder Technisch).
|
||||||
|
|
||||||
|
DEINE REGELN:
|
||||||
|
1. Deine Antwort muss zu 100% auf dem bereitgestellten KONTEXT basieren.
|
||||||
|
2. Halluziniere keine Fakten, die nicht in den Quellen stehen.
|
||||||
|
3. Antworte auf Deutsch (außer bei Code/Fachbegriffen).
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 1. STANDARD: Fakten & Wissen (Intent: FACT)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
rag_template: |
|
||||||
|
QUELLEN (WISSEN):
|
||||||
|
=========================================
|
||||||
|
{context_str}
|
||||||
|
=========================================
|
||||||
|
|
||||||
|
FRAGE:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
ANWEISUNG:
|
||||||
|
Beantworte die Frage präzise basierend auf den Quellen.
|
||||||
|
Fasse die Informationen zusammen. Sei objektiv und neutral.
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 2. DECISION: Strategie & Abwägung (Intent: DECISION)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
decision_template: |
|
||||||
|
KONTEXT (FAKTEN & STRATEGIE):
|
||||||
|
=========================================
|
||||||
|
{context_str}
|
||||||
|
=========================================
|
||||||
|
|
||||||
|
ENTSCHEIDUNGSFRAGE:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
ANWEISUNG:
|
||||||
|
Du agierst als mein Entscheidungs-Partner.
|
||||||
|
1. Analysiere die Faktenlage aus den Quellen.
|
||||||
|
2. Prüfe dies hart gegen meine strategischen Notizen (Typ [VALUE], [PRINCIPLE], [GOAL]).
|
||||||
|
3. Wäge ab: Passt die technische/faktische Lösung zu meinen Werten?
|
||||||
|
|
||||||
|
FORMAT:
|
||||||
|
- **Analyse:** (Kurze Zusammenfassung der Fakten)
|
||||||
|
- **Abgleich:** (Gibt es Konflikte mit Werten/Zielen? Nenne die Quelle!)
|
||||||
|
- **Empfehlung:** (Klare Meinung: Ja/Nein/Vielleicht mit Begründung)
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 3. EMPATHY: Der Spiegel / "Ich"-Modus (Intent: EMPATHY)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
empathy_template: |
|
||||||
|
KONTEXT (ERFAHRUNGEN & GLAUBENSSÄTZE):
|
||||||
|
=========================================
|
||||||
|
{context_str}
|
||||||
|
=========================================
|
||||||
|
|
||||||
|
SITUATION:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
ANWEISUNG:
|
||||||
|
Du agierst jetzt als mein empathischer Spiegel.
|
||||||
|
1. Versuche nicht sofort, das Problem technisch zu lösen.
|
||||||
|
2. Zeige Verständnis für die Situation basierend auf meinen eigenen Erfahrungen ([EXPERIENCE]) oder Glaubenssätzen ([BELIEF]), falls im Kontext vorhanden.
|
||||||
|
3. Antworte in der "Ich"-Form oder "Wir"-Form. Sei unterstützend.
|
||||||
|
|
||||||
|
TONFALL:
|
||||||
|
Ruhig, verständnisvoll, reflektiert. Keine Aufzählungszeichen, sondern fließender Text.
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 4. TECHNICAL: Der Coder (Intent: CODING)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
technical_template: |
|
||||||
|
KONTEXT (DOCS & SNIPPETS):
|
||||||
|
=========================================
|
||||||
|
{context_str}
|
||||||
|
=========================================
|
||||||
|
|
||||||
|
TASK:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
ANWEISUNG:
|
||||||
|
Du bist Senior Developer.
|
||||||
|
1. Ignoriere Smalltalk. Komm sofort zum Punkt.
|
||||||
|
2. Generiere validen, performanten Code basierend auf den Quellen.
|
||||||
|
3. Wenn Quellen fehlen, nutze dein allgemeines Programmierwissen, aber weise darauf hin.
|
||||||
|
|
||||||
|
FORMAT:
|
||||||
|
- Kurze Erklärung des Ansatzes.
|
||||||
|
- Markdown Code-Block (Copy-Paste fertig).
|
||||||
|
- Wichtige Edge-Cases.
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 5. INTERVIEW: Der "One-Shot Extractor" (Performance Mode)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
interview_template: |
|
||||||
|
TASK:
|
||||||
|
Du bist ein professioneller Ghostwriter. Verwandle den "USER INPUT" in eine strukturierte Notiz vom Typ '{target_type}'.
|
||||||
|
|
||||||
|
STRUKTUR (Nutze EXAKT diese Überschriften):
|
||||||
|
{schema_fields}
|
||||||
|
|
||||||
|
USER INPUT:
|
||||||
|
"{query}"
|
||||||
|
|
||||||
|
ANWEISUNG ZUM INHALT:
|
||||||
|
1. Analysiere den Input genau.
|
||||||
|
2. Schreibe die Inhalte unter die passenden Überschriften aus der STRUKTUR-Liste oben.
|
||||||
|
3. STIL: Schreibe flüssig, professionell und in der Ich-Perspektive. Korrigiere Grammatikfehler, aber behalte den persönlichen Ton bei.
|
||||||
|
4. Wenn Informationen für einen Abschnitt fehlen, schreibe nur: "[TODO: Ergänzen]". Erfinde nichts dazu.
|
||||||
|
|
||||||
|
OUTPUT FORMAT (YAML + MARKDOWN):
|
||||||
|
---
|
||||||
|
type: {target_type}
|
||||||
|
status: draft
|
||||||
|
title: (Erstelle einen treffenden, kurzen Titel für den Inhalt)
|
||||||
|
tags: [Tag1, Tag2]
|
||||||
|
---
|
||||||
|
|
||||||
|
# (Wiederhole den Titel hier)
|
||||||
|
|
||||||
|
## (Erster Begriff aus STRUKTUR)
|
||||||
|
(Text...)
|
||||||
|
|
||||||
|
## (Zweiter Begriff aus STRUKTUR)
|
||||||
|
(Text...)
|
||||||
|
|
||||||
|
(usw.)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 6. EDGE_ALLOCATION: Kantenfilter (Intent: OFFLINE_FILTER)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
edge_allocation_template: |
|
||||||
|
TASK:
|
||||||
|
Du bist ein strikter Selektor. Du erhältst eine Liste von "Kandidaten-Kanten" (Strings).
|
||||||
|
Wähle jene aus, die inhaltlich im "Textabschnitt" vorkommen oder relevant sind.
|
||||||
|
|
||||||
|
TEXTABSCHNITT:
|
||||||
|
"""
|
||||||
|
{chunk_text}
|
||||||
|
"""
|
||||||
|
|
||||||
|
KANDIDATEN (Auswahl-Pool):
|
||||||
|
{edge_list}
|
||||||
|
|
||||||
|
REGELN:
|
||||||
|
1. Die Kanten haben das Format "typ:ziel". Der "typ" ist variabel und kann ALLES sein (z.B. uses, blocks, inspired_by, loves, etc.).
|
||||||
|
2. Gib NUR die Strings aus der Kandidaten-Liste zurück, die zum Text passen.
|
||||||
|
3. Erfinde KEINE neuen Kanten. Nutze exakt die Schreibweise aus der Liste.
|
||||||
|
4. Antworte als flache JSON-Liste.
|
||||||
|
|
||||||
|
BEISPIEL (Zur Demonstration der Logik):
|
||||||
|
Input Text: "Das Projekt Alpha scheitert, weil Budget fehlt."
|
||||||
|
Input Kandidaten: ["blocks:Projekt Alpha", "inspired_by:Buch der Weisen", "needs:Budget"]
|
||||||
|
Output: ["blocks:Projekt Alpha", "needs:Budget"]
|
||||||
|
|
||||||
|
DEIN OUTPUT (JSON):
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# config/prompts.yaml — Persönlichkeit & RAG-Strategie
|
||||||
|
# Version: 2.0 (Audit Update)
|
||||||
|
|
||||||
|
system_prompt: |
|
||||||
|
Du bist 'mindnet', ein persönliches KI-Gedächtnis und der Digitale Zwilling deines Erschaffers ("User").
|
||||||
|
|
||||||
|
DEINE PERSÖNLICHKEIT & WERTE:
|
||||||
|
1. Pragmatismus: Du bevorzugst funktionierende Lösungen über theoretische Perfektion.
|
||||||
|
2. Transparenz: Du erfindest keine Fakten. Wenn Informationen im Kontext fehlen, sagst du das klar.
|
||||||
|
3. Vernetztes Denken: Du suchst aktiv nach Verbindungen zwischen den bereitgestellten Notizen.
|
||||||
|
4. Erklärbarkeit: Wenn du eine Aussage machst, beziehst du dich implizit auf die Quelle (z.B. "Wie in Projekt X definiert...").
|
||||||
|
|
||||||
|
DEINE AUFGABE:
|
||||||
|
Beantworte die Frage des Users ausschließlich basierend auf dem untenstehenden KONTEXT.
|
||||||
|
Der Kontext besteht aus Auszügen verschiedener Notizen. Achte besonders auf den [TYPE] der Notiz:
|
||||||
|
- [DECISION] erklärt das "Warum".
|
||||||
|
- [PROJECT] erklärt das "Was" und "Wann".
|
||||||
|
- [CONCEPT] liefert Definitionen.
|
||||||
|
- [VALUE] definiert die moralische/strategische Ausrichtung.
|
||||||
|
|
||||||
|
rag_template: |
|
||||||
|
HINTERGRUNDWISSEN (KONTEXT):
|
||||||
|
=========================================
|
||||||
|
{context_str}
|
||||||
|
=========================================
|
||||||
|
|
||||||
|
FRAGE DES USERS:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
ANWEISUNG:
|
||||||
|
Analysiere die Quellen oben. Synthetisiere eine Antwort, die die Frage präzise beantwortet.
|
||||||
|
Nutze Markdown für Struktur (Fettgedrucktes für Wichtiges).
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
system_prompt: |
|
||||||
|
Du bist 'mindnet', ein persönliches KI-Gedächtnis.
|
||||||
|
|
||||||
|
DEINE REGELN:
|
||||||
|
1. Antworte NUR basierend auf dem untenstehenden KONTEXT.
|
||||||
|
2. Achte auf den TYP der Quelle:
|
||||||
|
- [DECISION] enthält Begründungen (Warum?).
|
||||||
|
- [PROJECT] enthält Ziele (Was?).
|
||||||
|
- [CONCEPT] enthält Definitionen.
|
||||||
|
3. Sei präzise. Nenne konkrete technische Gründe, wenn sie im Text stehen.
|
||||||
|
4. Halluziniere nicht.
|
||||||
|
|
||||||
|
rag_template: |
|
||||||
|
KONTEXT (WISSEN):
|
||||||
|
=========================================
|
||||||
|
{context_str}
|
||||||
|
=========================================
|
||||||
|
|
||||||
|
FRAGE:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
ANWEISUNG:
|
||||||
|
Analysiere den Kontext. Wenn eine [DECISION] Quelle dabei ist, nutze deren Inhalt für die Begründung.
|
||||||
|
Antworte kurz und präzise auf Deutsch.
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
version: 1.0
|
||||||
|
|
||||||
|
scoring:
|
||||||
|
# W_sem: skaliert den Term (semantic_score * retriever_weight)
|
||||||
|
# Empfehlung Startwert: 1.0 → Semantik bleibt Hauptsignal
|
||||||
|
semantic_weight: 1.0
|
||||||
|
|
||||||
|
# W_edge: skaliert edge_bonus aus dem Subgraph
|
||||||
|
# Empfehlung: 0.7 → Graph ist deutlich spürbar, aber überstimmt Semantik nicht komplett
|
||||||
|
edge_weight: 0.7
|
||||||
|
|
||||||
|
# W_cent: skaliert centrality_bonus (Knoten-Zentralität im Subgraph)
|
||||||
|
# Empfehlung: 0.5 → zentrale Knoten werden bevorzugt, aber moderat
|
||||||
|
centrality_weight: 0.5
|
||||||
|
|
||||||
|
# Die nachfolgenden Werte überschreiben die Defaults aus app/core/retriever_config.
|
||||||
|
# Wenn neue Kantentypen, z.B. durch Referenzierung innerhalb einer md-Datei im vault anders gewichtet werden sollen, dann muss hier die Konfiguration erfolgen
|
||||||
|
edge_types:
|
||||||
|
references: 0.20
|
||||||
|
depends_on: 0.18
|
||||||
|
related_to: 0.15
|
||||||
|
similar_to: 0.12
|
||||||
|
belongs_to: 0.10
|
||||||
|
next: 0.06
|
||||||
|
prev: 0.06
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
version: 2.6.0 # Final WP-15 Config: Smart Edges & Strict/Soft Chunking
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# 1. CHUNKING PROFILES
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
|
chunking_profiles:
|
||||||
|
|
||||||
|
# A. SHORT & FAST
|
||||||
|
sliding_short:
|
||||||
|
strategy: sliding_window
|
||||||
|
enable_smart_edge_allocation: false
|
||||||
|
target: 200
|
||||||
|
max: 350
|
||||||
|
overlap: [30, 50]
|
||||||
|
|
||||||
|
# B. STANDARD & FAST
|
||||||
|
sliding_standard:
|
||||||
|
strategy: sliding_window
|
||||||
|
enable_smart_edge_allocation: false
|
||||||
|
target: 450
|
||||||
|
max: 650
|
||||||
|
overlap: [50, 100]
|
||||||
|
|
||||||
|
# C. SMART FLOW (Text-Fluss)
|
||||||
|
# Nutzt Sliding Window, aber mit LLM-Kanten-Analyse.
|
||||||
|
sliding_smart_edges:
|
||||||
|
strategy: sliding_window
|
||||||
|
enable_smart_edge_allocation: true
|
||||||
|
target: 400
|
||||||
|
max: 600
|
||||||
|
overlap: [50, 80]
|
||||||
|
|
||||||
|
# D. SMART STRUCTURE (Soft Split)
|
||||||
|
# Trennt bevorzugt an H2, fasst aber kleine Abschnitte zusammen ("Soft Mode").
|
||||||
|
structured_smart_edges:
|
||||||
|
strategy: by_heading
|
||||||
|
enable_smart_edge_allocation: true
|
||||||
|
split_level: 2
|
||||||
|
strict_heading_split: false
|
||||||
|
max: 600
|
||||||
|
target: 400
|
||||||
|
overlap: [50, 80]
|
||||||
|
|
||||||
|
# E. SMART STRUCTURE STRICT (H2 Hard Split)
|
||||||
|
# Trennt ZWINGEND an jeder H2.
|
||||||
|
# Verhindert, dass "Vater" und "Partner" (Profile) oder Werte verschmelzen.
|
||||||
|
structured_smart_edges_strict:
|
||||||
|
strategy: by_heading
|
||||||
|
enable_smart_edge_allocation: true
|
||||||
|
split_level: 2
|
||||||
|
strict_heading_split: true # Hard Mode
|
||||||
|
max: 600
|
||||||
|
target: 400
|
||||||
|
overlap: [50, 80]
|
||||||
|
|
||||||
|
# F. SMART STRUCTURE DEEP (H3 Hard Split + Merge-Check)
|
||||||
|
# Spezialfall für "Leitbild Prinzipien":
|
||||||
|
# - Trennt H1, H2, H3 hart.
|
||||||
|
# - Aber: Merged "leere" H2 (Tier 2) mit der folgenden H3 (MP1).
|
||||||
|
structured_smart_edges_strict_L3:
|
||||||
|
strategy: by_heading
|
||||||
|
enable_smart_edge_allocation: true
|
||||||
|
split_level: 3
|
||||||
|
strict_heading_split: true
|
||||||
|
max: 600
|
||||||
|
target: 400
|
||||||
|
overlap: [50, 80]
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# 2. DEFAULTS
|
||||||
|
# ==============================================================================
|
||||||
|
defaults:
|
||||||
|
retriever_weight: 1.0
|
||||||
|
chunking_profile: sliding_standard
|
||||||
|
edge_defaults: []
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# 3. TYPE DEFINITIONS
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
|
types:
|
||||||
|
|
||||||
|
# --- KERNTYPEN ---
|
||||||
|
|
||||||
|
experience:
|
||||||
|
chunking_profile: sliding_smart_edges
|
||||||
|
retriever_weight: 0.90
|
||||||
|
edge_defaults: ["derived_from", "references"]
|
||||||
|
detection_keywords: ["passiert", "erlebt", "gefühl", "situation", "reaktion"]
|
||||||
|
schema:
|
||||||
|
- "Situation (Was ist passiert?)"
|
||||||
|
- "Meine Reaktion (Was habe ich getan?)"
|
||||||
|
- "Ergebnis & Auswirkung"
|
||||||
|
- "Reflexion & Learning (Was lerne ich daraus?)"
|
||||||
|
|
||||||
|
project:
|
||||||
|
chunking_profile: sliding_smart_edges
|
||||||
|
retriever_weight: 0.97
|
||||||
|
edge_defaults: ["references", "depends_on"]
|
||||||
|
detection_keywords: ["projekt", "vorhaben", "ziel ist", "planen", "starten"]
|
||||||
|
schema:
|
||||||
|
- "Mission & Zielsetzung"
|
||||||
|
- "Aktueller Status & Blockaden"
|
||||||
|
- "Nächste konkrete Schritte"
|
||||||
|
|
||||||
|
decision:
|
||||||
|
# Strict, damit jede Entscheidung atomar bleibt
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
retriever_weight: 1.00
|
||||||
|
edge_defaults: ["caused_by", "references"]
|
||||||
|
detection_keywords: ["entschieden", "wahl", "optionen", "alternativen", "adr"]
|
||||||
|
schema:
|
||||||
|
- "Kontext & Problemstellung"
|
||||||
|
- "Betrachtete Optionen"
|
||||||
|
- "Die Entscheidung"
|
||||||
|
- "Begründung"
|
||||||
|
|
||||||
|
# --- PERSÖNLICHKEIT & IDENTITÄT ---
|
||||||
|
|
||||||
|
value:
|
||||||
|
# Strict, damit Werte nicht verschwimmen
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
retriever_weight: 1.00
|
||||||
|
edge_defaults: ["related_to"]
|
||||||
|
detection_keywords: ["wert", "wichtig ist", "moral", "ethik"]
|
||||||
|
schema: ["Definition", "Warum mir das wichtig ist", "Leitsätze"]
|
||||||
|
|
||||||
|
principle:
|
||||||
|
# L3 Strict für P3/P3a und Tier2/MP1 Logik
|
||||||
|
chunking_profile: structured_smart_edges_strict_L3
|
||||||
|
retriever_weight: 0.95
|
||||||
|
edge_defaults: ["derived_from", "references"]
|
||||||
|
detection_keywords: ["prinzip", "regel", "grundsatz", "leitlinie"]
|
||||||
|
schema: ["Das Prinzip", "Anwendung & Beispiele"]
|
||||||
|
|
||||||
|
belief:
|
||||||
|
chunking_profile: sliding_short
|
||||||
|
retriever_weight: 0.90
|
||||||
|
edge_defaults: ["related_to"]
|
||||||
|
schema: ["Der Glaubenssatz", "Ursprung & Reflexion"]
|
||||||
|
|
||||||
|
profile:
|
||||||
|
# Strict: Jede Rolle (H2) muss ein eigener Chunk sein
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
retriever_weight: 0.70
|
||||||
|
edge_defaults: ["references", "related_to"]
|
||||||
|
schema: ["Rolle / Identität", "Fakten & Daten", "Historie"]
|
||||||
|
|
||||||
|
# --- STRATEGIE & RISIKO ---
|
||||||
|
|
||||||
|
goal:
|
||||||
|
chunking_profile: sliding_smart_edges
|
||||||
|
retriever_weight: 0.95
|
||||||
|
edge_defaults: ["depends_on", "related_to"]
|
||||||
|
schema: ["Zielzustand", "Zeitrahmen & KPIs", "Motivation"]
|
||||||
|
|
||||||
|
risk:
|
||||||
|
chunking_profile: sliding_short
|
||||||
|
retriever_weight: 0.85
|
||||||
|
edge_defaults: ["related_to", "blocks"]
|
||||||
|
detection_keywords: ["risiko", "gefahr", "bedrohung"]
|
||||||
|
schema: ["Beschreibung des Risikos", "Auswirkungen", "Gegenmaßnahmen"]
|
||||||
|
|
||||||
|
# --- BASIS & WISSEN ---
|
||||||
|
|
||||||
|
concept:
|
||||||
|
chunking_profile: sliding_smart_edges
|
||||||
|
retriever_weight: 0.60
|
||||||
|
edge_defaults: ["references", "related_to"]
|
||||||
|
schema: ["Definition", "Kontext", "Verwandte Konzepte"]
|
||||||
|
|
||||||
|
task:
|
||||||
|
chunking_profile: sliding_short
|
||||||
|
retriever_weight: 0.80
|
||||||
|
edge_defaults: ["depends_on", "part_of"]
|
||||||
|
schema: ["Aufgabe", "Kontext", "Definition of Done"]
|
||||||
|
|
||||||
|
journal:
|
||||||
|
chunking_profile: sliding_standard
|
||||||
|
retriever_weight: 0.80
|
||||||
|
edge_defaults: ["references", "related_to"]
|
||||||
|
schema: ["Log-Eintrag", "Gedanken"]
|
||||||
|
|
||||||
|
source:
|
||||||
|
chunking_profile: sliding_standard
|
||||||
|
retriever_weight: 0.50
|
||||||
|
edge_defaults: []
|
||||||
|
schema: ["Metadaten", "Zusammenfassung", "Zitate"]
|
||||||
|
|
||||||
|
glossary:
|
||||||
|
chunking_profile: sliding_short
|
||||||
|
retriever_weight: 0.40
|
||||||
|
edge_defaults: ["related_to"]
|
||||||
|
schema: ["Begriff", "Definition"]
|
||||||
|
|
||||||
|
person:
|
||||||
|
chunking_profile: sliding_standard
|
||||||
|
retriever_weight: 0.50
|
||||||
|
edge_defaults: ["related_to"]
|
||||||
|
schema: ["Rolle", "Beziehung", "Kontext"]
|
||||||
|
|
||||||
|
event:
|
||||||
|
chunking_profile: sliding_standard
|
||||||
|
retriever_weight: 0.60
|
||||||
|
edge_defaults: ["related_to"]
|
||||||
|
schema: ["Datum & Ort", "Teilnehmer", "Ergebnisse"]
|
||||||
|
|
||||||
|
# --- FALLBACK ---
|
||||||
|
|
||||||
|
default:
|
||||||
|
chunking_profile: sliding_standard
|
||||||
|
retriever_weight: 1.00
|
||||||
|
edge_defaults: ["references"]
|
||||||
|
schema: ["Inhalt"]
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
# Mindnet v2.6 – Documentation Map & Governance
|
||||||
|
**Status:** Active
|
||||||
|
**Context:** Central Navigation & Maintenance Guide
|
||||||
|
|
||||||
|
## 1. Zweck dieses Dokuments
|
||||||
|
|
||||||
|
Diese Karte dient Entwicklern, dem Mindmaster und KI-Agenten als **zentraler Einstiegspunkt**. Sie beantwortet zwei Fragen:
|
||||||
|
1. **Navigation:** In welcher Datei finde ich Informationen zu Thema X?
|
||||||
|
2. **Wartung:** Ich arbeite an Feature Y – welche Dateien muss ich aktualisieren?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Verzeichnisstruktur & Inhalte
|
||||||
|
|
||||||
|
Das Repository ist in **logische Domänen** unterteilt.
|
||||||
|
|
||||||
|
### 📂 00_General (Grundlagen)
|
||||||
|
*Zielgruppe: Alle*
|
||||||
|
| Datei | Inhalt & Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `00_vision_and_strategy.md` | **Strategie.** Warum bauen wir das? Prinzipien (Privacy, Local-First), High-Level Architektur. |
|
||||||
|
| `00_glossary.md` | **Definitionen.** Was bedeutet "Smart Edge", "Traffic Control", "Chunk"? Verhindert Begriffsverwirrung. |
|
||||||
|
| `00_documentation_map.md` | **Dieser Index.** Navigationshilfe. |
|
||||||
|
|
||||||
|
### 📂 01_User_Manual (Anwendung)
|
||||||
|
*Zielgruppe: Mindmaster, Autoren, Power-User*
|
||||||
|
| Datei | Inhalt & Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `01_chat_usage_guide.md` | **Bedienung.** Wie steuere ich die Personas (Berater, Spiegel)? Wie nutze ich das Feedback? |
|
||||||
|
| `01_knowledge_design.md` | **Content-Regeln.** Die "Bibel" für den Vault. Erklärt Note-Typen, Matrix-Logik und Markdown-Syntax. |
|
||||||
|
|
||||||
|
### 📂 02_Concepts (Fachliche Logik)
|
||||||
|
*Zielgruppe: Architekten, Product Owner*
|
||||||
|
| Datei | Inhalt & Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `02_concept_graph_logic.md` | **Graph-Theorie.** Abstrakte Erklärung von Knoten, Kanten, Provenance und Idempotenz. |
|
||||||
|
| `02_concept_ai_personality.md`| **KI-Verhalten.** Konzepte hinter dem Hybrid Router, Empathie-Modell und "Teach-the-AI". |
|
||||||
|
|
||||||
|
### 📂 03_Technical_Reference (Technik & Code)
|
||||||
|
*Zielgruppe: Entwickler, DevOps. (Enthält JSON/YAML Beispiele)*
|
||||||
|
| Datei | Inhalt & Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `03_tech_data_model.md` | **Datenbank.** Exakte Qdrant-Schemas (Payloads) und Index-Anforderungen. |
|
||||||
|
| `03_tech_ingestion_pipeline.md`| **Import.** Ablauflogik (13 Schritte), Chunker-Profile, Smart Edge Allocation. |
|
||||||
|
| `03_tech_retrieval_scoring.md` | **Suche.** Die mathematischen Formeln für Scoring, Hybrid Search und Explanation Layer. |
|
||||||
|
| `03_tech_chat_backend.md` | **API & LLM.** Implementation des Routers, Traffic Control (Semaphore) und Feedback-Traceability. |
|
||||||
|
| `03_tech_frontend.md` | **UI & Graph.** Architektur des Streamlit-Frontends, State-Management, Cytoscape-Integration und Editor-Logik. |
|
||||||
|
| `03_tech_configuration.md` | **Config.** Referenztabellen für `.env`, `types.yaml` und `retriever.yaml`. |
|
||||||
|
|
||||||
|
### 📂 04_Operations (Betrieb)
|
||||||
|
*Zielgruppe: Administratoren*
|
||||||
|
| Datei | Inhalt & Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `04_admin_operations.md` | **Runbook.** Installation, Docker-Setup, Backup/Restore, Troubleshooting Guide. |
|
||||||
|
|
||||||
|
### 📂 05_Development (Code)
|
||||||
|
*Zielgruppe: Entwickler*
|
||||||
|
| Datei | Inhalt & Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `05_developer_guide.md` | **Workflow.** Hardware-Setup (Win/Pi/Beelink), Git-Flow, Test-Befehle, Modul-Interna. |
|
||||||
|
| `05_genai_best_practices.md` | **AI Workflow.** Prompt-Library, Templates und Best Practices für die Entwicklung mit LLMs. |
|
||||||
|
|
||||||
|
### 📂 06_Roadmap & 99_Archive
|
||||||
|
*Zielgruppe: Projektleitung*
|
||||||
|
| Datei | Inhalt & Zweck |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `06_active_roadmap.md` | **Zukunft.** Aktive Workpackages (WP16+), Release-Planung und WP-Historie (Tabelle). |
|
||||||
|
| `99_legacy_workpackages.md` | **Vergangenheit.** Detaillierte Archivdaten zu abgeschlossenen WPs (WP01–WP15). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Maintenance Guide: "Welche Datei muss ich ändern?"
|
||||||
|
|
||||||
|
Nutze diese Matrix, wenn du ein Workpackage bearbeitest, um die Dokumentation konsistent zu halten.
|
||||||
|
|
||||||
|
| Wenn du arbeitest an... | ...aktualisiere diese Dateien: |
|
||||||
|
| :--- | :--- |
|
||||||
|
| **Neuen Note-Typen** | 1. `01_knowledge_design.md` (Für Autoren)<br>2. `03_tech_configuration.md` (Technische Referenz)<br>3. `05_developer_guide.md` (Erweiterungs-How-To) |
|
||||||
|
| **Importer / Parsing** | `03_tech_ingestion_pipeline.md` |
|
||||||
|
| **Datenbank-Schema** | `03_tech_data_model.md` (Payloads anpassen) |
|
||||||
|
| **Retrieval / Scoring** | `03_tech_retrieval_scoring.md` (Formeln anpassen) |
|
||||||
|
| **Frontend / Visualisierung** | 1. `03_tech_frontend.md` (Technische Details)<br>2. `01_chat_usage_guide.md` (Bedienung) |
|
||||||
|
| **Chat-Logik / Prompts**| 1. `02_concept_ai_personality.md` (Konzept)<br>2. `03_tech_chat_backend.md` (Tech)<br>3. `01_chat_usage_guide.md` (User-Sicht) |
|
||||||
|
| **Deployment / Server** | `04_admin_operations.md` |
|
||||||
|
| **Neuen Features (Allg.)**| `06_active_roadmap.md` (Status Update) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Prinzipien für die Dokumentation (Governance)
|
||||||
|
|
||||||
|
Damit dieses System wartbar bleibt (auch für KI-Agenten wie NotebookLM), gelten folgende Regeln:
|
||||||
|
|
||||||
|
1. **Single Source of Truth:**
|
||||||
|
Kopiere keine Informationen. Referenziere sie.
|
||||||
|
* *Ausnahme:* Konkrete JSON-Beispiele in `03_Technical_Reference`. Diese müssen dort stehen, damit Entwickler nicht suchen müssen.
|
||||||
|
|
||||||
|
2. **Konkrete Beispiele:**
|
||||||
|
Technische Dokumente (`03_*`) müssen **immer** Code-Snippets (JSON, YAML, Shell) enthalten. Abstrakte Beschreibungen reichen nicht für die Implementierung.
|
||||||
|
|
||||||
|
3. **Human Readable:**
|
||||||
|
User Manuals (`01_*`) müssen Narrative und Szenarien enthalten ("Stell dir vor..."), keine technischen Auflistungen.
|
||||||
|
|
||||||
|
4. **KI-Optimiert (Context Header):**
|
||||||
|
Jede Datei muss mit einem YAML-Frontmatter beginnen, der `context`, `audience` und `scope` definiert. Dies hilft RAG-Systemen, den Inhalt korrekt einzuordnen.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer
|
||||||
|
context: "Beschreibung der Scoring-Formel."
|
||||||
|
---
|
||||||
|
```
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
---
|
||||||
|
doc_type: glossary
|
||||||
|
audience: all
|
||||||
|
status: active
|
||||||
|
version: 2.6.0
|
||||||
|
context: "Definitionen zentraler Begriffe und Entitäten im Mindnet-System."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet Glossar
|
||||||
|
|
||||||
|
**Quellen:** `appendix.md`, `Overview.md`
|
||||||
|
|
||||||
|
## Kern-Entitäten
|
||||||
|
|
||||||
|
* **Note:** Repräsentiert eine Markdown-Datei. Die fachliche Haupteinheit.
|
||||||
|
* **Chunk:** Ein Textabschnitt einer Note. Die technische Sucheinheit (Vektor). Durch neue Strategien kann dies ein Fließtext-Abschnitt oder ein logisches Kapitel (Heading) sein.
|
||||||
|
* **Edge:** Eine gerichtete Verbindung zwischen zwei Knoten (Chunks oder Notes).
|
||||||
|
* **Vault:** Der lokale Ordner mit den Markdown-Dateien (Source of Truth).
|
||||||
|
* **Frontmatter:** Der YAML-Header am Anfang einer Notiz (enthält `id`, `type`, `title`).
|
||||||
|
|
||||||
|
## Komponenten
|
||||||
|
|
||||||
|
* **Importer:** Das Python-Skript (`import_markdown.py`), das Markdown liest und in Qdrant schreibt.
|
||||||
|
* **Retriever:** Die Komponente, die sucht. Nutzt hybrides Scoring (Semantik + Graph).
|
||||||
|
* **Decision Engine:** Teil des Routers, der entscheidet, wie auf eine Anfrage reagiert wird (z.B. Strategie wählen).
|
||||||
|
* **Hybrid Router v5:** Die Logik, die erkennt, ob der User eine Frage stellt (`RAG`) oder einen Befehl gibt (`INTERVIEW`).
|
||||||
|
* **Draft Editor:** Die Web-UI-Komponente, in der generierte Notizen bearbeitet werden.
|
||||||
|
* **Traffic Control (WP15):** Ein Mechanismus im `LLMService`, der Prioritäten verwaltet (`realtime` für Chat vs. `background` für Import) und Hintergrund-Tasks mittels Semaphoren drosselt.
|
||||||
|
|
||||||
|
## Konzepte & Features
|
||||||
|
|
||||||
|
* **Active Intelligence:** Feature im Web-Editor, das während des Schreibens automatisch Links vorschlägt.
|
||||||
|
* **Smart Edge Allocation (WP15):** Ein KI-Verfahren, das prüft, ob ein Link in einer Notiz für einen spezifischen Textabschnitt relevant ist, statt ihn blind allen Chunks zuzuordnen.
|
||||||
|
* **Strict Heading Split:** Chunking-Strategie, bei der Überschriften (z.B. H2) als harte Grenzen dienen. Verhindert das Vermischen von Themen (z.B. zwei unterschiedliche Rollen in einem Chunk). Besitzt ein "Safety Net" für zu lange Abschnitte.
|
||||||
|
* **Soft Heading Split:** Chunking-Strategie, die Überschriften respektiert, aber kleine Abschnitte zusammenfasst, um Vektor-Kontext zu füllen ("Fuller Chunks").
|
||||||
|
* **Healing Parser:** UI-Funktion, die fehlerhaften Output des LLMs (z.B. defektes YAML) automatisch repariert.
|
||||||
|
* **Explanation Layer:** Die Schicht, die dem Nutzer erklärt, *warum* ein Suchergebnis gefunden wurde (z.B. "Weil Projekt X davon abhängt").
|
||||||
|
* **Provenance:** Die Herkunft einer Kante.
|
||||||
|
* `explicit`: Vom Mensch geschrieben.
|
||||||
|
* `smart`: Vom LLM validiert.
|
||||||
|
* `rule`: Durch Config-Regel erzeugt.
|
||||||
|
* **Matrix Logic:** Regelwerk, das den Typ einer Kante basierend auf Quell- und Ziel-Typ bestimmt (z.B. Erfahrung -> Wert = `based_on`).
|
||||||
|
* **Idempotenz:** Die Eigenschaft des Importers, bei mehrfacher Ausführung dasselbe Ergebnis zu liefern ohne Duplikate.
|
||||||
|
* **Resurrection Pattern:** UI-Technik, um User-Eingaben beim Tab-Wechsel zu erhalten.
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
---
|
||||||
|
doc_type: strategy
|
||||||
|
audience: all
|
||||||
|
status: active
|
||||||
|
version: 2.6
|
||||||
|
context: "Vision, Mission und Architekturprinzipien von Mindnet."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet Vision & Strategie
|
||||||
|
|
||||||
|
**Quellen:** `Programmplan_V2.2.md`
|
||||||
|
|
||||||
|
## 1. Programmauftrag
|
||||||
|
|
||||||
|
Mindnet v2.6 entwickelt ein persönliches, wachsendes KI-Gedächtnis. Es ist ein **Digitaler Zwilling**, der:
|
||||||
|
- Wissen, Erfahrungen und Werte speichert.
|
||||||
|
- Semantisch verknüpft (Graphen-basiert).
|
||||||
|
- Als Dialogpartner agiert (RAG-Chat).
|
||||||
|
- **Lokal und privat** läuft (Privacy First).
|
||||||
|
|
||||||
|
Es ist **kein statisches Archiv**, sondern ein lebendes System, das durch Interaktion (Feedback, Smart Edges) besser wird.
|
||||||
|
|
||||||
|
## 2. Vision
|
||||||
|
|
||||||
|
> „Ein persönliches semantisches Gedächtnis, das mit mir wächst, meine Persönlichkeit spiegelt und mir als intelligenter, erklärbarer, lernender Begleiter dient.“
|
||||||
|
|
||||||
|
**Kernprinzipien der Vision:**
|
||||||
|
* **Erklärbarkeit:** Jede Antwort muss begründbar sein ("Why-Layer").
|
||||||
|
* **Wachstum:** Das System startet klein und verdichtet sich.
|
||||||
|
* **Autonomie:** Es schlägt fehlende Kanten selbstständig vor (Smart Edges).
|
||||||
|
* **Persönlichkeit:** Es entscheidet basierend auf *deinen* Werten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Architekturprinzipien
|
||||||
|
|
||||||
|
Die folgenden Prinzipien steuern jede technische Entscheidung:
|
||||||
|
|
||||||
|
1. **Late Binding (Späte Semantik):**
|
||||||
|
Struktur und Interpretation werden in Konfigurationen (`types.yaml`, `prompts.yaml`) definiert, nicht direkt in den Vault-Dateien. Die "Persönlichkeit" ist Config, kein Code.
|
||||||
|
|
||||||
|
2. **Virtual Schema Layer:**
|
||||||
|
Markdown-Dateien benötigen nur minimale, robuste Angaben (Frontmatter). Komplexität (Chunk-Größe, Gewichte) wird zur Laufzeit injiziert.
|
||||||
|
|
||||||
|
3. **Self-Healing Graph:**
|
||||||
|
Der Graph wird regelmäßig auf Konsistenz geprüft. "Dangling Edges" werden bereinigt, fehlende Links durch Smart Edges ergänzt.
|
||||||
|
|
||||||
|
4. **Deterministische IDs:**
|
||||||
|
Notes und Chunks erhalten stabile IDs (UUIDv5). Der Graph ist jederzeit aus dem Markdown wiederaufbaubar.
|
||||||
|
|
||||||
|
5. **Full Explainability:**
|
||||||
|
Keine Blackbox. Jede Antwort liefert Metadaten (`[DECISION]`, `[PROJECT]`) und Begründungen.
|
||||||
|
|
||||||
|
6. **Persistence First:**
|
||||||
|
Obsidian (Markdown) bleibt die **einzige Quelle der Wahrheit**. Die Datenbank ist nur ein abgeleiteter Cache.
|
||||||
|
|
||||||
|
7. **Minimalinvasives Schreiben:**
|
||||||
|
Mindnet schreibt nie ungefragt in deine Notizen. Änderungen erfolgen nur über den Draft Editor oder mit expliziter Zustimmung.
|
||||||
|
|
||||||
|
8. **Incremental Growth:**
|
||||||
|
Das System muss bereits mit wenigen Notizen nützlich sein.
|
||||||
|
|
||||||
|
9. **Observability:**
|
||||||
|
Jeder Importlauf und jede Retriever-Anfrage ist logbar.
|
||||||
|
|
||||||
|
10. **Local First & Privacy:**
|
||||||
|
Nutzung lokaler LLMs (Ollama) für Inference. Keine Daten verlassen den Server.
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
---
|
||||||
|
doc_type: user_manual
|
||||||
|
audience: user, mindmaster
|
||||||
|
scope: chat, ui, feedback, graph
|
||||||
|
status: active
|
||||||
|
version: 2.6
|
||||||
|
context: "Anleitung zur Nutzung der Web-Oberfläche, der Chat-Personas und des Graph Explorers."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Chat & Graph Usage Guide
|
||||||
|
|
||||||
|
**Quellen:** `user_guide.md`
|
||||||
|
|
||||||
|
## 1. Was Mindnet für dich tut
|
||||||
|
|
||||||
|
Mindnet ist ein **assoziatives Gedächtnis** mit Persönlichkeit. Es unterscheidet sich von einer reinen Suche dadurch, dass es **kontextsensitiv** agiert.
|
||||||
|
|
||||||
|
**Das Gedächtnis (Der Graph):**
|
||||||
|
Wenn du nach "Projekt Alpha" suchst, findet Mindnet auch:
|
||||||
|
* **Abhängigkeiten:** "Technologie X wird benötigt".
|
||||||
|
* **Entscheidungen:** "Warum nutzen wir X?".
|
||||||
|
* **Ähnliches:** "Projekt Beta war ähnlich".
|
||||||
|
|
||||||
|
**Der Zwilling (Die Personas):**
|
||||||
|
Mindnet passt seinen Charakter an: Mal ist es der neutrale Bibliothekar, mal der strategische Berater, mal der empathische Spiegel.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Die Oberfläche (Web UI)
|
||||||
|
|
||||||
|
Seit Version 2.3.1 bedienst du Mindnet über eine grafische Oberfläche im Browser.
|
||||||
|
|
||||||
|
### 2.1 Der Chat-Bereich
|
||||||
|
* **Intent-Badge:** Über jeder Antwort siehst du ein Label (z.B. **⚖️ Intent: DECISION**).
|
||||||
|
* **Quellen-Karten:** Unter der Antwort findest du ausklappbare Karten ("Expanders").
|
||||||
|
* **Grüner Punkt:** Hohe Relevanz (Score > 0.8).
|
||||||
|
* **Klick darauf:** Zeigt den Textauszug und die **Begründung** (Explanation Layer).
|
||||||
|
|
||||||
|
### 2.2 Modus: 🕸️ Graph Explorer (Cytoscape)
|
||||||
|
*Neu in v2.6*: Eine interaktive Karte deines Wissens.
|
||||||
|
|
||||||
|
**Die Farb-Logik:**
|
||||||
|
* 🔴 **Roter Rahmen:** Das aktuelle **Zentrum** (Ego). Alle geladenen Knoten sind Nachbarn dieses Knotens.
|
||||||
|
* 🟡 **Gelber Rahmen:** Der **inspizierte** Knoten. Dessen Details siehst du im "Data Inspector" und in der Action-Bar.
|
||||||
|
|
||||||
|
**Bedienung:**
|
||||||
|
1. **Klick auf einen Knoten:** Wählt ihn aus (Gelb). Der Graph bleibt stabil, aber die Info-Leiste oben aktualisiert sich.
|
||||||
|
2. **Button "🎯 Als Zentrum setzen":** Lädt den Graphen neu und macht den ausgewählten Knoten zum roten Zentrum.
|
||||||
|
3. **Button "📝 Bearbeiten":** Springt mit dem Inhalt dieses Knotens direkt in den Editor.
|
||||||
|
|
||||||
|
**Layout & Persistenz:**
|
||||||
|
Du kannst in der linken Spalte die Physik (Abstoßung, Kantenlänge) einstellen. Diese Einstellungen werden in der **URL gespeichert**. Du kannst den Link als Lesezeichen speichern, um genau diese Ansicht wiederzufinden.
|
||||||
|
|
||||||
|
### 2.3 Modus: 📝 Manueller Editor
|
||||||
|
Ein Editor mit **"File System First"** Garantie.
|
||||||
|
* Wenn du eine Datei bearbeitest, liest Mindnet sie direkt von der Festplatte.
|
||||||
|
* **Resurrection:** Wenn du zwischendurch in den Graph wechselst und zurückkommst, ist dein getippter Text noch da.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Den Chat steuern (Intents)
|
||||||
|
|
||||||
|
Du steuerst die Persönlichkeit von Mindnet durch deine Wortwahl. Der **Hybrid Router v5** unterscheidet intelligent:
|
||||||
|
|
||||||
|
### 3.1 Frage-Modus (Wissen abrufen)
|
||||||
|
Ausgelöst durch `?` oder W-Wörter.
|
||||||
|
|
||||||
|
* **Entscheidung ("Soll ich?"):** Der **Berater**.
|
||||||
|
* Mindnet lädt deine Werte (`type: value`) und Ziele (`type: goal`).
|
||||||
|
* *Beispiel:* "Soll ich Tool X nutzen?" -> "Nein, Tool X speichert Daten in den USA. Das verstößt gegen dein Prinzip 'Privacy First'."
|
||||||
|
* **Empathie ("Ich fühle..."):** Der **Spiegel**.
|
||||||
|
* Mindnet lädt deine Erfahrungen (`type: experience`).
|
||||||
|
* *Beispiel:* "Ich bin frustriert." -> "Das erinnert mich an Projekt Y, da ging es uns ähnlich..."
|
||||||
|
* **Fakten ("Was ist?"):** Der **Bibliothekar**.
|
||||||
|
* Liefert präzise Definitionen.
|
||||||
|
|
||||||
|
### 3.2 Befehls-Modus (Interview)
|
||||||
|
Ausgelöst durch Aussagen wie "Neues Projekt", "Ich will festhalten".
|
||||||
|
|
||||||
|
* **Was passiert:** Mindnet sucht nicht, sondern öffnet den **Draft-Editor**.
|
||||||
|
* **Beispiel:** "Neue Erfahrung: Streit am Recyclinghof." -> Das System erstellt sofort eine strukturierte Notiz mit den Feldern "Situation", "Reaktion" und "Learning".
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Ergebnisse interpretieren (Explanation Layer)
|
||||||
|
|
||||||
|
Mindnet liefert eine **Begründung** ("Reasons"), warum es etwas gefunden hat.
|
||||||
|
Öffne eine Quellen-Karte, um zu sehen:
|
||||||
|
* *"Hohe textuelle Übereinstimmung."* (Semantik)
|
||||||
|
* *"Bevorzugt aufgrund des Typs 'decision'."* (Wichtigkeit)
|
||||||
|
* *"Verweist auf 'Projekt X' via 'depends_on'."* (Graph-Kontext)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Feedback & Lernen
|
||||||
|
|
||||||
|
Mindnet wird schlauer, wenn du es pflegst.
|
||||||
|
|
||||||
|
* **Globales Feedback (Sterne):** Bewertet die generierte Antwort (Prompting, Tonfall).
|
||||||
|
* **Granulares Feedback (Smileys):** Bewertet die einzelne Quelle.
|
||||||
|
* 😞 (Sad): Irrelevant. (Senkt das Gewicht dieser Verbindung).
|
||||||
|
* 😀 (Grin): Perfekter Treffer! (Stärkt diesen Typ/Kante).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Neues Wissen beisteuern (Authoring & Intelligence)
|
||||||
|
|
||||||
|
Mindnet lebt von deinem Input. Du hast drei Wege, Wissen einzugeben:
|
||||||
|
|
||||||
|
### 6.1 Weg A: Der Interview-Assistent (Auto-Drafting)
|
||||||
|
1. **Start:** Schreibe im Chat: *"Ich möchte ein neues Projekt 'Apollo' starten."*
|
||||||
|
2. **Generierung:** Mindnet erkennt `INTERVIEW`, wählt das Schema und erstellt einen Entwurf.
|
||||||
|
3. **Editor:** Die UI zeigt den Entwurf (`status: draft`).
|
||||||
|
* *Healing UI:* Falls das LLM Syntax-Fehler gemacht hat, hat der Editor sie bereits repariert.
|
||||||
|
4. **Speichern:** Klicke auf "💾 Speichern".
|
||||||
|
|
||||||
|
### 6.2 Weg B: Der Intelligence-Workflow
|
||||||
|
Wenn du im **manuellen Editor** schreibst, unterstützt dich Mindnet aktiv bei der Vernetzung:
|
||||||
|
|
||||||
|
1. **Schreiben:** Tippe deinen Text im Tab **"✏️ Inhalt"**.
|
||||||
|
2. **Analysieren:** Wechsle zum Tab **"🧠 Intelligence"** und klicke auf **"🔍 Analyse starten"**. Das System scannt deinen Text (Vektor-Suche & Exact Match).
|
||||||
|
3. **Vorschläge nutzen:**
|
||||||
|
* **Exakte Treffer:** Das System erkennt Begriffe wie "KI-Gedächtnis" als Alias für "Mindnet".
|
||||||
|
* **Semantische Treffer:** Das System findet inhaltlich verwandte Notizen.
|
||||||
|
* **Klick auf "➕ Einfügen":** Fügt den Link (z.B. `[[rel:related_to Mindnet]]`) an der Cursor-Position ein.
|
||||||
|
4. **Speichern:** Der Text wird sofort in den Vault geschrieben und indiziert.
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
---
|
||||||
|
doc_type: user_manual
|
||||||
|
audience: user, author
|
||||||
|
scope: vault, markdown, schema
|
||||||
|
status: active
|
||||||
|
version: 2.7.0
|
||||||
|
context: "Regelwerk für das Erstellen von Notizen im Vault. Die 'Source of Truth' für Autoren."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Knowledge Design Manual
|
||||||
|
|
||||||
|
**Quellen:** `knowledge_design.md`, `TYPE_REGISTRY_MANUAL.md`
|
||||||
|
|
||||||
|
## ⚡ Die 5 Goldenen Regeln (TL;DR)
|
||||||
|
|
||||||
|
Damit Mindnet als dein Digitaler Zwilling funktioniert, beachte beim Schreiben diese Grundsätze:
|
||||||
|
|
||||||
|
1. **Atomare Gedanken:** Eine Notiz = Ein Thema. Wenn du über zwei Projekte schreibst, mach zwei Notizen draus.
|
||||||
|
2. **Explizite Typen:** Setze immer den `type` im Frontmatter. Mindnet behandelt eine `decision` ("Wir machen X") völlig anders als ein `concept` ("Was ist X").
|
||||||
|
3. **Semantische Links:** Schreibe nicht nur `[[Link]]`, sondern `[[rel:depends_on Link]]`. Sag dem System *wie* Dinge zusammenhängen.
|
||||||
|
4. **Werte & Ziele definieren:** Damit die **Decision Engine** dich beraten kann, musst du deine Kriterien (`type: value`, `type: goal`) explizit als Notizen anlegen.
|
||||||
|
5. **Emotionales Bridging:** Damit die **Empathie** funktioniert, nutze in Erfahrungsberichten (`type: experience`) emotionale Schlüsselwörter ("Krise", "Freude", "Angst").
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Zweck & Scope
|
||||||
|
|
||||||
|
Mindnet ist mehr als eine Dokumentablage. Es ist ein vernetztes System, das deine Persönlichkeit abbildet. Die Markdown-Dateien in deinem Vault sind die **einzige Quelle der Wahrheit** ("Source of Truth"). Was nicht im Markdown steht, existiert für das System nicht.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Note-Struktur & Frontmatter
|
||||||
|
|
||||||
|
Jede Notiz benötigt einen YAML-Header (Frontmatter).
|
||||||
|
|
||||||
|
**Pflichtfelder:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
id: 20251212-projekt-alpha # Eindeutige Kennung (YYYYMMDD-slug empfohlen)
|
||||||
|
title: Projekt Alpha # Sprechender Titel
|
||||||
|
type: project # Steuert Chunking & Wichtigkeit
|
||||||
|
status: active # active, archived, draft
|
||||||
|
created: 2025-12-12 # ISO 8601
|
||||||
|
tags: [ki, entwicklung] # Taxonomie
|
||||||
|
---
|
||||||
|
```
|
||||||
|
|
||||||
|
**Optionale Felder & Overrides (Advanced):**
|
||||||
|
* `aliases`: [Alpha Projekt] – Wichtig für "Active Intelligence" (Exact Match).
|
||||||
|
* `visibility`: internal (default) / public.
|
||||||
|
* **NEU:** Du kannst die KI-Steuerung manuell überschreiben, wenn dir der Standard für den Typ nicht passt:
|
||||||
|
* `chunking_profile`: Zwingt den Chunker in einen Modus (z.B. `structured_smart_edges_strict`).
|
||||||
|
* `retriever_weight`: Setzt die Wichtigkeit manuell hoch/runter (z.B. `1.5` für extrem wichtig).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Typ-Referenz & Verhalten
|
||||||
|
|
||||||
|
Wähle den Typ, der die **Rolle** der Notiz am besten beschreibt. Der Typ steuert Chunking, Gewichtung und Kanten-Logik.
|
||||||
|
|
||||||
|
| Typ | Beschreibung & Einsatzzweck | Rolle im Chat (Intent) | Matrix-Logik |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **`concept`** | Fachbegriffe, Theorien. Zeitloses Wissen. | **FACT** | Ziel für `uses` |
|
||||||
|
| **`project`** | Ein Vorhaben mit Ziel, Dauer und Aufgaben. | **FACT / DECISION** | Quelle für `depends_on` |
|
||||||
|
| **`experience`** | Persönliche Erfahrung, Lektion oder Erkenntnis. | **EMPATHY** | Quelle für `based_on` |
|
||||||
|
| **`decision`** | Eine bewusst getroffene Entscheidung (ADR). | **DECISION** | Quelle für `caused_by` |
|
||||||
|
| **`value`** | Ein persönlicher Wert oder ein Prinzip. | **DECISION** | Ziel für `based_on` |
|
||||||
|
| **`principle`** | Handlungsleitlinie. | **DECISION** | Quelle für `derived_from` |
|
||||||
|
| **`goal`** | Ein strategisches Ziel. | **DECISION** | Ziel für `related_to` |
|
||||||
|
| **`risk`** | Ein identifiziertes Risiko. | **DECISION** | Quelle für `blocks` |
|
||||||
|
| **`journal`** | Zeitbezogener Log-Eintrag. | **FACT** | - |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Edges & Verlinkung
|
||||||
|
|
||||||
|
Mindnet versteht Zusammenhänge durch Kanten.
|
||||||
|
|
||||||
|
### 4.1 Inline-Relationen (Semantische Verknüpfung)
|
||||||
|
Dies ist die **mächtigste** Methode. Du sagst dem System explizit, **wie** Dinge zusammenhängen.
|
||||||
|
|
||||||
|
> "Daher [[rel:depends_on Qdrant]]."
|
||||||
|
> "Dieses Konzept ist [[rel:similar_to Pinecone]]."
|
||||||
|
|
||||||
|
**Gültige Relationen:**
|
||||||
|
* `depends_on`: Hängt ab von / Benötigt.
|
||||||
|
* `blocks`: Blockiert oder gefährdet (z.B. Risiko -> Projekt).
|
||||||
|
* `caused_by`: Wurde verursacht durch (Kausalität).
|
||||||
|
* `similar_to`: Ähnelt / Ist vergleichbar mit.
|
||||||
|
* `solves`: Löst (Problem).
|
||||||
|
* `based_on`: Basiert auf (Fundament).
|
||||||
|
|
||||||
|
### 4.2 Callout-Edges
|
||||||
|
Für Zusammenfassungen am Ende einer Notiz:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
> [!edge] related_to: [[Vector Embeddings]] [[AI Agents]]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Schreiben für den KI-Zwilling (Szenarien)
|
||||||
|
|
||||||
|
Damit der **RAG-Chat** dich berät, musst du "Futter" für die Decision Engine liefern.
|
||||||
|
|
||||||
|
### Szenario A: Decision Engine (`DECISION`)
|
||||||
|
* **Ziel:** Das System soll abwägen: "Passt Tool X zu mir?"
|
||||||
|
* **Vorgehen:** Erstelle Notizen mit `type: value` oder `type: goal`.
|
||||||
|
|
||||||
|
**Beispiel Notiz:**
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
type: value
|
||||||
|
title: Prinzip: Datensparsamkeit
|
||||||
|
---
|
||||||
|
Wir speichern nur das Minimum an Daten. Cloud-Uploads persönlicher Daten sind verboten, es sei denn, sie sind E2E-verschlüsselt.
|
||||||
|
```
|
||||||
|
|
||||||
|
* **Effekt:** Wenn du fragst "Soll ich Notion nutzen?", lädt die Engine diese Notiz und antwortet: *"Nein, Notion ist SaaS ohne E2E. Das verletzt dein Prinzip der Datensparsamkeit."*
|
||||||
|
|
||||||
|
### Szenario B: Empathie (`EMPATHY`)
|
||||||
|
* **Ziel:** Das System soll dich verstehen.
|
||||||
|
* **Vorgehen:** Erstelle `type: experience` mit **emotionalen Brückenwörtern**.
|
||||||
|
|
||||||
|
**Beispiel Notiz:**
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
type: experience
|
||||||
|
title: Erfahrung: Der Durchbruch nach der Krise
|
||||||
|
tags: [krise, hoffnung, grau, angst]
|
||||||
|
---
|
||||||
|
Es gibt Projektphasen, da wirkt alles **sinnlos** und **grau**.
|
||||||
|
Ich habe gelernt: Das ist oft das Zeichen kurz vor dem Durchbruch.
|
||||||
|
```
|
||||||
|
* **Effekt:** Bei "Alles ist grau" findet das System diese Notiz und spiegelt die Lektion zurück.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Best Practices & Beispiele
|
||||||
|
|
||||||
|
### 6.1 Beispiel: Projekt-Notiz (Standard)
|
||||||
|
Projekte profitieren von `depends_on`, um Abhängigkeiten zu klären.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
---
|
||||||
|
id: 20251115-proj-mindnet
|
||||||
|
title: Mindnet Implementierung
|
||||||
|
type: project
|
||||||
|
status: active
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet Implementierung
|
||||||
|
|
||||||
|
Wir bauen ein persönliches Wissensnetz.
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
Wir nutzen [[rel:depends_on Qdrant]] für die Vektorsuche und [[rel:depends_on FastAPI]] für das Backend.
|
||||||
|
|
||||||
|
## Architektur
|
||||||
|
Das Konzept basiert auf [[RAG Architecture]].
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 Beispiel: Advanced Tuning (Manuelles Override)
|
||||||
|
Hier zwingen wir das System, eine Entscheidung extrem kleinteilig (`strict`) zu zerlegen und in der Suche maximal zu priorisieren.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
---
|
||||||
|
id: 20251120-adr-vektordb
|
||||||
|
title: ADR: Wahl von Qdrant
|
||||||
|
type: decision
|
||||||
|
status: final
|
||||||
|
tags: [architektur, db]
|
||||||
|
# OVERRIDES: Wir wollen diese Notiz extrem wichtig machen und strikt trennen
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
retriever_weight: 1.5
|
||||||
|
---
|
||||||
|
|
||||||
|
# Entscheidung: Qdrant
|
||||||
|
|
||||||
|
Wir haben uns für Qdrant entschieden.
|
||||||
|
|
||||||
|
## Alternativen
|
||||||
|
Wir haben auch [[rel:similar_to Pinecone]] und [[rel:similar_to Weaviate]] betrachtet.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Virtual Schema Layer
|
||||||
|
|
||||||
|
Grundsätzlich gilt das Prinzip des **Virtual Schema Layers**. Die Logik (wie `chunk_size`) wird zentral in der `types.yaml` verwaltet.
|
||||||
|
**Aber:** Als Power-User hast du über die oben genannten Overrides (`chunking_profile`) jederzeit die Möglichkeit, aus diesem Standard auszubrechen, wenn eine spezifische Notiz eine Sonderbehandlung benötigt.
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
---
|
||||||
|
doc_type: concept
|
||||||
|
audience: architect, product_owner
|
||||||
|
scope: ai, router, personas
|
||||||
|
status: active
|
||||||
|
version: 2.6
|
||||||
|
context: "Fachkonzept der KI-Persönlichkeit, der Decision Engine und Erweiterungsstrategien."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Konzept: KI-Persönlichkeit & Router
|
||||||
|
|
||||||
|
**Quellen:** `mindnet_functional_architecture.md`, `Programmplan_V2.2.md`
|
||||||
|
|
||||||
|
Mindnet soll nicht wie eine Suchmaschine wirken, sondern wie ein **Digitaler Zwilling**. Dazu muss das System erkennen, **was** der Nutzer will, und seine "Persönlichkeit" anpassen.
|
||||||
|
|
||||||
|
## 1. Der Hybrid Router (Das Gehirn)
|
||||||
|
|
||||||
|
Jede Eingabe durchläuft den **Hybrid Router**. Er entscheidet über die Strategie.
|
||||||
|
|
||||||
|
### Modus A: RAG (Retrieval Augmented Generation)
|
||||||
|
* *Intent:* Der Nutzer hat eine Frage oder ein Problem (`FACT`, `DECISION`, `EMPATHY`).
|
||||||
|
* *Aktion:* Das System sucht im Gedächtnis und generiert eine Antwort.
|
||||||
|
|
||||||
|
### Modus B: Interview (Knowledge Capture)
|
||||||
|
* *Intent:* Der Nutzer will Wissen speichern (`INTERVIEW`).
|
||||||
|
* *Aktion:* Das System sucht **nicht**, sondern fragt ab und erstellt einen Draft.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Die Personas (Strategien)
|
||||||
|
|
||||||
|
Mindnet wechselt den Hut, je nach Situation.
|
||||||
|
|
||||||
|
### 2.1 Der Berater (Strategy: DECISION)
|
||||||
|
* **Auslöser:** Fragen wie "Soll ich...?", "Was ist besser?".
|
||||||
|
* **Strategic Retrieval:** Lädt aktiv Notizen der Typen `value` (Werte), `goal` (Ziele) und `risk` (Risiken), auch wenn sie im Text nicht direkt vorkommen.
|
||||||
|
* **Reasoning:** *"Wäge die Fakten gegen meine Werte ab. Sei strikt bei Risiken."*
|
||||||
|
|
||||||
|
### 2.2 Der Spiegel (Strategy: EMPATHY)
|
||||||
|
* **Auslöser:** Emotionale Aussagen ("Ich bin frustriert").
|
||||||
|
* **Strategic Retrieval:** Lädt `experience` (Erfahrungen) und `belief` (Glaubenssätze).
|
||||||
|
* **Reasoning:** *"Nutze meine eigenen Erfahrungen, um die Situation einzuordnen."*
|
||||||
|
|
||||||
|
### 2.3 Der Bibliothekar (Strategy: FACT)
|
||||||
|
* **Auslöser:** Sachfragen ("Was ist Qdrant?").
|
||||||
|
* **Behavior:** Präzise, neutral, kurz.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Future Concepts: The Empathic Digital Twin
|
||||||
|
|
||||||
|
Um Mindnet von einer Maschine zu einem echten Spiegel der Persönlichkeit zu entwickeln, sind folgende Konzepte in der Architektur angelegt:
|
||||||
|
|
||||||
|
### 3.1 Antizipation durch Erfahrung
|
||||||
|
* **Konzept:** Das System soll Konsequenzen vorhersagen ("Was passiert, wenn...?").
|
||||||
|
* **Logik:** *"In einer ähnlichen Situation (Projekt A) hat Entscheidung X zu Ergebnis Y geführt."* (Analogie-Schluss).
|
||||||
|
|
||||||
|
### 3.2 Empathie & "Ich"-Modus
|
||||||
|
* **Konzept:** Das System antwortet im Tonfall des Nutzers.
|
||||||
|
* **Umsetzung:** Few-Shot Prompting mit eigenen E-Mails/Texten als Stilvorlage.
|
||||||
|
|
||||||
|
### 3.3 Glaubenssätze & Rituale
|
||||||
|
* **Konzept:** Berücksichtigung weicher Faktoren.
|
||||||
|
* **Szenario:** Bei Terminplanungen werden Rituale ("Keine Meetings vor 10 Uhr") automatisch als harte Restriktion gegen Anfragen geprüft.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Erweiterbarkeit: Das "Teach-the-AI" Paradigma
|
||||||
|
|
||||||
|
Mindnet lernt nicht durch Training (Fine-Tuning), sondern durch **Konfiguration** und **Vernetzung**. Wenn du dem System ein neues Konzept beibringen willst, musst du an drei Stellen eingreifen.
|
||||||
|
|
||||||
|
**Beispiel: Du willst den Typ `risk` einführen.**
|
||||||
|
|
||||||
|
**1. Daten-Ebene (Physik)**
|
||||||
|
In `types.yaml`: Definiere Gewicht und Verhalten.
|
||||||
|
```yaml
|
||||||
|
risk:
|
||||||
|
retriever_weight: 0.90 # Hohe Priorität
|
||||||
|
edge_defaults: ["blocks"] # Automatische Kante zu Projekten
|
||||||
|
```
|
||||||
|
|
||||||
|
**2. Strategie-Ebene (Router)**
|
||||||
|
In `decision_engine.yaml`: Wann soll das geladen werden?
|
||||||
|
```yaml
|
||||||
|
DECISION:
|
||||||
|
inject_types: ["value", "risk"] # Füge 'risk' hinzu
|
||||||
|
```
|
||||||
|
|
||||||
|
**3. Kognitive Ebene (Verständnis)**
|
||||||
|
In `prompts.yaml`: Erkläre dem LLM, was ein Risiko ist.
|
||||||
|
|
||||||
|
**Fazit:** Nur wenn **Daten** (Vault), **Physik** (Config) und **Semantik** (Prompt) zusammenspielen, entsteht ein intelligenter Zwilling.
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
---
|
||||||
|
doc_type: concept
|
||||||
|
audience: architect, product_owner
|
||||||
|
scope: graph, logic, provenance
|
||||||
|
status: active
|
||||||
|
version: 2.6
|
||||||
|
context: "Fachliche Beschreibung des Wissensgraphen: Knoten, Kanten, Provenance und Matrix-Logik."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Konzept: Die Graph-Logik
|
||||||
|
|
||||||
|
**Quellen:** `mindnet_functional_architecture.md`, `chunking_strategy.md`
|
||||||
|
|
||||||
|
Mindnet ist keine reine Dokumentablage, sondern ein **semantischer Graph**. Dieses Dokument beschreibt, wie aus statischen Textdateien ein vernetztes Wissensobjekt wird.
|
||||||
|
|
||||||
|
## 1. Die Knoten (Nodes)
|
||||||
|
|
||||||
|
Der Graph besteht aus zwei Ebenen von Knoten.
|
||||||
|
|
||||||
|
### 1.1 Die Note (Das Fachobjekt)
|
||||||
|
Eine Note repräsentiert ein atomares Konzept (z.B. "Projekt Alpha").
|
||||||
|
* **Eigenschaften:** Titel, Typ, Tags, Erstellungsdatum.
|
||||||
|
* **Rolle:** Sie ist der Container für Metadaten und steuert via `type`, wie der Inhalt verarbeitet wird (siehe `types.yaml`).
|
||||||
|
* **Identität:** Definiert durch eine deterministische UUIDv5.
|
||||||
|
|
||||||
|
### 1.2 Der Chunk (Das Suchobjekt)
|
||||||
|
Da LLMs (Large Language Models) nicht unendlich viel Text auf einmal lesen können, werden Notes in kleinere Segmente (**Chunks**) zerlegt.
|
||||||
|
* **Eigenschaften:** Vektor (Embedding 768d), Textfenster, Link zum Vorgänger/Nachfolger.
|
||||||
|
* **Rolle:** Dies sind die eigentlichen Treffer bei einer Suche.
|
||||||
|
* **Hierarchie:** Jeder Chunk gehört streng zu einer Note (`belongs_to`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Die Kanten (Edges)
|
||||||
|
|
||||||
|
Kanten machen aus isolierten Informationen Wissen. Mindnet nutzt gerichtete Kanten mit semantischer Bedeutung.
|
||||||
|
|
||||||
|
### 2.1 Semantische Typen
|
||||||
|
|
||||||
|
| Kanten-Typ | Frage, die er beantwortet | Beispiel |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `references` | Worüber wird gesprochen? | Text erwähnt "Python". |
|
||||||
|
| `depends_on` | Was ist Voraussetzung? | Projekt braucht "Budget". |
|
||||||
|
| `caused_by` | Warum ist das passiert? | Bug durch "Commit X". |
|
||||||
|
| `blocks` | Was steht im Weg? | Risiko blockiert "Release". |
|
||||||
|
| `based_on` | Worauf fußt das? | Erfahrung basiert auf "Wert Y". |
|
||||||
|
| `derived_from` | Woher kommt das? | Prinzip stammt aus "Buch Z". |
|
||||||
|
| `related_to` | Was ist ähnlich? | "Hund" ist verwandt mit "Wolf". |
|
||||||
|
| `solves` | Was ist die Lösung? | "Qdrant" löst "Vektorsuche". |
|
||||||
|
|
||||||
|
### 2.2 Provenance (Herkunft & Vertrauen)
|
||||||
|
|
||||||
|
Nicht alle Kanten sind gleich viel wert. Mindnet unterscheidet in v2.6 drei Qualitätsstufen (**Provenance**), um Konflikte aufzulösen.
|
||||||
|
|
||||||
|
**1. Explicit (Der Mensch hat es gesagt)**
|
||||||
|
* *Quelle:* Inline-Links (`[[rel:...]]`) oder Wikilinks im Text.
|
||||||
|
* *Vertrauen:* **Hoch (1.0)**.
|
||||||
|
* *Bedeutung:* Dies ist hartes Faktenwissen. "Ich habe diesen Link bewusst gesetzt."
|
||||||
|
|
||||||
|
**2. Smart (Die KI hat es bestätigt)**
|
||||||
|
* *Quelle:* Smart Edge Allocation (WP15).
|
||||||
|
* *Vertrauen:* **Mittel (0.9)**.
|
||||||
|
* *Bedeutung:* Ein LLM hat geprüft, ob der Link im Kontext dieses Textabschnitts wirklich relevant ist. Dies filtert "Rauschen" heraus (z.B. Links im Footer, die nichts mit dem Absatz zu tun haben).
|
||||||
|
|
||||||
|
**3. Rule (Die Regel hat es vermutet)**
|
||||||
|
* *Quelle:* `types.yaml` Defaults.
|
||||||
|
* *Vertrauen:* **Niedrig (0.7)**.
|
||||||
|
* *Bedeutung:* Eine Heuristik. "Weil es ein Projekt ist, nehmen wir an, dass es von allen erwähnten Technologien abhängt."
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Matrix-Logik (Kontext-Sensitivität)
|
||||||
|
|
||||||
|
Mit WP11 wurde eine Intelligenz eingeführt, die Kanten-Typen nicht nur anhand des Quell-Typs, sondern auch anhand des Ziel-Typs bestimmt ("Matrix").
|
||||||
|
|
||||||
|
**Logik-Beispiele:**
|
||||||
|
|
||||||
|
* **Quelle `experience` → Ziel `value`**
|
||||||
|
* *Standard:* `references`
|
||||||
|
* *Matrix:* `based_on` (Erfahrungen basieren auf Werten).
|
||||||
|
|
||||||
|
* **Quelle `principle` → Ziel `source` (Buch)**
|
||||||
|
* *Standard:* `references`
|
||||||
|
* *Matrix:* `derived_from` (Prinzipien stammen aus Quellen).
|
||||||
|
|
||||||
|
* **Quelle `project` → Ziel `tool`**
|
||||||
|
* *Standard:* `references`
|
||||||
|
* *Matrix:* `uses` (Projekte nutzen Tools).
|
||||||
|
|
||||||
|
*Nutzen:* Dies erlaubt im Chat präzise Fragen wie: *"Auf welchen Werten basiert diese Entscheidung?"* (Suche nach eingehenden `based_on` Kanten).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Idempotenz & Konsistenz
|
||||||
|
|
||||||
|
Das System garantiert fachliche Konsistenz auch bei mehrfachen Importen.
|
||||||
|
* **Stabile IDs:** Importiert man dieselbe Datei zweimal, ändern sich die IDs der Knoten nicht.
|
||||||
|
* **Keine Duplikate:** Kanten werden dedupliziert. Die "stärkere" Quelle (Explicit > Smart > Rule) gewinnt.
|
||||||
|
* **Lösch-Garantie:** Wenn eine Notiz gelöscht wird, verschwinden auch alle ihre Chunks und ausgehenden Kanten (via `--sync-deletes`).
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer, architect
|
||||||
|
scope: backend, chat, ollama, traffic_control
|
||||||
|
status: active
|
||||||
|
version: 2.6
|
||||||
|
context: "Technische Implementierung des FastAPI-Routers, der Decision Engine und des Traffic Control Systems."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Chat Backend & Traffic Control
|
||||||
|
|
||||||
|
## 1. Hybrid Router (Decision Engine)
|
||||||
|
|
||||||
|
Der zentrale Einstiegspunkt für jede Chatanfrage ist der **Hybrid Router** (`app/routers/chat.py`). Er entscheidet dynamisch, welche Strategie gewählt wird, basierend auf dem User-Input.
|
||||||
|
|
||||||
|
### 1.1 Intent-Erkennung (Logik)
|
||||||
|
|
||||||
|
Der Router prüft den Input in drei Stufen (Wasserfall-Prinzip):
|
||||||
|
|
||||||
|
1. **Question Detection (Regelbasiert):**
|
||||||
|
* Prüfung auf Vorhandensein von `?` oder W-Wörtern (Wer, Wie, Was, Soll ich).
|
||||||
|
* Wenn positiv: **RAG Modus** (Interview wird blockiert).
|
||||||
|
2. **Keyword Scan (Fast Path):**
|
||||||
|
* Lädt `types.yaml` (Objekte, z.B. "Projekt") und `decision_engine.yaml` (Handlungen, z.B. "neu").
|
||||||
|
* Wenn Match (z.B. "Projekt" + "neu"): **INTERVIEW Modus**.
|
||||||
|
3. **LLM Fallback (Slow Path):**
|
||||||
|
* Wenn unklar: Anfrage an LLM zur Klassifizierung.
|
||||||
|
|
||||||
|
### 1.2 RAG Flow (Technisch)
|
||||||
|
|
||||||
|
Wenn der Intent `FACT` oder `DECISION` ist, wird folgender Flow ausgeführt:
|
||||||
|
|
||||||
|
1. **Pre-Processing:** Query Rewriting (optional).
|
||||||
|
2. **Context Enrichment:**
|
||||||
|
* Abruf via `retriever.py` (Hybrid Search).
|
||||||
|
* Injection von Metadaten (`[TYPE]`, `[SCORE]`) in den Prompt.
|
||||||
|
3. **Prompt Construction:** Assembly aus System-Prompt (Persona) + Context + Query.
|
||||||
|
4. **Streaming:** LLM-Antwort wird via **SSE (Server-Sent Events)** an den Client gestreamt.
|
||||||
|
5. **Post-Processing:** Anhängen des `Explanation` Layers (JSON-Breakdown) an das Ende des Streams.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Traffic Control (WP-15)
|
||||||
|
|
||||||
|
Das Traffic Control System (`app/core/llm_service.py`) schützt das System vor Überlastung, wenn rechenintensive Hintergrundprozesse (Smart Edge Import) und Latenz-kritische Chat-Anfragen gleichzeitig laufen.
|
||||||
|
|
||||||
|
### 2.1 Prioritäts-Semaphor
|
||||||
|
|
||||||
|
Jeder LLM-Request muss ein `priority`-Flag setzen.
|
||||||
|
|
||||||
|
**Prioritäten-Levels:**
|
||||||
|
|
||||||
|
| Priority | Verwendung | Limitierung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **realtime** | Chat-Anfragen | Keine (Hardware-Limit) |
|
||||||
|
| **background** | Smart Edge Allocation, Drafts | `MINDNET_LLM_BACKGROUND_LIMIT` |
|
||||||
|
|
||||||
|
**Funktionsweise:**
|
||||||
|
* Hintergrund-Tasks nutzen `asyncio.Semaphore`.
|
||||||
|
* Wenn das Limit (Default: 2) erreicht ist, warten weitere Import-Tasks.
|
||||||
|
* Chat-Tasks umgehen die Semaphore und werden sofort bearbeitet.
|
||||||
|
|
||||||
|
### 2.2 Timeout-Konfiguration
|
||||||
|
|
||||||
|
Deadlocks werden durch strikte Timeouts verhindert, die in der `.env` definiert sind.
|
||||||
|
|
||||||
|
* **Chat:** `MINDNET_LLM_TIMEOUT` (Default: 300s).
|
||||||
|
* **Frontend:** `MINDNET_API_TIMEOUT` (Default: 300s).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Feedback Traceability
|
||||||
|
|
||||||
|
Unterstützt das geplante Self-Tuning (WP08).
|
||||||
|
|
||||||
|
1. **Query ID:** Generiert bei jedem `/query` Call eine `UUIDv4`.
|
||||||
|
2. **Logging:** Speichert einen Snapshot in `data/logs/query_snapshot.jsonl` (Input + Retrieved Context).
|
||||||
|
3. **Feedback:** Der `/feedback` Endpoint verknüpft das User-Rating (1-5) mit der `query_id`.
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer, admin
|
||||||
|
scope: configuration, env
|
||||||
|
status: active
|
||||||
|
version: 2.7.0
|
||||||
|
context: "Referenztabellen für Umgebungsvariablen und YAML-Konfigurationen."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Konfigurations-Referenz
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt die Steuerungsdateien von Mindnet.
|
||||||
|
|
||||||
|
## 1. Environment Variablen (`.env`)
|
||||||
|
|
||||||
|
Diese Variablen steuern die Infrastruktur, Timeouts und Feature-Flags.
|
||||||
|
|
||||||
|
| Variable | Default | Beschreibung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `QDRANT_URL` | `http://localhost:6333` | URL zur Vektor-DB API. |
|
||||||
|
| `QDRANT_API_KEY` | *(leer)* | Optionaler Key für Absicherung. |
|
||||||
|
| `COLLECTION_PREFIX` | `mindnet` | Namensraum für Collections (erzeugt `{prefix}_notes` etc). |
|
||||||
|
| `VECTOR_DIM` | `768` | **Muss 768 sein** (für Nomic Embeddings). |
|
||||||
|
| `MINDNET_TYPES_FILE` | `config/types.yaml` | Pfad zur Typ-Registry. |
|
||||||
|
| `MINDNET_RETRIEVER_CONFIG`| `config/retriever.yaml`| Pfad zur Scoring-Konfiguration. |
|
||||||
|
| `MINDNET_DECISION_CONFIG` | `config/decision_engine.yaml` | Pfad zur Router & Intent Config. |
|
||||||
|
| `MINDNET_PROMPTS_PATH` | `config/prompts.yaml` | Pfad zu LLM Prompts. |
|
||||||
|
| `MINDNET_LLM_MODEL` | `phi3:mini` | Name des Chat-Modells (Ollama). |
|
||||||
|
| `MINDNET_EMBEDDING_MODEL` | `nomic-embed-text` | Name des Embedding-Modells (Ollama). |
|
||||||
|
| `MINDNET_OLLAMA_URL` | `http://127.0.0.1:11434`| URL zum LLM-Server. |
|
||||||
|
| `MINDNET_LLM_TIMEOUT` | `300.0` | Timeout in Sekunden (Erhöht für CPU Cold-Starts). |
|
||||||
|
| `MINDNET_API_TIMEOUT` | `300.0` | Frontend Timeout (Erhöht für Smart Edge Wartezeiten). |
|
||||||
|
| `MINDNET_LLM_BACKGROUND_LIMIT`| `2` | **Traffic Control (Neu):** Max. parallele Import-Tasks (Semaphore). |
|
||||||
|
| `MINDNET_VAULT_ROOT` | `./vault` | Pfad für Write-Back Operationen (Drafts). |
|
||||||
|
| `MINDNET_CHANGE_DETECTION_MODE` | `full` | **Change Detection (Neu):** `full` (Text + Meta) oder `body` (nur Text). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Typ-Registry (`types.yaml`)
|
||||||
|
|
||||||
|
Steuert das Import-Verhalten, Chunking und die Kanten-Logik pro Typ.
|
||||||
|
|
||||||
|
### 2.1 Konfigurations-Hierarchie (Override-Logik)
|
||||||
|
Seit Version 2.7.0 gilt für `chunking_profile` und `retriever_weight` folgende Priorität:
|
||||||
|
|
||||||
|
1. **Frontmatter (Höchste Prio):** Ein Wert direkt in der Markdown-Datei überschreibt alles.
|
||||||
|
* *Beispiel:* `chunking_profile: structured_smart_edges_strict` im Header einer Notiz erzwingt diesen Splitter, egal welcher Typ eingestellt ist.
|
||||||
|
2. **Type Config:** Der Standardwert für den `type` (z.B. `concept`) aus `types.yaml`.
|
||||||
|
3. **Global Default:** Fallback aus `defaults` in `types.yaml`.
|
||||||
|
|
||||||
|
### 2.2 Typ-Referenztabelle
|
||||||
|
|
||||||
|
| Typ (`type`) | Chunk Profile (Standard) | Retriever Weight | Smart Edges? | Beschreibung |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **concept** | `sliding_smart_edges` | 0.60 | Ja | Abstrakte Begriffe. |
|
||||||
|
| **project** | `sliding_smart_edges` | 0.97 | Ja | Aktive Vorhaben. |
|
||||||
|
| **decision** | `structured_smart_edges_strict` | 1.00 | Ja | Entscheidungen (ADRs). Atomar. |
|
||||||
|
| **experience** | `sliding_smart_edges` | 0.90 | Ja | Persönliche Learnings. |
|
||||||
|
| **journal** | `sliding_standard` | 0.80 | Nein | Logs / Dailies. |
|
||||||
|
| **value** | `structured_smart_edges_strict` | 1.00 | Ja | Werte/Prinzipien. Atomar. |
|
||||||
|
| **risk** | `sliding_short` | 0.90 | Nein | Risiken. |
|
||||||
|
| **person** | `sliding_standard` | 0.50 | Nein | Profile. |
|
||||||
|
| **source** | `sliding_standard` | 0.50 | Nein | Externe Quellen. |
|
||||||
|
| **event** | `sliding_standard` | 0.60 | Nein | Meetings. |
|
||||||
|
| **goal** | `sliding_smart_edges` | 0.95 | Nein | Strategische Ziele. |
|
||||||
|
| **belief** | `sliding_short` | 0.90 | Nein | Glaubenssätze. |
|
||||||
|
| **profile** | `structured_smart_edges_strict` | 0.70 | Nein | Rollenprofile. Strict Split. |
|
||||||
|
| **principle** | `structured_smart_edges_strict_L3`| 0.95 | Nein | Prinzipien. Tiefer Split (H3) für Mikro-Prinzipien. |
|
||||||
|
| **task** | `sliding_short` | 0.80 | Nein | Aufgaben. |
|
||||||
|
| **glossary** | `sliding_short` | 0.40 | Nein | Begriffsdefinitionen. |
|
||||||
|
| **default** | `sliding_standard` | 1.00 | Nein | Fallback. |
|
||||||
|
|
||||||
|
*Hinweis: `Smart Edges?` entspricht dem YAML-Key `enable_smart_edge_allocation: true`.*
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Retriever Config (`retriever.yaml`)
|
||||||
|
|
||||||
|
Steuert die Gewichtung der Scoring-Formel (WP04a).
|
||||||
|
|
||||||
|
**Beispielkonfiguration:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
scoring:
|
||||||
|
semantic_weight: 1.0 # Basis-Relevanz (Cosine Similarity)
|
||||||
|
edge_weight: 0.7 # Einfluss des Graphen (Bonus)
|
||||||
|
centrality_weight: 0.5 # Einfluss von Hubs
|
||||||
|
|
||||||
|
edge_weights:
|
||||||
|
# Multiplikatoren für den Edge-Bonus
|
||||||
|
depends_on: 1.5 # Harte Abhängigkeiten stark gewichten
|
||||||
|
blocks: 1.5 # Risiken stark gewichten
|
||||||
|
caused_by: 1.2 # Kausalitäten stärken
|
||||||
|
related_to: 0.5 # Weiche Themen schwächer gewichten
|
||||||
|
references: 0.8 # Standard-Referenzen
|
||||||
|
based_on: 1.3 # Werte-Bezug
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Edge Typen Referenz
|
||||||
|
|
||||||
|
Definiert die Semantik der `kind`-Felder in der Edge-Collection.
|
||||||
|
|
||||||
|
| Kind | Symmetrisch? | Herkunft (Primär) | Bedeutung |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `references` | Nein | Wikilink | Standard-Verweis. "Erwähnt X". |
|
||||||
|
| `belongs_to` | Nein | Struktur | Chunk gehört zu Note. |
|
||||||
|
| `next` / `prev` | Ja | Struktur | Lesereihenfolge. |
|
||||||
|
| `depends_on` | Nein | Inline / Default | Harte Abhängigkeit. |
|
||||||
|
| `related_to` | Ja | Callout / Default | Thematische Nähe. |
|
||||||
|
| `similar_to` | Ja | Inline | Inhaltliche Ähnlichkeit. |
|
||||||
|
| `caused_by` | Nein | Inline | Kausalität. |
|
||||||
|
| `solves` | Nein | Inline | Lösung für ein Problem. |
|
||||||
|
| `blocks` | Nein | Inline | Blockade / Risiko. |
|
||||||
|
| `derived_from` | Nein | Matrix | Herkunft (z.B. Prinzip -> Buch). |
|
||||||
|
| `based_on` | Nein | Matrix | Fundament (z.B. Erfahrung -> Wert). |
|
||||||
|
| `uses` | Nein | Matrix | Nutzung (z.B. Projekt -> Tool). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Decision Engine (`decision_engine.yaml`)
|
||||||
|
|
||||||
|
Steuert den Hybrid Router (WP06). Definiert, welche Keywords welche Strategie auslösen.
|
||||||
|
|
||||||
|
**Beispielauszug:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# Strategie-Definitionen
|
||||||
|
strategies:
|
||||||
|
DECISION:
|
||||||
|
description: "Hilfe bei Entscheidungen"
|
||||||
|
inject_types: ["value", "principle", "goal", "risk"] # Strategic Retrieval
|
||||||
|
llm_fallback_enabled: true
|
||||||
|
|
||||||
|
INTERVIEW:
|
||||||
|
description: "Wissenserfassung"
|
||||||
|
trigger_keywords: ["erstellen", "neu", "anlegen", "festhalten"]
|
||||||
|
|
||||||
|
EMPATHY:
|
||||||
|
description: "Emotionaler Support"
|
||||||
|
inject_types: ["experience", "belief"]
|
||||||
|
```
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer, architect
|
||||||
|
scope: database, qdrant, schema
|
||||||
|
status: active
|
||||||
|
version: 2.7.0
|
||||||
|
context: "Exakte Definition der Datenmodelle (Payloads) in Qdrant und Index-Anforderungen."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Technisches Datenmodell (Qdrant Schema)
|
||||||
|
|
||||||
|
## 1. Collections & Namenskonvention
|
||||||
|
|
||||||
|
Mindnet speichert Daten in drei getrennten Qdrant-Collections. Der Prefix ist via ENV `COLLECTION_PREFIX` konfigurierbar (Default: `mindnet`).
|
||||||
|
|
||||||
|
Das System nutzt folgende drei Collections:
|
||||||
|
* `{prefix}_notes`: Metadaten der Dateien.
|
||||||
|
* `{prefix}_chunks`: Vektorisierte Textsegmente.
|
||||||
|
* `{prefix}_edges`: Gerichtete Graph-Kanten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Note Payload (`mindnet_notes`)
|
||||||
|
|
||||||
|
Repräsentiert die Metadaten einer Markdown-Datei (1:1 Beziehung).
|
||||||
|
|
||||||
|
**JSON-Schema:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"note_id": "string (keyword)", // UUIDv5 (deterministisch) oder Slug
|
||||||
|
"title": "string (text)", // Titel aus Frontmatter
|
||||||
|
"type": "string (keyword)", // Logischer Typ (z.B. 'project', 'concept')
|
||||||
|
"retriever_weight": "float", // Effektive Wichtigkeit (Frontmatter > Type > Default)
|
||||||
|
"chunk_profile": "string", // Effektives Profil (Frontmatter > Type > Default)
|
||||||
|
"edge_defaults": ["string"], // Liste der aktiven Default-Kanten
|
||||||
|
"tags": ["string"], // Liste von Tags aus Frontmatter
|
||||||
|
"aliases": ["string"], // Synonyme für Discovery (WP-11)
|
||||||
|
"created": "string (iso-date)", // Erstellungsdatum
|
||||||
|
"updated": "integer", // Timestamp (File Modification Time)
|
||||||
|
"fulltext": "string (no-index)", // Gesamter Text (nur für Recovery/Export)
|
||||||
|
|
||||||
|
// NEU in v2.7: Multi-Hash für flexible Change Detection
|
||||||
|
"hashes": {
|
||||||
|
"body:parsed:canonical": "string", // Hash nur über den Text-Body
|
||||||
|
"full:parsed:canonical": "string" // Hash über Text + Metadaten (Tags, Title, Config)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Erforderliche Indizes:**
|
||||||
|
Es müssen Payload-Indizes für folgende Felder existieren:
|
||||||
|
* `note_id`
|
||||||
|
* `type`
|
||||||
|
* `tags`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Chunk Payload (`mindnet_chunks`)
|
||||||
|
|
||||||
|
Die atomare Sucheinheit. Enthält den Vektor.
|
||||||
|
|
||||||
|
**Vektor-Konfiguration:**
|
||||||
|
* Modell: `nomic-embed-text`
|
||||||
|
* Dimension: **768**
|
||||||
|
* Metrik: Cosine Similarity
|
||||||
|
|
||||||
|
**JSON-Schema:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"chunk_id": "string (keyword)", // Format: {note_id}#c{index} (z.B. 'abc-123#c01')
|
||||||
|
"note_id": "string (keyword)", // Foreign Key zur Note
|
||||||
|
"type": "string (keyword)", // Kopie aus Note (Denormalisiert für Filterung)
|
||||||
|
"text": "string (text)", // Reintext für Anzeige (ohne Overlap)
|
||||||
|
"window": "string (text)", // Text + Overlap (Basis für Embedding)
|
||||||
|
"ord": "integer", // Laufende Nummer (1..N) für Sortierung
|
||||||
|
"retriever_weight": "float", // Geerbt von Note (für schnelles Re-Ranking)
|
||||||
|
"chunk_profile": "string", // Geerbt von Note (für Debugging/Filtering)
|
||||||
|
"neighbors_prev": ["string"], // ID des Vorgängers (Linked List)
|
||||||
|
"neighbors_next": ["string"], // ID des Nachfolgers
|
||||||
|
"section": "string", // Pfad/Überschrift, zu der der Chunk gehört
|
||||||
|
"source_path": "string" // Relativer Pfad zur Datei
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Erforderliche Indizes:**
|
||||||
|
Es müssen Payload-Indizes für folgende Felder existieren:
|
||||||
|
* `note_id`
|
||||||
|
* `chunk_id`
|
||||||
|
* `type`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Edge Payload (`mindnet_edges`)
|
||||||
|
|
||||||
|
Gerichtete Kanten zwischen Knoten. Stark erweitert in v2.6 für Provenienz-Tracking.
|
||||||
|
|
||||||
|
**JSON-Schema:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"edge_id": "string (keyword)", // Deterministischer Hash aus (src, dst, kind)
|
||||||
|
"source_id": "string (keyword)", // Chunk-ID (Start)
|
||||||
|
"target_id": "string (keyword)", // Chunk-ID oder Note-Titel (bei Unresolved)
|
||||||
|
"kind": "string (keyword)", // Beziehungsart (z.B. 'depends_on')
|
||||||
|
"scope": "string (keyword)", // Immer 'chunk' (Legacy-Support: 'note')
|
||||||
|
"note_id": "string (keyword)", // Owner Note ID (Ursprung der Kante)
|
||||||
|
|
||||||
|
// Provenance & Quality (WP03/WP15)
|
||||||
|
"provenance": "keyword", // 'explicit', 'rule', 'smart', 'structure'
|
||||||
|
"rule_id": "string (keyword)", // Traceability: 'inline:rel', 'explicit:wikilink', 'smart:llm'
|
||||||
|
"confidence": "float" // Vertrauenswürdigkeit (0.0 - 1.0)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Erforderliche Indizes:**
|
||||||
|
Es müssen Payload-Indizes für folgende Felder existieren:
|
||||||
|
* `source_id`
|
||||||
|
* `target_id`
|
||||||
|
* `kind`
|
||||||
|
* `scope`
|
||||||
|
* `note_id`
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer, frontend_architect
|
||||||
|
scope: architecture, graph_viz, state_management
|
||||||
|
status: active
|
||||||
|
version: 2.7.0
|
||||||
|
context: "Technische Dokumentation des modularen Streamlit-Frontends, der Graph-Engines und des Editors."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Technical Reference: Frontend & Visualization
|
||||||
|
|
||||||
|
**Kontext:** Mindnet nutzt Streamlit nicht nur als einfaches UI, sondern als komplexe Applikation mit eigenem State-Management, Routing und Persistenz.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Architektur & Modularisierung (WP19)
|
||||||
|
|
||||||
|
Seit Version 2.6 ist das Frontend (`app/frontend/`) kein Monolith mehr, sondern in funktionale Module unterteilt.
|
||||||
|
|
||||||
|
### 1.1 Dateistruktur & Aufgaben
|
||||||
|
|
||||||
|
| Modul | Funktion |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `ui.py` | **Router.** Der Entrypoint. Initialisiert Session-State und entscheidet anhand der Sidebar-Auswahl, welche View gerendert wird. |
|
||||||
|
| `ui_config.py` | **Konstanten.** Zentraler Ort für Farben (`GRAPH_COLORS`), API-Endpunkte und Timeouts. |
|
||||||
|
| `ui_api.py` | **Backend-Bridge.** Kapselt alle `requests`-Aufrufe an die FastAPI. |
|
||||||
|
| `ui_callbacks.py` | **State Transitions.** Logik für View-Wechsel (z.B. Sprung vom Graph in den Editor). |
|
||||||
|
| `ui_utils.py` | **Helper.** Markdown-Parsing (`parse_markdown_draft`) und String-Normalisierung. |
|
||||||
|
| `ui_graph_service.py`| **Data Logic.** Holt Daten aus Qdrant und bereitet Nodes/Edges auf (unabhängig von der Vis-Library). |
|
||||||
|
| `ui_graph_cytoscape.py`| **View: Graph.** Implementierung mit `st-cytoscape` (COSE Layout). |
|
||||||
|
| `ui_editor.py` | **View: Editor.** Logik für Drafts, manuelles Editieren und **Async Feedback**. |
|
||||||
|
|
||||||
|
### 1.2 Konfiguration (`ui_config.py`)
|
||||||
|
|
||||||
|
Zentrale Steuerung der visuellen Semantik.
|
||||||
|
|
||||||
|
# Mapping von Node-Typen zu Farben (Hex)
|
||||||
|
GRAPH_COLORS = {
|
||||||
|
"project": "#ff9f43", # Orange
|
||||||
|
"decision": "#5f27cd", # Lila
|
||||||
|
"experience": "#feca57", # Gelb (Empathie)
|
||||||
|
"concept": "#54a0ff", # Blau
|
||||||
|
"risk": "#ff6b6b" # Rot
|
||||||
|
}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Graph Visualisierung
|
||||||
|
|
||||||
|
Mindnet nutzt primär **Cytoscape** für Stabilität bei großen Graphen.
|
||||||
|
|
||||||
|
### 2.1 Engine: Cytoscape (`st-cytoscape`)
|
||||||
|
* **Algorithmus:** `COSE` (Compound Spring Embedder).
|
||||||
|
* **Vorteil:** Verhindert Überlappungen aktiv (`nodeRepulsion`).
|
||||||
|
|
||||||
|
### 2.2 Architektur-Pattern: "Active Inspector, Passive Graph"
|
||||||
|
Ein häufiges Problem bei Streamlit-Graphen ist das "Flackern" (Re-Render) bei Klicks. Wir lösen das durch Entkopplung:
|
||||||
|
|
||||||
|
1. **Stable Key:** Der React-Key der Komponente hängt *nicht* von der Selektion ab, sondern nur vom Zentrum (`center_id`) und Layout-Settings.
|
||||||
|
2. **CSS-Selektion:** Wir nutzen **nicht** den nativen `:selected` State (buggy bei Single-Select), sondern injizieren eine CSS-Klasse `.inspected`.
|
||||||
|
|
||||||
|
**Stylesheet Implementierung (`ui_graph_cytoscape.py`):**
|
||||||
|
|
||||||
|
stylesheet = [
|
||||||
|
{
|
||||||
|
"selector": "node",
|
||||||
|
"style": { "background-color": "data(bg_color)" }
|
||||||
|
},
|
||||||
|
# Wir steuern das Highlight manuell über eine Klasse
|
||||||
|
{
|
||||||
|
"selector": ".inspected",
|
||||||
|
"style": {
|
||||||
|
"border-width": 6,
|
||||||
|
"border-color": "#FFC300", # Gelb/Gold
|
||||||
|
"z-index": 999
|
||||||
|
}
|
||||||
|
},
|
||||||
|
# Native Selektion wird unterdrückt/unsichtbar gemacht
|
||||||
|
{
|
||||||
|
"selector": "node:selected",
|
||||||
|
"style": { "overlay-opacity": 0, "border-width": 0 }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Editor & Single Source of Truth
|
||||||
|
|
||||||
|
Ein kritisches Design-Pattern ist der Umgang mit Datenkonsistenz beim Editieren ("File System First").
|
||||||
|
|
||||||
|
### 3.1 Das Problem
|
||||||
|
Qdrant speichert Metadaten und Chunks, aber das Feld `fulltext` im Payload kann veraltet sein oder Formatierungen verlieren.
|
||||||
|
|
||||||
|
### 3.2 Die Lösung (Logic Flow)
|
||||||
|
Der `switch_to_editor_callback` in `ui_callbacks.py` implementiert folgende Kaskade:
|
||||||
|
|
||||||
|
def switch_to_editor_callback(note_payload):
|
||||||
|
# 1. Pfad aus Qdrant Payload lesen
|
||||||
|
origin_fname = note_payload.get('path')
|
||||||
|
|
||||||
|
content = ""
|
||||||
|
# 2. Versuch: Hard Read von der Festplatte (Source of Truth)
|
||||||
|
if origin_fname and os.path.exists(origin_fname):
|
||||||
|
with open(origin_fname, "r", encoding="utf-8") as f:
|
||||||
|
content = f.read()
|
||||||
|
else:
|
||||||
|
# 3. Fallback: Rekonstruktion aus der DB ("Stitching")
|
||||||
|
# Nur Notfall, falls Docker-Volume fehlt
|
||||||
|
content = note_payload.get('fulltext', '')
|
||||||
|
|
||||||
|
# State setzen (Transport via Message-Bus)
|
||||||
|
st.session_state.messages.append({
|
||||||
|
"role": "assistant",
|
||||||
|
"intent": "INTERVIEW",
|
||||||
|
"content": content,
|
||||||
|
"origin_filename": origin_fname
|
||||||
|
})
|
||||||
|
st.session_state["sidebar_mode_selection"] = "📝 Manueller Editor"
|
||||||
|
|
||||||
|
### 3.3 Async Save Pattern (Neu in v2.7 / WP-14)
|
||||||
|
Um Timeouts bei der Smart-Edge-Berechnung zu vermeiden, nutzt der Editor ein **"Fire & Forget"** Muster.
|
||||||
|
|
||||||
|
1. **Request:** UI sendet Markdown an `/ingest/save`.
|
||||||
|
2. **Backend:**
|
||||||
|
* Validiert Request.
|
||||||
|
* Speichert Datei auf Disk (Persistenz garantiert).
|
||||||
|
* Startet `BackgroundTasks` für LLM-Analyse und Embedding.
|
||||||
|
* Returniert sofort `status: queued`.
|
||||||
|
3. **UI Feedback:**
|
||||||
|
* Editor zeigt "Erfolgreich eingereiht".
|
||||||
|
* User muss nicht warten.
|
||||||
|
* (ToDo: WebSocket Notification bei Abschluss).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. State Management Patterns
|
||||||
|
|
||||||
|
### 4.1 URL Persistenz (Deep Linking)
|
||||||
|
Layout-Einstellungen werden in der URL gespeichert, damit sie einen Page-Refresh (F5) überleben.
|
||||||
|
|
||||||
|
# ui_graph_cytoscape.py
|
||||||
|
def update_url_params():
|
||||||
|
st.query_params["depth"] = st.session_state.cy_depth
|
||||||
|
st.query_params["rep"] = st.session_state.cy_node_repulsion
|
||||||
|
|
||||||
|
# Init
|
||||||
|
if "cy_depth" not in st.session_state:
|
||||||
|
st.session_state.cy_depth = int(st.query_params.get("depth", 2))
|
||||||
|
|
||||||
|
### 4.2 Resurrection Pattern
|
||||||
|
Verhindert Datenverlust, wenn der Nutzer während des Tippens den Tab wechselt. Der Editor-Inhalt wird bei jedem Keystroke (`on_change`) in `st.session_state` gespiegelt und beim Neuladen der Komponente von dort wiederhergestellt.
|
||||||
|
|
||||||
|
### 4.3 Healing Parser (`ui_utils.py`)
|
||||||
|
Das LLM liefert oft invalides YAML oder Markdown. Der Parser (`parse_markdown_draft`):
|
||||||
|
* Repariert fehlende Frontmatter-Trenner (`---`).
|
||||||
|
* Extrahiert JSON/YAML aus Code-Blöcken.
|
||||||
|
* Normalisiert Tags (entfernt `#`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Constraints & Security (Known Limitations)
|
||||||
|
|
||||||
|
### 5.1 File System Security
|
||||||
|
Der Editor ("File System First") vertraut dem Pfad im Qdrant-Feld `path`.
|
||||||
|
* **Risiko:** Path Traversal (z.B. `../../etc/passwd`).
|
||||||
|
* **Mitigation:** Aktuell findet keine strikte Prüfung statt, ob der Pfad innerhalb des `./vault` Ordners liegt. Das System setzt voraus, dass die Vektor-Datenbank eine **Trusted Source** ist und nur vom internen Importer befüllt wird.
|
||||||
|
* **ToDo:** Bei Öffnung der API für Dritte muss hier eine `Path.resolve().is_relative_to(VAULT_ROOT)` Prüfung implementiert werden.
|
||||||
|
|
||||||
|
### 5.2 Browser Performance
|
||||||
|
Die Graph-Visualisierung (`st-cytoscape`) rendert Client-seitig im Browser.
|
||||||
|
* **Limit:** Ab ca. **500 Knoten/Kanten** kann das Rendering träge werden.
|
||||||
|
* **Design-Entscheidung:** Das UI ist auf **Ego-Graphen** (Nachbarn eines Knotens) und gefilterte Ansichten ausgelegt, nicht auf die Darstellung des gesamten Knowledge-Graphs ("Whole Brain Visualization").
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer, devops
|
||||||
|
scope: backend, ingestion, smart_edges
|
||||||
|
status: active
|
||||||
|
version: 2.7.0
|
||||||
|
context: "Detaillierte technische Beschreibung der Import-Pipeline, Chunking-Strategien und CLI-Befehle."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Ingestion Pipeline & Smart Processing
|
||||||
|
|
||||||
|
**Quellen:** `pipeline_playbook.md`, `Handbuch.md`
|
||||||
|
|
||||||
|
Die Ingestion transformiert Markdown in den Graphen. Entrypoint: `scripts/import_markdown.py` (CLI) oder `routers/ingest.py` (API).
|
||||||
|
|
||||||
|
## 1. Der Import-Prozess (14-Schritte-Workflow)
|
||||||
|
|
||||||
|
Der Prozess ist **asynchron** und **idempotent**.
|
||||||
|
|
||||||
|
1. **Trigger & Async Dispatch:**
|
||||||
|
* **API (`/save`):** Nimmt Request entgegen, validiert und startet Background-Task ("Fire & Forget"). Antwortet sofort mit `202/Queued`.
|
||||||
|
* **CLI:** Iteriert über Dateien und nutzt `asyncio.Semaphore` zur Drosselung.
|
||||||
|
2. **Markdown lesen:** Rekursives Scannen des Vaults.
|
||||||
|
3. **Frontmatter extrahieren:** Validierung von Pflichtfeldern (`id`, `type`, `title`).
|
||||||
|
4. **Config Resolution:**
|
||||||
|
* Bestimmung von `chunking_profile` und `retriever_weight`.
|
||||||
|
* **Priorität:** 1. Frontmatter (Override) -> 2. `types.yaml` (Type) -> 3. Default.
|
||||||
|
5. **Note-Payload generieren:**
|
||||||
|
* Erstellen des JSON-Objekts für `mindnet_notes`.
|
||||||
|
* **Multi-Hash Calculation:** Berechnet Hashtabellen für `body` (nur Text) und `full` (Text + Metadaten).
|
||||||
|
6. **Change Detection:**
|
||||||
|
* Vergleich des Hashes mit Qdrant.
|
||||||
|
* Strategie wählbar via ENV `MINDNET_CHANGE_DETECTION_MODE` (`full` oder `body`).
|
||||||
|
7. **Chunking anwenden:** Zerlegung des Textes basierend auf dem ermittelten Profil (siehe Kap. 3).
|
||||||
|
8. **Smart Edge Allocation (WP15):**
|
||||||
|
* Wenn `enable_smart_edge_allocation: true`: Der `SemanticAnalyzer` sendet Chunks an das LLM.
|
||||||
|
* **Traffic Control:** Request nutzt `priority="background"`. Semaphore (Limit via `.env`) drosselt die Last.
|
||||||
|
* **Resilienz:** Bei Timeout (Ollama) greift ein Fallback (Broadcasting an alle Chunks).
|
||||||
|
9. **Inline-Kanten finden:** Parsing von `[[rel:...]]`.
|
||||||
|
10. **Callout-Kanten finden:** Parsing von `> [!edge]`.
|
||||||
|
11. **Default-Edges erzeugen:** Anwendung der `edge_defaults` aus Registry.
|
||||||
|
12. **Strukturkanten erzeugen:** `belongs_to`, `next`, `prev`.
|
||||||
|
13. **Embedding (Async):** Generierung via `nomic-embed-text` (768 Dim).
|
||||||
|
14. **Diagnose:** Integritäts-Check nach dem Lauf.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Betrieb & CLI Befehle
|
||||||
|
|
||||||
|
### 2.1 Standard-Betrieb (Inkrementell)
|
||||||
|
Für regelmäßige Updates (Cronjob). Erkennt Änderungen via Hash.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export QDRANT_URL="http://localhost:6333"
|
||||||
|
export COLLECTION_PREFIX="mindnet"
|
||||||
|
# Steuert, wann eine Datei als "geändert" gilt
|
||||||
|
export MINDNET_CHANGE_DETECTION_MODE="full"
|
||||||
|
|
||||||
|
# Nutzt das Venv der Produktionsumgebung
|
||||||
|
/home/llmadmin/mindnet/.venv/bin/python3 -m scripts.import_markdown \
|
||||||
|
--vault ./vault \
|
||||||
|
--prefix "$COLLECTION_PREFIX" \
|
||||||
|
--apply \
|
||||||
|
--purge-before-upsert \
|
||||||
|
--sync-deletes
|
||||||
|
```
|
||||||
|
|
||||||
|
> **[!WARNING] Purge-Before-Upsert**
|
||||||
|
> Das Flag `--purge-before-upsert` ist kritisch. Es löscht vor dem Schreiben einer Note ihre alten Chunks/Edges. Ohne dieses Flag entstehen **"Geister-Chunks"** (alte Textabschnitte, die im Markdown gelöscht wurden, aber im Index verbleiben).
|
||||||
|
|
||||||
|
### 2.2 Full Rebuild (Clean Slate)
|
||||||
|
Notwendig bei Änderungen an `types.yaml` (z.B. neue Chunking-Profile) oder Modell-Wechsel.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 0. Modell sicherstellen
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
|
||||||
|
# 1. Qdrant Collections löschen (Wipe)
|
||||||
|
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
||||||
|
|
||||||
|
# 2. Vollständiger Import (Force)
|
||||||
|
# --force ignoriert alle Hashes und schreibt alles neu
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Chunking & Payload
|
||||||
|
|
||||||
|
Das Chunking ist profilbasiert und in `types.yaml` konfiguriert.
|
||||||
|
|
||||||
|
### 3.1 Profile und Strategien
|
||||||
|
|
||||||
|
| Profil | Strategie | Parameter | Einsatzgebiet |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `sliding_short` | `sliding_window` | Max: 350, Target: 200 | Kurze Logs, Chats, Risiken. |
|
||||||
|
| `sliding_standard` | `sliding_window` | Max: 650, Target: 450 | Massendaten (Journal, Quellen). |
|
||||||
|
| `sliding_smart_edges`| `sliding_window` | Max: 600, Target: 400 | Fließtexte mit hohem Wert (Projekte, Erfahrungen). |
|
||||||
|
| `structured_smart_edges` | `by_heading` | `strict: false` (Soft) | Strukturierte Texte, wo kleine Abschnitte gemergt werden dürfen. |
|
||||||
|
| `structured_smart_edges_strict` | `by_heading` | `strict: true` (Hard) | **Atomare Einheiten**: Entscheidungen, Werte, Profile. |
|
||||||
|
| `structured_smart_edges_strict_L3`| `by_heading` | `strict: true`, `level: 3` | Tief geschachtelte Prinzipien (Tier 2/MP1 Logik). |
|
||||||
|
|
||||||
|
### 3.2 Die `by_heading` Logik (v2.9 Hybrid)
|
||||||
|
|
||||||
|
Die Strategie `by_heading` zerlegt Texte anhand ihrer Struktur (Überschriften). Sie unterstützt seit v2.9 ein "Safety Net" gegen zu große Chunks.
|
||||||
|
|
||||||
|
* **Split Level:** Definiert die Tiefe (z.B. `2` = H1 & H2 triggern Split).
|
||||||
|
* **Modus "Strict" (`strict_heading_split: true`):**
|
||||||
|
* Jede Überschrift (`<= split_level`) erzwingt einen neuen Chunk.
|
||||||
|
* *Merge-Check:* Wenn der vorherige Chunk leer war (nur Überschriften), wird gemergt (verhindert verwaiste Überschriften).
|
||||||
|
* *Safety Net:* Wird ein Abschnitt zu lang (> `max` Token), wird auch ohne Überschrift getrennt.
|
||||||
|
* **Modus "Soft" (`strict_heading_split: false`):**
|
||||||
|
* **Hierarchie-Check:** Überschriften *oberhalb* des Split-Levels (z.B. H1 bei Level 2) erzwingen **immer** einen Split.
|
||||||
|
* **Füll-Logik:** Überschriften *auf* dem Split-Level (z.B. H2) lösen nur dann einen neuen Chunk aus, wenn der aktuelle Chunk die `target`-Größe erreicht hat.
|
||||||
|
* *Safety Net:* Auch hier greift das `max` Token Limit.
|
||||||
|
|
||||||
|
### 3.3 Payload-Felder (Qdrant)
|
||||||
|
|
||||||
|
* `text`: Der reine Inhalt (Anzeige im UI). Überschriften bleiben erhalten.
|
||||||
|
* `window`: Inhalt plus Overlap (für Embedding). Bei `by_heading` wird der Kontext (Eltern-Überschrift) oft vorangestellt.
|
||||||
|
* `chunk_profile`: Das effektiv genutzte Profil (zur Nachverfolgung).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Edge-Erzeugung & Prioritäten
|
||||||
|
|
||||||
|
Kanten werden nach Vertrauenswürdigkeit (`provenance`) priorisiert. Die höhere Prio gewinnt.
|
||||||
|
|
||||||
|
| Prio | Quelle | Rule ID | Confidence |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **1** | Inline | `inline:rel` | 0.95 |
|
||||||
|
| **2** | Callout | `callout:edge` | 0.90 |
|
||||||
|
| **3** | Wikilink | `explicit:wikilink` | 1.00 |
|
||||||
|
| **4** | Smart Edge | `smart:llm_filter` | 0.90 |
|
||||||
|
| **5** | Type Default | `edge_defaults` | 0.70 |
|
||||||
|
| **6** | Struktur | `structure` | 1.00 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Quality Gates & Tests
|
||||||
|
|
||||||
|
Diese Tests garantieren die Stabilität der Pipeline.
|
||||||
|
|
||||||
|
**1. Payload Dryrun (Schema-Check):**
|
||||||
|
Simuliert Import, prüft JSON-Schema Konformität.
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.payload_dryrun --vault ./test_vault
|
||||||
|
```
|
||||||
|
|
||||||
|
**2. Full Edge Check (Graph-Integrität):**
|
||||||
|
Prüft Invarianten (z.B. `next` muss reziprok zu `prev` sein).
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.edges_full_check
|
||||||
|
```
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer, data_scientist
|
||||||
|
scope: backend, retrieval, scoring
|
||||||
|
status: active
|
||||||
|
version: 2.6
|
||||||
|
context: "Formeln und Algorithmen des Hybrid Retrievers und Explanation Layer."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Retrieval & Scoring Algorithmen
|
||||||
|
|
||||||
|
Der Retriever (`app/core/retriever.py`) unterstützt **Semantic Search** und **Hybrid Search**. Seit v2.4 (WP04a) nutzt Mindnet ein gewichtetes Scoring-Modell, das Semantik, Graphentheorie und Metadaten kombiniert.
|
||||||
|
|
||||||
|
## 1. Scoring Formel (WP04a)
|
||||||
|
|
||||||
|
Der Gesamtscore eines Treffers berechnet sich als gewichtete Summe. Alle Gewichte ($W$) sind in `retriever.yaml` konfigurierbar.
|
||||||
|
|
||||||
|
$$
|
||||||
|
TotalScore = (W_{sem} \cdot S_{sem} \cdot \max(W_{type}, 0)) + (W_{edge} \cdot B_{edge}) + (W_{cent} \cdot B_{cent})
|
||||||
|
$$
|
||||||
|
|
||||||
|
### Die Komponenten
|
||||||
|
|
||||||
|
**1. Semantic Score ($S_{sem}$):**
|
||||||
|
* **Basis:** Cosine Similarity des Vektors.
|
||||||
|
* **Modell:** `nomic-embed-text` (768d).
|
||||||
|
* **Wertebereich:** 0.0 bis 1.0.
|
||||||
|
|
||||||
|
**2. Type Weight ($W_{type}$):**
|
||||||
|
* **Herkunft:** Feld `retriever_weight` aus der Note/Chunk Payload.
|
||||||
|
* **Zweck:** Priorisierung bestimmter Dokumententypen unabhängig vom Inhalt.
|
||||||
|
* **Beispiel:** Eine `decision` (Gewicht 1.0) schlägt ein `concept` (Gewicht 0.6) bei gleicher textueller Ähnlichkeit.
|
||||||
|
|
||||||
|
**3. Edge Bonus ($B_{edge}$):**
|
||||||
|
* **Kontext:** Berechnet im lokalen Subgraphen (Expansion Tiefe 1).
|
||||||
|
* **Logik:** Summe der `confidence` aller eingehenden Kanten, die von Knoten stammen, die *ebenfalls* im aktuellen Result-Set (oder dem übergebenen Kontext) enthalten sind.
|
||||||
|
* **Zweck:** Belohnt Chunks, die "im Thema" vernetzt sind.
|
||||||
|
|
||||||
|
**4. Centrality Bonus ($B_{cent}$):**
|
||||||
|
* **Kontext:** Berechnet im lokalen Subgraphen.
|
||||||
|
* **Logik:** Eine vereinfachte PageRank-Metrik (Degree Centrality) im temporären Graphen.
|
||||||
|
* **Zweck:** Belohnt "Hubs", die viele Verbindungen zu anderen Treffern haben.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Hybrid Retrieval Flow
|
||||||
|
|
||||||
|
Der Hybrid-Modus ist der Standard für den Chat (`/chat`). Er läuft in drei Phasen ab:
|
||||||
|
|
||||||
|
**Phase 1: Vector Search (Seed Generation)**
|
||||||
|
* Suche die Top-K (z.B. 20) Kandidaten via Embeddings in Qdrant.
|
||||||
|
* Dies sind die "Seeds" für den Graphen.
|
||||||
|
|
||||||
|
**Phase 2: Graph Expansion**
|
||||||
|
* Nutze `graph_adapter.expand(seeds, depth=1)`.
|
||||||
|
* Lade alle direkten Nachbarn (Incoming & Outgoing) der Seeds aus der `_edges` Collection.
|
||||||
|
* Konstruiere einen temporären `NetworkX`-Graphen im Speicher (`Subgraph`).
|
||||||
|
|
||||||
|
**Phase 3: Re-Ranking**
|
||||||
|
* Berechne für jeden Knoten im Subgraphen die Boni ($B_{edge}$, $B_{cent}$).
|
||||||
|
* Wende die Scoring-Formel an.
|
||||||
|
* Sortiere die Liste neu absteigend nach `TotalScore`.
|
||||||
|
* Schneide die Liste beim finalen Limit (z.B. 5) ab.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Explanation Layer (WP04b)
|
||||||
|
|
||||||
|
Wenn der Parameter `explain=True` an die API übergeben wird, generiert der Retriever ein `Explanation` Objekt für jeden Treffer.
|
||||||
|
|
||||||
|
**JSON-Struktur der Erklärung:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"score_breakdown": {
|
||||||
|
"semantic": 0.85,
|
||||||
|
"type_boost": 1.0,
|
||||||
|
"edge_bonus": 0.4,
|
||||||
|
"centrality": 0.1
|
||||||
|
},
|
||||||
|
"reasons": [
|
||||||
|
"Hohe textuelle Übereinstimmung (>0.85).",
|
||||||
|
"Bevorzugt, da Typ 'decision' (Gewicht 1.0).",
|
||||||
|
"Wird referenziert von 'Projekt Alpha' via 'depends_on'."
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Logik der Text-Generierung:**
|
||||||
|
* **Semantik:** Wenn $S_{sem} > 0.8$: "Hohe Übereinstimmung".
|
||||||
|
* **Typ:** Wenn $W_{type} > 0.8$: "Bevorzugt, da Typ X".
|
||||||
|
* **Graph:** Listet bis zu 3 eingehende Kanten mit hoher Konfidenz auf ("Wird referenziert von...").
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Konfiguration (`retriever.yaml`)
|
||||||
|
|
||||||
|
Diese Datei steuert die Balance der Formel.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
scoring:
|
||||||
|
semantic_weight: 1.0 # Basis-Relevanz (sollte immer ca. 1.0 sein)
|
||||||
|
edge_weight: 0.7 # Einfluss des Graphen (0.5 - 1.0 empfohlen)
|
||||||
|
centrality_weight: 0.5 # Einfluss der Zentralität (Hub-Bonus)
|
||||||
|
|
||||||
|
# Kanten-spezifische Gewichtung für den Edge-Bonus
|
||||||
|
edge_weights:
|
||||||
|
depends_on: 1.5 # Harte Abhängigkeiten sehr stark gewichten
|
||||||
|
blocks: 1.5 # Risiken/Blocker stark gewichten
|
||||||
|
caused_by: 1.2 # Kausalitäten moderat stärken
|
||||||
|
related_to: 0.5 # Weiche Themen schwächer gewichten
|
||||||
|
references: 0.8 # Standard-Referenzen
|
||||||
|
```
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
---
|
||||||
|
doc_type: operations_manual
|
||||||
|
audience: admin, devops
|
||||||
|
scope: deployment, maintenance, backup
|
||||||
|
status: active
|
||||||
|
version: 2.6
|
||||||
|
context: "Installationsanleitung, Systemd-Units und Wartungsprozesse."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Admin Operations Guide
|
||||||
|
|
||||||
|
## 1. Installation & Setup
|
||||||
|
|
||||||
|
### 1.1 Voraussetzungen
|
||||||
|
* **OS:** Ubuntu 22.04+ (empfohlen).
|
||||||
|
* **Tools:** Python 3.10+, Docker, Ollama.
|
||||||
|
* **Hardware:** Min. 8GB RAM, 4 CPU Cores (für Async Import).
|
||||||
|
|
||||||
|
### 1.2 Qdrant (Docker)
|
||||||
|
Startet die Vektor-DB mit persistentem Storage auf Port 6333.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run -d \
|
||||||
|
--name mindnet_qdrant \
|
||||||
|
--restart always \
|
||||||
|
-p 6333:6333 \
|
||||||
|
-v $(pwd)/qdrant_storage:/qdrant/storage \
|
||||||
|
qdrant/qdrant
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.3 Ollama (Modelle)
|
||||||
|
**Wichtig:** Seit v2.4 ist `nomic-embed-text` Pflicht für Embeddings.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Modelle laden
|
||||||
|
ollama pull phi3:mini
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
|
||||||
|
# Testen
|
||||||
|
curl http://localhost:11434/api/generate -d '{"model": "phi3:mini", "prompt":"Hi"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Deployment (Systemd Services)
|
||||||
|
|
||||||
|
Wir unterscheiden strikt zwischen **Prod** (Port 8001/8501) und **Dev** (Port 8002/8502).
|
||||||
|
|
||||||
|
### 2.1 Backend Service (`/etc/systemd/system/mindnet-prod.service`)
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[Unit]
|
||||||
|
Description=Mindnet API Prod (8001)
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=llmadmin
|
||||||
|
Group=llmadmin
|
||||||
|
WorkingDirectory=/home/llmadmin/mindnet
|
||||||
|
# Startet Uvicorn (Async Server)
|
||||||
|
ExecStart=/home/llmadmin/mindnet/.venv/bin/uvicorn app.main:app --host 0.0.0.0 --port 8001 --env-file .env
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 UI Service (`/etc/systemd/system/mindnet-ui-prod.service`)
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[Unit]
|
||||||
|
Description=Mindnet UI Prod (8501)
|
||||||
|
After=mindnet-prod.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=llmadmin
|
||||||
|
Group=llmadmin
|
||||||
|
WorkingDirectory=/home/llmadmin/mindnet
|
||||||
|
|
||||||
|
# Environment für Streamlit Port & API-Ziel
|
||||||
|
Environment="MINDNET_API_URL=http://localhost:8001"
|
||||||
|
Environment="MINDNET_API_TIMEOUT=300"
|
||||||
|
Environment="STREAMLIT_SERVER_PORT=8501"
|
||||||
|
Environment="STREAMLIT_SERVER_ADDRESS=0.0.0.0"
|
||||||
|
Environment="STREAMLIT_SERVER_HEADLESS=true"
|
||||||
|
|
||||||
|
# WICHTIG: Pfad zur neuen Router-Datei (ui.py)
|
||||||
|
ExecStart=/home/llmadmin/mindnet/.venv/bin/streamlit run app/frontend/ui.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Wartung & Cronjobs
|
||||||
|
|
||||||
|
### 3.1 Regelmäßiger Import (Cron)
|
||||||
|
Führt den Sync stündlich durch. Nutzt `--purge-before-upsert` für Sauberkeit.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Crontab Eintrag (user: llmadmin)
|
||||||
|
0 * * * * cd /home/llmadmin/mindnet && .venv/bin/python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --purge-before-upsert --sync-deletes >> ./logs/import.log 2>&1
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 Troubleshooting Guide
|
||||||
|
|
||||||
|
**Fehler: "ModuleNotFoundError: No module named 'st_cytoscape'"**
|
||||||
|
* Ursache: Alte Dependencies oder falsches Paket installiert.
|
||||||
|
* Lösung: Environment aktualisieren.
|
||||||
|
```bash
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip uninstall streamlit-cytoscapejs
|
||||||
|
pip install st-cytoscape
|
||||||
|
# Oder sicherheitshalber:
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
**Fehler: "Vector dimension error: expected 768, got 384"**
|
||||||
|
* Ursache: Alte DB (v2.2), neues Modell (v2.4).
|
||||||
|
* Lösung: **Full Reset** (siehe Kap. 4.2).
|
||||||
|
|
||||||
|
**Fehler: Import sehr langsam**
|
||||||
|
* Ursache: Smart Edges sind aktiv und analysieren jeden Chunk.
|
||||||
|
* Lösung: `MINDNET_LLM_BACKGROUND_LIMIT` prüfen oder Feature in `types.yaml` deaktivieren.
|
||||||
|
|
||||||
|
**Fehler: UI "Read timed out"**
|
||||||
|
* Ursache: Backend braucht für Smart Edges länger als 60s.
|
||||||
|
* Lösung: `MINDNET_API_TIMEOUT=300.0` in `.env` setzen (oder im Systemd Service).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Backup & Restore
|
||||||
|
|
||||||
|
### 4.1 Qdrant Snapshot
|
||||||
|
Sichert den Vektor-Index.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker stop mindnet_qdrant
|
||||||
|
tar -czf qdrant_backup_$(date +%F).tar.gz ./qdrant_storage
|
||||||
|
docker start mindnet_qdrant
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 Notfall-Rebuild (Clean Slate)
|
||||||
|
Wenn alles inkonsistent ist oder Dimensionen sich ändern:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. DB löschen
|
||||||
|
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
||||||
|
|
||||||
|
# 2. Neu importieren (Force Hash recalculation)
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
```
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
---
|
||||||
|
doc_type: operations_manual
|
||||||
|
audience: system_admin, devops
|
||||||
|
scope: server_lifecycle, disaster_recovery, maintenance, backup, monitoring
|
||||||
|
status: active
|
||||||
|
version: 1.9
|
||||||
|
hostname: llm-node
|
||||||
|
ip_address: 192.168.2.144
|
||||||
|
context: "Zentrale Dokumentation für Host-Konfiguration, Mindnet-Applikation, Gitea und Backup-Strategie. Aktualisiert um die Two-Stage Disaster Recovery und Backup-Monitoring."
|
||||||
|
created_date: 2025-12-14
|
||||||
|
last_updated: 2025-12-15
|
||||||
|
---
|
||||||
|
|
||||||
|
# Server Operations Manual: llm-node (192.168.2.144)
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt den Betrieb, die Wartung und die Wiederherstellung (Disaster Recovery) des Servers "llm-node".
|
||||||
|
|
||||||
|
## 1. Systemübersicht & Netzwerk
|
||||||
|
|
||||||
|
### 1.1 Host Details
|
||||||
|
* **Hostname:** `llm-node`
|
||||||
|
* **IP-Adresse:** `192.168.2.144`
|
||||||
|
* **OS:** Ubuntu Server
|
||||||
|
* **Qdrant Host-Volume Pfad:** `/home/llmadmin/docker/qdrant/qdrant_data` (Bind-Mount)
|
||||||
|
|
||||||
|
### 1.2 Storage & NAS Mount
|
||||||
|
Das System sichert auf ein Synology NAS via NFSv3.
|
||||||
|
|
||||||
|
* **Mount Point:** `/mnt/nas_backup`
|
||||||
|
* **Quelle:** `192.168.2.63:/volume1/Backup_LLM`
|
||||||
|
* **Fstab-Eintrag (Referenz für Restore):**
|
||||||
|
```text
|
||||||
|
192.168.2.63:/volume1/Backup_LLM /mnt/nas_backup nfs vers=3,_netdev,x-systemd.automount,nofail 0 0
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Dienste & Port-Matrix
|
||||||
|
|
||||||
|
### 2.1 Native Dienste (Systemd)
|
||||||
|
|
||||||
|
| Service | Port | User | Beschreibung |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **SSH** | 22 | root | Remote Zugriff |
|
||||||
|
| **Gitea** | 3000 | `git` | Git Version Control (User: git) |
|
||||||
|
| **Ollama** | 11434 | `ollama` | AI Model Server |
|
||||||
|
| **Mindnet Prod API** | 8001 | `llmadmin` | Backend Applikation |
|
||||||
|
| **Mindnet Dev API** | 8002 | `llmadmin` | Backend Applikation (Entwicklung) |
|
||||||
|
| **Mindnet Prod UI** | 8501 | `llmadmin` | Frontend Applikation |
|
||||||
|
| **Mindnet Dev UI** | 8502 | `llmadmin` | Frontend Applikation (Entwicklung) |
|
||||||
|
| **Act Runner** | 38703 | `root` | Gitea CI/CD Runner |
|
||||||
|
|
||||||
|
### 2.2 Docker Container
|
||||||
|
Übersicht der Container (`docker ps`).
|
||||||
|
|
||||||
|
| Container Name | Port | Beschreibung | Backup Strategie |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **qdrant** | 6333 | Vektor Datenbank (Container Name: `qdrant`) | **Stop -> Tar -> Start** (Konsistenter Snapshot) |
|
||||||
|
| **mindnet-embed** | 8990 | Embeddings Service | Volume Backup |
|
||||||
|
| **code-server** | 8443 | VS Code (Web) | Volume Backup |
|
||||||
|
| **silverbullet** | 13000 | Knowledge Base | Volume Backup |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Applikations-Management
|
||||||
|
|
||||||
|
### 3.1 Gitea (Git Server)
|
||||||
|
* **User:** `git`
|
||||||
|
* **Datenpfad:** `/var/lib/gitea`
|
||||||
|
* **Backup:** Konsistenter Dump (`gitea-dump.zip`) im `before_backup` Hook integriert.
|
||||||
|
|
||||||
|
### 3.2 Ollama (AI Models)
|
||||||
|
* **User:** `ollama`
|
||||||
|
* **Modell-Speicher:** `/usr/share/ollama/.ollama/models`
|
||||||
|
* **Backup:** Nur Metadaten. Blobs werden exkludiert.
|
||||||
|
|
||||||
|
### 3.3 Mindnet (AI App)
|
||||||
|
* **User:** `llmadmin`
|
||||||
|
* **Qdrant Storage:** `/home/llmadmin/docker/qdrant/qdrant_data`
|
||||||
|
* **Cronjob:** Regelmäßiger Import (stündlich) unter User `llmadmin`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Backup Strategie (Borgmatic)
|
||||||
|
|
||||||
|
**Status:** Automatisiert via `systemctl start borgmatic.timer`.
|
||||||
|
**Ziel:** `/mnt/nas_backup/borg_repo`
|
||||||
|
|
||||||
|
### 4.1 Konsistenz-Strategie
|
||||||
|
Alle schreibenden Dienste werden durch Hooks für das Backup vorbereitet:
|
||||||
|
|
||||||
|
### 4.2 Konfiguration (`/etc/borgmatic/config.yaml`)
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
source_directories:
|
||||||
|
- /etc
|
||||||
|
- /home
|
||||||
|
- /var
|
||||||
|
- /opt
|
||||||
|
- /root
|
||||||
|
|
||||||
|
repositories:
|
||||||
|
- path: /mnt/nas_backup/borg_repo
|
||||||
|
label: nas
|
||||||
|
|
||||||
|
exclude_patterns:
|
||||||
|
- /mnt/*
|
||||||
|
- /var/lib/gitea/data/tmp/*
|
||||||
|
# Ollama Blobs (Speicher sparen)
|
||||||
|
- /usr/share/ollama/.ollama/models/blobs/*
|
||||||
|
- /home/*/.ollama/models/blobs/*
|
||||||
|
# Qdrant Live-Daten exkludieren
|
||||||
|
- /home/llmadmin/docker/qdrant/qdrant_data/*
|
||||||
|
|
||||||
|
keep_daily: 7
|
||||||
|
keep_weekly: 4
|
||||||
|
keep_monthly: 6
|
||||||
|
|
||||||
|
before_backup:
|
||||||
|
- echo "--- Start Pre-Backup Hooks ---"
|
||||||
|
|
||||||
|
# 1. Ollama Liste sichern
|
||||||
|
- ollama list > /root/ollama_models_backup.txt
|
||||||
|
|
||||||
|
# 2. Gitea Dump
|
||||||
|
- echo "Erstelle Gitea Dump..."
|
||||||
|
- rm -f /var/lib/gitea/gitea-dump.zip
|
||||||
|
- runuser -u git -- gitea dump -c /etc/gitea/app.ini -f /var/lib/gitea/gitea-dump.zip
|
||||||
|
|
||||||
|
# 3. Qdrant Snapshot
|
||||||
|
- echo "Erstelle Qdrant Snapshot..."
|
||||||
|
- docker stop qdrant
|
||||||
|
- rm -f /home/llmadmin/qdrant_backup_latest.tar.gz
|
||||||
|
# Tar Archiv im Home-Verzeichnis erstellen (wird von Borg gesichert)
|
||||||
|
- tar -czf /home/llmadmin/qdrant_backup_latest.tar.gz -C /home/llmadmin/docker/qdrant qdrant_data
|
||||||
|
- docker start qdrant
|
||||||
|
|
||||||
|
after_backup:
|
||||||
|
- echo "Backup erfolgreich beendet."
|
||||||
|
# Nach erfolgreichem Backup wird das temporäre Tar-Archiv gelöscht
|
||||||
|
- rm -f /home/llmadmin/qdrant_backup_latest.tar.gz
|
||||||
|
|
||||||
|
on_error:
|
||||||
|
- echo "FEHLER aufgetreten! Versuche Container zu retten..."
|
||||||
|
- docker start qdrant
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Disaster Recovery (Wiederherstellung) - Two-Stage DR
|
||||||
|
|
||||||
|
Das Wiederherstellungsverfahren basiert auf einer **"Two-Stage DR"**-Strategie, die die Geschwindigkeit eines Basis-Images mit der Datenkonsistenz des Borgmatic-Archives kombiniert.
|
||||||
|
|
||||||
|
### 5.0 Vorbereitung: Erstellung des Basis-Images (Monatlich/Quartalsweise)
|
||||||
|
|
||||||
|
Dieses Image sichert das bootfähige System (OS, Pakete, Konfiguration) und dient als schneller Startpunkt bei einem Festplattenausfall.
|
||||||
|
|
||||||
|
1. **System Bereinigen:** Führen Sie eine Systembereinigung durch, um die Image-Größe zu minimieren.
|
||||||
|
```bash
|
||||||
|
sudo apt clean
|
||||||
|
sudo journalctl --vacuum-time=7d
|
||||||
|
```
|
||||||
|
2. **Booten vom Live-Medium:** Starten Sie den Server von einem **Ubuntu Live USB-Stick** (Größe min. 8 GB).
|
||||||
|
3. **Mount NAS:** Stellen Sie die Verbindung zum NAS her, um das Image direkt dorthin zu schreiben.
|
||||||
|
```bash
|
||||||
|
sudo mkdir /mnt/nas_backup
|
||||||
|
sudo mount -t nfs 192.168.2.63:/volume1/Backup_LLM /mnt/nas_backup
|
||||||
|
```
|
||||||
|
4. **Image erstellen und streamen:** Ermitteln Sie die Root-Partition des Servers (z.B. `/dev/sda1`) und erstellen Sie das komprimierte Image direkt auf dem NAS.
|
||||||
|
```bash
|
||||||
|
# Das Image wird direkt zum NAS gestreamt (USB-Stick benötigt nur 8GB für Live OS)
|
||||||
|
sudo dd if=/dev/sda1 bs=1M status=progress | gzip > /mnt/nas_backup/base_image_$(date +%Y%m%d).img.gz
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.1 Stage 1: Basis-Image Restore (Bare Metal Recovery)
|
||||||
|
|
||||||
|
Dieses Verfahren setzt das System auf den Stand des letzten Basis-Images zurück.
|
||||||
|
|
||||||
|
**Prozedur (Von Live-Medium booten):**
|
||||||
|
|
||||||
|
1. **Voraussetzungen:** Booten Sie den neuen/reparierten PC von einem **Live-Medium** (z.B. Ubuntu Live USB).
|
||||||
|
2. **Mount NAS (auf Live-System):** Stellen Sie die Verbindung zum Backup-Speicher her, um auf das Image zuzugreifen.
|
||||||
|
```bash
|
||||||
|
sudo mkdir /mnt/nas_backup
|
||||||
|
sudo mount -t nfs 192.168.2.63:/volume1/Backup_LLM /mnt/nas_backup
|
||||||
|
```
|
||||||
|
3. **Zielpartition identifizieren:** Ermitteln Sie den Gerätenamen der Root-Partition der **neuen** Festplatte (z.B. `/dev/sda1`). **ACHTUNG: Falsches Gerät löscht alle Daten!**
|
||||||
|
```bash
|
||||||
|
sudo fdisk -l
|
||||||
|
```
|
||||||
|
4. **Image Restore:** Schreiben Sie das komprimierte Basis-Image auf die neue Partition zurück. Ersetzen Sie `YYYYMMDD` durch das tatsächliche Datum und `/dev/sda1` durch Ihre Zielpartition.
|
||||||
|
```bash
|
||||||
|
sudo gunzip -c /mnt/nas_backup/base_image_YYYYMMDD.img.gz | sudo dd of=/dev/sda1 status=progress bs=1M
|
||||||
|
```
|
||||||
|
5. **Neustart:** Entfernen Sie den Live-USB und starten Sie das System neu. Es sollte nun in das wiederhergestellte Basis-OS booten.
|
||||||
|
|
||||||
|
### 5.2 Stage 2: Daten-Update (Borgmatic)
|
||||||
|
|
||||||
|
Nach dem Booten des Basis-Systems (Stage 1) werden die aktuellen Daten und die kritischen Applikations-Snapshots wiederhergestellt.
|
||||||
|
|
||||||
|
#### Schritt 1: Aktueller Daten Restore (Borg)
|
||||||
|
Das Borg-Repository ist dank des Basis-Images bereits in `/etc/borgmatic/config.yaml` und `/etc/fstab` bekannt.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Alle Daten aus dem letzten Archiv (latest) auf das laufende System wiederherstellen
|
||||||
|
sudo borgmatic extract --archive latest --path / --destination /
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Schritt 2: Dienste spezifisch wiederherstellen (Gitea/Qdrant/Ollama)
|
||||||
|
|
||||||
|
**A. Gitea (Aus Dump):**
|
||||||
|
1. Dump entpacken: `unzip /var/lib/gitea/gitea-dump.zip -d /tmp/gitea_restore`
|
||||||
|
2. Service starten: `systemctl enable --now gitea`
|
||||||
|
|
||||||
|
**B. Qdrant (Aus Snapshot):**
|
||||||
|
Das Tar-Archiv liegt im Home-Verzeichnis (`/home/llmadmin/`) und muss in das Volume-Verzeichnis entpackt werden.
|
||||||
|
|
||||||
|
1. Wechsle in das Host-Verzeichnis des Volumes:
|
||||||
|
```bash
|
||||||
|
cd /home/llmadmin/docker/qdrant
|
||||||
|
```
|
||||||
|
2. Entpacke das gesicherte Tar (stellt den Ordner `qdrant_data` wieder her):
|
||||||
|
```bash
|
||||||
|
sudo tar -xzf /home/llmadmin/qdrant_backup_latest.tar.gz
|
||||||
|
```
|
||||||
|
3. Container starten (Volume-Mount ist korrekt):
|
||||||
|
```bash
|
||||||
|
docker start qdrant
|
||||||
|
```
|
||||||
|
|
||||||
|
**C. Ollama (Smart Restore):**
|
||||||
|
1. Ollama installieren (falls im Basis-Image nicht enthalten).
|
||||||
|
2. Modelle mit dem Script aus `/root/ollama_models_backup.txt` neu ziehen:
|
||||||
|
```bash
|
||||||
|
sudo tail -n +2 /root/ollama_models_backup.txt | awk '{print $1}' | while read model; do ollama pull "$model"; done
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Log- und Fehleranalyse & Wartung
|
||||||
|
|
||||||
|
### 6.1 Backup-Überwachung (Monitoring)
|
||||||
|
|
||||||
|
Die Überprüfung der Backup-Korrektheit erfolgt über das Systemd Journal und die Borgmatic-Befehle.
|
||||||
|
|
||||||
|
| Aktion | Befehl | Zweck |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Prüfung letzter Lauf** | `sudo journalctl -u borgmatic --since "yesterday"` | Zeigt das Journal der letzten 24 Stunden, inklusive der Hooks und Fehler. |
|
||||||
|
| **Liste Archive** | `sudo borgmatic list` | Zeigt alle existierenden Archive, sortiert nach Datum/Uhrzeit. Dient zur Bestätigung, dass das Backup erstellt wurde. |
|
||||||
|
| **Repo-Integrität** | `sudo borgmatic check` | Führt eine Konsistenzprüfung des gesamten Repositorys durch (kann lange dauern). |
|
||||||
|
|
||||||
|
### 6.2 Granulare Wiederherstellung (Einzelne Dateien)
|
||||||
|
|
||||||
|
Um auf einzelne Dateien oder Verzeichnisse in einem Archiv zuzugreifen, wird das Archiv als virtuelles Dateisystem gemountet.
|
||||||
|
|
||||||
|
1. **Mount-Punkt erstellen:**
|
||||||
|
```bash
|
||||||
|
mkdir /tmp/borg_mount
|
||||||
|
```
|
||||||
|
2. **Archiv einhängen:** Hängen Sie das gewünschte Archiv (hier: `latest`) in den Mount-Punkt ein. Geben Sie bei Bedarf den vollständigen ARCHIVNAMEN an.
|
||||||
|
```bash
|
||||||
|
sudo borgmatic mount --destination /tmp/borg_mount --archive latest
|
||||||
|
```
|
||||||
|
3. **Dateizugriff:** Das gesamte Backup-Dateisystem ist nun unter `/tmp/borg_mount` verfügbar. Dateien können mit `cp` kopiert werden.
|
||||||
|
```bash
|
||||||
|
# Beispiel: Eine Datei aus dem Home-Verzeichnis wiederherstellen
|
||||||
|
sudo cp /tmp/borg_mount/home/llmadmin/wichtige_datei.txt /home/llmadmin/
|
||||||
|
```
|
||||||
|
4. **Archiv aushängen:** Nach dem Kopieren muss das virtuelle Dateisystem immer ausgehängt werden.
|
||||||
|
```bash
|
||||||
|
sudo umount /tmp/borg_mount
|
||||||
|
# Oder:
|
||||||
|
# sudo borgmatic umount /tmp/borg_mount
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Anhang
|
||||||
|
|
||||||
|
* **Qdrant Container Logs:** `docker logs qdrant`
|
||||||
|
* **Applikations-Logs:** `journalctl -u mindnet-prod`
|
||||||
@@ -0,0 +1,457 @@
|
|||||||
|
---
|
||||||
|
doc_type: developer_guide
|
||||||
|
audience: developer
|
||||||
|
scope: workflow, testing, architecture, modules
|
||||||
|
status: active
|
||||||
|
version: 2.6.1
|
||||||
|
context: "Umfassender Guide für Entwickler: Architektur, Modul-Interna (Deep Dive), Setup, Git-Workflow und Erweiterungs-Anleitungen."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet Developer Guide & Workflow
|
||||||
|
|
||||||
|
**Quellen:** `developer_guide.md`, `dev_workflow.md`, `Architecture_Audit_v2.6`
|
||||||
|
|
||||||
|
Dieser Guide ist die zentrale technische Referenz für Mindnet v2.6. Er vereint das technische Verständnis der Module mit dem operativen Workflow zwischen Windows (Dev) und Linux (Runtime).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Inhaltsverzeichnis
|
||||||
|
- [Mindnet Developer Guide \& Workflow](#mindnet-developer-guide--workflow)
|
||||||
|
- [Inhaltsverzeichnis](#inhaltsverzeichnis)
|
||||||
|
- [1. Einführung \& Systemüberblick](#1-einführung--systemüberblick)
|
||||||
|
- [Was ist Mindnet?](#was-ist-mindnet)
|
||||||
|
- [Kern-Philosophie](#kern-philosophie)
|
||||||
|
- [2. Architektur](#2-architektur)
|
||||||
|
- [2.1 High-Level Übersicht](#21-high-level-übersicht)
|
||||||
|
- [2.2 Datenfluss-Muster](#22-datenfluss-muster)
|
||||||
|
- [A. Ingestion (Write)](#a-ingestion-write)
|
||||||
|
- [B. Retrieval (Read)](#b-retrieval-read)
|
||||||
|
- [C. Visualisierung (Graph)](#c-visualisierung-graph)
|
||||||
|
- [3. Physische Architektur](#3-physische-architektur)
|
||||||
|
- [4. Projektstruktur \& Modul-Referenz (Deep Dive)](#4-projektstruktur--modul-referenz-deep-dive)
|
||||||
|
- [4.1 Verzeichnisbaum](#41-verzeichnisbaum)
|
||||||
|
- [4.2 Frontend Architecture (`app/frontend/`)](#42-frontend-architecture-appfrontend)
|
||||||
|
- [Frontend Design Patterns (Wichtig!)](#frontend-design-patterns-wichtig)
|
||||||
|
- [4.3 Backend Architecture (`app/`)](#43-backend-architecture-app)
|
||||||
|
- [4.4 Scripts \& Tooling (Die Admin-Toolbox)](#44-scripts--tooling-die-admin-toolbox)
|
||||||
|
- [1. Script-Übersicht](#1-script-übersicht)
|
||||||
|
- [2. Einsatzszenarien \& Bewertung](#2-einsatzszenarien--bewertung)
|
||||||
|
- [5. Maintenance \& "Kill List"](#5-maintenance--kill-list)
|
||||||
|
- [6. Lokales Setup (Development)](#6-lokales-setup-development)
|
||||||
|
- [7. Der Entwicklungs-Zyklus (Workflow)](#7-der-entwicklungs-zyklus-workflow)
|
||||||
|
- [Phase 1: Windows (Code)](#phase-1-windows-code)
|
||||||
|
- [Phase 2: Beelink (Test / Dev)](#phase-2-beelink-test--dev)
|
||||||
|
- [Phase 3: Release \& Deployment (Prod)](#phase-3-release--deployment-prod)
|
||||||
|
- [8. Erweiterungs-Guide: "Teach-the-AI"](#8-erweiterungs-guide-teach-the-ai)
|
||||||
|
- [Workflow A: Neuen Typ implementieren (z. B. `type: risk`)](#workflow-a-neuen-typ-implementieren-z-b-type-risk)
|
||||||
|
- [Workflow B: Graph-Farben ändern](#workflow-b-graph-farben-ändern)
|
||||||
|
- [9. Tests \& Debugging](#9-tests--debugging)
|
||||||
|
- [10. Troubleshooting \& One-Liners](#10-troubleshooting--one-liners)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Einführung & Systemüberblick
|
||||||
|
|
||||||
|
### Was ist Mindnet?
|
||||||
|
Mindnet ist ein **Hybrides Knowledge Management System**, das klassische Notizen (Markdown) mit KI-gestützter Analyse verbindet. Es kombiniert **RAG** (Retrieval Augmented Generation) mit einer **Graphen-Datenbank** (Qdrant), um Wissen nicht nur semantisch zu finden, sondern auch strukturell zu vernetzen.
|
||||||
|
|
||||||
|
### Kern-Philosophie
|
||||||
|
1. **Filesystem First:** Die Wahrheit liegt immer auf der Festplatte (Markdown-Dateien). Die Datenbank ist ein abgeleiteter Index.
|
||||||
|
2. **Hybrid Retrieval:** Relevanz entsteht aus Textähnlichkeit (Semantik) + Graphen-Verbindungen (Edges) + Wichtigkeit (Centrality).
|
||||||
|
3. **Active Intelligence:** Das System wartet nicht nur auf Anfragen, sondern schlägt beim Schreiben proaktiv Verbindungen vor ("Matrix Logic").
|
||||||
|
4. **Local Privacy:** Alle KI-Berechnungen (Ollama) laufen lokal. Keine Cloud-Abhängigkeit für Inference.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Architektur
|
||||||
|
|
||||||
|
### 2.1 High-Level Übersicht
|
||||||
|
Das System folgt einer strikten Trennung zwischen Frontend (Streamlit) und Backend (FastAPI), wobei bestimmte Performance-Pfade (Graph-Visualisierung) optimiert wurden.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
User((User))
|
||||||
|
|
||||||
|
subgraph "Frontend Layer (Streamlit)"
|
||||||
|
UI["ui.py Router"]
|
||||||
|
ViewChat["Chat View"]
|
||||||
|
ViewGraph["Graph View"]
|
||||||
|
ViewEditor["Editor View"]
|
||||||
|
Logic["Callbacks & State"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph "Backend Layer (FastAPI)"
|
||||||
|
API["main.py"]
|
||||||
|
RouterChat["Chat / RAG"]
|
||||||
|
RouterIngest["Ingest / Write"]
|
||||||
|
CoreRet["Retriever Engine"]
|
||||||
|
CoreIngest["Ingestion Pipeline"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph "Infrastructure & Services"
|
||||||
|
LLM["Ollama (Phi3/Nomic)"]
|
||||||
|
DB[("Qdrant Vector DB")]
|
||||||
|
FS["File System (.md)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
User <--> UI
|
||||||
|
UI -- "REST (Chat, Save, Feedback)" --> API
|
||||||
|
UI -. "Direct Read (Graph Viz Performance)" .-> DB
|
||||||
|
API -- "Embeddings & Completion" --> LLM
|
||||||
|
API -- "Read/Write" --> DB
|
||||||
|
API -- "Read/Write (Source of Truth)" --> FS
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 Datenfluss-Muster
|
||||||
|
|
||||||
|
#### A. Ingestion (Write)
|
||||||
|
Vom Markdown zur Vektor-Datenbank.
|
||||||
|
```mermaid
|
||||||
|
graph LR
|
||||||
|
MD["Markdown File"] --> Parser("Parser")
|
||||||
|
Parser --> Chunker("Chunker")
|
||||||
|
Chunker -- "Text Chunks" --> SemAn{"SemanticAnalyzer<br/>(LLM)"}
|
||||||
|
SemAn -- "Smart Edges" --> Embedder("Embedder")
|
||||||
|
Embedder --> DB[("Qdrant<br/>Points")]
|
||||||
|
|
||||||
|
style DB fill:#f9f,stroke:#333,stroke-width:2px
|
||||||
|
style SemAn fill:#ff9,stroke:#333,stroke-width:2px
|
||||||
|
```
|
||||||
|
|
||||||
|
#### B. Retrieval (Read)
|
||||||
|
Die hybride Suche für Chat & RAG.
|
||||||
|
```mermaid
|
||||||
|
graph LR
|
||||||
|
Query(["Query"]) --> Embed("Embedding")
|
||||||
|
Embed --> Hybrid{"Hybrid Search"}
|
||||||
|
|
||||||
|
subgraph Search Components
|
||||||
|
Vec["Vector Score"]
|
||||||
|
Graph["Graph/Edge Bonus"]
|
||||||
|
end
|
||||||
|
|
||||||
|
Vec --> Hybrid
|
||||||
|
Graph --> Hybrid
|
||||||
|
|
||||||
|
Hybrid --> Rank("Re-Ranking")
|
||||||
|
Rank --> Ctx["LLM Context"]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### C. Visualisierung (Graph)
|
||||||
|
Der optimierte Pfad für das Frontend.
|
||||||
|
```mermaid
|
||||||
|
graph LR
|
||||||
|
UI["Frontend UI"] --> Service("GraphService")
|
||||||
|
Service -- "Direct Read" --> DB[("Qdrant<br/>Edges Collection")]
|
||||||
|
DB --> Cyto["Cytoscape<br/>Rendering"]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Physische Architektur
|
||||||
|
|
||||||
|
Mindnet läuft in einer verteilten Umgebung (Post-WP15 Setup).
|
||||||
|
|
||||||
|
* **Windows 11 (VS Code):** Entwicklungsumgebung. **Nie** direkt auf `main` arbeiten!
|
||||||
|
* **Beelink (Runtime):** Der Server hostet zwei Instanzen via Systemd:
|
||||||
|
* **PROD:** API (Port 8001) + UI (Port 8501). Home: `~/mindnet`.
|
||||||
|
* **DEV:** API (Port 8002) + UI (Port 8502). Home: `~/mindnet_dev`.
|
||||||
|
* **Gitea (Raspberry Pi):** Versionskontrolle ("Safe"). Speichert den Code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Projektstruktur & Modul-Referenz (Deep Dive)
|
||||||
|
|
||||||
|
Das System ist modular aufgebaut. Hier ist die detaillierte Analyse aller Komponenten.
|
||||||
|
|
||||||
|
### 4.1 Verzeichnisbaum
|
||||||
|
|
||||||
|
```text
|
||||||
|
mindnet/
|
||||||
|
├── app/
|
||||||
|
│ ├── core/ # Business Logic & Algorithms
|
||||||
|
│ ├── routers/ # API Interface (FastAPI)
|
||||||
|
│ ├── services/ # External Integrations (LLM, DB)
|
||||||
|
│ ├── models/ # Pydantic DTOs
|
||||||
|
│ └── frontend/ # UI Logic (Streamlit)
|
||||||
|
├── config/ # Configuration Files (YAML)
|
||||||
|
├── scripts/ # CLI Tools (Ops & Maintenance)
|
||||||
|
└── vault/ # Local Content Storage
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 Frontend Architecture (`app/frontend/`)
|
||||||
|
|
||||||
|
Das Frontend ist eine Streamlit-App, die sich wie eine Single-Page-Application (SPA) verhält.
|
||||||
|
|
||||||
|
| Modul | Status | Verantwortung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **`ui.py`** | 🟢 **Core** | **Main Router.** Initialisiert Session-State und entscheidet anhand der Sidebar-Auswahl, welche View gerendert wird. |
|
||||||
|
| **`ui_config.py`** | 🟢 **Config** | **Constants.** Zentraler Ort für Farben (`GRAPH_COLORS`), API-URLs und Timeouts. Änderungen am Look & Feel passieren hier. |
|
||||||
|
| **`ui_chat.py`** | 🟢 **View** | **Chat UI.** Rendert Nachrichtenverlauf, Intent-Badges, Quellen-Expanders und Feedback-Buttons. |
|
||||||
|
| **`ui_editor.py`** | 🟢 **View** | **Editor UI.** Markdown-Editor mit Live-Vorschau. Integriert "Intelligence" (KI-Link-Vorschläge). |
|
||||||
|
| **`ui_graph_cytoscape.py`**| 🟢 **View** | **Modern Graph.** Interaktiver Graph basierend auf Cytoscape.js (COSE Layout). |
|
||||||
|
| **`ui_graph.py`** | 🟡 **Legacy** | **Graph UI (Fallback).** Alte Implementierung mittels `streamlit-agraph`. |
|
||||||
|
| **`ui_callbacks.py`** | 🟢 **Logic** | **State Controller.** Handhabt komplexe State-Übergänge (z.B. Graph -> Editor). |
|
||||||
|
| **`ui_utils.py`** | 🟢 **Logic** | **Helper.** Enthält den **Healing Parser** (`parse_markdown_draft`), der defektes JSON/YAML von LLMs repariert. |
|
||||||
|
| **`ui_api.py`** | 🟢 **Data** | **API Client.** Wrapper für Backend REST-Calls. |
|
||||||
|
| **`ui_graph_service.py`** | 🟢 **Data** | **Performance Hack.** Greift direkt auf Qdrant zu (bypass API), um Graphen schnell zu laden. |
|
||||||
|
|
||||||
|
#### Frontend Design Patterns (Wichtig!)
|
||||||
|
|
||||||
|
1. **Active Inspector Pattern (`ui_graph_cytoscape.py`)**
|
||||||
|
Um Re-Renders im Graphen zu vermeiden, nutzen wir CSS-Klassen. Wird ein Knoten angeklickt, ändert sich nur die CSS-Klasse (`.inspected`), aber die Physik-Simulation startet nicht neu. Das sorgt für ein stabiles UI-Gefühl.
|
||||||
|
|
||||||
|
2. **Resurrection Pattern (`ui_editor.py`)**
|
||||||
|
Streamlit neigt dazu, Eingaben bei Re-Runs zu "vergessen". Der Editor synchronisiert seinen Inhalt aggressiv in den `session_state`.
|
||||||
|
* Logik: `if widget_key not in session_state: restore_from_data_key()`.
|
||||||
|
* Ergebnis: Texteingaben überleben Tab-Wechsel.
|
||||||
|
|
||||||
|
3. **Filesystem First (`ui_callbacks.py`)**
|
||||||
|
Wenn man im Graphen auf "Bearbeiten" klickt:
|
||||||
|
1. Versucht das System, die **echte Datei** von der Festplatte zu lesen.
|
||||||
|
2. Nur wenn das fehlschlägt, wird der Text aus den Datenbank-Chunks rekonstruiert ("Stitching").
|
||||||
|
Dies verhindert, dass veraltete Datenbank-Stände die echten Dateien überschreiben.
|
||||||
|
|
||||||
|
### 4.3 Backend Architecture (`app/`)
|
||||||
|
|
||||||
|
Das Backend ist das Herzstück. Es stellt die Logik via REST-API bereit.
|
||||||
|
|
||||||
|
| Layer | Datei | Status | Verantwortung |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Entry** | `app/main.py` | 🟢 **Core** | **Entrypoint.** Initialisiert FastAPI, CORS, und bindet alle Router ein. |
|
||||||
|
| **Config** | `app/config.py` | 🟢 **Core** | **Settings.** Zentrale Konfiguration (Pydantic). Lädt Env-Vars für Qdrant, LLM und Pfade. |
|
||||||
|
| **Router** | `app/routers/chat.py` | 🟢 **API** | **Conversation API.** Haupt-Endpunkt für Chat. Entscheidet zwischen Interview- und RAG-Modus. |
|
||||||
|
| | `app/routers/ingest.py` | 🟢 **API** | **Write API.** Nimmt Markdown entgegen, steuert Ingestion und Discovery-Analyse. |
|
||||||
|
| | `app/routers/query.py` | 🟢 **API** | **Search API.** Klassischer Hybrid-Retriever Endpunkt. |
|
||||||
|
| | `app/routers/graph.py` | 🟢 **API** | **Viz API.** Liefert Knoten/Kanten für Frontend-Graphen (Cytoscape). |
|
||||||
|
| | `app/routers/tools.py` | 🟢 **API** | **Agent Specs.** Liefert JSON-Schemas für die Integration in externe Agenten (Ollama/MCP). |
|
||||||
|
| **Engine** | `app/core/ingestion.py` | ⚙️ **Core** | **Pipeline Controller.** Koordiniert Parsing, Hashing (Change-Detection) und DB-Upserts. |
|
||||||
|
| | `app/core/retriever.py` | ⚙️ **Core** | **Search Engine.** Berechnet Scores (Vektor + Graph + Centrality) und baut Erklärungen. |
|
||||||
|
| | `app/core/chunker.py` | ⚙️ **Core** | **Segmentation.** Zerlegt Text intelligent. Orchestriert `SemanticAnalyzer` für Smart Edges. |
|
||||||
|
| | `app/core/parser.py` | ⚙️ **Core** | **I/O.** Liest Markdown robust (Encoding-Fallback), trennt Frontmatter/Body. |
|
||||||
|
| | `app/core/derive_edges.py`| ⚙️ **Core** | **Link Extractor.** Findet Wikilinks, Callouts und Typed Relations im Text. |
|
||||||
|
| | `app/core/note_payload.py`| ⚙️ **Core** | **Builder.** Erzeugt JSON für `mindnet_notes`. Vererbt Configs (Frontmatter > Type > Default). |
|
||||||
|
| | `app/core/qdrant_points.py`| ⚙️ **Core** | **Object Mapper.** Wandelt Payloads in Qdrant `PointStruct`s um. Handhabt UUIDs. |
|
||||||
|
| **Services** | `app/services/llm_service.py`| 🧠 **AI** | **AI Client.** Async Client für Ollama. Verwaltet Concurrency (Semaphore). |
|
||||||
|
| | `app/services/embeddings_client.py`| 🧠 **AI** | **Vector Client.** Unified Client für Embeddings (Ollama/Nomic). Ersetzt lokale Modelle. |
|
||||||
|
| | `app/services/discovery.py`| 🧠 **AI** | **Intelligence.** "Matrix Logic" für Link-Vorschläge (WP-11). |
|
||||||
|
| | `app/services/semantic_analyzer.py`| 🧠 **AI** | **Filter.** KI-Validierung von Kanten im Hintergrund (Background Priority). |
|
||||||
|
|
||||||
|
### 4.4 Scripts & Tooling (Die Admin-Toolbox)
|
||||||
|
|
||||||
|
Der Ordner `scripts/` enthält verifizierte Werkzeuge für den Betrieb.
|
||||||
|
|
||||||
|
#### 1. Script-Übersicht
|
||||||
|
|
||||||
|
| Skript | Status | Zweck | Argumente & Parameter | Beispielaufruf |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **`import_markdown.py`** | 🟢 **Core** | **Ingestion.** Scannt den Vault und importiert Dateien asynchron in Qdrant. Beachtet Hashes. | `--vault PATH` (Quellordner)<br>`--prefix TEXT` (Collection Prefix)<br>`--force` (Erzwingt Re-Index)<br>`--apply` (Schreibt in DB; sonst Dry-Run) | `python3 scripts/import_markdown.py --vault ./vault --apply` |
|
||||||
|
| **`reset_qdrant.py`** | 🟢 **Core** | **DB-Reset.** Löscht Collections (`wipe`) oder leert sie (`truncate`). Legt Indizes neu an. | `--mode {wipe,truncate}`<br>`--prefix TEXT`<br>`--yes` (Keine Rückfrage)<br>`--no-indexes` (Skip Index-Erstellung) | `python3 -m scripts.reset_qdrant --mode wipe --yes` |
|
||||||
|
| **`health_check_mindnet.py`** | 🟢 **Ops** | **Monitoring.** Prüft API-Verfügbarkeit (`/query`) und Antwortqualität. Standalone (keine Imports). | `--url URL`<br>`--query TEXT`<br>`--top-k INT`<br>`--strict` (Exit-Code 1 bei Warnings) | `python3 scripts/health_check_mindnet.py --strict` |
|
||||||
|
| **`payload_dryrun.py`** | 🟡 **Dev** | **Debugger.** Simuliert die JSON-Erstellung (Payloads) ohne DB-Schreibzugriff. Prüft `types.yaml`. | `--vault PATH`<br>`--note-id ID` (Filter)<br>`--with-edges` (Zeigt Kanten) | `python3 -m scripts.payload_dryrun --vault ./vault --note-id "projekt-alpha"` |
|
||||||
|
| **`edges_full_check.py`** | 🟡 **Audit** | **Integritäts-Check.** Zählt Kanten in der DB und prüft logische Konsistenz (z.B. Chunk-Reihenfolge). | Keine (Liest Konfiguration nur aus Umgebungsvariablen `.env`) | `python3 -m scripts.edges_full_check` |
|
||||||
|
| **`resolve_unresolved_references.py`** | 🔵 **Maint** | **Link-Healer.** Repariert "tote" Links in der DB nachträglich und erzeugt Backlinks. | `--prefix TEXT`<br>`--limit INT`<br>`--apply` (Schreibt Änderungen) | `python3 -m scripts.resolve_unresolved_references --apply` |
|
||||||
|
| **`export_markdown.py`** | ⚪ **Utility** | **Reverse ETL.** Exportiert den Datenbank-Inhalt zurück in Markdown-Dateien (Backup/Recovery). | `--out PATH` (Ziel)<br>`--note-id ID`<br>`--include-edges {yaml,footer}`<br>`--flatten-paths` | `python3 -m scripts.export_markdown --out ./backup` |
|
||||||
|
|
||||||
|
#### 2. Einsatzszenarien & Bewertung
|
||||||
|
|
||||||
|
* **🟢 Essentiell für den Betrieb (Must-Have):**
|
||||||
|
* **`import_markdown.py`**: Das Arbeitspferd. Ohne dieses Skript kommen keine Daten ins System.
|
||||||
|
* **`reset_qdrant.py`**: Zwingend notwendig für CI/CD-Pipelines.
|
||||||
|
* **`health_check_mindnet.py`**: Ideal für Docker-Healthchecks.
|
||||||
|
|
||||||
|
* **🟡 Hilfreich für Entwicklung & Debugging (Should-Have):**
|
||||||
|
* **`payload_dryrun.py`**: Wertvoll, wenn man an der `config/types.yaml` arbeitet.
|
||||||
|
* **`edges_full_check.py`**: Wichtiges Diagnose-Tool für den Graphen.
|
||||||
|
|
||||||
|
* **🔵 Wartung & Spezialfälle (Nice-to-Have):**
|
||||||
|
* **`resolve_unresolved_references.py`**: Sinnvoll in einem "Knowledge Garden", wo oft Links auf noch nicht existierende Notizen gesetzt werden ("Red Links"). Dieses Skript "heilt" den Graphen nachträglich.
|
||||||
|
* **`export_markdown.py`**: Ein Notfall-Tool. Da Mindnet nach dem Prinzip "Filesystem First" arbeitet, ist ein Export aus der DB selten nötig, kann aber bei versehentlichem Löschen von Dateien lebensrettend sein.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Maintenance & "Kill List"
|
||||||
|
|
||||||
|
Folgende Dateien wurden im Audit v2.6 als veraltet, redundant oder "Zombie-Code" identifiziert und sollten entfernt werden.
|
||||||
|
|
||||||
|
| Datei | Diagnose | Empfohlene Aktion |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `app/embed_server.py` | **Zombie.** Alter Standalone-Server. | 🗑️ Löschen |
|
||||||
|
| `app/embeddings.py` | **Zombie.** Veraltete lokale Lib. **(Achtung: Erst Importe in `main.py` entfernen!)** | 🗑️ Löschen |
|
||||||
|
| `app/routers/embed_router.py` | **Zombie.** Nutzt `embeddings.py`. | 🗑️ Löschen |
|
||||||
|
| `app/routers/qdrant_router.py`| **Deprecated.** Keine Logik, nur CRUD. | 🗑️ Löschen |
|
||||||
|
| `app/core/edges.py` | **Redundant.** Ersetzt durch `derive_edges.py`. | 🗑️ Löschen |
|
||||||
|
| `app/core/ranking.py` | **Redundant.** Logik in `retriever.py` integriert. | 🗑️ Löschen |
|
||||||
|
| `app/core/type_registry.py` | **Redundant.** Logik in `ingestion.py` integriert. | 🗑️ Löschen |
|
||||||
|
| `app/core/env_vars.py` | **Veraltet.** Ersetzt durch `config.py`. | 🗑️ Löschen |
|
||||||
|
| `app/services/llm_ollama.py` | **Veraltet.** Ersetzt durch `llm_service.py`. | 🗑️ Löschen |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Lokales Setup (Development)
|
||||||
|
|
||||||
|
**Voraussetzungen:** Python 3.10+, Docker, Ollama.
|
||||||
|
|
||||||
|
**Installation:**
|
||||||
|
```bash
|
||||||
|
# 1. Repo & Venv
|
||||||
|
git clone <repo> mindnet
|
||||||
|
cd mindnet
|
||||||
|
python3 -m venv .venv
|
||||||
|
source .venv/bin/activate
|
||||||
|
|
||||||
|
# 2. Dependencies
|
||||||
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# 3. Ollama (Nomic ist Pflicht!)
|
||||||
|
ollama pull phi3:mini
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
```
|
||||||
|
|
||||||
|
**Konfiguration (`.env`):**
|
||||||
|
```ini
|
||||||
|
QDRANT_URL="http://localhost:6333"
|
||||||
|
MINDNET_OLLAMA_URL="http://localhost:11434"
|
||||||
|
MINDNET_LLM_MODEL="phi3:mini"
|
||||||
|
MINDNET_EMBEDDING_MODEL="nomic-embed-text"
|
||||||
|
COLLECTION_PREFIX="mindnet_dev"
|
||||||
|
VECTOR_DIM=768
|
||||||
|
MINDNET_LLM_BACKGROUND_LIMIT=2
|
||||||
|
MINDNET_API_URL="http://localhost:8002"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Der Entwicklungs-Zyklus (Workflow)
|
||||||
|
|
||||||
|
### Phase 1: Windows (Code)
|
||||||
|
1. **Basis aktualisieren:** `git checkout main && git pull`.
|
||||||
|
2. **Branch erstellen:** `git checkout -b feature/mein-feature`.
|
||||||
|
3. **Coden & Committen.**
|
||||||
|
4. **Push:** `git push origin feature/mein-feature`.
|
||||||
|
|
||||||
|
### Phase 2: Beelink (Test / Dev)
|
||||||
|
Hier prüfst du, ob dein Code auf Linux läuft.
|
||||||
|
1. **Einloggen:** `ssh user@beelink`.
|
||||||
|
2. **Ordner:** `cd ~/mindnet_dev`.
|
||||||
|
3. **Code holen:** `git fetch && git checkout feature/mein-feature && git pull`.
|
||||||
|
4. **Dependencies:** `pip install -r requirements.txt`.
|
||||||
|
5. **Restart:** `sudo systemctl restart mindnet-dev`.
|
||||||
|
6. **Validierung (Smoke Tests):**
|
||||||
|
* **Last-Test:** Starte `python3 -m scripts.import_markdown ...` im Terminal und chatte gleichzeitig im UI (Port 8502).
|
||||||
|
* **API Check:** `curl -X POST "http://localhost:8002/ingest/analyze" ...`
|
||||||
|
|
||||||
|
### Phase 3: Release & Deployment (Prod)
|
||||||
|
Wenn alles getestet ist:
|
||||||
|
1. **Gitea:** Pull Request erstellen und mergen.
|
||||||
|
2. **Deploy auf Prod (Beelink):**
|
||||||
|
```bash
|
||||||
|
cd ~/mindnet
|
||||||
|
git pull origin main
|
||||||
|
|
||||||
|
# Sicherstellen, dass Prod-Dependencies aktuell sind
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip install -r requirements.txt
|
||||||
|
ollama pull nomic-embed-text # Falls neue Modelle nötig sind
|
||||||
|
|
||||||
|
# Restart
|
||||||
|
sudo systemctl restart mindnet-prod
|
||||||
|
sudo systemctl restart mindnet-ui-prod
|
||||||
|
```
|
||||||
|
3. **Cleanup:** Branch löschen (lokal und remote).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Erweiterungs-Guide: "Teach-the-AI"
|
||||||
|
|
||||||
|
Mindnet lernt nicht durch Training (Fine-Tuning), sondern durch **Konfiguration** und **Vernetzung**.
|
||||||
|
|
||||||
|
### Workflow A: Neuen Typ implementieren (z. B. `type: risk`)
|
||||||
|
1. **Physik (`config/types.yaml`):**
|
||||||
|
```yaml
|
||||||
|
risk:
|
||||||
|
chunk_profile: sliding_short
|
||||||
|
retriever_weight: 0.90 # Sehr wichtig
|
||||||
|
edge_defaults: ["blocks"] # Automatische Kante
|
||||||
|
detection_keywords: ["gefahr", "risiko"]
|
||||||
|
```
|
||||||
|
2. **Strategie (`config/decision_engine.yaml`):**
|
||||||
|
```yaml
|
||||||
|
DECISION:
|
||||||
|
inject_types: ["value", "risk"] # <--- "risk" hinzufügen
|
||||||
|
```
|
||||||
|
*Ergebnis:* Wenn der Intent `DECISION` erkannt wird, sucht das System nun auch aktiv nach Risiken.
|
||||||
|
|
||||||
|
### Workflow B: Graph-Farben ändern
|
||||||
|
1. Öffne `app/frontend/ui_config.py`.
|
||||||
|
2. Bearbeite das Dictionary `GRAPH_COLORS`.
|
||||||
|
|
||||||
|
```python
|
||||||
|
GRAPH_COLORS = {
|
||||||
|
"project": "#FF4B4B",
|
||||||
|
"risk": "#8B0000" # Neu
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Tests & Debugging
|
||||||
|
|
||||||
|
**Unit Tests (Pytest):**
|
||||||
|
```bash
|
||||||
|
pytest tests/test_retriever_basic.py
|
||||||
|
pytest tests/test_chunking.py
|
||||||
|
```
|
||||||
|
|
||||||
|
**Pipeline Tests (Integration):**
|
||||||
|
```bash
|
||||||
|
# JSON-Schema prüfen
|
||||||
|
python3 -m scripts.payload_dryrun --vault ./test_vault
|
||||||
|
|
||||||
|
# Graph-Integrität prüfen
|
||||||
|
python3 -m scripts.edges_full_check
|
||||||
|
```
|
||||||
|
|
||||||
|
**E2E Smoke Tests:**
|
||||||
|
```bash
|
||||||
|
# Decision Engine
|
||||||
|
python tests/test_wp06_decision.py -p 8002 -e DECISION -q "Soll ich X tun?"
|
||||||
|
|
||||||
|
# Feedback
|
||||||
|
python tests/test_feedback_smoke.py --url http://localhost:8002/query
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Troubleshooting & One-Liners
|
||||||
|
|
||||||
|
**DB komplett zurücksetzen (Vorsicht!):**
|
||||||
|
```bash
|
||||||
|
# --yes überspringt die Bestätigung
|
||||||
|
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet_dev" --yes
|
||||||
|
```
|
||||||
|
|
||||||
|
**Graphen reparieren (Red Links auflösen):**
|
||||||
|
Nutze dies, wenn Kanten im Graphen ins Leere zeigen (weil die Notiz beim Import noch nicht da war).
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.resolve_unresolved_references --apply
|
||||||
|
```
|
||||||
|
|
||||||
|
**Einen einzelnen File inspizieren (Parser-Sicht):**
|
||||||
|
```bash
|
||||||
|
python3 tests/inspect_one_note.py --file ./vault/MeinFile.md
|
||||||
|
```
|
||||||
|
|
||||||
|
**Live-Logs sehen:**
|
||||||
|
```bash
|
||||||
|
journalctl -u mindnet-dev -f
|
||||||
|
journalctl -u mindnet-ui-dev -f
|
||||||
|
```
|
||||||
|
|
||||||
|
**"UnicodeDecodeError in .env":**
|
||||||
|
* **Ursache:** Umlaute oder Sonderzeichen in der `.env`.
|
||||||
|
* **Lösung:** Datei bereinigen (nur ASCII) und sicherstellen, dass UTF-8 ohne BOM genutzt wird.
|
||||||
|
|
||||||
|
**"Read timed out" im Frontend:**
|
||||||
|
* **Ursache:** Smart Edges brauchen länger als 60s.
|
||||||
|
* **Lösung:** `MINDNET_API_TIMEOUT=300.0` in `.env`.
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
---
|
||||||
|
doc_type: developer_guide
|
||||||
|
audience: developer, architect
|
||||||
|
scope: genai, prompting, workflow
|
||||||
|
status: active
|
||||||
|
version: 1.0
|
||||||
|
context: "Leitfaden für die effiziente Softwareentwicklung mit LLMs im Mindnet-Projekt."
|
||||||
|
---
|
||||||
|
|
||||||
|
# GenAI Development Best Practices & Prompt Library
|
||||||
|
|
||||||
|
Dieser Leitfaden definiert Standards für die Zusammenarbeit mit KI-Modellen (ChatGPT, Claude, Gemini) im Rahmen der Mindnet-Entwicklung. Ziel ist es, Halluzinationen zu minimieren, den Kontext effizient zu nutzen und die Dokumentation synchron zum Code zu halten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Grundprinzipien
|
||||||
|
|
||||||
|
### 1.1 Context is King (aber teuer)
|
||||||
|
LLMs haben ein begrenztes Kontext-Fenster.
|
||||||
|
* **Don't:** "Hier ist mein ganzer Code, fix den Bug." (Führt zu Vergessen von Details).
|
||||||
|
* **Do:** Nutze die **"Map & Fetch" Strategie**:
|
||||||
|
1. Gib der KI eine Inhaltsübersicht (z.B. `project_scan_report.json` oder `tree`).
|
||||||
|
2. Lass die KI entscheiden, welche Dateien sie für die Aufgabe benötigt.
|
||||||
|
3. Lade nur diese Dateien hoch.
|
||||||
|
|
||||||
|
### 1.2 Trust but Verify (Validierung)
|
||||||
|
* **Code:** Führe generierten Code **immer** lokal aus (Unit Tests oder Smoke Tests), bevor du ihn committest.
|
||||||
|
* **Pfade:** KIs erfinden gerne Pfade (z.B. `app/utils.py`, obwohl es `app/core/utils.py` ist). Prüfe Importe immer gegen die Projektstruktur.
|
||||||
|
* **Security:** Achte darauf, dass keine Secrets (API-Keys) in den Prompts landen und keine Secrets vom LLM halluziniert und hardcodiert werden.
|
||||||
|
|
||||||
|
### 1.3 Atomic Chats
|
||||||
|
Nutze für verschiedene Aufgaben frische Chat-Kontexte.
|
||||||
|
* Ein Chat für "Frontend Refactoring".
|
||||||
|
* Ein neuer Chat für "Documentation Update".
|
||||||
|
* *Grund:* Alte Chats akkumulieren "Rauschen" und führen zu Fehlern.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Prompt Library (Standard-Vorlagen)
|
||||||
|
|
||||||
|
Nutze diese Prompts, um konsistente Ergebnisse zu erzielen.
|
||||||
|
|
||||||
|
### 2.1 Der "Render-Safe" Prompt (System Instruction)
|
||||||
|
**Wann nutzen?** Immer am Anfang eines Chats, wenn die KI Markdown-Dateien oder Code generieren soll.
|
||||||
|
**Zweck:** Verhindert, dass die Antwort im Chat-Fenster abbricht, weil die KI Code-Blöcke falsch verschachtelt.
|
||||||
|
|
||||||
|
```text
|
||||||
|
# SYSTEM-ANWEISUNG: SICHERES MARKDOWN-RENDERING
|
||||||
|
|
||||||
|
Du agierst als technischer Assistent. Deine Aufgabe ist das Erstellen von Markdown-Dateien, die oft selbst Code-Blöcke enthalten.
|
||||||
|
|
||||||
|
**DAS PROBLEM:**
|
||||||
|
Wenn du eine Markdown-Datei generierst, die Code-Blöcke (```) enthält, und diese Ausgabe selbst in einen Code-Block packst, interpretiert das Chat-Interface das erste innere ``` oft fälschlicherweise als das Ende der Ausgabe.
|
||||||
|
|
||||||
|
**DIE REGEL (STRIKT BEFOLGEN):**
|
||||||
|
Um eine ununterbrochene Darstellung zu garantieren, musst du zwingend eine der folgenden Kapselungs-Methoden anwenden:
|
||||||
|
|
||||||
|
### Methode A: Die 4-Backtick-Methode (Bevorzugt)
|
||||||
|
Umschließe den **gesamten** Datei-Inhalt mit **4 Backticks** (````).
|
||||||
|
Dies erlaubt dir, innerhalb der Datei normale 3 Backticks zu verwenden.
|
||||||
|
|
||||||
|
### Methode B: Die 4-Space-Einrückung (Alternative)
|
||||||
|
Wenn du außen 3 Backticks verwendest, darfst du im Inneren **KEINE** Backticks verwenden.
|
||||||
|
Stattdessen müssen alle inneren Code-Beispiele mit **4 Leerzeichen (Spaces)** eingerückt werden.
|
||||||
|
|
||||||
|
**ZUSAMMENFASSUNG:**
|
||||||
|
Generiere niemals verschachtelte 3-Backtick-Blöcke innerhalb von 3-Backtick-Blöcken.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.2 Der "Doku-Update" Prompt (Nach WP-Abschluss)
|
||||||
|
**Wann nutzen?** Wenn ein Feature fertig codiert ist und die Doku (`docs/`) nachgezogen werden muss.
|
||||||
|
**Zweck:** Automatische Identifikation der betroffenen Doku-Dateien ohne manuelles Suchen.
|
||||||
|
|
||||||
|
**Vorbedingung:** Lade `docs/00_General/00_documentation_map.md` und `docs/06_Roadmap/06_active_roadmap.md` hoch.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du agierst als **Technical Documentation Lead**.
|
||||||
|
|
||||||
|
**Kontext:**
|
||||||
|
Wir haben soeben ein Workpackage (WP) abgeschlossen. Der Code ist implementiert.
|
||||||
|
Jetzt müssen wir die Systemdokumentation (Mindnet v2.6 Modular Docs) aktualisieren.
|
||||||
|
|
||||||
|
**Deine Aufgabe - Phase 1: Identifikation**
|
||||||
|
Analysiere die durchgeführten Änderungen dieses Workpackages (aus dem Chat-Verlauf).
|
||||||
|
Nutze die beiliegende `00_documentation_map.md`, um zu identifizieren, welche Dokumentations-Module betroffen sind.
|
||||||
|
|
||||||
|
**Mapping-Logik:**
|
||||||
|
* Neue Features? -> `00_glossary.md`, `02_Concepts/*`
|
||||||
|
* DB/Payloads geändert? -> `03_tech_data_model.md`
|
||||||
|
* Import/Algorithmus geändert? -> `03_tech_ingestion_pipeline.md`, `03_tech_retrieval_scoring.md`
|
||||||
|
* Neue Configs? -> `03_tech_configuration.md`, `04_admin_operations.md`
|
||||||
|
* UI/UX geändert? -> `01_User_Manual/*`, `03_tech_frontend.md`
|
||||||
|
|
||||||
|
**Output für Phase 1:**
|
||||||
|
Erstelle eine **Liste der betroffenen Dateien** mit Begründung.
|
||||||
|
Fordere mich explizit auf, dir diese Dateien hochzuladen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Deine Aufgabe - Phase 2: Sequenzielle Bearbeitung**
|
||||||
|
Sobald ich die Dateien hochgeladen habe:
|
||||||
|
1. Nimm dir **eine** Datei aus der Liste vor.
|
||||||
|
2. Schreibe den kompletten, aktualisierten Inhalt (Markdown).
|
||||||
|
* *Wichtig:* Halte dich an den bestehenden Stil und die "Render-Safe"-Regel (4 Backticks).
|
||||||
|
3. **Warte** nach der Ausgabe auf mein "OK", bevor du die nächste Datei bearbeitest.
|
||||||
|
|
||||||
|
**Bist du bereit für die Analyse?**
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.3 Der "Code Architect" Prompt (Refactoring & Analyse)
|
||||||
|
**Wann nutzen?** Wenn du dich in den Code einarbeiten willst oder Aufräumen musst.
|
||||||
|
**Vorbedingung:** Führe lokal `deep_scan.py` aus und lade `project_scan_report.json` hoch.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du agierst als **Senior Software Architect**.
|
||||||
|
|
||||||
|
**INPUT:**
|
||||||
|
Ich habe dir die Datei `project_scan_report.json` hochgeladen. Sie enthält eine Liste aller Dateien und ihrer Import-Beziehungen.
|
||||||
|
|
||||||
|
**DIE SOLL-STRUKTUR (4 SÄULEN):**
|
||||||
|
Jede Datei muss einem dieser Zweige zugeordnet werden können:
|
||||||
|
1. **Backend:** via `app/main.py`
|
||||||
|
2. **Frontend:** via `app/frontend/ui.py`
|
||||||
|
3. **Batch/Ops:** via `scripts/` (Produktions-Tools)
|
||||||
|
4. **Tests:** via `tests/`
|
||||||
|
|
||||||
|
**DEINE AUFGABE:**
|
||||||
|
Analysiere das JSON. Identifiziere "Zombies" (Dateien, die nirgends importiert werden und keinen klaren Entrypoint haben).
|
||||||
|
Erstelle eine:
|
||||||
|
1. **Modul-Tabelle** (Wer ruft wen auf?).
|
||||||
|
2. **Lösch-Vorschlagsliste** (Dead Code).
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Workflow für ein Workpackage (WP)
|
||||||
|
|
||||||
|
Ein typisches Mindnet-Feature wird so entwickelt:
|
||||||
|
|
||||||
|
1. **Start:** Neuer Chat. Prompt **2.1 (Render-Safe)** eingeben.
|
||||||
|
2. **Kontext:** `project_scan_report.json` oder relevante Core-Dateien hochladen.
|
||||||
|
3. **Code:** Feature implementieren (Iterativ).
|
||||||
|
4. **Test:** Code lokal validieren.
|
||||||
|
5. **Doku:**
|
||||||
|
* Neuer Chat (optional, für sauberen Kontext).
|
||||||
|
* Prompt **2.1** + Prompt **2.2 (Doku-Update)** eingeben.
|
||||||
|
* Doku aktualisieren lassen.
|
||||||
|
6. **Commit:** Code + Doku zusammen pushen.
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
---
|
||||||
|
doc_type: roadmap
|
||||||
|
audience: product_owner, developer
|
||||||
|
status: active
|
||||||
|
version: 2.7
|
||||||
|
context: "Aktuelle Planung für kommende Features (ab WP16), Release-Strategie und Historie der abgeschlossenen WPs."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet Active Roadmap
|
||||||
|
|
||||||
|
**Aktueller Stand:** v2.6.0 (Post-WP15/WP19)
|
||||||
|
**Fokus:** Visualisierung, Exploration & Intelligent Ingestion.
|
||||||
|
|
||||||
|
## 1. Programmstatus
|
||||||
|
|
||||||
|
Wir haben mit der Implementierung des Graph Explorers (WP19) und der Smart Edge Allocation (WP15) die Basis für ein intelligentes, robustes System gelegt. Der nächste Schritt (WP19a) vertieft die Analyse, während WP16 die "Eingangs-Intelligenz" erhöht.
|
||||||
|
|
||||||
|
| Phase | Fokus | Status |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Phase A** | Fundament & Import | ✅ Fertig |
|
||||||
|
| **Phase B** | Semantik & Graph | ✅ Fertig |
|
||||||
|
| **Phase C** | Persönlichkeit | ✅ Fertig |
|
||||||
|
| **Phase D** | Interaktion & Tools | ✅ Fertig |
|
||||||
|
| **Phase E** | Maintenance & Visualisierung | 🚀 Aktiv |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Historie: Abgeschlossene Workpackages
|
||||||
|
|
||||||
|
Eine Übersicht der implementierten Features zum schnellen Auffinden von Funktionen. Details siehe `99_legacy_workpackages.md`.
|
||||||
|
|
||||||
|
| WP | Titel | Ergebnis / Kern-Feature |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **WP-01** | Knowledge Design | Definition von `types.yaml` und Note-Typen (Project, Concept, etc.). |
|
||||||
|
| **WP-02** | Chunking Strategy | Implementierung von Sliding-Window und Hash-basierter Änderungserkennung. |
|
||||||
|
| **WP-03** | Import-Pipeline | Asynchroner Importer, der Markdown in Qdrant (Notes/Edges) schreibt. |
|
||||||
|
| **WP-04a**| Retriever Scoring | Hybride Suche: `Score = Semantik + GraphBonus + TypGewicht`. |
|
||||||
|
| **WP-04b**| Explanation Layer | Transparenz: API liefert "Reasons" (Warum wurde das gefunden?). |
|
||||||
|
| **WP-04c**| Feedback Loop | Logging von User-Feedback (JSONL) als Basis für Learning. |
|
||||||
|
| **WP-05** | RAG-Chat | Integration von Ollama (`phi3`) und Context-Enrichment im Prompt. |
|
||||||
|
| **WP-06** | Decision Engine | Hybrid Router unterscheidet Frage (`RAG`) vs. Handlung (`Interview`). |
|
||||||
|
| **WP-07** | Interview-Assistent | One-Shot Extraction: Erzeugt Markdown-Drafts aus User-Input. |
|
||||||
|
| **WP-10** | Web UI | Streamlit-Frontend als Ersatz für das Terminal. |
|
||||||
|
| **WP-10a**| Draft Editor | GUI-Komponente zum Bearbeiten und Speichern generierter Notizen. |
|
||||||
|
| **WP-11** | Backend Intelligence | `nomic-embed-text` (768d) und Matrix-Logik für Kanten-Typisierung. |
|
||||||
|
| **WP-15** | Smart Edge Allocation | LLM-Filter für Kanten in Chunks + Traffic Control (Semaphore) + Strict Chunking. |
|
||||||
|
| **WP-19** | Graph Visualisierung | **Frontend Modularisierung:** Umbau auf `ui_*.py`.<br>**Graph Engines:** Parallelbetrieb von Cytoscape (COSE) und Agraph.<br>**Tools:** "Single Source of Truth" Editor, Persistenz via URL. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Offene Workpackages (Planung)
|
||||||
|
|
||||||
|
Diese Features stehen als nächstes an oder befinden sich in der Umsetzung.
|
||||||
|
|
||||||
|
### WP-19a – Graph Intelligence & Discovery (Sprint-Fokus)
|
||||||
|
**Status:** 🚀 Startklar
|
||||||
|
**Ziel:** Vom "Anschauen" zum "Verstehen". Deep-Dive Werkzeuge für den Graphen.
|
||||||
|
* **Discovery Screen:** Neuer Tab für semantische Suche ("Finde Notizen über Vaterschaft") und Wildcard-Filter.
|
||||||
|
* **Filter-Logik:** "Zeige nur Wege, die zu `type:decision` führen".
|
||||||
|
* **Chunk Inspection:** Umschaltbare Granularität (Notiz vs. Chunk) zur Validierung des Smart Chunkers.
|
||||||
|
|
||||||
|
### WP-14 – Review / Refactoring / Dokumentation
|
||||||
|
**Status:** 🟡 Laufend (Phase E)
|
||||||
|
**Ziel:** Technische Schulden abbauen, die durch schnelle Feature-Entwicklung (WP15/WP19) entstanden sind.
|
||||||
|
* **Refactoring `chunker.py`:** Die Datei ist monolithisch geworden (Parsing, Strategien, LLM-Orchestrierung).
|
||||||
|
* *Lösung:* Aufteilung in ein Package `app/core/chunking/` mit Modulen (`strategies.py`, `orchestration.py`, `utils.py`).
|
||||||
|
* **Dokumentation:** Kontinuierliche Synchronisation von Code und Docs (v2.6 Stand).
|
||||||
|
|
||||||
|
### WP-16 – Auto-Discovery & Intelligent Ingestion
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Ziel:** Das System soll "dumme" Textdateien beim Import automatisch analysieren, strukturieren und anreichern, bevor sie gespeichert werden.
|
||||||
|
**Kern-Features:**
|
||||||
|
1. **Smart Link Enricher:** Automatisches Erkennen von fehlenden Kanten in Texten ohne explizite Wikilinks. Ein "Enricher" scannt Text vor dem Import, findet Keywords (z.B. "Mindnet") und schlägt Links vor (`[[Mindnet]]`).
|
||||||
|
2. **Structure Analyzer (Auto-Strategy):**
|
||||||
|
* *Problem:* Manuelle Zuweisung von `chunking_profile` in `types.yaml` ist starr.
|
||||||
|
* *Lösung:* Vorschalten einer Analysestufe im Importer (`chunker.py`), die die Text-Topologie prüft und die Strategie wählt.
|
||||||
|
* *Metrik 1 (Heading Density):* Verhältnis `Anzahl Überschriften / Wortanzahl`. Hohe Dichte (> 1/200) -> Indikator für `structured_smart_edges`. Niedrige Dichte -> `sliding_smart_edges`.
|
||||||
|
* *Metrik 2 (Variance):* Regelmäßigkeit der Abstände zwischen Headings.
|
||||||
|
3. **Context-Aware Hierarchy Merging:**
|
||||||
|
* *Problem:* Leere Zwischenüberschriften (z.B. "Tier 2") gingen früher als bedeutungslose Chunks verloren oder wurden isoliert.
|
||||||
|
* *Lösung:* Generalisierung der Logik aus WP-15, die leere Eltern-Elemente automatisch mit dem ersten Kind-Element verschmilzt ("Tier 2 + MP1"), um den Kontext für das Embedding zu wahren.
|
||||||
|
|
||||||
|
### WP-17 – Conversational Memory (Gedächtnis)
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Ziel:** Echte Dialoge statt Request-Response.
|
||||||
|
* **Tech:** Erweiterung des `ChatRequest` DTO um `history`.
|
||||||
|
* **Logik:** Token-Management (Context Window Balancing zwischen RAG-Doks und Chat-Verlauf).
|
||||||
|
|
||||||
|
### WP-18 – Graph Health & Maintenance
|
||||||
|
**Status:** 🟡 Geplant (Prio 2)
|
||||||
|
**Ziel:** Konsistenzprüfung ("Garbage Collection").
|
||||||
|
* **Feature:** Cronjob `check_graph_integrity.py`.
|
||||||
|
* **Funktion:** Findet "Dangling Edges" (Links auf gelöschte Notizen) und repariert/löscht sie.
|
||||||
|
|
||||||
|
### WP-13 – MCP-Integration & Agenten-Layer
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Ziel:** mindnet als MCP-Server bereitstellen, damit Agenten (Claude Desktop, OpenAI) standardisierte Tools nutzen können.
|
||||||
|
* **Umfang:** MCP-Server mit Tools (`mindnet_query`, `mindnet_explain`, etc.).
|
||||||
|
|
||||||
|
### WP-20 – Cloud Hybrid Mode (Optional)
|
||||||
|
**Status:** ⚪ Optional
|
||||||
|
**Ziel:** "Turbo-Modus" für Massen-Imports.
|
||||||
|
* **Konzept:** Switch in `.env`, um statt Ollama (Lokal) auf Google Gemini (Cloud) umzuschalten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Abhängigkeiten & Release-Plan
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
WP19(Graph Viz) --> WP19a(Discovery)
|
||||||
|
WP19a --> WP17(Memory)
|
||||||
|
WP15(Smart Edges) --> WP16(Auto-Discovery)
|
||||||
|
WP15 --> WP14(Refactoring)
|
||||||
|
WP03(Import) --> WP18(Health Check)
|
||||||
|
WP03/WP04 --> WP13(MCP)
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
---
|
||||||
|
doc_type: operations
|
||||||
|
audience: developer, admin
|
||||||
|
status: active
|
||||||
|
version: 1.0
|
||||||
|
context: "Sammlung von Initialisierungs-Prompts für neue Chat-Sessions. Jeder Prompt entspricht dem Projektauftrag für ein spezifisches Workpackage."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet WP-Handover Prompts
|
||||||
|
|
||||||
|
**Verwendung:**
|
||||||
|
Kopiere den entsprechenden Block in ein **neues** Chat-Fenster, um die KI-Instanz exakt auf den Kontext und die Ziele des Workpackages einzustellen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## WP-19a: Graph Intelligence & Discovery
|
||||||
|
|
||||||
|
**Status:** 🚀 Startklar
|
||||||
|
**Fokus:** Frontend-Erweiterung, Semantische Suche, Filterung.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der Lead Developer für "Mindnet", ein lokales RAG-System (Python/FastAPI/Streamlit/Qdrant).
|
||||||
|
Wir starten jetzt **WP-19a: Graph Intelligence & Discovery**.
|
||||||
|
|
||||||
|
**Status Quo (v2.6.0):**
|
||||||
|
- Backend: Async API mit `/query` (Hybrid Search) und `/chat`.
|
||||||
|
- Frontend: Modularisiertes Streamlit (`ui.py`, `ui_graph.py`).
|
||||||
|
- Daten: Qdrant Indizes (`notes`, `chunks`, `edges`) sind gefüllt.
|
||||||
|
|
||||||
|
**Dein Auftrag (WP-19a):**
|
||||||
|
Implementiere "Deep Dive" Werkzeuge im Frontend, um den Graphen nicht nur zu sehen, sondern zu verstehen.
|
||||||
|
1. **Neues UI-Modul:** Erstelle `app/frontend/ui_discovery.py`.
|
||||||
|
2. **Discovery Tab:** Implementiere eine Oberfläche für:
|
||||||
|
- Semantische Suche (ohne Chat-Modus).
|
||||||
|
- Wildcard-Filter ("Zeige alle Notes vom Typ 'decision'").
|
||||||
|
- Pfad-Analyse ("Wie sind Note A und Note B verbunden?").
|
||||||
|
3. **Chunk Inspection:** Baue einen Toggle, der im Graph-Explorer zwischen "Note-View" (grob) und "Chunk-View" (fein) umschaltet.
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Nutze `st.session_state` für Persistenz zwischen Re-Renders.
|
||||||
|
- Halte die Business-Logik im Backend (ggf. neue Endpoints in `app/routers/query.py`).
|
||||||
|
- Gib vollständigen, lauffähigen Code aus.
|
||||||
|
|
||||||
|
Bitte bestätige die Übernahme und skizziere die Architektur für `ui_discovery.py`.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## WP-13: MCP Integration & Agenten-Layer
|
||||||
|
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Fokus:** Schnittstelle für externe Agenten (Claude Desktop).
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der Lead Developer für "Mindnet" (Python/FastAPI/Qdrant).
|
||||||
|
Wir starten jetzt **WP-13: MCP Integration**.
|
||||||
|
|
||||||
|
**Status Quo (v2.6.0):**
|
||||||
|
- Das System läuft stabil asynchron.
|
||||||
|
- `types.yaml` steuert die Logik.
|
||||||
|
- Es existieren Services für Retrieval und Graph-Access.
|
||||||
|
|
||||||
|
**Dein Auftrag (WP-13):**
|
||||||
|
Implementiere einen MCP-Server (Model Context Protocol), der Mindnet als "Tool" für Claude Desktop verfügbar macht.
|
||||||
|
1. **Server:** Erstelle `app/mcp_server.py` basierend auf dem `mcp`-SDK.
|
||||||
|
2. **Tools:** Implementiere folgende Tools:
|
||||||
|
- `search_notes(query)`: Nutzt unseren Hybriden Retriever.
|
||||||
|
- `read_note(id)`: Liest Fulltext einer Notiz.
|
||||||
|
- `list_connections(id)`: Zeigt Edges an.
|
||||||
|
- `Notes(content)`: (Optional) Nutzt die Ingestion-Pipeline.
|
||||||
|
3. **Integration:** Nutze die bestehenden Services (`Retriever`, `QdrantClient`) wieder – kein redundanter Code!
|
||||||
|
4. **Async:** Achte auf Kompatibilität zwischen MCP und unserem `asyncio` Core.
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Halte dich strikt an die Architektur in `mindnet_technical_architecture.md`.
|
||||||
|
- Aktualisiere den `admin_guide.md` mit Anweisungen zur Einbindung in Claude Desktop config.
|
||||||
|
|
||||||
|
Bitte bestätige die Übernahme und zeige einen ersten Entwurf für `app/mcp_server.py`.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## WP-14: Review & Refactoring
|
||||||
|
|
||||||
|
**Status:** 🟡 Laufend
|
||||||
|
**Fokus:** Code-Qualität, Modularisierung, Technische Schulden.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der Software-Architekt für "Mindnet".
|
||||||
|
Wir starten **WP-14: Review & Refactoring**.
|
||||||
|
|
||||||
|
**Status Quo (v2.6.0):**
|
||||||
|
- Das System ist funktional mächtig, aber einige Dateien (z.B. `chunker.py`) sind monolithisch geworden.
|
||||||
|
- Dokumentation und Code müssen synchronisiert werden.
|
||||||
|
|
||||||
|
**Dein Auftrag (WP-14):**
|
||||||
|
1. **Refactoring `chunker.py`:** Zerlege den Monolithen in ein sauberes Package `app/core/chunking/`.
|
||||||
|
- `strategies.py`: Enthält `sliding_window` und `by_heading` Logik.
|
||||||
|
- `orchestration.py`: Enthält `assemble_chunks` und Smart-Edge-Flow.
|
||||||
|
- `utils.py`: Helper.
|
||||||
|
2. **Cleanup:** Entferne veraltete / auskommentierte Code-Blöcke im gesamten Projekt.
|
||||||
|
3. **Doc-Sync:** Prüfe, ob alle Parameter in `types.yaml` auch im Code verwendet werden (Dead Config Detection).
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Funktionalität darf sich nicht ändern (Regression Tests!).
|
||||||
|
- Imports in `scripts/import_markdown.py` müssen angepasst werden.
|
||||||
|
|
||||||
|
Bitte bestätige und beginne mit der Strukturierung des neuen `chunking` Packages.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## WP-16: Auto-Discovery & Intelligent Ingestion
|
||||||
|
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Fokus:** Automatisierung beim Import, "Smarter Text".
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der Lead Developer für "Mindnet".
|
||||||
|
Wir starten **WP-16: Auto-Discovery & Intelligent Ingestion**.
|
||||||
|
|
||||||
|
**Status Quo (v2.6.0):**
|
||||||
|
- Import verlässt sich auf explizite Wikilinks und manuelle Profil-Wahl in `types.yaml`.
|
||||||
|
- Smart Edges filtern nur vorhandene Links.
|
||||||
|
|
||||||
|
**Dein Auftrag (WP-16):**
|
||||||
|
Mache den Import intelligenter, bevor Daten gespeichert werden.
|
||||||
|
1. **Structure Analyzer:** Erweitere den Chunker um eine Vor-Analyse.
|
||||||
|
- Berechne "Heading Density" (Überschriften pro Wort).
|
||||||
|
- Wähle automatisch `structured` (hohe Dichte) oder `sliding` (niedrige Dichte), wenn `profile: auto` gesetzt ist.
|
||||||
|
2. **Smart Link Enricher:** Implementiere einen Service, der im Text nach Keywords sucht, die als Titel anderer Notizen existieren (Exact Match & Fuzzy Match).
|
||||||
|
- Schlage diese als `suggested_edges` vor.
|
||||||
|
3. **Hierarchy Merging:** Generalisiere die Logik, dass leere Überschriften ("Tier 2") automatisch mit dem folgenden Inhalt verschmelzen.
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Performance beachten! Der Import darf nicht ewig dauern.
|
||||||
|
- Änderungen am Content nur im RAM, Original-Datei bleibt unangetastet (außer User will Writeback).
|
||||||
|
|
||||||
|
Bitte bestätige und skizziere den Algorithmus für den Structure Analyzer.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## WP-17: Conversational Memory
|
||||||
|
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Fokus:** Dialog-Qualität, Kontext.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der AI-Engineer für "Mindnet".
|
||||||
|
Wir starten **WP-17: Conversational Memory**.
|
||||||
|
|
||||||
|
**Status Quo (v2.6.0):**
|
||||||
|
- Chat ist "stateless". Jede Anfrage wird isoliert betrachtet.
|
||||||
|
- RAG funktioniert, aber Rückfragen ("Was meinst du damit?") scheitern.
|
||||||
|
|
||||||
|
**Dein Auftrag (WP-17):**
|
||||||
|
Implementiere ein Kurzzeitgedächtnis für den Chat.
|
||||||
|
1. **API Update:** Erweitere `ChatRequest` (DTO) um ein Feld `history: List[Message]`.
|
||||||
|
2. **Frontend:** Passe `ui.py` an, um die letzten N Nachrichten mitzusenden.
|
||||||
|
3. **Token Management:** Implementiere eine Logik im `LLMService`, die das Kontext-Fenster (z.B. 4k Token) balanciert:
|
||||||
|
- System Prompt (fest)
|
||||||
|
- RAG Chunks (hoch gewichtet)
|
||||||
|
- Chat History (auffüllen bis Limit)
|
||||||
|
4. **Prompting:** Integriere `{chat_history}` in das Template in `prompts.yaml`.
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Nutze effizientes Truncation (älteste Nachrichten zuerst weg).
|
||||||
|
- History darf RAG-Wissen nicht verdrängen (Reserviere min. 60% für RAG).
|
||||||
|
|
||||||
|
Bitte bestätige und zeige das aktualisierte Pydantic-Modell für `ChatRequest`.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## WP-18: Graph Health & Maintenance
|
||||||
|
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Fokus:** Datenintegrität, Garbage Collection.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der DevOps Engineer für "Mindnet".
|
||||||
|
Wir starten **WP-18: Graph Health & Maintenance**.
|
||||||
|
|
||||||
|
**Status Quo (v2.6.0):**
|
||||||
|
- Import ist asynchron. Bei Timeouts kann der DB-Stand vom File-System abweichen (Hash-Mismatch).
|
||||||
|
- Gelöschte Notizen hinterlassen "Dangling Edges".
|
||||||
|
|
||||||
|
**Dein Auftrag (WP-18):**
|
||||||
|
1. **Transactional Ingestion:** Implementiere einen "Two-Phase Commit" für den Import.
|
||||||
|
- Der File-Hash für die Änderungserkennung darf erst aktualisiert werden, wenn der Qdrant-Upsert *bestätigt* erfolgreich war.
|
||||||
|
2. **Integrity Script:** Erstelle `scripts/check_graph_integrity.py`.
|
||||||
|
- Prüfe: Gibt es Edges, deren `target_id` nicht in `notes` existiert?
|
||||||
|
- Aktion: Report oder Auto-Delete.
|
||||||
|
3. **Resolve References:** Erweitere das Skript um Logik, die "Unresolved Targets" (Text-Links) nachträglich in echte UUID-Links wandelt, wenn die Ziel-Notiz später importiert wurde.
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Sicherheit geht vor Geschwindigkeit.
|
||||||
|
- Keine Datenlöschung ohne Log-Eintrag.
|
||||||
|
|
||||||
|
Bitte bestätige und skizziere die Logik für den Transactional Hash Update.
|
||||||
|
```
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
---
|
||||||
|
doc_type: archive
|
||||||
|
audience: historian, architect
|
||||||
|
status: archived
|
||||||
|
context: "Archivierte Details zu abgeschlossenen Workpackages (WP01-WP19). Referenz für historische Design-Entscheidungen."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Legacy Workpackages (Archiv)
|
||||||
|
|
||||||
|
**Quellen:** `Programmplan_V2.2.md`, `Active Roadmap`
|
||||||
|
|
||||||
|
**Status:** Abgeschlossen / Implementiert.
|
||||||
|
Dieses Dokument dient als Referenz für die Entstehungsgeschichte von Mindnet v2.6.
|
||||||
|
|
||||||
|
## Phase A: Fundament (WP01-03)
|
||||||
|
|
||||||
|
### WP-01 – Wissensdesign
|
||||||
|
* **Ziel:** Definition der Datenstruktur.
|
||||||
|
* **Ergebnis:** Entscheidung gegen komplexe Ontologien (RDF/OWL), für pragmatische Typen (`project`, `concept`). Definition der YAML-Frontmatter-Pflichtfelder.
|
||||||
|
* **Artefakt:** `01_knowledge_design.md`.
|
||||||
|
|
||||||
|
### WP-02 – Chunking & Hash-Strategie
|
||||||
|
* **Ziel:** Texte suchbar machen und Änderungen erkennen.
|
||||||
|
* **Ergebnis:** Implementierung des `SlidingWindowChunker`. Einführung von UUIDv5 für deterministische IDs.
|
||||||
|
* **Learning:** Starre Chunking-Grenzen zerschneiden oft den Kontext. Daher Einführung von Overlap (50 Tokens).
|
||||||
|
|
||||||
|
### WP-03 – Import-Pipeline & Edge-System
|
||||||
|
* **Ziel:** Markdown in Vektoren wandeln.
|
||||||
|
* **Ergebnis:** Der "Importer" (`import_markdown.py`). Entscheidung, Kanten (`_edges`) als eigene Collection zu führen statt als Payload in Chunks (für bessere Graphen-Algorithmen wie Centrality).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase B: Semantik (WP04)
|
||||||
|
|
||||||
|
### WP-04a – Retriever & Graph-Scoring
|
||||||
|
* **Ziel:** Bessere Suchergebnisse als reines Vektor-Matching.
|
||||||
|
* **Ergebnis:** Die Formel `Score = Semantik + GraphBonus + TypGewicht`.
|
||||||
|
* **Learning:** Reine Vektorsuche reichte nicht, um den Kontext ("Warum ist das wichtig?") zu erfassen. Der "Graph Bonus" war der Durchbruch für assoziatives Finden.
|
||||||
|
|
||||||
|
### WP-04b – Explanation Layer ("Why-Layer")
|
||||||
|
* **Ziel:** Transparenz.
|
||||||
|
* **Ergebnis:** `explain=True` Parameter. Die API liefert menschenlesbare Gründe ("Gefunden, weil Projekt Alpha davon abhängt").
|
||||||
|
|
||||||
|
### WP-04c – Feedback Logging
|
||||||
|
* **Ziel:** Datenbasis für zukünftiges Lernen schaffen.
|
||||||
|
* **Ergebnis:** Das "Data Flywheel". Jede Suche und Bewertung wird in JSONL-Dateien geloggt (`search_history.jsonl`, `feedback.jsonl`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase C: Persönlichkeit (WP05-07)
|
||||||
|
|
||||||
|
### WP-05 – RAG-Chat
|
||||||
|
* **Ziel:** Natürliche Sprache statt Suchergebnisse.
|
||||||
|
* **Ergebnis:** Integration von Ollama (`phi3`).
|
||||||
|
* **Tech:** Prompt-Engineering (`prompts.yaml`) statt Fine-Tuning, um flexibel zu bleiben.
|
||||||
|
|
||||||
|
### WP-06 – Decision Engine
|
||||||
|
* **Ziel:** Strategische Beratung statt nur Fakten.
|
||||||
|
* **Ergebnis:** Der Hybrid Router.
|
||||||
|
* **Konzept:** Unterscheidung von *Fragen* (RAG) und *Handlungen* (Interview). Strategisches Laden von Werten (`type: value`), um Entscheidungen moralisch zu begründen.
|
||||||
|
|
||||||
|
### WP-07 – Interview-Assistent
|
||||||
|
* **Ziel:** Bekämpfung des "Writer's Block".
|
||||||
|
* **Ergebnis:** One-Shot Extraction. Der Chatbot generiert aus einem losen Satz ("Neues Projekt Alpha") einen strukturierten Markdown-Draft.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase D: Interaktion (WP10-15)
|
||||||
|
|
||||||
|
### WP-10/10a – Web UI & Draft Editor
|
||||||
|
* **Ziel:** Usability für Nicht-Techniker.
|
||||||
|
* **Ergebnis:** Streamlit App. Ablösung des Terminals.
|
||||||
|
* **Feature:** "Healing Parser", der defektes JSON vom LLM repariert.
|
||||||
|
|
||||||
|
### WP-11 – Backend Intelligence
|
||||||
|
* **Ziel:** Automatisierung der Vernetzung.
|
||||||
|
* **Ergebnis:** AsyncIO Umstellung für Performance. Einführung von `nomic-embed-text` (768d) für präzise Semantik. Matrix-Logik für automatische Kanten-Typisierung.
|
||||||
|
|
||||||
|
### WP-15 – Smart Edge Allocation (Meilenstein)
|
||||||
|
* **Problem:** "Broadcasting". Ein Chunk erbte alle Links der Note, auch irrelevante. Das verwässerte die Suchergebnisse.
|
||||||
|
* **Lösung:** LLM prüft jeden Chunk auf Link-Relevanz.
|
||||||
|
* **Tech:** Einführung von **Traffic Control** (Semaphore), um Import und Chat zu parallelisieren, ohne die Hardware zu überlasten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase E: Visualisierung & Maintenance (WP19)
|
||||||
|
|
||||||
|
### WP-19 – Graph Visualisierung & Modularisierung
|
||||||
|
* **Ziel:** Transparenz über die Datenstruktur schaffen und technische Schulden (Monolith) abbauen.
|
||||||
|
* **Ergebnis:**
|
||||||
|
* **Modularisierung:** Aufsplittung der `ui.py` in Router, Services und Views (`ui_*.py`).
|
||||||
|
* **Graph Explorer:** Einführung von `st-cytoscape` für stabile, nicht-überlappende Layouts (COSE) als Ergänzung zur Legacy-Engine (Agraph).
|
||||||
|
* **Single Source of Truth:** Der Editor lädt Inhalte nun direkt vom Dateisystem statt aus (potenziell veralteten) Vektor-Payloads.
|
||||||
|
* **UX:** Einführung von URL-Persistenz für Layout-Settings und CSS-basiertes Highlighting zur Vermeidung von Re-Renders.
|
||||||
@@ -0,0 +1,465 @@
|
|||||||
|
# mindnet v2.2 – Dokumentationsrahmenplan
|
||||||
|
**Datei:** `docs/mindnet_docs_master_plan_v2.2.md`
|
||||||
|
**Stand:** 2025-12-06
|
||||||
|
**Bezug:** Programmplan mindnet v2.2 :contentReference[oaicite:0]{index=0}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Zweck dieses Rahmenplans
|
||||||
|
|
||||||
|
Dieser Rahmenplan definiert:
|
||||||
|
|
||||||
|
- die **Zieldokumente** der mindnet v2.2 Dokumentation,
|
||||||
|
- deren **Dateinamen, Zielgruppen, Inhalte und Quellen**,
|
||||||
|
- die **Zuordnung** zu Workpackages (WP) und Release-Tags,
|
||||||
|
- die **Regeln zum Informations-Erhalt** (keine inhaltlichen Verluste),
|
||||||
|
- die **empfohlene Bearbeitungsreihenfolge**.
|
||||||
|
|
||||||
|
Alle hier beschriebenen Zieldokumente werden als **eigene Markdown-Dateien** gepflegt und sind Teil von WP-14 _Review / Refactoring / Dokumentation_ (Phase E). :contentReference[oaicite:1]{index=1}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Prinzipien zur Sicherung der Informationen
|
||||||
|
|
||||||
|
Um zu verhindern, dass Inhalte oder Ergebnisse verloren gehen, gelten folgende Prinzipien:
|
||||||
|
|
||||||
|
1. **Programmplan v2.2 als Masterreferenz**
|
||||||
|
- Programmauftrag, Vision, Phasenmodell und WP-Status werden **nicht verändert**, sondern nur referenziert.
|
||||||
|
- `Programmplan_V2.2.md` bleibt das führende Dokument für Ziele, WPs, Ampelstatus. :contentReference[oaicite:2]{index=2}
|
||||||
|
|
||||||
|
2. **Keine unkontrollierte Löschung von Inhalten**
|
||||||
|
- Bestehende Dokumente (`knowledge_design.md`, `chunking_strategy.md`, `mindnet_technical_architecture.md`, `Handbuch.md`, `TYPE_REGISTRY_MANUAL.md`, `docs_mindnet_retriever.md`, `wp04_retriever_scoring.md`) werden **nicht gelöscht**, sondern:
|
||||||
|
- vollständig archiviert,
|
||||||
|
- in die neuen Zieldokumente **überführt**,
|
||||||
|
- oder **explizit** in den Anhängen (I) als „legacy / historisch“ verlinkt.
|
||||||
|
|
||||||
|
3. **Explizite Quellenzuordnung („Building Blocks“)**
|
||||||
|
- Für jede Sektion eines Zieldokuments wird angegeben, aus **welchen bestehenden Dateien und Abschnitten** der Inhalt stammt.
|
||||||
|
- Neue Inhalte (z. B. User Guide H) werden klar als „neu, v2.2“ gekennzeichnet.
|
||||||
|
|
||||||
|
4. **Ist-Stand vs. Roadmap trennen**
|
||||||
|
- Implementierter Stand v2.2: WP01–WP04a (🟢) mit Importer, Chunking, Edge-Pipeline, Typ-Registry und hybrider Retriever.
|
||||||
|
- Geplante Features (Self-Healing, Virtual Schema Layer, Explanation Layer, Feedback-Logging, MCP-Agenten) werden als **Roadmap-Funktionen** kenntlich gemacht (Phase B–D, WPs 05–13).
|
||||||
|
|
||||||
|
5. **Versionierbarkeit**
|
||||||
|
- Alle Zieldokumente tragen im Kopf eine **Version** und **Stand-Datum** sowie optional einen Verweis auf den letzten Gitea-Tag (z. B. `mindnet_v2.2_docs_initial`, `WP04a-Retriever_final`). :contentReference[oaicite:6]{index=6}
|
||||||
|
- Änderungen werden im Abschnitt „Changelog“ der jeweiligen Datei notiert.
|
||||||
|
|
||||||
|
6. **Keine funktionalen Annahmen ohne Verifikation**
|
||||||
|
- Wo das Verhalten nicht eindeutig aus Code-/Handbuch-/WP-Dokumenten hervorgeht, wird der Punkt zunächst als _offene Frage_ markiert und nicht als Tatsache dokumentiert.
|
||||||
|
- Verifizierte Funktionen (z. B. `import_markdown`, Edge-Schema, `types.yaml`, `/query`, Scoring-Formel) werden exakt gemäß der bestehenden Dokumente beschrieben.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Zieldokumente der mindnet v2.2 Dokumentation
|
||||||
|
|
||||||
|
### 3.1 Übersichtstabelle
|
||||||
|
|
||||||
|
| ID | Zieldatei | Rolle/Zielgruppe | Hauptquellen (Building Blocks) |
|
||||||
|
|----|------------------------------------------|---------------------------------------------|--------------------------------|
|
||||||
|
| A | `mindnet_overview_v2.2.md` | Einstieg für alle Rollen | Programmplan v2.2, Knowledge Design |
|
||||||
|
| B | `mindnet_functional_architecture_v2.2.md`| Architekt:innen, Mindmaster | Knowledge Design, Functional Architecture, Programmplan |
|
||||||
|
| C | `mindnet_technical_architecture_v2.2.md` | Entwickler:innen, Tech-Architekt:innen | mindnet_technical_architecture, chunking_strategy, Handbuch |
|
||||||
|
| D | `mindnet_knowledge_design_manual_v2.2.md`| Vault-Autor:innen, Mindmaster, Analyst:innen| knowledge_design, TYPE_REGISTRY_MANUAL, Functional Architecture |
|
||||||
|
| E | `mindnet_pipeline_playbook_v2.2.md` | Dev/Ops, Tech-Lead | mindnet_v2_implementation_playbook, Handbuch, chunking_strategy, docs_mindnet_retriever, wp04_retriever_scoring |
|
||||||
|
| F | `mindnet_developer_guide_v2.2.md` | Entwickler:innen (Code, API, Tests) | Technical Architecture, Handbuch, docs_mindnet_retriever |
|
||||||
|
| G | `mindnet_admin_guide_v2.2.md` | Admins, Betreiber | Handbuch, Implementation Playbook, Programmplan (Governance) |
|
||||||
|
| H | `mindnet_user_guide_v2.2.md` | Endnutzer:innen, Agent-User | Knowledge Design, Programmplan (Use Cases), spätere MCP-WPs |
|
||||||
|
| I | `mindnet_appendices_v2.2.md` | Alle Rollen (Referenzen, Tabellen) | TYPE_REGISTRY_MANUAL, chunking_strategy, WP-Übersicht, Edge-Referenz |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Detailpläne pro Zieldokument (Inhaltsverzeichnis & Building Blocks)
|
||||||
|
|
||||||
|
### A) `mindnet_overview_v2.2.md`
|
||||||
|
|
||||||
|
#### Zweck & Zielgruppe
|
||||||
|
- Einstieg in mindnet für alle Rollen (Owner, Mindmaster, Developer, Admin, Agenten-Entwickler).
|
||||||
|
- Auf 3–5 Seiten: _Was ist mindnet? Wie ist es gedacht? Wie lese ich die Dokumentation?_ :contentReference[oaicite:17]{index=17}
|
||||||
|
|
||||||
|
#### Geplantes Inhaltsverzeichnis
|
||||||
|
|
||||||
|
1. **Einführung**
|
||||||
|
1. Programmauftrag & Vision (v2.2)
|
||||||
|
2. Was mindnet ist – und was nicht
|
||||||
|
2. **Drei Ebenen von mindnet**
|
||||||
|
1. Content-Ebene (Vault, Notes, Chunks)
|
||||||
|
2. Semantische Ebene (Edges, Typen, Retriever)
|
||||||
|
3. Identitäts- / Persönlichkeits-Ebene (Werte, Entscheidungen, Profile – Roadmap)
|
||||||
|
3. **End-to-End-Überblick**
|
||||||
|
1. Datenfluss: Vault → Import → Qdrant → Retriever → Antwort
|
||||||
|
2. WP-Phasenmodell (A–E) und aktueller Stand (WP01–04a grün)
|
||||||
|
4. **Rollen & Perspektiven**
|
||||||
|
1. Mindmaster / Owner
|
||||||
|
2. Autor:in (Vault-Notes)
|
||||||
|
3. Developer / Architect
|
||||||
|
4. Administrator:in
|
||||||
|
5. Agenten & LLMs (MCP-Perspektive)
|
||||||
|
5. **Leserführung durch die Dokumentation**
|
||||||
|
1. Welche Datei für welche Rolle?
|
||||||
|
2. Wie mit Ist-Stand vs. Roadmap umgehen?
|
||||||
|
6. **Glossar zentraler Begriffe**
|
||||||
|
- mindnet, Vault, Note, Chunk, Edge, Type, Identity, Self-Healing, Self-Tuning, Explanation Layer, Virtual Schema Layer, etc.
|
||||||
|
|
||||||
|
#### Building Blocks (Quellen-Mapping)
|
||||||
|
|
||||||
|
- Programmauftrag & Vision → `Programmplan_V2.2.md`, Kapitel 1–2. :contentReference[oaicite:18]{index=18}
|
||||||
|
- Phasenmodell & WPs → `Programmplan_V2.1.md`/v2.2, Kapitel 5–9 (angepasst auf v2.2-Stand).
|
||||||
|
- High-Level-Architektur → `knowledge_design.md`, Kapitel 1–3 (Ziel, Zielarchitektur, Collections). :contentReference[oaicite:20]{index=20}
|
||||||
|
- Rollenmodell → Ableitung aus Knowledge Design + Programmplan (Owner, Agenten, MCP-WPs).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### B) `mindnet_functional_architecture_v2.2.md`
|
||||||
|
|
||||||
|
#### Zweck & Zielgruppe
|
||||||
|
- Fachliche Architektur von mindnet (Konzeptmodell).
|
||||||
|
- Für Architekt:innen, Mindmaster, Knowledge-Designer.
|
||||||
|
|
||||||
|
#### Geplantes Inhaltsverzeichnis
|
||||||
|
|
||||||
|
1. **Ziel & Einordnung**
|
||||||
|
1. Bezug zu Programmauftrag & WPs (WP01–WP07, WP10–12)
|
||||||
|
2. **Kernkonzepte**
|
||||||
|
1. Notes & Note-Typen (concept, experience, project, decision, value, principle, person, event, …)
|
||||||
|
2. Chunks & Sections
|
||||||
|
3. Edges (Struktur, explizit, inline, Default-Kanten)
|
||||||
|
4. Typen-Registry & Virtual Schema Layer (fachliche Sicht, Roadmap)
|
||||||
|
3. **Graph-Modell**
|
||||||
|
1. Knotenarten (Notes, Chunks, Identity Nodes, People)
|
||||||
|
2. Kantenarten (belongs_to, references, similar_to, depends_on, related_to, next/prev, …)
|
||||||
|
3. Scope & Provenienz (chunk vs. note, rule_id, confidence)
|
||||||
|
4. **End-to-End fachlicher Datenfluss**
|
||||||
|
1. Erfassung von Wissen (Note erstellen)
|
||||||
|
2. Import & Graphaufbau
|
||||||
|
3. Retrieval & Begründungspfade
|
||||||
|
4. Self-Healing & Retroactive Edges (WP06/07 – Roadmap)
|
||||||
|
5. **Szenarien & Use Cases**
|
||||||
|
1. Wissensspeicherung (z. B. Leitbild, Projekt, Erfahrung)
|
||||||
|
2. Entscheidungen & Why-Layer (WP04b – Roadmap)
|
||||||
|
3. Persönlichkeits-/Identitätsmodell (WP10–12 – Roadmap)
|
||||||
|
6. **Rollenmodell (fachliche Sicht)**
|
||||||
|
1. Mindmaster
|
||||||
|
2. Content-Autor:innen
|
||||||
|
3. Analyst:innen (Graph-Leser)
|
||||||
|
7. **Designprinzipien (fachlich)**
|
||||||
|
- Late Binding, Virtual Schema, Self-Healing, Minimalinvasives Schreiben etc.
|
||||||
|
|
||||||
|
#### Building Blocks
|
||||||
|
|
||||||
|
- `knowledge_design.md` – Kapitel 1–4, 6–7 (Ziel, Architektur, Collections, Identitäten, Prinzipien). :contentReference[oaicite:28]{index=28}
|
||||||
|
- `mindnet_functional_architecture.md` – alle Kapitel (Kernkonzepte, Edgetypen, Provenienz, Rollen). :contentReference[oaicite:29]{index=29}
|
||||||
|
- `chunking_strategy.md` – Edges, Datenmodell, Graph-Sicht. :contentReference[oaicite:30]{index=30}
|
||||||
|
- Programmplan – WPs 01–07, 10–12 für Roadmap-Features.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### C) `mindnet_technical_architecture_v2.2.md`
|
||||||
|
|
||||||
|
#### Zweck & Zielgruppe
|
||||||
|
- Technische Architektur des Systems: Collections, Payload-Felder, Services, Schemata.
|
||||||
|
- Für Entwickler:innen und Tech-Architekt:innen.
|
||||||
|
|
||||||
|
#### Geplantes Inhaltsverzeichnis
|
||||||
|
|
||||||
|
1. **Ziel & Scope**
|
||||||
|
1. Abgrenzung zur funktionalen Architektur
|
||||||
|
2. Bezug zu WPs 02–04a, 05 (Schema, Importer, Retriever)
|
||||||
|
2. **Systemübersicht**
|
||||||
|
1. Komponentenübersicht (Importer, Qdrant, Retriever-API, Embedding-Service, n8n/MCP-Ausblick)
|
||||||
|
2. Ports, Dienste, Hauptverzeichnisse
|
||||||
|
3. **Datenmodell in Qdrant**
|
||||||
|
1. Notes (`mindnet_notes`)
|
||||||
|
2. Chunks (`mindnet_chunks`)
|
||||||
|
3. Edges (`mindnet_edges`)
|
||||||
|
4. Optionale Collections (`mindnet_people`, zukünftige)
|
||||||
|
4. **Typ-Registry & Konfiguration**
|
||||||
|
1. `config/types.yaml` – Aufbau, Defaults, Typauflösung (Ist-Stand: Frontmatter-Overrides deaktiviert)
|
||||||
|
2. `config/retriever.yaml` – Scoringgewichte, Edge-Typ-Gewichte :contentReference[oaicite:35]{index=35}
|
||||||
|
5. **Import-Pipeline (technische Sicht)**
|
||||||
|
1. Discovery & Parsing (`import_markdown.py`)
|
||||||
|
2. Hash-/Idempotenz-Mechanismus (ENV-Variablen, Baseline-Modi)
|
||||||
|
3. Chunking (`chunker.py`, `chunk_payload.py`)
|
||||||
|
4. Edge-Erzeugung (`derive_edges.py`)
|
||||||
|
5. Roundtrip & Tests (Export & Vault-Vergleich)
|
||||||
|
6. **Retriever-Architektur**
|
||||||
|
1. API (FastAPI-Endpunkt `/query`)
|
||||||
|
2. Semantik- und Hybridmodus
|
||||||
|
3. Subgraph & Graph-API (expand)
|
||||||
|
4. Scoring-Formel und Komponenten (semantik, edges, centrality) :contentReference[oaicite:37]{index=37}
|
||||||
|
7. **Offene technische Punkte / Roadmap**
|
||||||
|
1. Explanation Layer (WP04b)
|
||||||
|
2. Feedback-Logging (WP04c)
|
||||||
|
3. Virtual Schema Layer (WP05)
|
||||||
|
4. Self-Healing & Self-Tuning (WP06–08)
|
||||||
|
|
||||||
|
#### Building Blocks
|
||||||
|
|
||||||
|
- `mindnet_technical_architecture.md` – Kerntext. :contentReference[oaicite:39]{index=39}
|
||||||
|
- `chunking_strategy.md` – Datenmodell & Chunk-Details. :contentReference[oaicite:40]{index=40}
|
||||||
|
- `Handbuch.md` – ENV, Skripte, Runbooks. :contentReference[oaicite:41]{index=41}
|
||||||
|
- `wp04_retriever_scoring.md` / `docs_mindnet_retriever.md` – Retriever-Details. :contentReference[oaicite:42]{index=42}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### D) `mindnet_knowledge_design_manual_v2.2.md`
|
||||||
|
|
||||||
|
#### Zweck & Zielgruppe
|
||||||
|
- Konkrete Anleitung für das Schreiben und Strukturieren von Notes & Chunks im Vault.
|
||||||
|
- Für dich als Owner/Mindmaster und alle, die Notes erstellen.
|
||||||
|
|
||||||
|
#### Geplantes Inhaltsverzeichnis
|
||||||
|
|
||||||
|
1. **Zweck & Scope**
|
||||||
|
1. Rolle des Vaults als „Source of Truth“
|
||||||
|
2. **Note-Struktur & Frontmatter**
|
||||||
|
1. Pflicht- und optionale Felder (id, title, type, tags, status, created/updated, …)
|
||||||
|
2. Empfehlungen für IDs, Pfade und Namenskonventionen
|
||||||
|
3. **Note-Typen & Typ-Registry**
|
||||||
|
1. Übersicht der Typen (concept, project, experience, decision, value, principle, person, event, …)
|
||||||
|
2. Typ-spezifische Einsatzempfehlungen
|
||||||
|
3. Zusammenspiel mit `types.yaml` (retriever_weight, chunk_profile, edge_defaults)
|
||||||
|
4. **Edges & Referenzen in Notes**
|
||||||
|
1. Wikilinks (`[[Note]]`) → `references`
|
||||||
|
2. Inline-Relationen (`[[rel:depends_on XYZ]]`, `similar_to`, `related_to`)
|
||||||
|
3. Callout-Edges (`> [!edge] …`)
|
||||||
|
4. Strukturkanten (Ordner, belongs_to)
|
||||||
|
5. **Best Practices**
|
||||||
|
1. Beispiele für gut modellierte Notes (Projekt, Entscheidung, Erfahrung)
|
||||||
|
2. Typische Anti-Patterns und wie man sie vermeidet
|
||||||
|
6. **Langfristige Stabilität**
|
||||||
|
1. Virtual Schema Layer – was bedeutet das für Note-Autoren? (Wenig Änderungen in bestehenden Notes, Logik in Configs) :contentReference[oaicite:46]{index=46}
|
||||||
|
|
||||||
|
#### Building Blocks
|
||||||
|
|
||||||
|
- `knowledge_design.md` – Kerntext + Beispiele. :contentReference[oaicite:47]{index=47}
|
||||||
|
- `TYPE_REGISTRY_MANUAL.md` – Typ-Registry & Verhalten. :contentReference[oaicite:48]{index=48}
|
||||||
|
- `mindnet_functional_architecture.md` – ergänzende Konzepte & Edges. :contentReference[oaicite:49]{index=49}
|
||||||
|
- `chunking_strategy.md` – Inline-Relationen, Edges, Datenmodell. :contentReference[oaicite:50]{index=50}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### E) `mindnet_pipeline_playbook_v2.2.md`
|
||||||
|
|
||||||
|
#### Zweck & Zielgruppe
|
||||||
|
- End-to-End-Playbook für die gesamte Pipeline:
|
||||||
|
- Importer,
|
||||||
|
- Chunking,
|
||||||
|
- Edge-Erzeugung,
|
||||||
|
- Retriever & Scoring,
|
||||||
|
- (perspektivisch) Explanation Layer, Self-Healing, Self-Tuning.
|
||||||
|
- Für Dev/Ops und technische Leads.
|
||||||
|
|
||||||
|
#### Geplantes Inhaltsverzeichnis
|
||||||
|
|
||||||
|
1. **Zweck & Einordnung**
|
||||||
|
1. Bezug zu WPs 02–04a (Ist) und 04b–08 (Roadmap)
|
||||||
|
2. **Import-Pipeline (Runbook-Sicht)**
|
||||||
|
1. Inputs (Vault, Config-Files, ENV)
|
||||||
|
2. Standardläufe (Initialimport, inkrementelle Updates, Sync-Deletes)
|
||||||
|
3. Baseline-Builds & Hash-Modi
|
||||||
|
3. **Chunking & Payload-Aufbau**
|
||||||
|
1. Chunk-Profile, Overlaps, Fenster
|
||||||
|
2. Feldbesetzung (`text`, `window`, `section_title`, `neighbors`, …)
|
||||||
|
4. **Edge-Erzeugung**
|
||||||
|
1. Strukturkanten (belongs_to, next, prev)
|
||||||
|
2. Explizite Edges (Wikilinks, Inline-Relationen, Callouts)
|
||||||
|
3. Typ-Default-Kanten aus `types.yaml`
|
||||||
|
5. **Retriever & Scoring**
|
||||||
|
1. Konfiguration (`retriever.yaml`, ENV)
|
||||||
|
2. Scoring-Formel und Parameter
|
||||||
|
3. Semantik- vs. Hybridmodus
|
||||||
|
4. Test- und Smoke-Suites
|
||||||
|
6. **Quality Gates & Tests**
|
||||||
|
1. Roundtrip-Tests (Vault → Qdrant → Export)
|
||||||
|
2. Chunk-Integrität und Fenster-Checks
|
||||||
|
3. Retriever-Regressionstests
|
||||||
|
7. **Ausblick: Self-Healing, Retroactive Edges, Self-Tuning**
|
||||||
|
1. Geplante Batch-Jobs und Feedback-Pipelines (WP06–08)
|
||||||
|
|
||||||
|
#### Building Blocks
|
||||||
|
|
||||||
|
- `mindnet_v2_implementation_playbook.md` – Policies, Teststrategie, KPIs. :contentReference[oaicite:57]{index=57}
|
||||||
|
- `Handbuch.md` – Skripte & Test-Runbooks. :contentReference[oaicite:58]{index=58}
|
||||||
|
- `chunking_strategy.md` – Chunk- & Edge-Strategie. :contentReference[oaicite:59]{index=59}
|
||||||
|
- `docs_mindnet_retriever.md` / `wp04_retriever_scoring.md` – Retriever-Praktiken & Tests. :contentReference[oaicite:60]{index=60}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### F) `mindnet_developer_guide_v2.2.md`
|
||||||
|
|
||||||
|
#### Zweck & Zielgruppe
|
||||||
|
- Konzentrierte Sicht für Entwickler:innen:
|
||||||
|
- wie das Projekt strukturiert ist,
|
||||||
|
- wie man es lokal aufsetzt,
|
||||||
|
- wie man neue Features implementiert/testet.
|
||||||
|
|
||||||
|
#### Geplantes Inhaltsverzeichnis
|
||||||
|
|
||||||
|
1. **Projektstruktur**
|
||||||
|
1. Verzeichnisbaum (app/, scripts/, tests/, config/, …)
|
||||||
|
2. **Lokale Entwicklungsumgebung**
|
||||||
|
1. Abhängigkeiten, venv, ENV
|
||||||
|
2. Starten von Services (Qdrant, API, ggf. ollama)
|
||||||
|
3. **APIs & Module**
|
||||||
|
1. Importer-Skripte
|
||||||
|
2. Core-Module (Chunker, Edge-Engine, Retriever)
|
||||||
|
3. FastAPI-Endpunkte (`/query`, evtl. Admin-Endpoints)
|
||||||
|
4. **Tests & Debugging**
|
||||||
|
1. pytest-Suites
|
||||||
|
2. Logging & Diagnoseskripte
|
||||||
|
5. **Guidelines für Erweiterungen**
|
||||||
|
1. Neue Typen & Edge-Regeln
|
||||||
|
2. Änderungen am Datenmodell
|
||||||
|
3. Umgang mit Schema-Änderungen (Virtual Schema Layer)
|
||||||
|
|
||||||
|
#### Building Blocks
|
||||||
|
|
||||||
|
- `mindnet_technical_architecture.md` – Modul- & API-Beschreibungen. :contentReference[oaicite:63]{index=63}
|
||||||
|
- `Handbuch.md` – Skripte & Beispiele. :contentReference[oaicite:64]{index=64}
|
||||||
|
- `docs_mindnet_retriever.md` – API-Beispiele für den Retriever. :contentReference[oaicite:65]{index=65}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### G) `mindnet_admin_guide_v2.2.md`
|
||||||
|
|
||||||
|
#### Zweck & Zielgruppe
|
||||||
|
- Betriebshandbuch für mindnet:
|
||||||
|
- Installation,
|
||||||
|
- Konfiguration,
|
||||||
|
- Backup/Restore,
|
||||||
|
- Monitoring,
|
||||||
|
- Troubleshooting.
|
||||||
|
|
||||||
|
#### Geplantes Inhaltsverzeichnis
|
||||||
|
|
||||||
|
1. **Zielgruppe & Scope**
|
||||||
|
2. **Initial Setup**
|
||||||
|
1. Voraussetzungen (Ubuntu, Docker/Qdrant, Python-Umgebung)
|
||||||
|
2. ENV-Variablen & Config-Files (types.yaml, retriever.yaml)
|
||||||
|
3. **Betrieb im Alltag**
|
||||||
|
1. Regelmäßige Imports
|
||||||
|
2. Umgang mit Fehlermeldungen im Importer
|
||||||
|
3. Health-Checks für Qdrant & API
|
||||||
|
4. **Update-Prozess**
|
||||||
|
1. Vorgehen bei Schema-/Code-Updates
|
||||||
|
2. Umgang mit neuen Typen und Policies
|
||||||
|
5. **Backup & Restore**
|
||||||
|
1. Qdrant-Snapshots
|
||||||
|
2. Vault-Backup (Obsidian)
|
||||||
|
3. Konsistenzprüfungen
|
||||||
|
6. **Monitoring & Logging**
|
||||||
|
1. typische Logquellen (Importer, API, n8n)
|
||||||
|
7. **Governance & Sicherheit**
|
||||||
|
1. Bezug zur Programm-Governance (WP14, MCP-Sicherheit)
|
||||||
|
|
||||||
|
#### Building Blocks
|
||||||
|
|
||||||
|
- `Handbuch.md` – Betriebsskripte & ENV. :contentReference[oaicite:69]{index=69}
|
||||||
|
- `mindnet_v2_implementation_playbook.md` – Policies/Resilienz. :contentReference[oaicite:70]{index=70}
|
||||||
|
- Programmplan – Governance / WP14. :contentReference[oaicite:71]{index=71}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### H) `mindnet_user_guide_v2.2.md`
|
||||||
|
|
||||||
|
#### Zweck & Zielgruppe
|
||||||
|
- Anleitung für Nutzer:innen (inkl. späterer Chat-Agenten-User):
|
||||||
|
- wie man mindnet im Alltag nutzt,
|
||||||
|
- wie man Fragen stellt,
|
||||||
|
- wie man neue Gedanken einbringt.
|
||||||
|
|
||||||
|
#### Geplantes Inhaltsverzeichnis
|
||||||
|
|
||||||
|
1. **Was mindnet für dich tut**
|
||||||
|
1. Persönliches Gedächtnis
|
||||||
|
2. KI-Zwilling als Gesprächspartner :contentReference[oaicite:72]{index=72}
|
||||||
|
2. **Zugänge zu mindnet**
|
||||||
|
1. Obsidian-Vault
|
||||||
|
2. Chat-Agent (lokal, n8n-Workflows)
|
||||||
|
3. (später) Interview-Assistent, MCP-Tools
|
||||||
|
3. **Gute Fragen an mindnet**
|
||||||
|
1. Beispiel-Queries (Wissensabruf, Entscheidungen, Reflexionen)
|
||||||
|
4. **Neue Inhalte eingeben**
|
||||||
|
1. Notes in Obsidian erstellen
|
||||||
|
2. Typen und Links bewusst setzen (vereinfachte Version aus D)
|
||||||
|
5. **Ergebnisse interpretieren**
|
||||||
|
1. Was bedeutet ein Treffer-Set?
|
||||||
|
2. Wie sind Scores zu lesen? (nur Ist-Stand, Explanation Layer als Ausblick)
|
||||||
|
6. **Feedback & Lernen**
|
||||||
|
1. Manuelles Feedback (gut/schlecht) – Roadmap WP04c/08
|
||||||
|
|
||||||
|
#### Building Blocks
|
||||||
|
|
||||||
|
- Programmplan – Vision & Use-Cases. :contentReference[oaicite:76]{index=76}
|
||||||
|
- Knowledge Design – Autorensicht (stark vereinfacht). :contentReference[oaicite:77]{index=77}
|
||||||
|
- Retriever-Dokumente – Scoring & Interpretation. :contentReference[oaicite:78]{index=78}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### I) `mindnet_appendices_v2.2.md`
|
||||||
|
|
||||||
|
#### Zweck & Zielgruppe
|
||||||
|
- Referenzen, Tabellen, technische Details, die Hauptdokumente nicht überfrachten sollen.
|
||||||
|
|
||||||
|
#### Geplantes Inhaltsverzeichnis
|
||||||
|
|
||||||
|
1. **Typenreferenz (Auszug aus `types.yaml`)**
|
||||||
|
- Tabellenform: Typ, chunk_profile, edge_defaults, retriever_weight
|
||||||
|
2. **Edge-Typen & Bedeutungen**
|
||||||
|
- belongs_to, references, depends_on, similar_to, related_to, next, prev, …
|
||||||
|
3. **Datenmodelle (JSON-Skizzen)**
|
||||||
|
- Note, Chunk, Edge-Payload (aktuell implementierter Stand)
|
||||||
|
4. **Relevante ENV-Variablen & Konfigurationen**
|
||||||
|
- Hash-Settings, COLLECTION_PREFIX, MINDNET_TYPES_FILE, MINDNET_RETRIEVER_CONFIG etc.
|
||||||
|
5. **WP-Übersicht & Status**
|
||||||
|
- kompakte Tabelle aller WPs mit Status (🟢/🟡) und Verweisen auf relevante Dokumente.
|
||||||
|
6. **Historische Dokumente**
|
||||||
|
- Verweis auf alte Versionen (`mindnet_functional_architecture.md`, ältere Playbooks), falls diese nicht vollständig eingearbeitet werden.
|
||||||
|
|
||||||
|
#### Building Blocks
|
||||||
|
|
||||||
|
- `TYPE_REGISTRY_MANUAL.md` – Typen-Referenz. :contentReference[oaicite:84]{index=84}
|
||||||
|
- `chunking_strategy.md` – JSON-Beispiele. :contentReference[oaicite:85]{index=85}
|
||||||
|
- `mindnet_technical_architecture.md` – Felder & Prioritäten. :contentReference[oaicite:86]{index=86}
|
||||||
|
- Programmplan – WP-Tabellen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Bearbeitungsreihenfolge (Empfehlung)
|
||||||
|
|
||||||
|
Aus Sicht der Informationssicherung und Konsistenz ist folgende Reihenfolge sinnvoll:
|
||||||
|
|
||||||
|
1. **C – `mindnet_technical_architecture_v2.2.md`**
|
||||||
|
- Begründung:
|
||||||
|
- bildet den **aktuellen implementierten Stand** von WP02–WP04a am präzisesten ab,
|
||||||
|
- ist stark an konkrete Felder, Collections und Skripte gebunden (hier ist der Ist-Stand am eindeutigsten belegbar),
|
||||||
|
- ist die Grundlage für Developer Guide, Playbook und Admin Guide.
|
||||||
|
|
||||||
|
2. **E – `mindnet_pipeline_playbook_v2.2.md`**
|
||||||
|
- Konsolidiert Handbuch + Implementation-Playbook + WP04-Dokumente.
|
||||||
|
|
||||||
|
3. **D – `mindnet_knowledge_design_manual_v2.2.md`**
|
||||||
|
- Stellt sicher, dass das Wissensdesign stabil dokumentiert ist, bevor Overview/User Guide entstehen.
|
||||||
|
|
||||||
|
4. **A – `mindnet_overview_v2.2.md`**
|
||||||
|
- Kann sich dann sauber auf die finalisierte fachliche/technische Sicht stützen.
|
||||||
|
|
||||||
|
5. **F, G, H, I**
|
||||||
|
- Developer/Admin/User Guides & Appendices, basierend auf den konsolidierten Kern-Dokumenten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Nächster konkreter Schritt
|
||||||
|
|
||||||
|
Als nächstes finalisieren wir gemäß dieser Reihenfolge das Dokument:
|
||||||
|
|
||||||
|
> **C – `mindnet_technical_architecture_v2.2.md`**
|
||||||
|
|
||||||
|
Dabei gehen wir wie folgt vor:
|
||||||
|
|
||||||
|
1. Bestehendes `mindnet_technical_architecture.md` **vollständig** als Basis übernehmen. :contentReference[oaicite:89]{index=89}
|
||||||
|
2. Fehlende Details aus `chunking_strategy.md`, `Handbuch.md`, `TYPE_REGISTRY_MANUAL.md` und `wp04_retriever_scoring.md` integrieren (ohne Informationsverlust).
|
||||||
|
3. Ist-Stand vs. Roadmap klar kennzeichnen (WP04b–08, WP05–07).
|
||||||
|
|
||||||
|
Dieses Vorgehen hält die technische Wahrheit konsistent und liefert eine stabile Basis für alle nachfolgenden Dokumente.
|
||||||
@@ -0,0 +1,705 @@
|
|||||||
|
# mindnet v2.4 — Programmplan
|
||||||
|
**Version:** 2.7.0 (Post-WP15: Roadmap Erweiterung für Graph-Health & Visualisierung)
|
||||||
|
**Stand:** 2025-12-12
|
||||||
|
**Status:** Aktiv
|
||||||
|
|
||||||
|
---
|
||||||
|
- [mindnet v2.4 — Programmplan](#mindnet-v24--programmplan)
|
||||||
|
- [1. Programmauftrag](#1-programmauftrag)
|
||||||
|
- [2. Vision](#2-vision)
|
||||||
|
- [3. Programmziele](#3-programmziele)
|
||||||
|
- [3.1 Kurzfristig (Abgeschlossen / Laufend)](#31-kurzfristig-abgeschlossen--laufend)
|
||||||
|
- [3.2 Mittelfristig (Nächste Schritte)](#32-mittelfristig-nächste-schritte)
|
||||||
|
- [3.3 Langfristig](#33-langfristig)
|
||||||
|
- [4. Architekturprinzipien](#4-architekturprinzipien)
|
||||||
|
- [5. Programmstruktur (Phasenmodell)](#5-programmstruktur-phasenmodell)
|
||||||
|
- [6. Workpackages – detaillierte Übersicht](#6-workpackages--detaillierte-übersicht)
|
||||||
|
- [Legende Aufwand / Komplexität](#legende-aufwand--komplexität)
|
||||||
|
- [WP-01 – Wissensdesign (abgeschlossen)](#wp-01--wissensdesign-abgeschlossen)
|
||||||
|
- [WP-02 – Chunking \& Hash-Strategie (abgeschlossen)](#wp-02--chunking--hash-strategie-abgeschlossen)
|
||||||
|
- [WP-03 – Import-Pipeline \& Edge-System v2 (abgeschlossen)](#wp-03--import-pipeline--edge-system-v2-abgeschlossen)
|
||||||
|
- [WP-04a – Retriever \& Graph-Scoring (abgeschlossen)](#wp-04a--retriever--graph-scoring-abgeschlossen)
|
||||||
|
- [WP-04b – Explanation Layer ("Why-Layer") (abgeschlossen)](#wp-04b--explanation-layer-why-layer-abgeschlossen)
|
||||||
|
- [WP-04c – Feedback Logging \& Bewertungsdaten (abgeschlossen)](#wp-04c--feedback-logging--bewertungsdaten-abgeschlossen)
|
||||||
|
- [WP-05 – Persönlichkeitsmodell \& RAG-Chat (abgeschlossen)](#wp-05--persönlichkeitsmodell--rag-chat-abgeschlossen)
|
||||||
|
- [WP-05b – Advanced Chat (Optional)](#wp-05b--advanced-chat-optional)
|
||||||
|
- [WP-06 – Decision Engine \& Hybrid Router (abgeschlossen)](#wp-06--decision-engine--hybrid-router-abgeschlossen)
|
||||||
|
- [WP-07 – Interview-Assistent (abgeschlossen)](#wp-07--interview-assistent-abgeschlossen)
|
||||||
|
- [WP-08 – Self-Tuning v1/v2 (geplant)](#wp-08--self-tuning-v1v2-geplant)
|
||||||
|
- [WP-09 – Vault-Onboarding \& Migration (geplant)](#wp-09--vault-onboarding--migration-geplant)
|
||||||
|
- [WP-10 – Chat-Interface \& Writeback (abgeschlossen)](#wp-10--chat-interface--writeback-abgeschlossen)
|
||||||
|
- [WP-10a – GUI Evolution: Draft Editor (abgeschlossen)](#wp-10a--gui-evolution-draft-editor-abgeschlossen)
|
||||||
|
- [WP-11 – Backend Intelligence \& Persistence (abgeschlossen)](#wp-11--backend-intelligence--persistence-abgeschlossen)
|
||||||
|
- [WP-12 – Knowledge Rewriter (Soft Mode, geplant)](#wp-12--knowledge-rewriter-soft-mode-geplant)
|
||||||
|
- [WP-13 – MCP-Integration \& Agenten-Layer (geplant)](#wp-13--mcp-integration--agenten-layer-geplant)
|
||||||
|
- [WP-14 – Review / Refactoring / Dokumentation (geplant)](#wp-14--review--refactoring--dokumentation-geplant)
|
||||||
|
- [WP-15 – Smart Edge Allocation \& Chunking Strategies (abgeschlossen)](#wp-15--smart-edge-allocation--chunking-strategies-abgeschlossen)
|
||||||
|
- [WP-16 – Auto-Discovery \& Enrichment (geplant)](#wp-16--auto-discovery--enrichment-geplant)
|
||||||
|
- [WP-17 – Conversational Memory (Dialog-Gedächtnis) (geplant)](#wp-17--conversational-memory-dialog-gedächtnis-geplant)
|
||||||
|
- [WP-18 – Graph Health \& Maintenance (NEU, geplant)](#wp-18--graph-health--maintenance-neu-geplant)
|
||||||
|
- [WP-19 – Graph Visualisierung \& Explorer (NEU, geplant)](#wp-19--graph-visualisierung--explorer-neu-geplant)
|
||||||
|
- [WP-20 – Cloud Hybrid Mode (Gemini) (NEU, geplant)](#wp-20--cloud-hybrid-mode-gemini-neu-geplant)
|
||||||
|
- [7. Abhängigkeiten (vereinfacht, aktualisiert)](#7-abhängigkeiten-vereinfacht-aktualisiert)
|
||||||
|
- [8. Laufzeit- \& Komplexitätsindikatoren (aktualisiert)](#8-laufzeit---komplexitätsindikatoren-aktualisiert)
|
||||||
|
- [9. Programmfortschritt (Ampel, aktualisiert)](#9-programmfortschritt-ampel-aktualisiert)
|
||||||
|
- [10. Governance \& Versionierung](#10-governance--versionierung)
|
||||||
|
- [11. Executive Summary](#11-executive-summary)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Programmauftrag
|
||||||
|
|
||||||
|
mindnet v2.4 entwickelt ein persönliches, wachsendes KI-Gedächtnis, das:
|
||||||
|
|
||||||
|
- Wissen, Erfahrungen, Werte und Entscheidungen speichert,
|
||||||
|
- diese Informationen semantisch verknüpft und rekonstruierbar macht,
|
||||||
|
- einen KI-Zwilling aufbaut, der ähnlich argumentiert, entscheidet und reflektiert wie du,
|
||||||
|
- über mehrere Kanäle gefüttert wird:
|
||||||
|
- Obsidian-Markdown (primäre Quelle),
|
||||||
|
- Chat-basierter Agent (Decision Engine & RAG-Chat aktiv),
|
||||||
|
- Interview-Assistent (One-Shot Extraction aktiv),
|
||||||
|
- **Draft Editor (Active Intelligence aktiv)**,
|
||||||
|
- automatisch neue Zusammenhänge erkennt und vernetzt (Edges, Typen, Hinweise),
|
||||||
|
- sich durch Rückmeldungen (Feedback) selbst verbessert (Self-Tuning).
|
||||||
|
|
||||||
|
Langfristig soll mindnet als **digitales Gegenüber** funktionieren, das:
|
||||||
|
|
||||||
|
- dich versteht,
|
||||||
|
- deine Denkweise reflektiert,
|
||||||
|
- deine Werte kennt und verwendet,
|
||||||
|
- Entscheidungen begründen kann („Warum?“),
|
||||||
|
- Erinnerungen einordnet,
|
||||||
|
- und für deine Nachkommen als dialogfähiger Gesprächspartner zur Verfügung steht.
|
||||||
|
|
||||||
|
mindnet ist **kein statisches Wissensarchiv**, sondern ein **lebendes, lernendes Gedächtnismodell** mit Fokus auf:
|
||||||
|
|
||||||
|
- persönliche Perspektive,
|
||||||
|
- erklärbare Begründungspfade (Why-Layer),
|
||||||
|
- kontinuierliche Erweiterbarkeit,
|
||||||
|
- robuste technische Basis (lokal, nachvollziehbar, versioniert).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Vision
|
||||||
|
|
||||||
|
> „Ein persönliches semantisches Gedächtnis, das mit mir wächst, meine Persönlichkeit spiegelt und mir als intelligenter, erklärbarer, lernender Begleiter dient.“
|
||||||
|
|
||||||
|
Kernprinzipien der Vision:
|
||||||
|
|
||||||
|
- **Erklärbarkeit:**
|
||||||
|
Jede Antwort muss über Edges, Scores, Werte-Bezüge und Herkunftsnotizen begründbar sein. Das System kann Entscheidungen auf zugrundeliegende `[DECISION]`-Notizen zurückführen.
|
||||||
|
|
||||||
|
- **Wachstum:**
|
||||||
|
Das System arbeitet von Anfang an mit unvollständigen Daten, kann aber schrittweise dichter werden, ohne dass alte Notizen massenhaft manuell angepasst werden müssen.
|
||||||
|
|
||||||
|
- **Flexibilität (Late Binding):**
|
||||||
|
Semantik wird überwiegend in Konfiguration (z. B. `types.yaml`, `prompts.yaml`, `decision_engine.yaml`) festgelegt. Die Persönlichkeit entsteht durch das Config-Design, nicht durch Hardcoding.
|
||||||
|
|
||||||
|
- **Autonomie & Self-Healing:**
|
||||||
|
mindnet schlägt fehlende Typen, Relationen und Edges vor (z. B. aus Inline-Relationen, Edge-Defaults, Ähnlichkeitsbeziehungen) und baut damit einen „self-healing graph“ auf.
|
||||||
|
|
||||||
|
- **Lernen & Self-Tuning:**
|
||||||
|
Feedback zu Antworten (gut/schlecht, relevant/nicht relevant) fließt in Score-Gewichte, Policies und ggf. Edge-Struktur ein.
|
||||||
|
|
||||||
|
- **Persönlichkeit:**
|
||||||
|
Entscheidungen werden wert- und erfahrungsbasiert begründet; das System agiert als KI-Zwilling durch Nutzung lokaler LLMs (z.B. Phi-3/Mistral) und eines Intent-Routers.
|
||||||
|
|
||||||
|
- **Incremental Growth:**
|
||||||
|
Das System muss mit wenigen, heterogenen Notizen starten und sich fortlaufend verdichten können – ohne Retro-Massenmigrationen im Vault.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Programmziele
|
||||||
|
|
||||||
|
### 3.1 Kurzfristig (Abgeschlossen / Laufend)
|
||||||
|
|
||||||
|
- Automatische Sammlung von Wissen aus Markdown-Vault.
|
||||||
|
- Aufbau eines stabilen Graph-Speichers in Qdrant (`*_notes`, `*_chunks`, `*_edges`).
|
||||||
|
- Semantischer und graphbasierter Retriever (WP-04a abgeschlossen).
|
||||||
|
- **Erklärbarkeit:** Why-Layer liefert Begründungen zu Treffern (WP-04b abgeschlossen).
|
||||||
|
- **Feedback-Loop:** Systematisches Logging von Suche und Bewertung (WP-04c abgeschlossen).
|
||||||
|
- **RAG-Chat:** KI antwortet in natürlicher Sprache auf Basis von Wissen und Persönlichkeit (WP-05 abgeschlossen).
|
||||||
|
- **Decision Engine:** System erkennt Intent (Fakt vs. Entscheidung) und wägt Werte ab (WP-06 abgeschlossen).
|
||||||
|
- **Multi-Persona:** System wechselt den Tonfall (Empathisch vs. Analytisch) situativ (WP-06 abgeschlossen).
|
||||||
|
- **Chat Interface:** Web-basiertes Frontend (Streamlit) für einfache Interaktion und Feedback-Gabe (WP-10 abgeschlossen).
|
||||||
|
- **Interview-Assistent (WP-07):** One-Shot Extraction von Notizen ("Neues Projekt anlegen") ist live.
|
||||||
|
- **Active Intelligence (WP-11):** Automatische Link-Vorschläge (Matrix-Logik) während des Schreibens.
|
||||||
|
- Technische Basis: FastAPI (Async), Qdrant (768 Dim), Ollama (Phi-3/Nomic), Streamlit.
|
||||||
|
- Automatisierte Erkennung von Beziehungen:
|
||||||
|
- Wikilinks, Inline-Relationen, Callout-Edges, Typ-Defaults.
|
||||||
|
- „Mitwachsendes“ Schema ohne Obsidian-Umstrukturierungen:
|
||||||
|
- Neues Wissen kann sofort erfasst werden,
|
||||||
|
- bestehende Notizen bleiben gültig (Virtual Schema Layer).
|
||||||
|
|
||||||
|
### 3.2 Mittelfristig (Nächste Schritte)
|
||||||
|
|
||||||
|
- **Self-Tuning (WP-08):** Optimierung der Gewichte in `retriever.yaml` basierend auf dem gesammelten Feedback.
|
||||||
|
- Agenten können über MCP-Tools (`mindnet_query`, `mindnet_chat`) auf mindnet zugreifen (WP-13).
|
||||||
|
|
||||||
|
### 3.3 Langfristig
|
||||||
|
|
||||||
|
- KI-Zwilling, der deinen Stil, deine Werte und deine typische Denkweise repräsentiert.
|
||||||
|
- Weitgehend autonomes Self-Tuning der Wissensstruktur (auf Basis gespeicherter Feedback-Daten & Policies).
|
||||||
|
- Lebenslanges Gedächtnis, das
|
||||||
|
- konsistent bleibt,
|
||||||
|
- wächst,
|
||||||
|
- sich weiterentwickelt,
|
||||||
|
- und deine Geschichte für deine Nachkommen erzählbar und erlebbar macht.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Architekturprinzipien
|
||||||
|
|
||||||
|
Die folgenden Prinzipien steuern alle Workpackages und Entscheidungen:
|
||||||
|
|
||||||
|
1. **Late Binding (späte Semantik)**
|
||||||
|
- Struktur und Interpretation werden in Konfigurationen (z. B. `types.yaml`, `prompts.yaml`, `decision_engine.yaml`) definiert, nicht direkt in den Vault-Dateien.
|
||||||
|
- Die "Persönlichkeit" des Chats ist ein Prompt-Template, kein Code.
|
||||||
|
|
||||||
|
2. **Virtual Schema Layer**
|
||||||
|
- Typen, Regeln, Policies, Edge-Defaults werden im Schema-Layer beschrieben.
|
||||||
|
- Markdown-Dateien benötigen nur minimale, robuste Angaben (Titel, Typ, optionale Properties).
|
||||||
|
|
||||||
|
3. **Self-Healing Graph**
|
||||||
|
- Der Graph wird regelmäßig analysiert (Edges, Centrality, fehlende Links).
|
||||||
|
- Automatisierte Jobs ergänzen fehlende Kanten.
|
||||||
|
|
||||||
|
4. **Deterministische IDs**
|
||||||
|
- Notes, Chunks und Edges erhalten stabile IDs (z. B. UUIDv5).
|
||||||
|
- Der Graph ist jederzeit wiederaufbaubar (Import-Pipeline idempotent).
|
||||||
|
|
||||||
|
5. **Full Explainability & Context Enrichment**
|
||||||
|
- Jeder Score, jede Beziehung muss nachvollziehbar sein.
|
||||||
|
- Dem LLM werden Metadaten (`[DECISION]`, `[PROJECT]`) injiziert, um Halluzinationen zu vermeiden und logische Schlüsse zu ermöglichen.
|
||||||
|
|
||||||
|
6. **Persistence First**
|
||||||
|
- Obsidian bleibt die primäre Quelle der Wahrheit.
|
||||||
|
- mindnet ergänzt, schlägt Änderungen vor, schreibt aber nur kontrolliert.
|
||||||
|
|
||||||
|
7. **Minimalinvasives Schreiben**
|
||||||
|
- Automatische Veränderungen an Markdown-Dateien erfolgen ausschließlich nach expliziter Zustimmung.
|
||||||
|
|
||||||
|
8. **Incremental Growth & Early Value**
|
||||||
|
- Das System muss bereits mit wenigen Notizen und einem kleinen Vault sinnvolle Antworten liefern.
|
||||||
|
- Feedback-Mechanismen werden früh eingeführt.
|
||||||
|
|
||||||
|
9. **Observability & Testbarkeit**
|
||||||
|
- Jeder Importlauf, jede Retriever-Anfrage und jede Policy-Änderung soll prüfbar sein.
|
||||||
|
|
||||||
|
10. **Local First & Privacy**
|
||||||
|
- Nutzung lokaler LLMs (Ollama) für Inference. Keine Daten verlassen den Server.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Programmstruktur (Phasenmodell)
|
||||||
|
|
||||||
|
Phase A – Fundament & Import (Fertig)
|
||||||
|
Phase B – Semantik, Graph & Lernen (Fertig)
|
||||||
|
Phase C – Persönlichkeitsmodell & KI-Zwilling (Fertig)
|
||||||
|
Phase D – Agenten, MCP & Interaktion (Aktiv)
|
||||||
|
Phase E – Maintenance, Visualisierung & Scaling (Neu)
|
||||||
|
|
||||||
|
Alle Workpackages sind einer Phase zugeordnet. WP-01 bis WP-07 und WP-10/10a/11 sind erfolgreich abgeschlossen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Workpackages – detaillierte Übersicht
|
||||||
|
|
||||||
|
### Legende Aufwand / Komplexität
|
||||||
|
|
||||||
|
- Aufwand: Niedrig / Mittel / Hoch
|
||||||
|
- Komplexität: Niedrig / Mittel / Hoch
|
||||||
|
|
||||||
|
Die Status-Ampel zeigt den aktuellen Stand gemäß Programmfortschritt.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-01 – Wissensdesign (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** A
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Grundlegendes Schema für mindnet festlegen (`knowledge_design.md`), inkl.:
|
||||||
|
- Note-Typen (z. B. `concept`, `experience`, `project`, `decision`, `value`).
|
||||||
|
- Standard-Properties und Grundstruktur von Edges.
|
||||||
|
- Abbildung zentraler Lebens-Bereiche.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- `knowledge_design.md` und `types.yaml` definieren die Zielarchitektur.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-02 – Chunking & Hash-Strategie (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** A
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Festlegen und implementieren einer robusten Chunking-Strategie und einer Hash-Logik zur Änderungserkennung.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- Implementierte Chunker-Logik mit Overlap.
|
||||||
|
- Stabile Hash-Strategie zur sicheren Änderungserkennung.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-03 – Import-Pipeline & Edge-System v2 (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** A/B
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Durchgängige Import-Pipeline von Markdown → Notes/Chunks/Edges in Qdrant mit deterministischen IDs.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- Vollständige E2E-Import-Pipeline.
|
||||||
|
- Vollständiges Edge-Modell (Strukturkanten, Wikilinks, Inline-Relationen).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-04a – Retriever & Graph-Scoring (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** B
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Aufbau eines hybriden Retrievers, der Semantik, Typwissen und Graph-Informationen kombiniert.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- Hybrides Scoring-Modell (Semantic + Edge + Centrality).
|
||||||
|
- Konfiguration über `retriever.yaml`.
|
||||||
|
- `/query` Endpoint aktiv.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-04b – Explanation Layer ("Why-Layer") (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** B
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Treffererklärungen liefern, die verständlich machen, warum ein Ergebnis gewählt wurde.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- **DTO-Erweiterung:** `QueryHit` enthält `explanation`, `breakdown` und `reason`.
|
||||||
|
- **Logic:** Graph-Adapter unterstützt `incoming_edges` (Reverse Lookup) für Authority-Erklärungen.
|
||||||
|
- **Output:** `/query` Endpoint liefert auf Wunsch (`explain: true`) menschenlesbare Begründungen ("Verweist auf...").
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-04c – Feedback Logging & Bewertungsdaten (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** B
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Grundlage für Self-Tuning schaffen durch systematisches Logging.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- **Data Flywheel:** Logging von Queries und User-Feedback in lokalen JSONL-Dateien.
|
||||||
|
- **Search Log:** Speichert Query + Score-Snapshot in `data/logs/search_history.jsonl`.
|
||||||
|
- **Feedback Log:** Speichert User-Ratings in `data/logs/feedback.jsonl`.
|
||||||
|
- **Traceability:** Durchgängige `query_id` von Request bis Feedback.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-05 – Persönlichkeitsmodell & RAG-Chat (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** C
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Aufbau eines RAG-Systems, das in natürlicher Sprache antwortet und Kontext versteht.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- **Infrastruktur:** Integration von Ollama (Phi-3 Mini) in den Service-Layer.
|
||||||
|
- **Router:** `/chat` Endpoint mit "Hybrid Retrieval Enforcement".
|
||||||
|
- **Context Enrichment:** Injection von Metadaten (`[TYPE]`, `[SCORE]`) in den Prompt, damit kleine Modelle (SLMs) komplexe Zusammenhänge ("Warum?") verstehen.
|
||||||
|
- **Config:** `prompts.yaml` steuert System-Prompt und RAG-Template.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Mittel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-05b – Advanced Chat (Optional)
|
||||||
|
|
||||||
|
**Phase:** C
|
||||||
|
**Status:** ⚪ optional
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Erweiterung des Chats um Gedächtnis (History) und einfache Tools.
|
||||||
|
|
||||||
|
**Umfang:**
|
||||||
|
- Implementierung von `ChatHistory` (vergangene Nachrichten in den Kontext).
|
||||||
|
- Einfache Tool-Nutzung (z.B. "Suche in Web").
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-06 – Decision Engine & Hybrid Router (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** C
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Transformation vom reinen Wissens-Abrufer zum strategischen Entscheidungspartner durch Intent-Erkennung.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- **Hybrid Intent Router:** Kombination aus schnellem Keyword-Matching und intelligentem LLM-Fallback zur Erkennung der Absicht (`DECISION`, `EMPATHY`, `FACT`, `CODING`).
|
||||||
|
- **Strategic Retrieval:** Gezieltes Nachladen von Werten (`value`), Zielen (`goal`) oder Erfahrungen (`experience`) basierend auf dem Intent.
|
||||||
|
- **Multi-Persona:** Dynamische Anpassung des Tonfalls (Berater vs. Spiegel vs. Techniker) durch `prompts.yaml`.
|
||||||
|
- **Late Binding:** Vollständige Konfiguration via `decision_engine.yaml`.
|
||||||
|
- **Robustheit:** Konfigurierbare Timeouts für CPU-Inference.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Hoch
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-07 – Interview-Assistent (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** C/D
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Dialogbasierter Erfassungs-Assistent, der strukturierte Interviews führt und daraus konsistente Markdown-Notizen generiert.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- **One-Shot Extractor:** Extrahiert Notiz-Inhalte aus einem Prompt.
|
||||||
|
- **Schema Injection:** Typspezifische Pflichtfelder (Late Binding).
|
||||||
|
- **Draft Generator:** Liefert validen Markdown-Codeblock mit `status: draft`.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Niedrig/Mittel
|
||||||
|
- Komplexität: Mittel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-08 – Self-Tuning v1/v2 (geplant)
|
||||||
|
|
||||||
|
**Phase:** B/C
|
||||||
|
**Status:** 🟡 geplant (Nächster Fokus)
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Aufbau eines Self-Tuning-Mechanismus, der auf Basis von Feedback-Daten (WP-04c) Vorschläge für Retriever- und Policy-Anpassungen macht.
|
||||||
|
|
||||||
|
**Umfang:**
|
||||||
|
- Auswertung der JSONL-Feedback-Daten.
|
||||||
|
- Regel-basierte Anpassungs-Vorschläge für `retriever.yaml` und Typ-Prioritäten.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Hoch
|
||||||
|
- Komplexität: Hoch
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-09 – Vault-Onboarding & Migration (geplant)
|
||||||
|
|
||||||
|
**Phase:** B
|
||||||
|
**Status:** 🟡 geplant
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Sicherstellen, dass bestehende und neue Obsidian-Vaults schrittweise in mindnet integriert werden können – ohne Massenumbau.
|
||||||
|
|
||||||
|
**Umfang:**
|
||||||
|
- Tools zur Analyse des Vault-Status.
|
||||||
|
- Empfehlungen für minimale Anpassungen.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Niedrig/Mittel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-10 – Chat-Interface & Writeback (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** D
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Ablösung der Terminal-Interaktion durch ein grafisches Interface.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- **Tech-Stack:** Streamlit Frontend (`app/frontend/ui.py`).
|
||||||
|
- **Funktionen:** Chat-Verlauf, Visualisierung von Intents und Quellen (Expander).
|
||||||
|
- **Feedback:** Globales Rating (Sterne) und granulare Quellen-Bewertung (Faces).
|
||||||
|
- **Writeback:** Mockup-Interface für neue Einträge (Vorbereitung WP-07).
|
||||||
|
- **Deployment:** Systemd-Services für Prod (8501) und Dev (8502).
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Hoch
|
||||||
|
- Komplexität: Hoch
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-10a – GUI Evolution: Draft Editor (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** D
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Anpassung der GUI an komplexe Interaktionsmuster, die durch den Interview-Assistenten und Knowledge-Builder entstehen.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- **Draft Editor:** Interaktive `st.text_area` für generierte Entwürfe.
|
||||||
|
- **Sanitizer:** `normalize_meta_and_body` zur Korrektur von LLM-Fehlern.
|
||||||
|
- **Download/Copy:** Export-Funktionen für Markdown.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Mittel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-11 – Backend Intelligence & Persistence (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** D
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Ermöglichung von "Active Intelligence" durch asynchrone Verarbeitung und semantische Analyse im Hintergrund.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- **Async Core:** Umstellung der Pipeline auf `asyncio` und `httpx` (Vermeidung von Blockaden).
|
||||||
|
- **Nomic Embeddings:** Integration von `nomic-embed-text` (768 Dim) für State-of-the-Art Semantik.
|
||||||
|
- **Matrix Logic:** Regelwerk für kontextsensitive Kanten (`experience` + `value` -> `based_on`).
|
||||||
|
- **Sliding Window:** Analyse langer Texte für Link-Vorschläge.
|
||||||
|
- **Persistence API:** Neuer Endpunkt `/ingest/save` für atomares Speichern & Indizieren.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Hoch
|
||||||
|
- Komplexität: Hoch
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-12 – Knowledge Rewriter (Soft Mode, geplant)
|
||||||
|
|
||||||
|
**Phase:** C/D
|
||||||
|
**Status:** 🟡 geplant
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Optionaler Assistent, der vorhandene Notes „aufräumt“, zusammenfasst oder reorganisiert – ausschließlich mit expliziter Freigabe.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Niedrig/Mittel
|
||||||
|
- Komplexität: Mittel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-13 – MCP-Integration & Agenten-Layer (geplant)
|
||||||
|
|
||||||
|
**Phase:** D
|
||||||
|
**Status:** 🟡 geplant
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
mindnet als MCP-Server bereitstellen, damit Agenten/LLMs standardisierte Tools nutzen können.
|
||||||
|
|
||||||
|
**Umfang:**
|
||||||
|
- MCP-Server mit Tools (`mindnet_query`, `mindnet_explain`, etc.).
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Mittel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-14 – Review / Refactoring / Dokumentation (geplant)
|
||||||
|
|
||||||
|
**Phase:** E
|
||||||
|
**Status:** 🟡 geplant
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Aufräumen, dokumentieren, stabilisieren – insbesondere für Onboarding Dritter und Langfrist-Betrieb.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Niedrig/Mittel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-15 – Smart Edge Allocation & Chunking Strategies (abgeschlossen)
|
||||||
|
|
||||||
|
**Phase:** D
|
||||||
|
**Status:** 🟢 abgeschlossen
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Einführung einer intelligenten Verteilung von Wissenskanten an spezifische Text-Chunks, um die Präzision des Retrievals zu erhöhen, ohne die Stabilität des Systems durch lange LLM-Verarbeitungszeiten zu gefährden.
|
||||||
|
|
||||||
|
**Erreichte Ergebnisse:**
|
||||||
|
- **5-Stufen-Workflow:** Implementierung von "Smart Edge Allocation" (Global Scan -> Deterministic Split -> LLM Filter -> Injection -> Fallback).
|
||||||
|
- **Neue Chunking-Strategien:** Einführung von `by_heading` (für strukturierte Daten) und verbessertem `sliding_window` als deterministische Basis.
|
||||||
|
- **Robustheit:** Trennung von Zerlegung (Code) und Analyse (LLM). Bei LLM-Fehlern oder Timeouts greift ein Fallback-Mechanismus (Datenverlust ausgeschlossen).
|
||||||
|
- **Architektur:** Trennung der Orchestrierung (`chunker.py`) von der KI-Logik (`semantic_analyzer.py`).
|
||||||
|
- **Konfiguration:** Steuerung über `types.yaml` (`enable_smart_edge_allocation`) ermöglicht granulare Anpassung pro Notiztyp.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Hoch
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-16 – Auto-Discovery & Enrichment (geplant)
|
||||||
|
|
||||||
|
**Phase:** D
|
||||||
|
**Status:** 🟡 geplant
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Automatisches Erkennen und Vorschlagen von fehlenden Kanten in "dummem" Text (ohne explizite Wikilinks) vor der Speicherung. Umwandlung von Text in "smarten Text" durch Nutzung des `DiscoveryService`.
|
||||||
|
|
||||||
|
**Umfang:**
|
||||||
|
- Integration eines "Enrichers" in die Ingestion-Pipeline (Schritt 0).
|
||||||
|
- Unterscheidung zwischen "Hard Candidates" (explizite Links) und "Soft Candidates" (Vektor-basierte Vorschläge).
|
||||||
|
- LLM-basierte Verifikation der Vorschläge zur Vermeidung von Halluzinationen.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Hoch
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-17 – Conversational Memory (Dialog-Gedächtnis) (geplant)
|
||||||
|
|
||||||
|
**Phase:** D
|
||||||
|
**Status:** 🟡 geplant
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Erweiterung des Chat-Backends von einem statischen Request-Response-Modell zu einem zustandsbehafteten Dialogsystem ("Multi-Turn Conversation"). Das System soll sich an vorherige Aussagen im aktuellen Gesprächsverlauf erinnern, um Rückfragen ("Was meinst du damit?") korrekt zu interpretieren.
|
||||||
|
|
||||||
|
**Umfang:**
|
||||||
|
- **API-Erweiterung:** `ChatRequest` DTO erhält ein `history`-Feld (Liste von Nachrichten).
|
||||||
|
- **Context Management:** Implementierung einer Token-Budget-Logik, die dynamisch zwischen RAG-Kontext (Dokumente) und Dialog-Verlauf (History) balanciert, um das Kontextfenster (8k) optimal zu nutzen.
|
||||||
|
- **Prompt Engineering:** Integration eines `{chat_history}` Platzhalters in den System-Prompt.
|
||||||
|
- **Frontend-Update:** Die `ui.py` muss die letzten N Nachrichtenpaare (User/AI) bei jedem Request mitsenden.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Mittel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-18 – Graph Health & Maintenance (NEU, geplant)
|
||||||
|
|
||||||
|
**Phase:** E
|
||||||
|
**Status:** 🟡 geplant (Prio 2)
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Sicherstellung der Konsistenz des Wissensgraphen bei Löschungen oder Umbenennungen von Notizen ("Dangling Edges").
|
||||||
|
|
||||||
|
**Architektur-Idee:**
|
||||||
|
- **Health-Check Script:** Ein Cronjob (`scripts/check_graph_integrity.py`), der alle Kanten prüft, ob ihre `target_id` noch in `mindnet_notes` existiert.
|
||||||
|
- **Report:** Ausgabe von "Broken Links" als Liste für den User.
|
||||||
|
- **Auto-Heal (Optional):** Markieren von defekten Kanten als `broken` statt hartem Löschen.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Niedrig
|
||||||
|
- Komplexität: Mittel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-19 – Graph Visualisierung & Explorer (NEU, geplant)
|
||||||
|
|
||||||
|
**Phase:** E
|
||||||
|
**Status:** 🟡 geplant (Prio 1)
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Schaffung von Vertrauen und Transparenz durch Visualisierung der vom "Smart Chunker" erzeugten Verbindungen.
|
||||||
|
|
||||||
|
**Architektur-Idee:**
|
||||||
|
- **Frontend-Erweiterung:** Neuer Tab "🕸️ Graph" in Streamlit.
|
||||||
|
- **Tech-Stack:** Integration von `streamlit-agraph` oder `pyvis`.
|
||||||
|
- **Feature:** Visualisierung der Nachbarschaft einer Notiz (Ego-Graph) oder eines Suchergebnisses.
|
||||||
|
- **Nutzen:** Schnelle Validierung, ob Smart Edges korrekt gesetzt wurden.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Mittel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WP-20 – Cloud Hybrid Mode (Gemini) (NEU, geplant)
|
||||||
|
|
||||||
|
**Phase:** E
|
||||||
|
**Status:** ⚪ optional
|
||||||
|
|
||||||
|
**Ziel:**
|
||||||
|
Optionale Beschleunigung ("Turbo-Modus") für Massen-Imports oder komplexe Analysen durch Nutzung externer High-Performance LLMs (Google Gemini 1.5 Flash), unter Beachtung des Datenschutzes.
|
||||||
|
|
||||||
|
**Architektur-Idee:**
|
||||||
|
- **Provider-Switch:** Erweiterung des `LLMService` um einen Provider-Parameter (`ollama` vs. `gemini`).
|
||||||
|
- **Konfiguration:** `types.yaml` oder `.env` erlaubt Umschalten pro Umgebung (z.B. Dev=Cloud, Prod=Local).
|
||||||
|
- **Privacy:** Warnhinweis im UI, wenn Daten die lokale Umgebung verlassen.
|
||||||
|
|
||||||
|
**Aufwand / Komplexität:**
|
||||||
|
- Aufwand: Mittel
|
||||||
|
- Komplexität: Niedrig
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Abhängigkeiten (vereinfacht, aktualisiert)
|
||||||
|
|
||||||
|
WP01-03 → WP04-06 (Core)
|
||||||
|
WP11 → WP15 (Smart Edges)
|
||||||
|
WP15 → WP19 (Visualisierung - zur Kontrolle)
|
||||||
|
WP15 → WP16 (Auto-Discovery)
|
||||||
|
WP03 → WP18 (Maintenance)
|
||||||
|
WP10 → WP17 (Memory)
|
||||||
|
WP20 (Cloud) ist unabhängig/optional.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Laufzeit- & Komplexitätsindikatoren (aktualisiert)
|
||||||
|
|
||||||
|
| WP | Aufwand | Komplexität |
|
||||||
|
|-------|----------------|------------------|
|
||||||
|
| WP15 | Mittel | Hoch |
|
||||||
|
| WP16 | Mittel | Hoch |
|
||||||
|
| WP17 | Mittel | Mittel |
|
||||||
|
| WP18 | Niedrig | Mittel |
|
||||||
|
| WP19 | Mittel | Mittel |
|
||||||
|
| WP20 | Mittel | Niedrig |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Programmfortschritt (Ampel, aktualisiert)
|
||||||
|
|
||||||
|
| WP | Status | Titel |
|
||||||
|
|-------|--------|-------|
|
||||||
|
| WP01-14| 🟢 | (Basis-System) |
|
||||||
|
| WP15 | 🟢 | Smart Edge Allocation |
|
||||||
|
| WP16 | 🟡 | Auto-Discovery |
|
||||||
|
| WP17 | 🟡 | Conversational Memory |
|
||||||
|
| WP18 | 🟡 | Graph Health (Neu) |
|
||||||
|
| WP19 | 🟡 | Visualization (Neu) |
|
||||||
|
| WP20 | ⚪ | Cloud Mode (Neu) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Governance & Versionierung
|
||||||
|
|
||||||
|
- Versionierung über Gitea (Branches, Tags, Releases).
|
||||||
|
- Feature-Branch Workflow mit "Sync First" Strategie.
|
||||||
|
- Jede wesentliche Änderung an Architektur/Schema erhält einen eigenen Commit.
|
||||||
|
- Jedes Workpackage erhält ein eigenes Chat-Fenster mit dediziertem Prompt (WP-Hand-Over).
|
||||||
|
- Programmleitung verantwortet Konsistenz und Priorisierung.
|
||||||
|
- **Modell-Governance:** Das verwendete LLM (z.B. `phi3:mini`) wird in der `.env` und `config.py` festgeschrieben. Updates erfordern Tests gegen die "Why-Layer" Referenzfragen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. Executive Summary
|
||||||
|
|
||||||
|
mindnet v2.4 ist so aufgesetzt, dass:
|
||||||
|
|
||||||
|
- du **schrittweise** Wissen erfassen kannst (Obsidian + Chat + Interview-Drafts),
|
||||||
|
- die Struktur **mitwächst**, ohne Retro-Massenarbeit im Vault,
|
||||||
|
- ein **hybrider Retriever** qualitativ hochwertige, erklärbare Antworten liefert,
|
||||||
|
- ein **Self-Healing- und Self-Tuning-Mechanismus** vorbereitet ist (durch WP-04c Feedback-Daten),
|
||||||
|
- ein **Persönlichkeitsmodell** (Decision Engine, Empathie) existiert und den Tonfall situativ anpasst,
|
||||||
|
- eine **grafische Oberfläche** (WP-10/10a) existiert, die komplexe Zusammenhänge visualisiert und Co-Creation ermöglicht,
|
||||||
|
- **Active Intelligence** (WP-11) dich beim Schreiben unterstützt, indem es automatisch Verknüpfungen vorschlägt,
|
||||||
|
- langfristig ein **KI-Zwilling** aufgebaut wird, der deine Werte, Erfahrungen und Denkweise spiegelt,
|
||||||
|
- die technische Architektur (AsyncIO, Qdrant 768d, YAML-Policies) lokal, nachvollziehbar und performant bleibt.
|
||||||
|
|
||||||
|
Dieser Programmplan bildet die konsolidierte Grundlage (v2.4.0) für alle weiteren Arbeiten.
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
# mindnet v2.4 – Knowledge Design Manual
|
||||||
|
**Datei:** `docs/mindnet_knowledge_design_manual_v2.6.md`
|
||||||
|
**Stand:** 2025-12-12
|
||||||
|
**Status:** **FINAL** (Integrierter Stand WP01–WP15)
|
||||||
|
**Quellen:** `knowledge_design.md`, `TYPE_REGISTRY_MANUAL.md`, `chunking_strategy.md`, `mindnet_functional_architecture.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ⚡ Die 5 Goldenen Regeln (TL;DR)
|
||||||
|
|
||||||
|
Damit Mindnet als dein Digitaler Zwilling funktioniert, beachte beim Schreiben diese Grundsätze:
|
||||||
|
|
||||||
|
1. **Atomare Gedanken:** Eine Notiz = Ein Thema. Wenn du über zwei Projekte schreibst, mach zwei Notizen draus.
|
||||||
|
2. **Explizite Typen:** Setze immer den `type` im Frontmatter. Mindnet behandelt eine `decision` ("Wir machen X") völlig anders als ein `concept` ("Was ist X").
|
||||||
|
3. **Semantische Links:** Schreibe nicht nur `[[Link]]`, sondern `[[rel:depends_on Link]]`. Sag dem System *wie* Dinge zusammenhängen.
|
||||||
|
4. **Werte & Ziele definieren:** Damit die **Decision Engine** dich beraten kann, musst du deine Kriterien (`type: value`, `type: goal`) explizit als Notizen anlegen.
|
||||||
|
5. **Emotionales Bridging:** Damit die **Empathie** funktioniert, nutze in Erfahrungsberichten (`type: experience`) emotionale Schlüsselwörter ("Krise", "Freude", "Angst"), damit der Vektor-Retriever sie bei Gefühls-Anfragen findet.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Zweck & Scope
|
||||||
|
|
||||||
|
Dieses Handbuch ist die **primäre Arbeitsanweisung** für dich als Mindmaster (Owner) und alle Autoren, die Inhalte im mindnet-Vault erstellen.
|
||||||
|
|
||||||
|
### 1.1 Zielsetzung
|
||||||
|
Mindnet ist mehr als eine Dokumentablage. Es ist ein vernetztes System, das deine Persönlichkeit, Entscheidungen und Erfahrungen abbildet.
|
||||||
|
Seit Version 2.6 verfügt Mindnet über:
|
||||||
|
* **Hybrid Router:** Das System erkennt, ob du Fakten, Entscheidungen oder Empathie brauchst.
|
||||||
|
* **Smart Edge Allocation:** Das System prüft deine Links intelligent und bindet sie nur an die Textabschnitte (Chunks), wo sie wirklich relevant sind.
|
||||||
|
* **Web UI (WP10):** Du kannst direkt sehen, welche Quellen genutzt wurden.
|
||||||
|
* **Active Intelligence (WP11):** Das System hilft dir beim Schreiben und Vernetzen (Link-Vorschläge).
|
||||||
|
|
||||||
|
### 1.2 Der Vault als „Source of Truth“
|
||||||
|
Die Markdown-Dateien in deinem Vault sind die **einzige Quelle der Wahrheit**.
|
||||||
|
* Mindnet importiert diesen Zustand deterministisch in die Datenbank (Qdrant).
|
||||||
|
* Änderungen an IDs, Typen oder Inhalten müssen **immer** im Markdown erfolgen, niemals direkt in der Datenbank.
|
||||||
|
* Was nicht im Markdown steht (z. B. implizites Wissen im Kopf), existiert für das System nicht.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Note-Struktur & Frontmatter
|
||||||
|
|
||||||
|
Jede Notiz benötigt einen YAML-Header (Frontmatter) am Dateianfang. Dieser Block macht die Notiz maschinenlesbar.
|
||||||
|
|
||||||
|
### 2.1 Pflichtfelder
|
||||||
|
Jede Datei muss mindestens folgende Felder enthalten, um korrekt verarbeitet zu werden:
|
||||||
|
|
||||||
|
---
|
||||||
|
id: 20251110-projekt-alpha-8a9b2c # Eindeutige Kennung (YYYYMMDD-slug)
|
||||||
|
title: Projekt Alpha # Sprechender Titel (wird in Suchergebnissen angezeigt)
|
||||||
|
type: project # Steuert Verarbeitung & Vernetzung (siehe Kap. 3)
|
||||||
|
status: active # active, archived oder 'draft' (für generierte Notes)
|
||||||
|
created: 2025-11-10 # Erstellungsdatum (ISO 8601 oder YYYY-MM-DD)
|
||||||
|
updated: 2025-12-07 # Letzte Änderung
|
||||||
|
tags: [ki, entwicklung] # Taxonomie für Filterung
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.2 Optionale Felder
|
||||||
|
Diese Felder sind technisch nicht zwingend, aber für bestimmte Typen sinnvoll:
|
||||||
|
|
||||||
|
lang: de # Sprache (Default: de)
|
||||||
|
aliases: [Alpha Projekt, Project A] # Synonyme (WICHTIG für Exact Match in Intelligence)
|
||||||
|
visibility: internal # internal (default), public, private
|
||||||
|
|
||||||
|
> **Hinweis:** Felder wie `retriever_weight` oder `chunk_profile` sollten **nicht** mehr manuell im Frontmatter gesetzt werden. Diese werden zentral über den `type` gesteuert (siehe Kap. 3), um die Wartbarkeit zu sichern.
|
||||||
|
|
||||||
|
### 2.3 Empfehlungen für IDs und Pfade
|
||||||
|
|
||||||
|
**Die ID (Identifikator):**
|
||||||
|
* Muss global eindeutig und **stabil** sein.
|
||||||
|
* Darf sich nicht ändern, wenn die Datei umbenannt oder verschoben wird.
|
||||||
|
* **Empfehlung:** `YYYYMMDD-slug` (z. B. `20231027-vektor-db`). Dies garantiert Eindeutigkeit und Chronologie.
|
||||||
|
|
||||||
|
**Dateinamen & Pfade:**
|
||||||
|
* Pfade dienen der menschlichen Ordnung (Ordnerstruktur), sind für Mindnet aber sekundär.
|
||||||
|
* Dateinamen sollten dem Titel entsprechen (`Projekt Alpha.md`) oder dem Slug (`projekt-alpha.md`).
|
||||||
|
* Sonderzeichen vermeiden (außer Bindestrich und Unterstrich).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Note-Typen & Typ-Registry
|
||||||
|
|
||||||
|
Der `type` ist der wichtigste Hebel im Knowledge Design. Er steuert nicht nur das Gewicht bei der Suche, sondern seit WP-06 auch, **wann** eine Notiz aktiv in den Chat geholt wird ("Strategic Retrieval") und seit WP-15, **ob Smart Edges aktiviert sind**.
|
||||||
|
|
||||||
|
### 3.1 Übersicht der Kern-Typen
|
||||||
|
|
||||||
|
Mindnet unterscheidet verschiedene Wissensarten. Wähle den Typ, der die **Rolle** der Notiz am besten beschreibt:
|
||||||
|
|
||||||
|
| Typ | Beschreibung & Einsatzzweck | Rolle im Chat (Intent) | Interview Schema (WP07) | Matrix-Logik (WP11) |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **`concept`** | Fachbegriffe, Theorien. Zeitloses Wissen. | **FACT** | Titel, Definition, Tags | Ziel für `uses` |
|
||||||
|
| **`project`** | Ein Vorhaben mit Ziel, Dauer und Aufgaben. | **FACT / DECISION** | Ziel, Status, Stakeholder | Quelle für `uses`, `depends_on` |
|
||||||
|
| **`experience`** | Persönliche Erfahrung, Lektion oder Erkenntnis. | **EMPATHY** | Situation, Erkenntnis, Emotionen | Quelle für `based_on`, `derived_from` |
|
||||||
|
| **`decision`** | Eine bewusst getroffene Entscheidung (ADR). | **DECISION** | Kontext, Entscheidung, Alternativen | Quelle für `depends_on`, `caused_by` |
|
||||||
|
| **`value`** | Ein persönlicher Wert oder ein Prinzip. | **DECISION** | Definition, Anti-Beispiel | Ziel für `based_on` |
|
||||||
|
| **`principle`** | Handlungsleitlinie. | **DECISION** | Regel, Ausnahme | Quelle für `derived_from` |
|
||||||
|
| **`goal`** | Ein strategisches Ziel (kurz- oder langfristig). | **DECISION** | Zeitrahmen, KPIs, Werte | Ziel für `related_to` |
|
||||||
|
| **`risk`** | Ein identifiziertes Risiko oder eine Gefahr. | **DECISION** | Auswirkung, Wahrscheinlichkeit | Quelle für `blocks` |
|
||||||
|
| **`belief`** | Glaubenssatz / Überzeugung. | **EMPATHY** | Ursprung, Mantra | - |
|
||||||
|
| **`person`** | Eine reale Person (Netzwerk, Autor). | **FACT** | Rolle, Kontext | - |
|
||||||
|
| **`journal`** | Zeitbezogener Log-Eintrag, Daily Note. | **FACT** | Datum, Tags | - |
|
||||||
|
| **`source`** | Externe Quelle (Buch, PDF, Artikel). | **FACT** | Autor, URL | - |
|
||||||
|
|
||||||
|
### 3.2 Zusammenspiel mit `types.yaml`
|
||||||
|
|
||||||
|
Der `type` steuert im Hintergrund drei technische Mechanismen:
|
||||||
|
|
||||||
|
1. **`retriever_weight` (Wichtigkeit):**
|
||||||
|
* Ein `concept` (0.6) wiegt weniger als ein `project` (0.97) oder eine `decision` (1.0).
|
||||||
|
2. **`chunk_profile` (Textzerlegung):**
|
||||||
|
* `journal` (short): Wird fein zerlegt.
|
||||||
|
* `experience` (sliding_smart_edges): Wird intelligent analysiert.
|
||||||
|
3. **`enable_smart_edge_allocation` (WP15):**
|
||||||
|
* Wenn `true`: Das System analysiert jeden Abschnitt mit KI, um zu prüfen, ob verlinkte Themen dort wirklich relevant sind. Das erhöht die Präzision massiv.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Edges & Referenzen in Notes
|
||||||
|
|
||||||
|
Um aus isolierten Dateien ein **Netzwerk** zu machen, nutzen wir Verlinkungen. In Version 2.2 sind diese Verlinkungen die Basis für den **Hybrid Retriever** (Suche über Nachbarn).
|
||||||
|
|
||||||
|
### 4.1 Wikilinks (Die Basis-Referenz)
|
||||||
|
Der klassische Obsidian-Link.
|
||||||
|
|
||||||
|
Wir nutzen [[Qdrant]] als Vektordatenbank.
|
||||||
|
|
||||||
|
* **Bedeutung:** "Diese Notiz erwähnt Qdrant."
|
||||||
|
* **Edge-Typ:** `references`
|
||||||
|
|
||||||
|
### 4.2 Inline-Relationen (Semantische Verknüpfung)
|
||||||
|
Dies ist die **mächtigste** Methode. Du sagst dem System explizit, **wie** Dinge zusammenhängen.
|
||||||
|
|
||||||
|
Daher [[rel:depends_on Qdrant]].
|
||||||
|
Dieses Konzept ist [[rel:similar_to Pinecone]].
|
||||||
|
|
||||||
|
* **Syntax:** `[[rel:RELATION ZIEL]]`.
|
||||||
|
* **Gültige Relationen:**
|
||||||
|
* `depends_on`: Hängt ab von / Benötigt. (Trigger für hohe Graph-Relevanz).
|
||||||
|
* `similar_to`: Ähnelt / Ist vergleichbar mit.
|
||||||
|
* `related_to`: Hat zu tun mit (allgemein).
|
||||||
|
* `caused_by`: Wurde verursacht durch (Kausalität).
|
||||||
|
* `solves`: Löst (Problem).
|
||||||
|
* **`blocks`:** Blockiert oder gefährdet (z.B. Risiko -> Projekt).
|
||||||
|
* **`derived_from`:** Stammt ab von (z.B. Prinzip -> Buch, Erfahrung -> Wert).
|
||||||
|
* **`based_on`:** Basiert auf (Fundament).
|
||||||
|
* **`uses`:** Nutzt (Werkzeug/Konzept).
|
||||||
|
|
||||||
|
### 4.3 Callout-Edges (Kuratierte Listen)
|
||||||
|
Für Zusammenfassungen oder "Siehe auch"-Blöcke am Ende einer Notiz.
|
||||||
|
|
||||||
|
> [!edge] related_to: [[Vector Embeddings]] [[AI Agents]]
|
||||||
|
|
||||||
|
* **Funktion:** Erzeugt `related_to`-Kanten zu allen genannten Zielen in dieser Zeile.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Schreiben für den KI-Zwilling (New in v2.3/2.4)
|
||||||
|
|
||||||
|
Damit der **RAG-Chat (WP05/06)** nicht nur dumm Fakten wiedergibt, sondern dich berät, musst du "Futter" für die Decision Engine und das Empathie-Modul liefern.
|
||||||
|
|
||||||
|
### 5.1 Futter für die Decision Engine (`DECISION`)
|
||||||
|
Das System soll abwägen: "Passt Tool X zu mir?". Dazu muss es wissen, was "Du" bist.
|
||||||
|
|
||||||
|
**Best Practice: Werte definieren**
|
||||||
|
Erstelle Notizen mit `type: value`.
|
||||||
|
|
||||||
|
---
|
||||||
|
type: value
|
||||||
|
title: Prinzip: Datensparsamkeit
|
||||||
|
---
|
||||||
|
# Prinzip: Datensparsamkeit
|
||||||
|
Wir speichern nur das Minimum an Daten. Cloud-Uploads persönlicher Daten sind verboten, es sei denn, sie sind E2E-verschlüsselt.
|
||||||
|
|
||||||
|
**Best Practice: Ziele definieren**
|
||||||
|
Erstelle Notizen mit `type: goal`.
|
||||||
|
|
||||||
|
---
|
||||||
|
type: goal
|
||||||
|
title: Ziel: Unabhängigkeit 2026
|
||||||
|
---
|
||||||
|
# Ziel: Unabhängigkeit 2026
|
||||||
|
Bis Ende 2026 wollen wir alle SaaS-Abos durch Self-Hosted Lösungen ersetzt haben.
|
||||||
|
|
||||||
|
*Effekt:* Wenn du fragst "Soll ich Notion nutzen?", lädt die Engine diese beiden Notizen und antwortet: *"Nein, Notion ist SaaS und nicht E2E-verschlüsselt. Das verletzt dein Prinzip der Datensparsamkeit und dein Ziel der Unabhängigkeit."*
|
||||||
|
|
||||||
|
### 5.2 Futter für den Empathie-Modus (`EMPATHY`)
|
||||||
|
Das System soll dich verstehen, wenn du sagst: "Alles ist grau." Dazu braucht es deine Resonanzerfahrungen.
|
||||||
|
|
||||||
|
**Best Practice: Erfahrungen & Bridging**
|
||||||
|
Erstelle Notizen mit `type: experience`. Nutze im Text **emotionale Brückenwörter**, damit der Retriever auch bei abstrakten Gefühlen ("grau") einen Treffer landet.
|
||||||
|
|
||||||
|
---
|
||||||
|
type: experience
|
||||||
|
title: Erfahrung: Der Durchbruch nach der Krise
|
||||||
|
tags: [krise, hoffnung, grau, angst]
|
||||||
|
---
|
||||||
|
# Erfahrung: Der Durchbruch nach der Krise
|
||||||
|
Es gibt Projektphasen, da wirkt alles **sinnlos** und **grau**.
|
||||||
|
Ich habe gelernt: Das ist oft das Zeichen kurz vor dem Durchbruch.
|
||||||
|
Mein Mantra in solchen Zeiten: "Einfach weitermachen, der Nebel lichtet sich."
|
||||||
|
|
||||||
|
*Effekt:* Wenn du im Chat jammerst ("Alles ist sinnlos"), findet das System diese Notiz und spiegelt dir deine eigene Erfahrung zurück.
|
||||||
|
|
||||||
|
### 5.3 Schreiben für den Chat (UI Optimization)
|
||||||
|
Da deine Notizen im Web-Interface (WP10) angezeigt werden:
|
||||||
|
* **Kurze Absätze:** Das LLM liest besser, und der Mensch scannt schneller.
|
||||||
|
* **Klare Headings:** Nutze H1/H2, um dem Chunker logische Trennlinien zu geben.
|
||||||
|
|
||||||
|
### 5.4 Der Interview-Modus (Auto-Drafting)
|
||||||
|
Seit v2.4 (WP07) kann Mindnet Notizen für dich entwerfen.
|
||||||
|
|
||||||
|
* **Wie:** Schreibe im Chat einfach: *"Ich möchte ein neues Projekt 'Alpha' anlegen, Ziel ist die Markteroberung."*
|
||||||
|
* **Was passiert:** Mindnet erkennt den Wunsch (`INTERVIEW`), wählt das Schema für `project` und generiert **sofort** einen Markdown-Entwurf.
|
||||||
|
* **Ergebnis:** Du erhältst einen Code-Block mit `status: draft`. Diesen kannst du im Draft-Editor (UI) direkt bearbeiten und herunterladen.
|
||||||
|
* **Drafts:** Enthalten oft Platzhalter `[TODO]`. Das ist Absicht. Ergänze sie im Editor.
|
||||||
|
|
||||||
|
### 5.5 Futter für das Risikomanagement (`DECISION`)
|
||||||
|
Damit Mindnet dich vor Fehlern warnen kann, musst du Risiken explizit machen.
|
||||||
|
|
||||||
|
**Best Practice: Risiken definieren**
|
||||||
|
Erstelle Notizen mit `type: risk`. Nutze `blocks` oder `related_to`, um sie mit Projekten zu verknüpfen.
|
||||||
|
|
||||||
|
---
|
||||||
|
type: risk
|
||||||
|
title: Risiko: Vendor Lock-in bei Cloud-DBs
|
||||||
|
tags: [architektur, kosten, abhängigkeit]
|
||||||
|
---
|
||||||
|
# Risiko: Vendor Lock-in bei Cloud-DBs
|
||||||
|
Die Nutzung proprietärer Cloud-Datenbanken führt langfristig zu hohen Migrationskosten.
|
||||||
|
Dies [[rel:blocks Ziel Unabhängigkeit 2026]].
|
||||||
|
|
||||||
|
*Effekt:* Wenn du fragst "Soll ich AWS DynamoDB nutzen?", erkennt die Decision Engine den Konflikt mit deinem Ziel "Unabhängigkeit" durch die Kante `blocks` und den hohen `retriever_weight` des Risikos.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Best Practices & Beispiele (Klassik)
|
||||||
|
|
||||||
|
### 6.1 Beispiel: Projekt-Notiz
|
||||||
|
Projekte profitieren von `depends_on`, um Abhängigkeiten zu klären.
|
||||||
|
|
||||||
|
---
|
||||||
|
id: 20251115-proj-mindnet
|
||||||
|
title: Mindnet Implementierung
|
||||||
|
type: project
|
||||||
|
status: active
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet Implementierung
|
||||||
|
|
||||||
|
Wir bauen ein persönliches Wissensnetz.
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
Wir nutzen [[rel:depends_on Qdrant]] für die Vektorsuche und [[rel:depends_on FastAPI]] für das Backend.
|
||||||
|
|
||||||
|
## Architektur
|
||||||
|
Das Konzept basiert auf [[RAG Architecture]]. (Automatisch 'depends_on' durch Typ-Default).
|
||||||
|
|
||||||
|
### 6.2 Beispiel: Entscheidung (Decision Record)
|
||||||
|
Entscheidungen sind hoch gewichtet (`retriever_weight: 1.0`).
|
||||||
|
|
||||||
|
---
|
||||||
|
id: 20251120-adr-vektordb
|
||||||
|
title: ADR: Wahl von Qdrant
|
||||||
|
type: decision
|
||||||
|
status: final
|
||||||
|
tags: [architektur, db]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Entscheidung: Qdrant
|
||||||
|
|
||||||
|
Wir haben uns für Qdrant entschieden.
|
||||||
|
|
||||||
|
## Alternativen
|
||||||
|
Wir haben auch [[rel:similar_to Pinecone]] und [[rel:similar_to Weaviate]] betrachtet.
|
||||||
|
|
||||||
|
## Begründung
|
||||||
|
Qdrant erlaubt lokalen Betrieb und [[rel:solves Payload Filtering Requirements]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Langfristige Stabilität & Virtual Schema Layer
|
||||||
|
|
||||||
|
Mindnet ist auf Langlebigkeit ausgelegt.
|
||||||
|
|
||||||
|
### 7.1 Das "Virtual Schema" Prinzip
|
||||||
|
Wir vermeiden es, Logik in den Markdown-Dateien hart zu kodieren.
|
||||||
|
* Statt in jeder Notiz zu schreiben `chunk_size: 500`, schreiben wir nur `type: essay`.
|
||||||
|
* Wie groß ein Chunk für ein Essay ist, definieren wir in der Konfiguration (`types.yaml`).
|
||||||
|
|
||||||
|
### 7.2 Was bedeutet das für dich?
|
||||||
|
* Du kannst dich auf den Inhalt konzentrieren.
|
||||||
|
* Wenn wir in Zukunft basierend auf Feedback lernen, dass "Projekte" noch wichtiger sind, ändern wir **eine Zeile** in der Konfiguration, und das gesamte System passt sich beim nächsten Import an.
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
# Mindnet v2.4 – Overview & Einstieg
|
||||||
|
**Datei:** `docs/mindnet_overview_v2.6.md`
|
||||||
|
**Stand:** 2025-12-12
|
||||||
|
**Status:** **FINAL** (Inkl. Smart Edges, Traffic Control & Healing UI)
|
||||||
|
**Version:** 2.6.0
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Einführung: Was ist Mindnet?
|
||||||
|
|
||||||
|
**Mindnet** ist ein persönliches, lokales KI-Gedächtnis. Es ist der Versuch, einen **Digitalen Zwilling** deines Wissens und deiner Persönlichkeit zu erschaffen.
|
||||||
|
|
||||||
|
Anders als herkömmliche Notiz-Apps (wie Obsidian oder Evernote), die Texte nur passiv speichern, ist Mindnet ein **aktives System**:
|
||||||
|
* Es **versteht** Zusammenhänge über einen Wissensgraphen.
|
||||||
|
* Es **begründet** Antworten ("Warum ist das so?").
|
||||||
|
* Es **unterstützt** beim Schreiben: Es schlägt automatisch Verbindungen zu bestehendem Wissen vor ("Active Intelligence").
|
||||||
|
* Es **antwortet** situativ angepasst: Mal als Strategieberater, mal als empathischer Spiegel, und neu: **als Interviewer, der hilft, Wissen zu erfassen.**
|
||||||
|
|
||||||
|
### Die Vision
|
||||||
|
> „Ein System, das nicht nur speichert, was ich weiß, sondern auch wie ich denke, fühle und arbeite.“
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Die drei Ebenen des Systems
|
||||||
|
|
||||||
|
Mindnet arbeitet auf drei Schichten, die aufeinander aufbauen:
|
||||||
|
|
||||||
|
### Ebene 1: Content (Das Gedächtnis)
|
||||||
|
* **Quelle:** Dein lokaler Obsidian-Vault (Markdown).
|
||||||
|
* **Funktion:** Speicherung von Fakten, Projekten und Logs.
|
||||||
|
* **Technik:** Async Import-Pipeline, Smart Chunking (LLM-gestützte Kantenzuweisung), Vektor-Datenbank (Qdrant).
|
||||||
|
* **Status:** 🟢 Live (WP01–WP03, WP11, WP15).
|
||||||
|
|
||||||
|
### Ebene 2: Semantik (Das Verstehen)
|
||||||
|
* **Funktion:** Verknüpfung von isolierten Notizen zu einem Netzwerk.
|
||||||
|
* **Logik:** "Projekt A *hängt ab von* Entscheidung B".
|
||||||
|
* **Technik:** Hybrider Retriever (Graph + Nomic Embeddings), Explanation Engine.
|
||||||
|
* **Status:** 🟢 Live (WP04, WP11, WP15).
|
||||||
|
|
||||||
|
### Ebene 3: Identität & Interaktion (Die Persönlichkeit)
|
||||||
|
* **Funktion:** Interaktion, Bewertung und Co-Creation.
|
||||||
|
* **Logik:**
|
||||||
|
* "Ich empfehle Lösung X, weil sie unserem Wert 'Datensparsamkeit' entspricht."
|
||||||
|
* "Ich sehe, du willst ein Projekt starten. Lass uns die Eckdaten erfassen."
|
||||||
|
* **Technik:**
|
||||||
|
* **Hybrid Router v5:** Erkennt Absichten (Frage vs. Befehl) und unterscheidet Objekte (`types.yaml`) von Handlungen (`decision_engine.yaml`).
|
||||||
|
* **Traffic Control:** Priorisiert Chat-Anfragen ("Realtime") vor Hintergrund-Jobs ("Background").
|
||||||
|
* **One-Shot Extraction:** Generiert Entwürfe für neue Notizen.
|
||||||
|
* **Active Intelligence:** Schlägt Links während des Schreibens vor.
|
||||||
|
* **Status:** 🟢 Live (WP05–WP07, WP10, WP15).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. End-to-End Architektur
|
||||||
|
|
||||||
|
Der Datenfluss in Mindnet ist zyklisch ("Data Flywheel"):
|
||||||
|
|
||||||
|
1. **Input:** Du schreibst Notizen in Obsidian **ODER** lässt sie von Mindnet im Chat entwerfen.
|
||||||
|
2. **Intelligence (Live):** Während du schreibst, analysiert Mindnet den Text und schlägt Verknüpfungen vor (Sliding Window Analyse).
|
||||||
|
3. **Ingest:** Ein asynchrones Python-Skript importiert und zerlegt die Daten.
|
||||||
|
* **Neu (Smart Edges):** Ein LLM analysiert jeden Textabschnitt und entscheidet, welche Kanten relevant sind.
|
||||||
|
4. **Intent Recognition:** Der Router analysiert deine Eingabe: Ist es eine Frage (RAG) oder ein Befehl (Interview)?
|
||||||
|
5. **Retrieval / Action:**
|
||||||
|
* Bei Fragen: Das System sucht Inhalte passend zum Intent.
|
||||||
|
* Bei Interviews: Das System wählt das passende Schema (z.B. Projekt-Vorlage).
|
||||||
|
6. **Generation:** Ein lokales LLM (Ollama) formuliert die Antwort oder den Markdown-Draft.
|
||||||
|
7. **Feedback:** Du bewertest die Antwort. Das System lernt (langfristig) daraus.
|
||||||
|
|
||||||
|
**Tech-Stack:**
|
||||||
|
* **Backend:** Python 3.10+, FastAPI (Async).
|
||||||
|
* **Datenbank:** Qdrant (Vektor & Graph, 768 Dim).
|
||||||
|
* **KI:** Ollama (Phi-3 Mini für Chat, Nomic für Embeddings) – 100% lokal.
|
||||||
|
* **Traffic Control:** Semaphore-Logik zur Lastverteilung zwischen Chat und Import.
|
||||||
|
* **Frontend:** Streamlit Web-UI (v2.5) mit Healing Parser.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Dokumentations-Wegweiser
|
||||||
|
|
||||||
|
Wo findest du was?
|
||||||
|
|
||||||
|
| Wenn du... | ...lies dieses Dokument |
|
||||||
|
| :--- | :--- |
|
||||||
|
| **...wissen willst, wie man Notizen schreibt.** | `mindnet_knowledge_design_manual_v2.6.md` |
|
||||||
|
| **...das System installieren oder betreiben musst.** | `mindnet_admin_guide_v2.6.md` |
|
||||||
|
| **...am Python-Code entwickeln willst.** | `mindnet_developer_guide_v2.6.md` |
|
||||||
|
| **...die Pipeline (Import -> RAG) verstehen willst.** | `mindnet_pipeline_playbook_v2.6.md` |
|
||||||
|
| **...die genaue JSON-Struktur oder APIs suchst.** | `mindnet_technical_architecture_v2.6.md` |
|
||||||
|
| **...verstehen willst, was fachlich passiert.** | `mindnet_functional_architecture_v2.6.md` |
|
||||||
|
| **...den aktuellen Projektstatus suchst.** | `mindnet_appendices_v2.6.md` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Rollen im System
|
||||||
|
|
||||||
|
* **Mindmaster (User/Owner):** Du. Du erstellst Inhalte, stellst Fragen und gibst Feedback. Du definierst die Werte (`type: value`).
|
||||||
|
* **Mindnet (Der Agent):** Der digitale Zwilling. Er agiert als pragmatischer, transparenter Assistent und Analyst.
|
||||||
|
* **Administrator:** Verantwortlich für Docker-Container, Backups und LLM-Ressourcen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Aktueller Fokus
|
||||||
|
|
||||||
|
Wir haben die **Smart Edge Allocation (WP15)** und die **System-Stabilisierung (Traffic Control)** erfolgreich abgeschlossen.
|
||||||
|
Das System kann nun aktiv helfen, Wissen zu strukturieren, ohne dabei unter Last zusammenzubrechen. Der Fokus verschiebt sich nun in Richtung **Conversational Memory (WP17)** und **MCP Integration (WP13)**.
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
# Mindnet v2.4 – Admin Guide
|
||||||
|
**Datei:** `docs/mindnet_admin_guide_v2.6.md`
|
||||||
|
**Stand:** 2025-12-12
|
||||||
|
**Status:** **FINAL** (Inkl. Traffic Control & Smart Edge Config)
|
||||||
|
**Quellen:** `Handbuch.md`, `mindnet_developer_guide_v2.6.md`.
|
||||||
|
|
||||||
|
> Dieses Handbuch richtet sich an **Administratoren**. Es beschreibt Installation, Konfiguration, Backup-Strategien, Monitoring und den sicheren Betrieb der Mindnet-Instanz (API + UI + DB).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Zielgruppe & Scope
|
||||||
|
|
||||||
|
Mindnet ist als **Multi-Service-Architektur** konzipiert, die lokal oder auf einem privaten Server läuft.
|
||||||
|
Wir unterscheiden strikt zwischen:
|
||||||
|
* **Production:** Backend (8001) + Frontend (8501). Stabiler `main` Branch.
|
||||||
|
* **Development:** Backend (8002) + Frontend (8502). Experimentelle Feature-Branches.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Initial Setup & Installation
|
||||||
|
|
||||||
|
### 2.1 Systemvoraussetzungen
|
||||||
|
* **OS:** Linux (Ubuntu 22.04+ empfohlen) oder macOS.
|
||||||
|
* **Runtime:** Python 3.10+, Docker (für Qdrant), Ollama (für LLM).
|
||||||
|
* **Hardware:**
|
||||||
|
* CPU: 4+ Cores empfohlen (für Async Import & Inference).
|
||||||
|
* RAM: Min. 8GB empfohlen (4GB System + 4GB für Phi-3/Qdrant).
|
||||||
|
* Disk: SSD empfohlen für Qdrant-Performance.
|
||||||
|
|
||||||
|
### 2.2 Installation (Code)
|
||||||
|
|
||||||
|
# 1. Repository klonen
|
||||||
|
git clone <repo-url> /home/llmadmin/mindnet
|
||||||
|
cd /home/llmadmin/mindnet
|
||||||
|
|
||||||
|
# 2. Umgebung einrichten
|
||||||
|
python3 -m venv .venv
|
||||||
|
source .venv/bin/activate
|
||||||
|
|
||||||
|
# 3. Dependencies installieren (inkl. Streamlit, HTTPX)
|
||||||
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# 4. Verzeichnisse anlegen
|
||||||
|
mkdir -p logs qdrant_storage data/logs vault
|
||||||
|
|
||||||
|
### 2.3 Qdrant Setup (Docker)
|
||||||
|
Wir nutzen Qdrant als Vektor-Datenbank. Persistenz ist wichtig.
|
||||||
|
|
||||||
|
docker run -d \
|
||||||
|
--name mindnet_qdrant \
|
||||||
|
--restart always \
|
||||||
|
-p 6333:6333 \
|
||||||
|
-v $(pwd)/qdrant_storage:/qdrant/storage \
|
||||||
|
qdrant/qdrant
|
||||||
|
|
||||||
|
### 2.4 Ollama Setup (LLM & Embeddings)
|
||||||
|
Mindnet benötigt einen lokalen LLM-Server für Chat UND Embeddings.
|
||||||
|
**WICHTIG (Update v2.4):** Es muss zwingend `nomic-embed-text` installiert sein, sonst startet der Import nicht.
|
||||||
|
|
||||||
|
# 1. Installieren (Linux Script)
|
||||||
|
curl -fsSL https://ollama.com/install.sh | sh
|
||||||
|
|
||||||
|
# 2. Modelle laden
|
||||||
|
ollama pull phi3:mini # Für Chat/Reasoning
|
||||||
|
ollama pull nomic-embed-text # Für Vektoren (768 Dim)
|
||||||
|
|
||||||
|
# 3. Testen
|
||||||
|
curl http://localhost:11434/api/generate -d '{"model": "phi3:mini", "prompt":"Hi"}'
|
||||||
|
|
||||||
|
### 2.5 Konfiguration (ENV)
|
||||||
|
Erstelle eine `.env` Datei im Root-Verzeichnis. Achte besonders auf `VECTOR_DIM` und das neue `MINDNET_LLM_BACKGROUND_LIMIT`.
|
||||||
|
|
||||||
|
# Server Config
|
||||||
|
UVICORN_HOST=0.0.0.0
|
||||||
|
|
||||||
|
# Qdrant Verbindung
|
||||||
|
QDRANT_URL="http://localhost:6333"
|
||||||
|
|
||||||
|
# Mindnet Core Settings
|
||||||
|
COLLECTION_PREFIX="mindnet"
|
||||||
|
MINDNET_TYPES_FILE="./config/types.yaml"
|
||||||
|
MINDNET_VAULT_ROOT="./vault"
|
||||||
|
|
||||||
|
# WICHTIG: Dimension auf 768 setzen (für Nomic)
|
||||||
|
VECTOR_DIM=768
|
||||||
|
|
||||||
|
# AI Modelle (Ollama)
|
||||||
|
MINDNET_OLLAMA_URL="http://127.0.0.1:11434"
|
||||||
|
MINDNET_LLM_MODEL="phi3:mini"
|
||||||
|
MINDNET_EMBEDDING_MODEL="nomic-embed-text"
|
||||||
|
|
||||||
|
# Timeouts (Erhöht für Async/Nomic/Smart Edges)
|
||||||
|
MINDNET_LLM_TIMEOUT=300.0
|
||||||
|
MINDNET_API_TIMEOUT=300.0 # Wichtig: Frontend muss warten können
|
||||||
|
|
||||||
|
# Traffic Control (Neu in v2.6)
|
||||||
|
# Begrenzt parallele LLM-Calls im Import, um Chat stabil zu halten.
|
||||||
|
MINDNET_LLM_BACKGROUND_LIMIT=2
|
||||||
|
|
||||||
|
# Configs
|
||||||
|
MINDNET_PROMPTS_PATH="./config/prompts.yaml"
|
||||||
|
MINDNET_DECISION_CONFIG="./config/decision_engine.yaml"
|
||||||
|
|
||||||
|
### 2.6 Deployment via Systemd (Backend & Frontend)
|
||||||
|
|
||||||
|
Mindnet benötigt zwei Services pro Umgebung: API (Uvicorn) und UI (Streamlit).
|
||||||
|
|
||||||
|
**Production Backend (`/etc/systemd/system/mindnet-prod.service`):**
|
||||||
|
|
||||||
|
[Unit]
|
||||||
|
Description=Mindnet API Prod (8001)
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=llmadmin
|
||||||
|
Group=llmadmin
|
||||||
|
WorkingDirectory=/home/llmadmin/mindnet
|
||||||
|
# Async Server Start
|
||||||
|
ExecStart=/home/llmadmin/mindnet/.venv/bin/uvicorn app.main:app --host 0.0.0.0 --port 8001 --env-file .env
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
|
||||||
|
**Production Frontend (`/etc/systemd/system/mindnet-ui-prod.service`):**
|
||||||
|
|
||||||
|
[Unit]
|
||||||
|
Description=Mindnet UI Prod (8501)
|
||||||
|
After=mindnet-prod.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=llmadmin
|
||||||
|
Group=llmadmin
|
||||||
|
WorkingDirectory=/home/llmadmin/mindnet
|
||||||
|
|
||||||
|
# Environment Variables
|
||||||
|
Environment="MINDNET_API_URL=http://localhost:8001"
|
||||||
|
Environment="MINDNET_API_TIMEOUT=300"
|
||||||
|
Environment="STREAMLIT_SERVER_PORT=8501"
|
||||||
|
Environment="STREAMLIT_SERVER_ADDRESS=0.0.0.0"
|
||||||
|
Environment="STREAMLIT_SERVER_HEADLESS=true"
|
||||||
|
|
||||||
|
ExecStart=/home/llmadmin/mindnet/.venv/bin/streamlit run app/frontend/ui.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
|
||||||
|
**Firewall (UFW):**
|
||||||
|
Öffne die Ports für den Zugriff:
|
||||||
|
|
||||||
|
sudo ufw allow 8501/tcp # Prod UI
|
||||||
|
sudo ufw allow 8502/tcp # Dev UI (falls gewünscht)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Betrieb im Alltag
|
||||||
|
|
||||||
|
### 3.1 Regelmäßige Importe
|
||||||
|
Der Vault-Zustand sollte regelmäßig (z.B. stündlich per Cronjob) nach Qdrant synchronisiert werden. Das Skript nutzt nun **AsyncIO**, **Smart Edges** und **Traffic Control**.
|
||||||
|
|
||||||
|
**Cronjob-Beispiel (stündlich):**
|
||||||
|
|
||||||
|
0 * * * * cd /home/llmadmin/mindnet && .venv/bin/python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --purge-before-upsert --sync-deletes >> ./logs/import.log 2>&1
|
||||||
|
|
||||||
|
**Hinweis zu Smart Edges:**
|
||||||
|
Der Import dauert nun länger (ca. 2-3 Min pro Datei), da das LLM intensiv genutzt wird. Dank `MINDNET_LLM_BACKGROUND_LIMIT=2` bleibt der Server dabei aber für den Chat responsive.
|
||||||
|
|
||||||
|
### 3.2 Health-Checks
|
||||||
|
Prüfe regelmäßig, ob alle Komponenten laufen.
|
||||||
|
|
||||||
|
sudo systemctl status mindnet-prod
|
||||||
|
sudo systemctl status mindnet-ui-prod
|
||||||
|
sudo systemctl status ollama
|
||||||
|
|
||||||
|
### 3.3 Logs & Monitoring
|
||||||
|
* **Backend Fehler:** `journalctl -u mindnet-prod -f`
|
||||||
|
* **Frontend Fehler:** `journalctl -u mindnet-ui-prod -f`
|
||||||
|
* **LLM Fehler:** `journalctl -u ollama -f`
|
||||||
|
* **Fachliche Logs:** `data/logs/search_history.jsonl`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Troubleshooting (Update v2.6)
|
||||||
|
|
||||||
|
### "Vector dimension error: expected dim: 768, got 384"
|
||||||
|
* **Ursache:** Du versuchst, in eine alte Qdrant-Collection (mit 384 Dim aus v2.2) neue Embeddings (mit 768 Dim von Nomic) zu schreiben.
|
||||||
|
* **Lösung:** Full Reset erforderlich.
|
||||||
|
1. `python -m scripts.reset_qdrant --mode wipe --prefix mindnet --yes` (Löscht DB).
|
||||||
|
2. `python -m scripts.import_markdown ...` (Baut neu auf).
|
||||||
|
|
||||||
|
### "500 Internal Server Error" beim Speichern/Chatten
|
||||||
|
* **Ursache:** Oft Timeout bei Ollama, wenn `nomic-embed-text` noch nicht im RAM geladen ist ("Cold Start") oder der Import die GPU blockiert.
|
||||||
|
* **Lösung:**
|
||||||
|
1. `MINDNET_LLM_TIMEOUT` in `.env` auf `300.0` setzen.
|
||||||
|
2. `MINDNET_LLM_BACKGROUND_LIMIT` auf `1` reduzieren (falls Hardware schwach).
|
||||||
|
|
||||||
|
### Import ist sehr langsam
|
||||||
|
* **Ursache:** Smart Edges sind aktiv (`types.yaml`) und analysieren jeden Chunk.
|
||||||
|
* **Lösung:**
|
||||||
|
* Akzeptieren (für bessere Qualität).
|
||||||
|
* Oder für Massen-Initial-Import in `types.yaml` temporär `enable_smart_edge_allocation: false` setzen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Backup & Restore
|
||||||
|
|
||||||
|
Datensicherheit ruht auf drei Säulen: Vault (Source), Qdrant (Index), JSONL-Logs (Lern-Daten).
|
||||||
|
|
||||||
|
### 5.1 Vault-Backup (Priorität 1)
|
||||||
|
Der Markdown-Vault ist die **Single Source of Truth**.
|
||||||
|
|
||||||
|
### 5.2 Qdrant-Snapshots (Priorität 2)
|
||||||
|
Für schnelle Wiederherstellung des Suchindex.
|
||||||
|
|
||||||
|
docker stop mindnet_qdrant
|
||||||
|
tar -czf qdrant_backup_$(date +%F).tar.gz ./qdrant_storage
|
||||||
|
docker start mindnet_qdrant
|
||||||
|
|
||||||
|
### 5.3 Notfall-Wiederherstellung (Rebuild)
|
||||||
|
Wenn die Datenbank korrupt ist oder Modelle gewechselt werden:
|
||||||
|
|
||||||
|
# 1. DB komplett leeren (Wipe)
|
||||||
|
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
||||||
|
# 2. Alles neu importieren (Force re-calculates Hashes)
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Governance & Sicherheit
|
||||||
|
|
||||||
|
### 6.1 Zugriffsschutz
|
||||||
|
Mindnet hat aktuell **keine integrierte Authentifizierung**.
|
||||||
|
* **Frontend:** Streamlit auf Port 8501 ist offen. Nutze Nginx Basic Auth oder VPN.
|
||||||
|
* **API:** Sollte nicht direkt im öffentlichen Netz stehen.
|
||||||
|
* **Qdrant:** Auf `127.0.0.1` beschränken.
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
# Mindnet v2.4 – Appendices & Referenzen
|
||||||
|
**Datei:** `docs/mindnet_appendices_v2.6.md`
|
||||||
|
**Stand:** 2025-12-12
|
||||||
|
**Status:** **FINAL** (Integrierter Stand WP01–WP15)
|
||||||
|
**Quellen:** `TYPE_REGISTRY_MANUAL.md`, `chunking_strategy.md`, `mindnet_technical_architecture.md`, `Handbuch.md`.
|
||||||
|
|
||||||
|
> Dieses Dokument bündelt Tabellen, Schemata und technische Referenzen, die in den Prozess-Dokumenten (Playbook, Guides) den Lesefluss stören würden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Anhang A: Typ-Registry Referenz (Default-Werte)
|
||||||
|
|
||||||
|
Diese Tabelle zeigt die Standard-Konfiguration der `types.yaml` (Stand v2.6 / Config v1.6).
|
||||||
|
|
||||||
|
| Typ (`type`) | Chunk Profile | Retriever Weight | Smart Edges? | Beschreibung |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **concept** | `sliding_smart_edges` | 0.60 | **Ja** | Abstrakte Begriffe, Theorien. |
|
||||||
|
| **project** | `sliding_smart_edges` | 0.97 | **Ja** | Aktive Vorhaben. Hohe Priorität. |
|
||||||
|
| **decision** | `structured_smart_edges` | 1.00 | **Ja** | Entscheidungen (ADRs). Höchste Prio. |
|
||||||
|
| **experience** | `sliding_smart_edges` | 0.90 | **Ja** | Persönliche Learnings. Intensiv analysiert. |
|
||||||
|
| **journal** | `sliding_standard` | 0.80 | Nein | Zeitgebundene Logs. Performance-optimiert. |
|
||||||
|
| **person** | `sliding_standard` | 0.50 | Nein | Personen-Profile. |
|
||||||
|
| **source** | `sliding_standard` | 0.50 | Nein | Externe Quellen (Bücher, PDFs). |
|
||||||
|
| **event** | `sliding_standard` | 0.60 | Nein | Meetings, Konferenzen. |
|
||||||
|
| **value** | `structured_smart_edges` | 1.00 | **Ja** | Persönliche Werte/Prinzipien. |
|
||||||
|
| **principle** | `structured_smart_edges` | 1.00 | **Ja** | Handlungsleitlinien. |
|
||||||
|
| **profile** | `structured_smart_edges` | 0.80 | **Ja** | Eigene Identitäts-Beschreibungen. |
|
||||||
|
| **goal** | `sliding_standard` | 0.95 | Nein | Strategische Ziele. |
|
||||||
|
| **belief** | `sliding_short` | 0.90 | Nein | Glaubenssätze. |
|
||||||
|
| **risk** | `sliding_short` | 0.90 | Nein | Risiken & Gefahren. |
|
||||||
|
| **task** | `sliding_short` | 0.70 | Nein | Aufgaben. |
|
||||||
|
| **glossary** | `sliding_short` | 0.50 | Nein | Begriffsdefinitionen. |
|
||||||
|
| **default** | `sliding_standard` | 1.00 | Nein | Fallback, wenn Typ unbekannt. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Anhang B: Edge-Typen & Semantik
|
||||||
|
|
||||||
|
Referenz aller implementierten Kantenarten (`kind`).
|
||||||
|
|
||||||
|
| Kind | Herkunft (Primär) | Symmetrisch? | Bedeutung & Nutzung |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `references` | Wikilink `[[...]]` | Nein | Standard-Verweis. "Erwähnt X". |
|
||||||
|
| `belongs_to` | Struktur (Auto) | Nein | Verknüpft Chunk mit seiner Note. |
|
||||||
|
| `next` / `prev` | Struktur (Auto) | Ja (Logisch) | Definiert Lesereihenfolge der Chunks. |
|
||||||
|
| `depends_on` | Inline / Default | Nein | Harte Abhängigkeit. "Braucht X um zu funktionieren". |
|
||||||
|
| `related_to` | Callout / Default | Ja (Oft) | Thematische Nähe. "Siehe auch X". |
|
||||||
|
| `similar_to` | Inline | Ja | Inhaltliche Ähnlichkeit. "Ist wie X". |
|
||||||
|
| `caused_by` | Inline | Nein | Kausalität. "X ist der Grund für Y". |
|
||||||
|
| `solves` | Inline | Nein | Lösung. "Tool X löst Problem Y". |
|
||||||
|
| `blocks` | Inline | Nein | **NEU:** Blockade. "Risiko X blockiert Projekt Y". |
|
||||||
|
| `derived_from` | Matrix / Default | Nein | Herkunft. "Erkenntnis stammt aus Prinzip X". |
|
||||||
|
| `based_on` | Matrix | Nein | Fundament. "Erfahrung basiert auf Wert Y". |
|
||||||
|
| `uses` | Matrix | Nein | Nutzung. "Projekt nutzt Konzept Z". |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Anhang C: Datenmodelle (JSON Payloads)
|
||||||
|
|
||||||
|
Diese sind die Felder, die effektiv in Qdrant gespeichert werden.
|
||||||
|
|
||||||
|
### C.1 Note Payload (`mindnet_notes`)
|
||||||
|
|
||||||
|
{
|
||||||
|
"note_id": "string (keyword)", // UUIDv5 oder Slug
|
||||||
|
"title": "string (text)", // Titel aus Frontmatter
|
||||||
|
"type": "string (keyword)", // Typ (z.B. 'project')
|
||||||
|
"retriever_weight": "float", // Numerische Wichtigkeit (0.0-1.0)
|
||||||
|
"chunk_profile": "string", // Genutztes Profil (z.B. 'sliding_smart_edges')
|
||||||
|
"edge_defaults": ["string"], // Liste der aktiven Default-Kanten
|
||||||
|
"tags": ["string"], // Liste von Tags
|
||||||
|
"created": "string (iso-date)", // Erstellungsdatum
|
||||||
|
"updated": "integer", // Timestamp
|
||||||
|
"fulltext": "string (no-index)" // Gesamter Text (für Recovery)
|
||||||
|
}
|
||||||
|
|
||||||
|
### C.2 Chunk Payload (`mindnet_chunks`)
|
||||||
|
|
||||||
|
{
|
||||||
|
"chunk_id": "string (keyword)", // Format: {note_id}#c{index}
|
||||||
|
"note_id": "string (keyword)", // FK zur Note
|
||||||
|
"type": "string (keyword)", // Typ-Kopie aus Note
|
||||||
|
"text": "string (text)", // Reintext für Anzeige (ohne Overlap)
|
||||||
|
"window": "string (text)", // Text + Overlap (für Embedding)
|
||||||
|
"ord": "integer", // Laufende Nummer (1..N)
|
||||||
|
"retriever_weight": "float", // Kopie aus Note (für Query-Speed)
|
||||||
|
"chunk_profile": "string", // Vererbt von Note
|
||||||
|
"neighbors_prev": ["string"], // ID des Vorgängers
|
||||||
|
"neighbors_next": ["string"] // ID des Nachfolgers
|
||||||
|
}
|
||||||
|
|
||||||
|
### C.3 Edge Payload (`mindnet_edges`)
|
||||||
|
|
||||||
|
{
|
||||||
|
"edge_id": "string (keyword)", // Deterministischer Hash
|
||||||
|
"source_id": "string (keyword)", // Chunk-ID (Start)
|
||||||
|
"target_id": "string (keyword)", // Chunk-ID oder Note-Titel (Ziel)
|
||||||
|
"kind": "string (keyword)", // z.B. 'depends_on'
|
||||||
|
"scope": "string (keyword)", // Immer 'chunk'
|
||||||
|
"rule_id": "string (keyword)", // Traceability: 'inline:rel', 'explicit:wikilink'
|
||||||
|
"confidence": "float", // 0.0 - 1.0
|
||||||
|
"note_id": "string (keyword)", // Owner Note ID
|
||||||
|
"provenance": "keyword" // 'explicit', 'rule', 'smart' (NEU)
|
||||||
|
}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Anhang D: Environment Variablen
|
||||||
|
|
||||||
|
Diese Variablen steuern das Verhalten der Skripte und Container.
|
||||||
|
|
||||||
|
| Variable | Default | Beschreibung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `QDRANT_URL` | `http://localhost:6333` | URL zur Vektor-DB. |
|
||||||
|
| `QDRANT_API_KEY` | *(leer)* | API-Key für Absicherung (optional). |
|
||||||
|
| `COLLECTION_PREFIX` | `mindnet` | Namensraum für Collections (`{prefix}_notes` etc). |
|
||||||
|
| `VECTOR_DIM` | `768` | **NEU:** Dimension für Embeddings (für Nomic). |
|
||||||
|
| `MINDNET_TYPES_FILE` | `config/types.yaml` | Pfad zur Typ-Registry. |
|
||||||
|
| `MINDNET_RETRIEVER_CONFIG`| `config/retriever.yaml`| Pfad zur Scoring-Konfiguration. |
|
||||||
|
| `MINDNET_PROMPTS_PATH` | `config/prompts.yaml` | Pfad zu LLM-Prompts (Neu in v2.2). |
|
||||||
|
| `MINDNET_DECISION_CONFIG` | `config/decision_engine.yaml` | Router & Interview Config (Neu in v2.3). |
|
||||||
|
| `MINDNET_LLM_MODEL` | `phi3:mini` | Name des Chat-Modells. |
|
||||||
|
| `MINDNET_EMBEDDING_MODEL` | `nomic-embed-text` | **NEU:** Name des Vektor-Modells. |
|
||||||
|
| `MINDNET_OLLAMA_URL` | `http://127.0.0.1:11434`| URL zum LLM-Server (Neu in v2.2). |
|
||||||
|
| `MINDNET_LLM_TIMEOUT` | `300.0` | Timeout für Ollama (Erhöht für CPU-Inference). |
|
||||||
|
| `MINDNET_API_TIMEOUT` | `300.0` | **NEU:** Frontend Timeout (Erhöht für Smart Edges). |
|
||||||
|
| `MINDNET_LLM_BACKGROUND_LIMIT`| `2` | **NEU:** Max. parallele Import-Tasks (Traffic Control). |
|
||||||
|
| `MINDNET_VAULT_ROOT` | `./vault` | **NEU:** Pfad für Write-Back Operationen. |
|
||||||
|
| `MINDNET_HASH_COMPARE` | `Body` | Vergleichsmodus für Import (`Body`, `Frontmatter`, `Full`). |
|
||||||
|
| `MINDNET_HASH_SOURCE` | `parsed` | Quelle für Hash (`parsed`, `raw`, `file`). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Anhang E: Glossar
|
||||||
|
|
||||||
|
* **Active Intelligence:** Feature, das während des Schreibens Links vorschlägt.
|
||||||
|
* **Async Ingestion:** Non-blocking Import-Prozess zur Vermeidung von Timeouts.
|
||||||
|
* **Decision Engine:** Komponente, die den Intent prüft und Strategien wählt (WP06).
|
||||||
|
* **Draft Editor:** Web-Komponente zur Bearbeitung generierter Notizen (WP10a).
|
||||||
|
* **Explanation Layer:** Komponente, die Scores und Graphen als Begründung liefert.
|
||||||
|
* **Healing Parser:** UI-Funktion, die defektes YAML von LLMs repariert (v2.5).
|
||||||
|
* **Hybrid Router:** Kombination aus Keyword-Matching und LLM-Klassifizierung für Intents.
|
||||||
|
* **Matrix Logic:** Regelwerk, das Kanten-Typen basierend auf Quell- und Ziel-Typ bestimmt.
|
||||||
|
* **Nomic:** Das neue, hochpräzise Embedding-Modell (768 Dim).
|
||||||
|
* **One-Shot Extractor:** LLM-Strategie zur sofortigen Generierung von Drafts ohne Rückfragen (WP07).
|
||||||
|
* **RAG (Retrieval Augmented Generation):** Kombination aus Suche und Text-Generierung.
|
||||||
|
* **Resurrection Pattern:** UI-Technik, um Eingaben bei Tab-Wechseln zu erhalten.
|
||||||
|
* **Smart Edge Allocation:** LLM-basierte Prüfung, ob ein Link zu einem Chunk passt (WP15).
|
||||||
|
* **Traffic Control:** Priorisierung von Chat-Anfragen ("Realtime") vor Import-Last ("Background") im LLM-Service (v2.6).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Anhang F: Workpackage Status (v2.6.0)
|
||||||
|
|
||||||
|
Aktueller Implementierungsstand der Module.
|
||||||
|
|
||||||
|
| WP | Titel | Status | Anmerkung |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **WP01** | Knowledge Design | 🟢 Live | Typen, Frontmatter definiert. |
|
||||||
|
| **WP02** | Chunking Strategy | 🟢 Live | Profilbasiertes Chunking aktiv. |
|
||||||
|
| **WP03** | Edge Logic / Import | 🟢 Live | Neue Importer-Pipeline mit Provenance. |
|
||||||
|
| **WP04a**| Retriever Scoring | 🟢 Live | Hybrider Score (Semantik + Graph). |
|
||||||
|
| **WP04b**| Explanation Layer | 🟢 Live | API liefert Reasons & Breakdown. |
|
||||||
|
| **WP04c**| Feedback Loop | 🟢 Live | Logging (JSONL) & Traceability aktiv. |
|
||||||
|
| **WP05** | Persönlichkeit / Chat | 🟢 Live | RAG-Integration mit Context Enrichment. |
|
||||||
|
| **WP06** | Decision Engine | 🟢 Live | Hybrid Router v5, Strategic Retrieval. |
|
||||||
|
| **WP07** | Interview Assistent | 🟢 Live | **One-Shot Extractor & Schemas aktiv.** |
|
||||||
|
| **WP08** | Self-Tuning | 🔴 Geplant | Auto-Adjustment der Gewichte. |
|
||||||
|
| **WP10** | Chat Interface | 🟢 Live | Web-Interface (Streamlit). |
|
||||||
|
| **WP10a**| Draft Editor | 🟢 Live | **Interaktives UI & Healing Parser.** |
|
||||||
|
| **WP11** | Backend Intelligence | 🟢 Live | **Async Ingestion, Nomic, Matrix.** |
|
||||||
|
| **WP15** | Smart Edge Allocation | 🟢 Live | **LLM-Filter & Traffic Control.** |
|
||||||
|
| **WP16** | Auto-Discovery | 🟡 Geplant | UX & Retrieval Tuning. |
|
||||||
|
| **WP17** | Conversational Memory | 🟡 Geplant | Dialog-Gedächtnis. |
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
# Mindnet v2.4 – Entwickler-Workflow
|
||||||
|
**Datei:** `docs/DEV_WORKFLOW.md`
|
||||||
|
**Stand:** 2025-12-12 (Aktualisiert: v2.6 mit Traffic Control)
|
||||||
|
|
||||||
|
Dieses Handbuch beschreibt den Entwicklungszyklus zwischen **Windows PC** (IDE), **Raspberry Pi** (Gitea) und **Beelink** (Runtime/Server).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Die Architektur
|
||||||
|
|
||||||
|
* **Windows 11 (VS Code):** Hier schreibst du Code. **Nie** direkt auf `main` arbeiten!
|
||||||
|
* **Raspberry Pi (Gitea):** Der Tresor. Speichert den Code und verwaltet Versionen.
|
||||||
|
* **Beelink (Runtime):** Hier läuft die Software. Wir nutzen **Systemd-Services**:
|
||||||
|
* **PROD:**
|
||||||
|
* API: `mindnet-prod` (Port 8001). Ordner: `~/mindnet`.
|
||||||
|
* UI: `mindnet-ui-prod` (Port 8501).
|
||||||
|
* **DEV:**
|
||||||
|
* API: `mindnet-dev` (Port 8002). Ordner: `~/mindnet_dev`.
|
||||||
|
* UI: `mindnet-ui-dev` (Port 8502).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Der Zyklus: Von der Idee zum Release
|
||||||
|
|
||||||
|
### Phase 1: Entwicklung (Windows / VS Code)
|
||||||
|
|
||||||
|
Hier erstellst du die neue Funktion in einer sicheren Umgebung.
|
||||||
|
|
||||||
|
1. **Basis aktualisieren (WICHTIG!):**
|
||||||
|
Bevor du startest, muss dein lokales `main` auf dem Stand des Servers sein.
|
||||||
|
* Klicke unten links auf den aktuellen Branch und wähle **`main`**.
|
||||||
|
* Klicke links im Menü "Source Control" auf die **drei Punkte (...)** -> **Pull** (oder das Synchronisieren-Symbol).
|
||||||
|
* *Erst jetzt hast du alle Dateien!*
|
||||||
|
|
||||||
|
2. **Branch erstellen:**
|
||||||
|
* Klicke wieder unten links auf `main`.
|
||||||
|
* Wähle `+ Create new branch...`.
|
||||||
|
* Gib den Namen ein: `feature/was-ich-tue` (z.B. `feature/wp15-traffic-control`).
|
||||||
|
* Drücke **Enter**.
|
||||||
|
|
||||||
|
3. **Sicherheits-Check:**
|
||||||
|
* Steht unten links jetzt dein Feature-Branch? **Nur dann darfst du Code ändern!**
|
||||||
|
|
||||||
|
4. **Coden:**
|
||||||
|
* Nimm deine Änderungen vor (z.B. neue Schemas in `types.yaml` oder Async-Logik in `ingestion.py`).
|
||||||
|
|
||||||
|
5. **Sichern & Hochladen:**
|
||||||
|
* **Source Control** Icon (Gabel-Symbol) -> Nachricht eingeben -> **Commit**.
|
||||||
|
* **Publish Branch** (oder "Sync Changes"), um den Branch zum Raspberry Pi (Gitea) zu senden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 2: Testen (Beelink / `mindnet_dev`)
|
||||||
|
|
||||||
|
Hier prüfst du, ob dein neuer Code auf dem echten Server läuft.
|
||||||
|
|
||||||
|
1. **Einloggen:**
|
||||||
|
`ssh user@<BEELINK-IP>`
|
||||||
|
|
||||||
|
2. **In die Werkstatt gehen:**
|
||||||
|
`cd /home/llmadmin/mindnet_dev`
|
||||||
|
|
||||||
|
3. **Code holen:**
|
||||||
|
```bash
|
||||||
|
git fetch
|
||||||
|
# Tipp: 'git branch -r' zeigt alle verfügbaren Branches an
|
||||||
|
git checkout feature/wp15-traffic-control
|
||||||
|
git pull
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Umgebung vorbereiten (WICHTIG für v2.6):**
|
||||||
|
Prüfe deine `.env` Datei. Sie benötigt jetzt Einträge für die Traffic Control.
|
||||||
|
```bash
|
||||||
|
nano .env
|
||||||
|
```
|
||||||
|
**Ergänze/Prüfe:**
|
||||||
|
```ini
|
||||||
|
# Traffic Control (Neu in v2.6)
|
||||||
|
MINDNET_LLM_BACKGROUND_LIMIT=2 # Max. parallele Import-Tasks
|
||||||
|
MINDNET_API_TIMEOUT=300.0 # Frontend wartet länger
|
||||||
|
MINDNET_EMBEDDING_MODEL="nomic-embed-text"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Dependencies aktualisieren:**
|
||||||
|
```bash
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip install -r requirements.txt
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
```
|
||||||
|
|
||||||
|
5. **Test-Server aktualisieren (WICHTIG):**
|
||||||
|
Der Code ist da, aber die Prozesse im RAM sind noch alt. Wir müssen die Services neustarten.
|
||||||
|
|
||||||
|
**Option A: Standard (Als Service laufen lassen)**
|
||||||
|
Ideal, wenn du nur testen willst, ob es läuft.
|
||||||
|
```bash
|
||||||
|
# 1. API neustarten (Backend)
|
||||||
|
sudo systemctl restart mindnet-dev
|
||||||
|
# 2. UI neustarten (Frontend)
|
||||||
|
sudo systemctl restart mindnet-ui-dev
|
||||||
|
|
||||||
|
# Logs prüfen (um Fehler zu sehen):
|
||||||
|
journalctl -u mindnet-dev -f
|
||||||
|
```
|
||||||
|
|
||||||
|
**Option B: Manuell Debuggen (Direct Output)**
|
||||||
|
Ideal, wenn du Print-Ausgaben direkt sehen willst oder der Service dauernd crasht.
|
||||||
|
```bash
|
||||||
|
# 1. Services stoppen (wichtig, sonst sind Ports 8002/8502 belegt!)
|
||||||
|
sudo systemctl stop mindnet-dev
|
||||||
|
sudo systemctl stop mindnet-ui-dev
|
||||||
|
|
||||||
|
# 2. Manuell starten (z.B. API)
|
||||||
|
uvicorn app.main:app --host 0.0.0.0 --port 8002 --env-file .env
|
||||||
|
```
|
||||||
|
|
||||||
|
6. **Validieren (Smoke Tests v2.6):**
|
||||||
|
|
||||||
|
* **Test A: Last-Test (Traffic Control):**
|
||||||
|
1. Starte einen Import im Terminal: `python3 -m scripts.import_markdown ...`
|
||||||
|
2. Öffne **gleichzeitig** `http://<IP>:8502` im Browser.
|
||||||
|
3. Stelle eine Chat-Frage ("Was ist Mindnet?").
|
||||||
|
4. **Erwartung:** Der Chat antwortet sofort (Realtime Lane), während der Import im Hintergrund weiterläuft (Background Lane).
|
||||||
|
|
||||||
|
* **Test B: API Check**
|
||||||
|
```bash
|
||||||
|
curl -X POST "http://localhost:8002/ingest/analyze" -d '{"text": "mindnet", "type": "journal"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 3: Release (Gitea / Raspberry Pi)
|
||||||
|
|
||||||
|
Wenn der Test auf Port 8002 / 8502 erfolgreich war:
|
||||||
|
|
||||||
|
1. Öffne Gitea im Browser.
|
||||||
|
2. Erstelle einen **Pull Request** (Dein Branch -> `main`).
|
||||||
|
3. **Merge** den Pull Request.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 4: Deployment (Beelink / `mindnet`)
|
||||||
|
|
||||||
|
Jetzt bringen wir die Änderung in das Live-System (Port 8001 / 8501).
|
||||||
|
|
||||||
|
1. **Deploy-Agent (Automatisch):**
|
||||||
|
Wenn dein `deploy.yml` aktiv ist, passiert das jetzt von selbst!
|
||||||
|
|
||||||
|
2. **Manuell (Falls nötig):**
|
||||||
|
```bash
|
||||||
|
cd /home/llmadmin/mindnet
|
||||||
|
git pull origin main
|
||||||
|
|
||||||
|
# Dependencies updaten & Modelle checken
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip install -r requirements.txt
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
|
||||||
|
# .env prüfen (Traffic Control)
|
||||||
|
# Ggf. MINDNET_LLM_BACKGROUND_LIMIT=2 hinzufügen
|
||||||
|
|
||||||
|
# Falls sich die Vektor-Dimension geändert hat (v2.4 Upgrade):
|
||||||
|
# python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
||||||
|
# python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
|
||||||
|
# Produktions-Services neustarten
|
||||||
|
sudo systemctl restart mindnet-prod
|
||||||
|
sudo systemctl restart mindnet-ui-prod
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 5: Aufräumen (Optional aber empfohlen)
|
||||||
|
|
||||||
|
Damit das Chaos nicht wächst, löschen wir den fertigen Branch.
|
||||||
|
|
||||||
|
1. **Gitea:** Im Pull Request auf "Delete Branch" klicken.
|
||||||
|
2. **Beelink (Dev):**
|
||||||
|
```bash
|
||||||
|
cd ~/mindnet_dev
|
||||||
|
git checkout main
|
||||||
|
git pull
|
||||||
|
git branch -d feature/wp15-traffic-control
|
||||||
|
```
|
||||||
|
3. **VS Code:**
|
||||||
|
* Auf `main` wechseln.
|
||||||
|
* Sync drücken.
|
||||||
|
* `F1` -> `Git: Delete Branch` -> Branch auswählen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Cheat Sheet: Die wichtigsten Befehle
|
||||||
|
|
||||||
|
| Wo? | Befehl | Was tut es? |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Beelink** | `sudo systemctl restart mindnet-dev` | **Neustart Dev-Backend (Port 8002).** |
|
||||||
|
| **Beelink** | `sudo systemctl restart mindnet-ui-dev` | **Neustart Dev-Frontend (Port 8002).** |
|
||||||
|
| **Beelink** | `journalctl -u mindnet-dev -f` | **Live-Logs Backend.** |
|
||||||
|
| **Beelink** | `python debug_analysis.py` | **Prüft Aliases & Scores.** |
|
||||||
|
| **Beelink** | `python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet_dev" --yes` | **Löscht & Repariert DB.** |
|
||||||
|
| **Beelink** | `python3 -m scripts.import_markdown --vault ./vault_master --prefix "mindnet_dev" --apply --force` | **Löscht & Repariert DB.** |
|
||||||
|
| **Beelink** | `source .venv/bin/activate` | **Aktivieren des virtual environments** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Troubleshooting
|
||||||
|
|
||||||
|
**"Read timed out" im Frontend**
|
||||||
|
* **Ursache:** Backend braucht für Smart Edges länger als 60s.
|
||||||
|
* **Lösung:** `MINDNET_API_TIMEOUT=300.0` in `.env` setzen und Services neustarten.
|
||||||
|
|
||||||
|
**Import ist extrem langsam**
|
||||||
|
* **Ursache:** Smart Edges analysieren jeden Chunk mit LLM.
|
||||||
|
* **Lösung:**
|
||||||
|
* Akzeptieren (Qualität vor Speed).
|
||||||
|
* Oder temporär in `config/types.yaml`: `enable_smart_edge_allocation: false`.
|
||||||
|
|
||||||
|
**"UnicodeDecodeError in .env"**
|
||||||
|
* **Ursache:** Umlaute oder Sonderzeichen in der `.env` Datei.
|
||||||
|
* **Lösung:** `.env` bereinigen (nur ASCII nutzen) und sicherstellen, dass sie UTF-8 ohne BOM ist.
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
# Mindnet v2.4 – Developer Guide
|
||||||
|
**Datei:** `docs/mindnet_developer_guide_v2.6.md`
|
||||||
|
**Stand:** 2025-12-12
|
||||||
|
**Status:** **FINAL** (Inkl. Async Core, Nomic, Traffic Control & Frontend State)
|
||||||
|
**Quellen:** `mindnet_technical_architecture.md`, `Handbuch.md`, `DEV_WORKFLOW.md`.
|
||||||
|
|
||||||
|
> **Zielgruppe:** Entwickler:innen.
|
||||||
|
> **Zweck:** Anleitung zum Aufsetzen der Entwicklungsumgebung, Verständnis der Modulstruktur und Durchführung von Tests.
|
||||||
|
|
||||||
|
---
|
||||||
|
- [Mindnet v2.4 – Developer Guide](#mindnet-v24--developer-guide)
|
||||||
|
- [1. Projektstruktur (Post-WP15)](#1-projektstruktur-post-wp15)
|
||||||
|
- [2. Lokales Setup (Development)](#2-lokales-setup-development)
|
||||||
|
- [2.1 Voraussetzungen](#21-voraussetzungen)
|
||||||
|
- [2.2 Installation](#22-installation)
|
||||||
|
- [2.3 Konfiguration (Environment)](#23-konfiguration-environment)
|
||||||
|
- [2.4 Dienste starten (API \& UI)](#24-dienste-starten-api--ui)
|
||||||
|
- [3. Core-Module \& Entwicklung](#3-core-module--entwicklung)
|
||||||
|
- [3.1 Der Importer (`scripts.import_markdown`)](#31-der-importer-scriptsimport_markdown)
|
||||||
|
- [3.2 Der Hybrid Router (`app.routers.chat`)](#32-der-hybrid-router-approuterschat)
|
||||||
|
- [3.3 Der Retriever (`app.core.retriever`)](#33-der-retriever-appcoreretriever)
|
||||||
|
- [3.4 Das Frontend (`app.frontend.ui`)](#34-das-frontend-appfrontendui)
|
||||||
|
- [3.5 Embedding Service (`app.services.embeddings_client`)](#35-embedding-service-appservicesembeddings_client)
|
||||||
|
- [3.6 Traffic Control (`app.services.llm_service`)](#36-traffic-control-appservicesllm_service)
|
||||||
|
- [4. Tests \& Debugging](#4-tests--debugging)
|
||||||
|
- [4.1 Unit Tests (Pytest)](#41-unit-tests-pytest)
|
||||||
|
- [4.2 Integration / Pipeline Tests](#42-integration--pipeline-tests)
|
||||||
|
- [4.3 Smoke Tests (E2E)](#43-smoke-tests-e2e)
|
||||||
|
- [5. Das "Teach-the-AI" Paradigma (Context Intelligence)](#5-das-teach-the-ai-paradigma-context-intelligence)
|
||||||
|
- [A. Workflow: Einen neuen Typ implementieren (z. B. `type: risk`)](#a-workflow-einen-neuen-typ-implementieren-z-b-type-risk)
|
||||||
|
- [B. Workflow: Neue Beziehungen (Edges) nutzen (z. B. `beeinflusst_von`)](#b-workflow-neue-beziehungen-edges-nutzen-z-b-beeinflusst_von)
|
||||||
|
- [C. Workflow: Interview-Schema anpassen (WP07)](#c-workflow-interview-schema-anpassen-wp07)
|
||||||
|
- [Fazit](#fazit)
|
||||||
|
- [6. Nützliche Einzeiler](#6-nützliche-einzeiler)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Projektstruktur (Post-WP15)
|
||||||
|
|
||||||
|
Der Code ist modular in `app` (Logik), `scripts` (CLI) und `config` (Steuerung) getrennt.
|
||||||
|
|
||||||
|
mindnet/
|
||||||
|
├── app/
|
||||||
|
│ ├── core/ # Kernlogik
|
||||||
|
│ │ ├── ingestion.py # NEU: Async Ingestion Service mit Change Detection
|
||||||
|
│ │ ├── chunker.py # Smart Chunker Orchestrator
|
||||||
|
│ │ ├── derive_edges.py # Edge-Erzeugung (WP03 Logik)
|
||||||
|
│ │ ├── retriever.py # Scoring & Hybrid Search
|
||||||
|
│ │ ├── qdrant.py # DB-Verbindung
|
||||||
|
│ │ └── ...
|
||||||
|
│ ├── models/ # Pydantic DTOs
|
||||||
|
│ │ └── dto.py # Zentrale DTO-Definition
|
||||||
|
│ ├── routers/ # FastAPI Endpoints
|
||||||
|
│ │ ├── query.py # Suche
|
||||||
|
│ │ ├── ingest.py # NEU: Save/Analyze (WP11)
|
||||||
|
│ │ ├── chat.py # Hybrid Router v5 & Interview Logic
|
||||||
|
│ │ ├── feedback.py # Feedback (WP04c)
|
||||||
|
│ │ └── ...
|
||||||
|
│ ├── services/ # Interne & Externe Dienste
|
||||||
|
│ │ ├── llm_service.py # Ollama Client mit Traffic Control
|
||||||
|
│ │ ├── semantic_analyzer.py# NEU: LLM-Filter für Edges (WP15)
|
||||||
|
│ │ ├── embeddings_client.py# Async Embeddings (HTTPX)
|
||||||
|
│ │ ├── feedback_service.py # Logging (JSONL Writer)
|
||||||
|
│ │ └── discovery.py # NEU: Intelligence Logic (WP11)
|
||||||
|
│ ├── frontend/ # NEU (WP10)
|
||||||
|
│ │ └── ui.py # Streamlit Application inkl. Healing Parser
|
||||||
|
│ └── main.py # Entrypoint der API
|
||||||
|
├── config/ # YAML-Konfigurationen (Single Source of Truth)
|
||||||
|
│ ├── types.yaml # Import-Regeln & Smart-Edge Config
|
||||||
|
│ ├── prompts.yaml # LLM Prompts & Interview Templates
|
||||||
|
│ ├── decision_engine.yaml # Router-Strategien (Actions only)
|
||||||
|
│ └── retriever.yaml # Scoring-Regeln & Kantengewichte
|
||||||
|
├── data/
|
||||||
|
│ └── logs/ # Lokale Logs (search_history.jsonl, feedback.jsonl)
|
||||||
|
├── scripts/ # CLI-Tools (Import, Diagnose, Reset)
|
||||||
|
├── tests/ # Pytest Suite & Smoke Scripts
|
||||||
|
└── vault/ # Dein lokaler Markdown-Content (Git-ignored)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Lokales Setup (Development)
|
||||||
|
|
||||||
|
### 2.1 Voraussetzungen
|
||||||
|
* **Python:** 3.10 oder höher.
|
||||||
|
* **Docker:** Für Qdrant.
|
||||||
|
* **Ollama:** Für lokale LLM-Inference (erforderlich für `/chat` und Embeddings).
|
||||||
|
* **Vault:** Ein Ordner mit Markdown-Dateien (z.B. `./mindnet_v2_test_vault` für Tests).
|
||||||
|
|
||||||
|
### 2.2 Installation
|
||||||
|
|
||||||
|
# 1. Repository klonen & Verzeichnis wechseln
|
||||||
|
git clone <repo> mindnet
|
||||||
|
cd mindnet
|
||||||
|
|
||||||
|
# 2. Virtual Environment erstellen
|
||||||
|
python3 -m venv .venv
|
||||||
|
source .venv/bin/activate
|
||||||
|
|
||||||
|
# 3. Abhängigkeiten installieren (inkl. Streamlit)
|
||||||
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# 4. Ollama Setup (Modelle laden)
|
||||||
|
# Chat-Modell (Phi-3)
|
||||||
|
ollama pull phi3:mini
|
||||||
|
# Embedding-Modell (Nomic) - PFLICHT für v2.4!
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
|
||||||
|
### 2.3 Konfiguration (Environment)
|
||||||
|
Erstelle eine `.env` Datei im Root-Verzeichnis.
|
||||||
|
|
||||||
|
# Qdrant Verbindung
|
||||||
|
QDRANT_URL="http://localhost:6333"
|
||||||
|
QDRANT_API_KEY="" # Leer lassen für lokal
|
||||||
|
|
||||||
|
# Mindnet Core Settings
|
||||||
|
COLLECTION_PREFIX="mindnet_dev"
|
||||||
|
VECTOR_DIM=768 # NEU: 768 für Nomic (vorher 384)
|
||||||
|
MINDNET_TYPES_FILE="./config/types.yaml"
|
||||||
|
MINDNET_RETRIEVER_CONFIG="./config/retriever.yaml"
|
||||||
|
MINDNET_VAULT_ROOT="./vault"
|
||||||
|
|
||||||
|
# LLM / RAG Settings (WP06/07)
|
||||||
|
MINDNET_LLM_MODEL="phi3:mini"
|
||||||
|
MINDNET_EMBEDDING_MODEL="nomic-embed-text" # NEU
|
||||||
|
MINDNET_OLLAMA_URL="http://127.0.0.1:11434"
|
||||||
|
MINDNET_LLM_TIMEOUT=300.0 # Timeout für CPU-Inference Cold-Starts
|
||||||
|
MINDNET_DECISION_CONFIG="./config/decision_engine.yaml"
|
||||||
|
MINDNET_LLM_BACKGROUND_LIMIT=2 # NEU: Limit für parallele Import-Tasks
|
||||||
|
|
||||||
|
# Frontend Settings (WP10)
|
||||||
|
MINDNET_API_URL="http://localhost:8002"
|
||||||
|
MINDNET_API_TIMEOUT=300.0 # Erhöht wegen Smart Edge Berechnung
|
||||||
|
|
||||||
|
# Import-Strategie
|
||||||
|
MINDNET_HASH_COMPARE="Body"
|
||||||
|
MINDNET_HASH_SOURCE="parsed"
|
||||||
|
|
||||||
|
### 2.4 Dienste starten (API & UI)
|
||||||
|
|
||||||
|
Wir entwickeln mit zwei Services. Du kannst sie manuell in zwei Terminals starten oder die Systemd-Services nutzen (siehe `admin_guide.md`).
|
||||||
|
|
||||||
|
**Terminal A: Backend (API)**
|
||||||
|
|
||||||
|
# Startet auf Port 8002 (Dev Standard)
|
||||||
|
uvicorn app.main:app --host 0.0.0.0 --port 8002 --env-file .env --reload
|
||||||
|
|
||||||
|
**Terminal B: Frontend (UI)**
|
||||||
|
|
||||||
|
# Startet auf Port 8502 (Dev Standard)
|
||||||
|
# --server.port 8502 verhindert Konflikte mit Prod (8501)
|
||||||
|
streamlit run app/frontend/ui.py --server.port 8502
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Core-Module & Entwicklung
|
||||||
|
|
||||||
|
### 3.1 Der Importer (`scripts.import_markdown`)
|
||||||
|
Dies ist das komplexeste Modul.
|
||||||
|
* **Einstieg:** `scripts/import_markdown.py` -> `main_async()`.
|
||||||
|
* **Smart Edges:** Nutzt `app.core.chunker` und `app.services.semantic_analyzer` zur Kanten-Filterung.
|
||||||
|
* **Idempotenz:** Der Importer muss mehrfach laufen können, ohne Duplikate zu erzeugen. Wir nutzen deterministische IDs (UUIDv5).
|
||||||
|
* **Robustheit:** In `ingestion.py` sind Mechanismen wie Change Detection und Robust File I/O (fsync) implementiert.
|
||||||
|
|
||||||
|
### 3.2 Der Hybrid Router (`app.routers.chat`)
|
||||||
|
Hier liegt die Logik für Intent Detection (WP06) und Interview-Modus (WP07).
|
||||||
|
* **Question Detection:** Prüft zuerst, ob der Input eine Frage ist. Falls ja -> RAG.
|
||||||
|
* **Keyword Match:** Prüft Keywords in `decision_engine.yaml` und `types.yaml`.
|
||||||
|
* **Priority:** Ruft `llm_service` mit `priority="realtime"` auf.
|
||||||
|
|
||||||
|
### 3.3 Der Retriever (`app.core.retriever`)
|
||||||
|
Hier passiert das Scoring.
|
||||||
|
* **Hybrid Search:** Der Chat-Endpoint erzwingt `mode="hybrid"`.
|
||||||
|
* **Strategic Retrieval:** In `chat.py` wird der Retriever *zweimal* aufgerufen, wenn ein Intent (z.B. `DECISION`) eine Injection (`value`) erfordert.
|
||||||
|
|
||||||
|
### 3.4 Das Frontend (`app.frontend.ui`)
|
||||||
|
Eine Streamlit-App (WP10).
|
||||||
|
* **Resurrection Pattern:** Das UI nutzt ein spezielles State-Management, um Eingaben bei Tab-Wechseln (Chat <-> Editor) zu erhalten. Widgets synchronisieren sich mit `st.session_state`.
|
||||||
|
* **Healing Parser:** Die Funktion `parse_markdown_draft` repariert defekte YAML-Frontmatter (fehlendes `---`) automatisch.
|
||||||
|
* **Logik:** Ruft `/chat`, `/feedback` und `/ingest/analyze` Endpoints der API auf.
|
||||||
|
|
||||||
|
### 3.5 Embedding Service (`app.services.embeddings_client`)
|
||||||
|
**Neu in v2.4:**
|
||||||
|
* Nutzt `httpx.AsyncClient` für non-blocking Calls an Ollama (Primary Mode).
|
||||||
|
* Besitzt einen **Fallback** auf `requests` (Synchron), falls Legacy-Skripte ihn nutzen.
|
||||||
|
* Unterstützt dediziertes Embedding-Modell (`nomic-embed-text`) getrennt vom Chat-Modell.
|
||||||
|
|
||||||
|
### 3.6 Traffic Control (`app.services.llm_service`)
|
||||||
|
**Neu in v2.6 (Version 2.8.0):**
|
||||||
|
* Stellt sicher, dass Batch-Prozesse (Import) den Live-Chat nicht ausbremsen.
|
||||||
|
* **Methode:** `generate_raw_response(..., priority="background")` aktiviert eine Semaphore.
|
||||||
|
* **Limit:** Konfigurierbar über `MINDNET_LLM_BACKGROUND_LIMIT` (Default: 2) in der `.env`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Tests & Debugging
|
||||||
|
|
||||||
|
Wir unterscheiden drei Test-Ebenen. Ein Pull Request sollte alle passieren.
|
||||||
|
|
||||||
|
### 4.1 Unit Tests (Pytest)
|
||||||
|
Für isolierte Logik (Parsing, Scoring).
|
||||||
|
|
||||||
|
pytest tests/test_retriever_basic.py
|
||||||
|
pytest tests/test_chunking.py
|
||||||
|
pytest tests/test_edges_all.py
|
||||||
|
|
||||||
|
### 4.2 Integration / Pipeline Tests
|
||||||
|
Prüfen den Datenfluss von Markdown bis Qdrant-JSON.
|
||||||
|
* **Payload Dryrun:** Prüft JSON-Schema Konformität.
|
||||||
|
|
||||||
|
python3 -m scripts.payload_dryrun --vault ./mindnet_v2_test_vault
|
||||||
|
|
||||||
|
* **Edge Checks:** Prüft Graph-Invarianten.
|
||||||
|
|
||||||
|
python3 -m scripts.edges_full_check
|
||||||
|
|
||||||
|
### 4.3 Smoke Tests (E2E)
|
||||||
|
Prüfen das laufende System gegen eine echte Qdrant-Instanz und Ollama.
|
||||||
|
|
||||||
|
# 1. API Test (Decision Engine)
|
||||||
|
python tests/test_wp06_decision.py -p 8002 -e DECISION -q "Soll ich X tun?"
|
||||||
|
|
||||||
|
# 2. UI Test (Manuell)
|
||||||
|
# Öffne http://localhost:8502
|
||||||
|
# Stelle eine Frage und prüfe Intent-Badge und Quellen-Anzeige.
|
||||||
|
|
||||||
|
# 3. Feedback Test
|
||||||
|
python tests/test_feedback_smoke.py --url http://localhost:8002/query
|
||||||
|
|
||||||
|
# 4. Intelligence Test (WP11)
|
||||||
|
python debug_analysis.py
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Das "Teach-the-AI" Paradigma (Context Intelligence)
|
||||||
|
|
||||||
|
Mindnet lernt nicht durch Training (Fine-Tuning), sondern durch **Konfiguration**, **Vernetzung** und **Prompting**. Dies ist der **Core-Workflow** für Erweiterungen.
|
||||||
|
|
||||||
|
### A. Workflow: Einen neuen Typ implementieren (z. B. `type: risk`)
|
||||||
|
|
||||||
|
**1. Daten-Ebene (`config/types.yaml`)**
|
||||||
|
Definiere die "Physik" des Typs (Import-Regeln und Basis-Wichtigkeit).
|
||||||
|
|
||||||
|
risk:
|
||||||
|
chunk_profile: sliding_short # Risiken sind oft kurze Statements
|
||||||
|
retriever_weight: 0.90 # Sehr wichtig
|
||||||
|
edge_defaults: ["blocks"] # Automatische Kante zu verlinkten Projekten
|
||||||
|
detection_keywords: ["gefahr", "risiko"]
|
||||||
|
|
||||||
|
**2. Strategie-Ebene (`config/decision_engine.yaml`)**
|
||||||
|
Damit dieser Typ aktiv geladen wird, musst du ihn einer Strategie zuordnen.
|
||||||
|
|
||||||
|
DECISION:
|
||||||
|
inject_types: ["value", "principle", "goal", "risk"] # <--- "risk" hinzugefügt
|
||||||
|
|
||||||
|
*Ergebnis:* Wenn der Intent `DECISION` erkannt wird, sucht das System nun auch aktiv nach Risiken.
|
||||||
|
|
||||||
|
**3. Kognitive Ebene (`config/prompts.yaml`)**
|
||||||
|
Erkläre dem LLM im Template, was es damit tun soll.
|
||||||
|
|
||||||
|
### B. Workflow: Neue Beziehungen (Edges) nutzen (z. B. `beeinflusst_von`)
|
||||||
|
|
||||||
|
Beziehungen sind der Klebstoff für die "Why"-Erklärungen.
|
||||||
|
|
||||||
|
**1. Erfassung im Vault (Markdown)**
|
||||||
|
Nutze die Inline-Syntax im Fließtext:
|
||||||
|
> "Die Entscheidung für Qdrant wurde [[rel:beeinflusst_von Budgetkürzung 2024]]."
|
||||||
|
|
||||||
|
**2. Gewichtung (`config/retriever.yaml`)**
|
||||||
|
Konfiguriere `edge_weights`, wenn Kausalität wichtiger ist als Ähnlichkeit.
|
||||||
|
|
||||||
|
### C. Workflow: Interview-Schema anpassen (WP07)
|
||||||
|
|
||||||
|
Wenn Mindnet neue Fragen stellen soll:
|
||||||
|
|
||||||
|
**1. Schema erweitern (`config/types.yaml`)**
|
||||||
|
Füge das Feld in die Liste ein (Neu: Schemas liegen jetzt hier).
|
||||||
|
|
||||||
|
project:
|
||||||
|
schema:
|
||||||
|
- "Titel"
|
||||||
|
- "Ziel"
|
||||||
|
- "Budget (Neu)"
|
||||||
|
|
||||||
|
**2. Keine Code-Änderung nötig**
|
||||||
|
Der `One-Shot Extractor` (Prompt Template) liest diese Liste dynamisch.
|
||||||
|
|
||||||
|
### Fazit
|
||||||
|
* **Vault:** Liefert das Wissen.
|
||||||
|
* **Config:** Liefert die Strategie (Router & Weights).
|
||||||
|
* **Prompt:** Liefert die Interpretation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Nützliche Einzeiler
|
||||||
|
|
||||||
|
**DB komplett zurücksetzen (Vorsicht!):**
|
||||||
|
|
||||||
|
# --yes überspringt die Bestätigung
|
||||||
|
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet_dev" --yes
|
||||||
|
|
||||||
|
**Einen einzelnen File inspizieren (Parser-Sicht):**
|
||||||
|
|
||||||
|
python3 tests/inspect_one_note.py --file ./vault/MeinFile.md
|
||||||
|
|
||||||
|
**Live-Logs sehen (Systemd):**
|
||||||
|
|
||||||
|
# Backend
|
||||||
|
journalctl -u mindnet-dev -f
|
||||||
|
# Frontend
|
||||||
|
journalctl -u mindnet-ui-dev -f
|
||||||
@@ -0,0 +1,494 @@
|
|||||||
|
# Mindnet v2.4 – Fachliche Architektur
|
||||||
|
**Datei:** `docs/mindnet_functional_architecture_v2.6.md`
|
||||||
|
**Stand:** 2025-12-12
|
||||||
|
**Status:** **FINAL** (Integrierter Stand WP01–WP15: Smart Edges & Traffic Control)
|
||||||
|
|
||||||
|
> Dieses Dokument beschreibt **was** Mindnet fachlich tut und **warum** – mit Fokus auf die Erzeugung und Nutzung von **Smart Edges** (Kanten), die Logik des Retrievers und den **RAG-Chat** (Decision Engine, Interview-Modus & Persönlichkeit).
|
||||||
|
|
||||||
|
---
|
||||||
|
<details>
|
||||||
|
<summary>📖 <b>Inhaltsverzeichnis (Klicken zum Öffnen)</b></summary>
|
||||||
|
|
||||||
|
- [Mindnet v2.4 – Fachliche Architektur](#mindnet-v24--fachliche-architektur)
|
||||||
|
- [](#)
|
||||||
|
- [0) Zielbild \& Grundprinzip](#0-zielbild--grundprinzip)
|
||||||
|
- [1) Notizen \& Chunks (fachliche Perspektive)](#1-notizen--chunks-fachliche-perspektive)
|
||||||
|
- [1.1 Notiz (Note)](#11-notiz-note)
|
||||||
|
- [1.2 Chunk](#12-chunk)
|
||||||
|
- [2) Edges – fachliche Typen \& Bedeutung](#2-edges--fachliche-typen--bedeutung)
|
||||||
|
- [2.1 Struktur-Kanten (Das Skelett)](#21-struktur-kanten-das-skelett)
|
||||||
|
- [2.2 Inhalts-Kanten (explizit)](#22-inhalts-kanten-explizit)
|
||||||
|
- [2.3 Typ-basierte Default-Kanten (Regelbasiert)](#23-typ-basierte-default-kanten-regelbasiert)
|
||||||
|
- [2.4 Smart Edge Allocation (LLM-gefiltert) – Neu in v2.6](#24-smart-edge-allocation-llm-gefiltert--neu-in-v26)
|
||||||
|
- [2.5 Matrix-Logik (Kontextsensitive Kanten)](#25-matrix-logik-kontextsensitive-kanten)
|
||||||
|
- [3) Edge-Payload – Felder \& Semantik](#3-edge-payload--felder--semantik)
|
||||||
|
- [4) Typ-Registry (`config/types.yaml`)](#4-typ-registry-configtypesyaml)
|
||||||
|
- [4.1 Zweck](#41-zweck)
|
||||||
|
- [4.2 Beispiel (auslieferungsnah)](#42-beispiel-auslieferungsnah)
|
||||||
|
- [5) Der Retriever (Funktionaler Layer)](#5-der-retriever-funktionaler-layer)
|
||||||
|
- [5.1 Scoring-Modell](#51-scoring-modell)
|
||||||
|
- [5.2 Erklärbarkeit (Explainability) – WP04b](#52-erklärbarkeit-explainability--wp04b)
|
||||||
|
- [5.3 Graph-Expansion](#53-graph-expansion)
|
||||||
|
- [6) Context Intelligence \& Intent Router (WP06–WP15)](#6-context-intelligence--intent-router-wp06wp15)
|
||||||
|
- [6.1 Das Problem: Statische vs. Dynamische Antworten](#61-das-problem-statische-vs-dynamische-antworten)
|
||||||
|
- [6.2 Der Hybrid Router v5 (Action vs. Question)](#62-der-hybrid-router-v5-action-vs-question)
|
||||||
|
- [6.3 Traffic Control (Realtime vs. Background)](#63-traffic-control-realtime-vs-background)
|
||||||
|
- [6.4 Strategic Retrieval (Injektion von Werten)](#64-strategic-retrieval-injektion-von-werten)
|
||||||
|
- [6.5 Reasoning (Das Gewissen)](#65-reasoning-das-gewissen)
|
||||||
|
- [6.6 Der Interview-Modus (One-Shot Extraction)](#66-der-interview-modus-one-shot-extraction)
|
||||||
|
- [6.7 Active Intelligence (Link Suggestions)](#67-active-intelligence-link-suggestions)
|
||||||
|
- [7) Future Concepts: The Empathic Digital Twin (Ausblick)](#7-future-concepts-the-empathic-digital-twin-ausblick)
|
||||||
|
- [7.1 Antizipation durch Erfahrung](#71-antizipation-durch-erfahrung)
|
||||||
|
- [7.2 Empathie \& "Ich"-Modus](#72-empathie--ich-modus)
|
||||||
|
- [7.3 Glaubenssätze \& Rituale](#73-glaubenssätze--rituale)
|
||||||
|
- [8) Erweiterbarkeit \& Teaching (Context Intelligence)](#8-erweiterbarkeit--teaching-context-intelligence)
|
||||||
|
- [A. Workflow: Einen neuen Typ implementieren (z. B. `type: risk`)](#a-workflow-einen-neuen-typ-implementieren-z-b-type-risk)
|
||||||
|
- [B. Workflow: Neue Beziehungen nutzen (z. B. `beeinflusst_von`)](#b-workflow-neue-beziehungen-nutzen-z-b-beeinflusst_von)
|
||||||
|
- [9) Feedback \& Lernen – WP04c/WP10](#9-feedback--lernen--wp04cwp10)
|
||||||
|
- [9.1 Der Feedback-Loop](#91-der-feedback-loop)
|
||||||
|
- [10) Confidence \& Provenance – wozu?](#10-confidence--provenance--wozu)
|
||||||
|
- [11) Semantik ausgewählter `kind`-Werte](#11-semantik-ausgewählter-kind-werte)
|
||||||
|
- [12) Frontmatter-Eigenschaften – Rolle \& Empfehlung](#12-frontmatter-eigenschaften--rolle--empfehlung)
|
||||||
|
- [13) Lösch-/Update-Garantien (Idempotenz)](#13-lösch-update-garantien-idempotenz)
|
||||||
|
- [14) Beispiel – Von Markdown zu Kanten](#14-beispiel--von-markdown-zu-kanten)
|
||||||
|
- [15) Referenzen (Projektdateien \& Leitlinien)](#15-referenzen-projektdateien--leitlinien)
|
||||||
|
- [16) Workpackage Status (v2.6.0)](#16-workpackage-status-v260)
|
||||||
|
|
||||||
|
</details>
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0) Zielbild & Grundprinzip
|
||||||
|
|
||||||
|
Mindnet wandelt Obsidian-Markdown-Notizen in einen **dynamischen Graphen aus Punkten und Kanten** um.
|
||||||
|
Die drei zentralen Artefakt-Sammlungen lauten:
|
||||||
|
|
||||||
|
- `mindnet_notes` – genau **eine** Note pro Markdown-Datei (Metadaten & Hashes)
|
||||||
|
- `mindnet_chunks` – semantische Teilstücke einer Note (Fenster/„Chunks“)
|
||||||
|
- `mindnet_edges` – gerichtete Beziehungen zwischen Knoten (Chunks/Notes)
|
||||||
|
|
||||||
|
Die Import-Pipeline (seit v2.6 mit **Traffic Control** und **Smart Edges**) erzeugt diese Artefakte **deterministisch** und **idempotent** (erneute Läufe überschreiben konsistent statt zu duplizieren). Die Import-Schritte sind: *parse → chunk → embed → smart-edge-allocation → upsert*.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1) Notizen & Chunks (fachliche Perspektive)
|
||||||
|
|
||||||
|
### 1.1 Notiz (Note)
|
||||||
|
- Repräsentiert eine fachliche Einheit (z. B. *„Vector DB Basics“*, *„KI-Projekt“*).
|
||||||
|
- Trägt Eigenschaften (Titel, Typ, Zeitstempel, optionale Policies).
|
||||||
|
- **Typ** (*type*) steuert u. a. Chunk-Profil und Default-Relationen (siehe §4).
|
||||||
|
- **retriever_weight** und **chunk_profile** werden systematisch an Note **und** Chunks gespiegelt, damit der Retriever beides nutzen kann.
|
||||||
|
|
||||||
|
### 1.2 Chunk
|
||||||
|
- Ausschnitt/Textfenster aus der Note, als eigenständiger Such-Anker.
|
||||||
|
- Jeder Chunk gehört **genau einer** Note.
|
||||||
|
- Chunks bilden eine Sequenz (1…N) – das ermöglicht *next/prev*.
|
||||||
|
- **Update v2.4:** Chunks werden jetzt durch das Modell `nomic-embed-text` in **768-dimensionale Vektoren** umgewandelt. Dies erlaubt eine deutlich höhere semantische Auflösung als frühere Modelle (384 Dim).
|
||||||
|
- **Update v2.6 (Smart Chunking):** Ein Chunk ist nicht mehr nur ein dummer Textblock, der alle Links der Mutter-Notiz erbt. Durch die **Smart Edge Allocation (WP15)** "weiß" jeder Chunk genau, welche Kanten inhaltlich zu ihm gehören (siehe 2.4).
|
||||||
|
|
||||||
|
> **Wichtig:** Chunking-Profile (short/medium/long/sliding_smart_edges) kommen aus `types.yaml` (per Note-Typ), können aber lokal überschrieben werden. Die effektiven Werte werden bei der Payload-Erzeugung bestimmt.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2) Edges – fachliche Typen & Bedeutung
|
||||||
|
|
||||||
|
Edges kodieren Beziehungen. Sie sind **gerichtet** und werden in `mindnet_edges` gespeichert. Die Erzeugung folgt einer strengen Priorität: **Inline > Callout > Defaults > Struktur**.
|
||||||
|
|
||||||
|
### 2.1 Struktur-Kanten (Das Skelett)
|
||||||
|
- **belongs_to**: *Chunk → Note* (Zuordnung)
|
||||||
|
- **next / prev**: Kettenbeziehungen zwischen aufeinanderfolgenden Chunks derselben Note.
|
||||||
|
→ ermöglichen „lineares Weiterlesen“ oder Kontextpfade in Antworten.
|
||||||
|
Diese Kanten entstehen immer, unabhängig von Inhalten.
|
||||||
|
|
||||||
|
### 2.2 Inhalts-Kanten (explizit)
|
||||||
|
Hier unterscheidet v2.6 präzise zwischen verschiedenen Quellen der Evidenz:
|
||||||
|
|
||||||
|
1. **Explizite Inline-Relationen (Höchste Priorität):**
|
||||||
|
Im Fließtext notierte, semantisch qualifizierte Relationen.
|
||||||
|
* Syntax: `[[rel:depends_on Embeddings 101]]`
|
||||||
|
* Fachliche Aussage: "Hängt ab von", "Ähnlich zu".
|
||||||
|
* *rule_id*: `inline:rel`
|
||||||
|
* *confidence*: ~0.95
|
||||||
|
|
||||||
|
2. **Callout-Edges (Kuratierte Listen):**
|
||||||
|
Redaktionell gepflegte Listen am Ende einer Notiz (z.B. "Siehe auch").
|
||||||
|
* Syntax: `> [!edge] related_to: [[Vector DB Basics]]`
|
||||||
|
* *rule_id*: `callout:edge`
|
||||||
|
* *confidence*: ~0.90
|
||||||
|
|
||||||
|
3. **Wikilinks (Standard-Referenzen):**
|
||||||
|
Der klassische Obsidian-Link.
|
||||||
|
* Syntax: `[[Vector DB Basics]]`
|
||||||
|
* Typ: `references`
|
||||||
|
* *rule_id*: `explicit:wikilink`
|
||||||
|
* *confidence*: 1.0
|
||||||
|
|
||||||
|
> Alle expliziten Quellen (Wikilink, Inline-Rel, Callout) sind **Primärbelege**.
|
||||||
|
|
||||||
|
### 2.3 Typ-basierte Default-Kanten (Regelbasiert)
|
||||||
|
Jede Note hat einen *Typ* (z. B. `concept`, `project`, `profile`). In `config/types.yaml` definieren wir pro Typ **edge_defaults**, z. B.:
|
||||||
|
|
||||||
|
- `concept`: `["references","related_to"]`
|
||||||
|
- `project`: `["references","depends_on"]`
|
||||||
|
|
||||||
|
Regel: **Für jede gefundene explizite Referenz** (s. o.) werden **zusätzliche** Edges nach diesen Defaults erzeugt.
|
||||||
|
Beispiel: Ein *project* mit `edge_defaults=["depends_on"]` erzeugt zu *jedem* explizit referenzierten Ziel **zusätzlich** eine `depends_on`-Kante.
|
||||||
|
Diese Kanten tragen *provenance=rule* und eine **rule_id** der Form `edge_defaults:{note_type}:{relation}` sowie eine geringere Confidence (~0.7).
|
||||||
|
|
||||||
|
### 2.4 Smart Edge Allocation (LLM-gefiltert) – Neu in v2.6
|
||||||
|
Mit **WP15** wurde ein intelligenter Filter eingeführt, um das Problem des "Broadcasting" zu lösen. Früher erbte jeder Chunk einer Notiz *alle* Links der Notiz, was zu unpräzisem Retrieval führte.
|
||||||
|
|
||||||
|
**Der neue Prozess:**
|
||||||
|
1. **Scan:** Das System sammelt alle expliziten Links der gesamten Notiz.
|
||||||
|
2. **Chunking:** Der Text wird in Abschnitte zerlegt.
|
||||||
|
3. **Analyse (LLM):** Ein lokales LLM (Semantic Analyzer) liest jeden Chunk einzeln.
|
||||||
|
4. **Entscheidung:** Das LLM entscheidet für jeden Link aus Schritt 1: *"Ist dieser Link im Kontext dieses spezifischen Textabschnitts relevant?"*
|
||||||
|
5. **Zuweisung:** Nur wenn das LLM zustimmt, wird die Kante am Chunk erstellt.
|
||||||
|
|
||||||
|
*Steuerung:* Dies ist pro Typ in der `types.yaml` konfigurierbar (`enable_smart_edge_allocation: true`).
|
||||||
|
|
||||||
|
### 2.5 Matrix-Logik (Kontextsensitive Kanten)
|
||||||
|
Mit WP-11 wurde eine Intelligenz eingeführt, die Kanten-Typen nicht nur anhand des Quell-Typs, sondern auch anhand des Ziel-Typs bestimmt ("Matrix").
|
||||||
|
|
||||||
|
**Beispiel für `Source Type: experience`:**
|
||||||
|
* Wenn Ziel ist `value` -> Kante: `based_on`
|
||||||
|
* Wenn Ziel ist `principle` -> Kante: `derived_from`
|
||||||
|
* Wenn Ziel ist `project` -> Kante: `related_to`
|
||||||
|
|
||||||
|
Dies ermöglicht im Graphen präzise Abfragen wie "Zeige alle Erfahrungen, die auf Wert X basieren" (via `based_on`), was mit generischen `related_to` Kanten nicht möglich wäre.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3) Edge-Payload – Felder & Semantik
|
||||||
|
|
||||||
|
Jede Kante hat mindestens:
|
||||||
|
|
||||||
|
- `kind` – Beziehungsart *(belongs_to, next, prev, references, related_to, depends_on, similar_to, based_on, uses, …)*
|
||||||
|
- `scope` – `"chunk"` (Standard in v2.2)
|
||||||
|
- `source_id`, `target_id` – Quell-/Ziel-Knoten (Chunk-IDs oder Note-Titel bei unresolved Targets)
|
||||||
|
- `note_id` – **Owner-Note** (die Note, aus der die Kante stammt)
|
||||||
|
|
||||||
|
Erweiterte/abgeleitete Felder (WP03 Superset):
|
||||||
|
|
||||||
|
- `provenance` – `"explicit"` (Wikilink/Inline/Callout), `"rule"` (Typ-Defaults) oder neu `"smart"` (vom LLM validiert).
|
||||||
|
- `rule_id` – maschinenlesbare Regelquelle (z.B. `inline:rel`, `edge_defaults:project:depends_on`)
|
||||||
|
- `confidence` – 0.0–1.0; Heuristik zur Gewichtung im Scoring.
|
||||||
|
|
||||||
|
**Dedup-Schlüssel** (fachlich): Gleichlautende `(source_id, target_id, kind, scope, rule_id)` werden nicht mehrfach geschrieben.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4) Typ-Registry (`config/types.yaml`)
|
||||||
|
|
||||||
|
### 4.1 Zweck
|
||||||
|
- Steuert **Chunking-Profile** (`short|medium|long`) **pro Typ**
|
||||||
|
- Liefert **retriever_weight** (Note-/Chunk-Gewichtung im Ranking) **pro Typ**
|
||||||
|
- Definiert **edge_defaults** je Typ (s. o.)
|
||||||
|
- **Neu in v2.6:** Steuert `enable_smart_edge_allocation` (LLM-Filter) und `detection_keywords` für den Hybrid Router.
|
||||||
|
|
||||||
|
Der Importer lädt die Registry aus `MINDNET_TYPES_FILE` oder nutzt Fallbacks. **Frontmatter-Overrides** für Profile werden in v2.2 weitgehend ignoriert zugunsten einer zentralen Governance in der YAML-Datei.
|
||||||
|
|
||||||
|
### 4.2 Beispiel (auslieferungsnah)
|
||||||
|
version: 2.6.0
|
||||||
|
types:
|
||||||
|
concept:
|
||||||
|
chunk_profile: medium
|
||||||
|
edge_defaults: ["references", "related_to"]
|
||||||
|
retriever_weight: 0.60
|
||||||
|
experience:
|
||||||
|
chunk_profile: sliding_smart_edges
|
||||||
|
enable_smart_edge_allocation: true # WP15: LLM prüft Kanten
|
||||||
|
detection_keywords: ["passiert", "erlebt", "situation"] # WP06: Router-Trigger
|
||||||
|
schema: # WP07: Interview-Struktur
|
||||||
|
- "Situation (Was ist passiert?)"
|
||||||
|
- "Meine Reaktion (Was habe ich getan?)"
|
||||||
|
|
||||||
|
**Auflösung im Importer**
|
||||||
|
- `effective_chunk_profile(note_type, registry)` → `"short|medium|long"|None`
|
||||||
|
- `effective_retriever_weight(note_type, registry)` → `float|None`
|
||||||
|
- Ergebnis wird in `note_payload` **und** `chunk_payloads` gespiegelt.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5) Der Retriever (Funktionaler Layer)
|
||||||
|
|
||||||
|
Der Retriever ist in v2.2 der zentrale Zugangspunkt. Er realisiert die **Hybride Suche**.
|
||||||
|
|
||||||
|
### 5.1 Scoring-Modell
|
||||||
|
Die Relevanz eines Treffers ergibt sich nicht mehr nur aus Textähnlichkeit, sondern aus einer gewichteten Formel:
|
||||||
|
|
||||||
|
total_score =
|
||||||
|
semantic_weight * semantic_score
|
||||||
|
+ edge_weight * edge_bonus
|
||||||
|
+ centrality_weight * centrality_bonus
|
||||||
|
+ type_weight * retriever_weight
|
||||||
|
|
||||||
|
* **semantic_score:** Vektorähnlichkeit (Qdrant).
|
||||||
|
* **retriever_weight:** Wichtigkeit des Typs (z.B. Projekte > Quellen).
|
||||||
|
* **edge_bonus:** Belohnung für Chunks, die im Kontext der Anfrage stark vernetzt sind (Summe der Confidence eingehender relevanter Kanten).
|
||||||
|
* **centrality_bonus:** Belohnung für Knoten, die zentrale Hubs im lokalen Graphen darstellen.
|
||||||
|
|
||||||
|
### 5.2 Erklärbarkeit (Explainability) – WP04b
|
||||||
|
Der Retriever ist keine Blackbox mehr. Er liefert auf Wunsch (`explain=True`) eine strukturierte Begründung (`Explanation`-Objekt).
|
||||||
|
|
||||||
|
**Die "Warum"-Logik:**
|
||||||
|
1. **Semantik:** Prüfung der Cosine-Similarity ("Sehr hohe textuelle Übereinstimmung").
|
||||||
|
2. **Typ:** Prüfung des `retriever_weight` ("Bevorzugt, da Entscheidung").
|
||||||
|
3. **Graph (Kontext):**
|
||||||
|
* **Hub (Outgoing):** Worauf verweist dieser Treffer? ("Verweist auf Qdrant").
|
||||||
|
* **Authority (Incoming):** Wer verweist auf diesen Treffer? ("Wird referenziert von Projekt Alpha").
|
||||||
|
|
||||||
|
Die API gibt diese Analysen als menschenlesbare Sätze (`reasons`) und als Datenstruktur (`score_breakdown`) zurück.
|
||||||
|
|
||||||
|
### 5.3 Graph-Expansion
|
||||||
|
Der Hybrid-Modus lädt dynamisch die Nachbarschaft der Top-K Vektor-Treffer ("Seeds") über `graph_adapter.expand`. Dies baut einen temporären `NetworkX`-artigen Graphen im Speicher (Klasse `Subgraph`), auf dem Boni berechnet werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6) Context Intelligence & Intent Router (WP06–WP15)
|
||||||
|
|
||||||
|
Seit WP06 agiert Mindnet nicht mehr statisch, sondern passt seine Suchstrategie dem **Intent** (der Absicht) des Nutzers an. Dies ist die Transformation vom reinen Wissens-Abrufer zum strategischen Partner.
|
||||||
|
|
||||||
|
### 6.1 Das Problem: Statische vs. Dynamische Antworten
|
||||||
|
* **Früher (Pre-WP06):** Jede Frage ("Was ist X?" oder "Soll ich X?") wurde gleich behandelt -> Fakten-Retrieval.
|
||||||
|
* **Heute (WP06):** Das System erkennt, *was* der User will (Rat, Fakten oder Datenerfassung) und wechselt den Modus.
|
||||||
|
|
||||||
|
### 6.2 Der Hybrid Router v5 (Action vs. Question)
|
||||||
|
Der Router wurde in v2.6 (WP15) weiterentwickelt, um Fehlalarme zu vermeiden.
|
||||||
|
|
||||||
|
1. **Frage-Erkennung:**
|
||||||
|
* Das System prüft zuerst: Enthält der Satz ein `?` oder typische W-Wörter (Wer, Wie, Was)?
|
||||||
|
* Wenn **JA** -> Gehe in den **RAG Modus** (Intent `FACT` oder `DECISION`). Interviews werden hier blockiert.
|
||||||
|
|
||||||
|
2. **Befehls-Erkennung (Fast Path):**
|
||||||
|
* Wenn **NEIN** (keine Frage), prüft das System auf Keywords in `types.yaml` ("Projekt", "Erfahrung").
|
||||||
|
* Treffer -> **INTERVIEW Modus** (Erfassen). Das Schema wird aus `types.yaml` geladen.
|
||||||
|
|
||||||
|
3. **LLM Fallback (Slow Path):**
|
||||||
|
* Wenn beides fehlschlägt, entscheidet das LLM über den Intent.
|
||||||
|
|
||||||
|
### 6.3 Traffic Control (Realtime vs. Background)
|
||||||
|
Um den Live-Betrieb (Chat) nicht durch den ressourcenintensiven Smart-Import (LLM-Analyse) zu gefährden, implementiert v2.6 ein **Traffic Control System** im `LLMService`.
|
||||||
|
|
||||||
|
* **Realtime Lane (Chat):** Anfragen aus dem Chat erhalten `priority="realtime"`. Sie umgehen alle Warteschlangen und werden sofort bearbeitet.
|
||||||
|
* **Background Lane (Import):** Anfragen zur Kantenanalyse erhalten `priority="background"`. Sie werden durch eine **Semaphore** gedrosselt (Standard: max 2 parallel), um die Hardware nicht zu überlasten.
|
||||||
|
|
||||||
|
### 6.4 Strategic Retrieval (Injektion von Werten)
|
||||||
|
Im Modus `DECISION` führt das System eine **zweite Suchstufe** aus. Es sucht nicht nur nach semantisch passenden Texten zur Frage, sondern erzwingt das Laden von strategischen Notizen wie:
|
||||||
|
* **Values (`type: value`):** Moralische Werte (z.B. "Privacy First").
|
||||||
|
* **Principles (`type: principle`):** Handlungsanweisungen.
|
||||||
|
* **Goals (`type: goal`):** Strategische Ziele.
|
||||||
|
|
||||||
|
### 6.5 Reasoning (Das Gewissen)
|
||||||
|
Das LLM erhält im Prompt die explizite Anweisung: *"Wäge die Fakten (aus der Suche) gegen die injizierten Werte ab."*
|
||||||
|
Dadurch entstehen Antworten, die nicht nur technisch korrekt sind, sondern subjektiv passend ("Tool X passt nicht zu deinem Ziel Z").
|
||||||
|
|
||||||
|
### 6.6 Der Interview-Modus (One-Shot Extraction)
|
||||||
|
Wenn der User Wissen erfassen will ("Ich möchte ein neues Projekt anlegen"), wechselt Mindnet in den **Interview-Modus**.
|
||||||
|
|
||||||
|
* **Late Binding Schema:** Das System lädt ein konfiguriertes Schema für den Ziel-Typ (z.B. `project`: Pflichtfelder sind Titel, Ziel, Status).
|
||||||
|
* **One-Shot Extraction:** Statt eines langen Dialogs extrahiert das LLM **sofort** alle verfügbaren Infos aus dem Prompt und generiert einen validen Markdown-Draft mit Frontmatter.
|
||||||
|
* **Healing Parser (v2.5):** Falls das LLM die YAML-Syntax beschädigt (z.B. fehlendes Ende), repariert das Frontend den Entwurf automatisch.
|
||||||
|
* **UI-Integration:** Das Frontend rendert statt einer Chat-Antwort einen **interaktiven Editor** (WP10), in dem der Entwurf finalisiert werden kann.
|
||||||
|
|
||||||
|
### 6.7 Active Intelligence (Link Suggestions)
|
||||||
|
Im **Draft Editor** (Frontend) unterstützt das System den Autor aktiv.
|
||||||
|
* **Analyse:** Ein "Sliding Window" scannt den Text im Hintergrund (auch lange Entwürfe).
|
||||||
|
* **Erkennung:** Es findet Begriffe ("Mindnet") und semantische Konzepte ("Autofahrt in Italien").
|
||||||
|
* **Matching:** Es prüft gegen den Index (Aliases und Vektoren).
|
||||||
|
* **Vorschlag:** Es bietet fertige Markdown-Links an (z.B. `[[rel:related_to ...]]`), die per Klick eingefügt werden.
|
||||||
|
* **Logik:** Dabei kommt die in 2.5 beschriebene **Matrix-Logik** zum Einsatz, um den korrekten Kanten-Typ vorzuschlagen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7) Future Concepts: The Empathic Digital Twin (Ausblick)
|
||||||
|
|
||||||
|
Um Mindnet von einer Entscheidungsmaschine zu einem echten **Spiegel der Persönlichkeit** zu entwickeln, sind folgende Erweiterungen konzeptionell vorgesehen:
|
||||||
|
|
||||||
|
### 7.1 Antizipation durch Erfahrung
|
||||||
|
* **Konzept:** Das System soll Konsequenzen vorhersagen ("Was passiert, wenn...?").
|
||||||
|
* **Umsetzung:** Neben Werten werden vergangene Erfahrungen (`type: experience`) geladen.
|
||||||
|
* **Logik:** *"In einer ähnlichen Situation (Projekt A) hat Entscheidung X zu Ergebnis Y geführt."*
|
||||||
|
|
||||||
|
### 7.2 Empathie & "Ich"-Modus
|
||||||
|
* **Konzept:** Das System antwortet nicht wie ein Roboter, sondern im Tonfall und Stil des Nutzers.
|
||||||
|
* **Umsetzung (Few-Shot Prompting):** Der System-Prompt wird dynamisch mit Beispielen gefüttert, wie der Nutzer typischerweise auf E-Mails oder Fragen antwortet.
|
||||||
|
* **Datenbasis:** `type: profile` oder `type: manifesto` definieren das Selbstbild.
|
||||||
|
|
||||||
|
### 7.3 Glaubenssätze & Rituale
|
||||||
|
* **Konzept:** Berücksichtigung weicher Faktoren und Gewohnheiten.
|
||||||
|
* **Umsetzung:** Erweiterung der `decision_engine.yaml` um `inject_types: ["belief", "ritual"]`.
|
||||||
|
* **Szenario:** Bei Terminplanungen werden Rituale ("Keine Meetings vor 10 Uhr") automatisch als harte Restriktion gegen Anfragen geprüft.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8) Erweiterbarkeit & Teaching (Context Intelligence)
|
||||||
|
|
||||||
|
Mindnet lernt nicht durch klassisches Training (Fine-Tuning), sondern durch **Konfiguration**, **Vernetzung** und **Prompting**. Dies ist das **"Teach-the-AI" Paradigma**: Wenn du dem System ein neues Konzept beibringen willst, musst du an drei Stellen eingreifen.
|
||||||
|
|
||||||
|
### A. Workflow: Einen neuen Typ implementieren (z. B. `type: risk`)
|
||||||
|
|
||||||
|
1. **Physik definieren (`config/types.yaml`)**
|
||||||
|
Steuere, wie schwer der Inhalt wiegt und wie er vernetzt wird.
|
||||||
|
```yaml
|
||||||
|
risk:
|
||||||
|
chunk_profile: short # Risiken sind oft kurze Statements
|
||||||
|
retriever_weight: 0.90 # Hohe Priorität im Ranking
|
||||||
|
edge_defaults: ["blocks"] # Automatische Kante zu verlinkten Projekten
|
||||||
|
detection_keywords: ["gefahr", "risiko"] # Für den Hybrid Router
|
||||||
|
```
|
||||||
|
*Effekt:* Der Router erkennt das Wort "Risiko" und bietet ein Interview an. Der Retriever spült diese Notizen bei relevanten Anfragen nach oben.
|
||||||
|
|
||||||
|
2. **Semantik erklären (`config/prompts.yaml` / `decision_engine.yaml`)**
|
||||||
|
Bringe dem LLM bei, wie es mit diesem Typ umgehen soll. Füge `risk` zur `DECISION`-Strategie hinzu (`inject_types`), damit es bei Entscheidungen geladen wird.
|
||||||
|
|
||||||
|
### B. Workflow: Neue Beziehungen nutzen (z. B. `beeinflusst_von`)
|
||||||
|
|
||||||
|
Beziehungen sind der Klebstoff für logische Schlussfolgerungen.
|
||||||
|
|
||||||
|
1. **Erfassung im Vault (Markdown)**
|
||||||
|
Nutze die Inline-Syntax. Du musst nichts vorab definieren.
|
||||||
|
> "Die Entscheidung für Qdrant wurde [[rel:beeinflusst_von Budgetkürzung 2024]]."
|
||||||
|
|
||||||
|
2. **Gewichtung justieren (`config/retriever.yaml`)**
|
||||||
|
Standardmäßig sind alle Kanten gleich `1.0`. Wenn Kausalität wichtiger ist als Ähnlichkeit, definiere dies hier:
|
||||||
|
```yaml
|
||||||
|
retriever:
|
||||||
|
edge_weights:
|
||||||
|
beeinflusst_von: 1.5 # Starker Boost: Zieht Ursachen in den Kontext
|
||||||
|
related_to: 0.5 # Schwacher Boost: Nur "nice to know"
|
||||||
|
```
|
||||||
|
*Effekt:* Bei der Frage nach "Qdrant" landet die "Budgetkürzung" (Ursache) im Kontext, weil die Kante stark ist.
|
||||||
|
|
||||||
|
3. **Interpretation (Prompting)**
|
||||||
|
Das LLM erkennt im RAG-Kontext: `Qdrant --[beeinflusst_von]--> Budgetkürzung`.
|
||||||
|
Es kann daraus den Satz formulieren: *"Die Wahl fiel vermutlich aufgrund der Budgetkürzung auf Qdrant."*
|
||||||
|
|
||||||
|
**Fazit:** Nur wenn **Daten** (Vault), **Physik** (Config) und **Semantik** (Prompt) zusammenspielen, entsteht ein intelligenter Zwilling.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9) Feedback & Lernen – WP04c/WP10
|
||||||
|
|
||||||
|
Das System verfügt nun über ein **Kurzzeitgedächtnis für Interaktionen**, das die Basis für zukünftiges Lernen bildet.
|
||||||
|
|
||||||
|
### 9.1 Der Feedback-Loop
|
||||||
|
Die Interaktion erfolgt primär über das **Web-Interface (WP10)**.
|
||||||
|
|
||||||
|
1. **Suche (Situation):**
|
||||||
|
Wenn ein Nutzer eine Anfrage stellt, loggt Mindnet die "Situation":
|
||||||
|
* Den Query-Text.
|
||||||
|
* Die Top-K Ergebnisse.
|
||||||
|
* Den exakten `score_breakdown` zu diesem Zeitpunkt.
|
||||||
|
* Eine eindeutige `query_id` wird generiert.
|
||||||
|
|
||||||
|
2. **Bewertung (Label):**
|
||||||
|
Der Nutzer bewertet die Antwort (**Sterne**) oder einzelne Quellen (**Faces**) im Frontend.
|
||||||
|
Dieses Feedback wird unter Referenzierung der `query_id` in `feedback.jsonl` gespeichert.
|
||||||
|
|
||||||
|
3. **Lernen (Perspektive WP08):**
|
||||||
|
Durch die Verknüpfung von Situation und Bewertung entstehen Trainingsdaten. Mindnet kann später analysieren: *"Nutzer bevorzugen Treffer mit hohem Edge-Bonus, auch wenn der Text weniger passt."* -> Konsequenz: `edge_weight` erhöhen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10) Confidence & Provenance – wozu?
|
||||||
|
|
||||||
|
Der Retriever kann Edges gewichten:
|
||||||
|
- **provenance**: *explicit* > *smart* (Neu) > *rule*
|
||||||
|
- **confidence**: numerische Feinsteuerung
|
||||||
|
- **retriever_weight (Note/Chunk)**: skaliert die Relevanz des gesamten Knotens
|
||||||
|
|
||||||
|
Eine typische Gewichtung (konfigurierbar in `retriever.yaml`) ist:
|
||||||
|
`explicit: 1.0`, `smart: 0.9`, `rule: 0.8`. Damit bevorzugt der Graph **kuratiertes Wissen** (explizit notierte Links) vor „erweiterten“ Default-Ableitungen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11) Semantik ausgewählter `kind`-Werte
|
||||||
|
|
||||||
|
- `references` – „Nutzt/erwähnt“; neutral, aber stützend für Kontext.
|
||||||
|
- `related_to` – Ähnlichkeit/Verwandtschaft (symmetrisch interpretierbar).
|
||||||
|
- `similar_to` – noch engere Ähnlichkeit; oft aus Inline-Rel (bewusst gesetzt).
|
||||||
|
- `depends_on` – fachliche Abhängigkeit (z. B. „Projekt X hängt von Y ab“).
|
||||||
|
- **Neu in v2.4 (Matrix):**
|
||||||
|
- `based_on` – Erfahrung basiert auf Wert.
|
||||||
|
- `derived_from` – Erkenntnis stammt aus Prinzip.
|
||||||
|
- `uses` – Projekt nutzt Konzept.
|
||||||
|
- `belongs_to`, `next`, `prev` – Struktur.
|
||||||
|
|
||||||
|
> Symmetrische Relationen (z. B. `related_to`, `similar_to`) können **explizit** nur einseitig notiert sein, aber im Retriever beidseitig interpretiert werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12) Frontmatter-Eigenschaften – Rolle & Empfehlung
|
||||||
|
|
||||||
|
Frontmatter-Eigenschaften (Properties) bleiben **minimiert**:
|
||||||
|
- **type** – steuert Typ-Defaults via Registry (Pflicht für differenziertes Verhalten).
|
||||||
|
- **tags** – für klassische Filterung.
|
||||||
|
- **retriever_weight / chunk_profile** – Sollten **nicht** manuell gesetzt werden (Best Practice: `types.yaml` nutzen).
|
||||||
|
- **links** – Veraltet. Bitte Links primär über Text (Wikilink/Inline/Callout) pflegen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13) Lösch-/Update-Garantien (Idempotenz)
|
||||||
|
|
||||||
|
- Jede Note hat einen stabilen **note_id** (Frontmatter/Hash).
|
||||||
|
- Vor einem Upsert können *alte Chunks/Edges einer Note* gefiltert gelöscht werden (`note_id`-Filter) – das hält Collections sauber bei Re-Imports.
|
||||||
|
- Die Import-Skripte unterstützen Modi wie `--purge-before-upsert` und `--sync-deletes`, um den Graph sauber zu halten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 14) Beispiel – Von Markdown zu Kanten
|
||||||
|
|
||||||
|
**Markdown (Auszug)**
|
||||||
|
# Relations Showcase
|
||||||
|
…
|
||||||
|
Wir nutzen [[rel:depends_on Qdrant Vektordatenbank]] für die Suche.
|
||||||
|
…
|
||||||
|
Siehe auch: [[Embeddings 101]]
|
||||||
|
|
||||||
|
> [!edge] related_to: [[Vector DB Basics]]
|
||||||
|
|
||||||
|
**Ergebnis (fachlich - Smart Edges)**
|
||||||
|
Das LLM analysiert jeden Chunk.
|
||||||
|
1. Chunk 1 ("Wir nutzen..."): Enthält `depends_on(Chunk→Qdrant)`. Das LLM bestätigt: Relevant. -> Kante wird erstellt.
|
||||||
|
2. Chunk 2 ("Siehe auch..."): Enthält `references(Chunk→Embeddings)`. Das LLM bestätigt.
|
||||||
|
3. **Wichtig:** Ein Chunk 3 ("Die Benutzeroberfläche ist blau..."), der keine Erwähnung von Qdrant hat, bekommt **keine** `depends_on` Kante zu Qdrant, auch wenn die Note global verlinkt ist. Das ist der Gewinn von WP15.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 15) Referenzen (Projektdateien & Leitlinien)
|
||||||
|
|
||||||
|
- Import-Pipeline & Registry-Auflösung: `scripts/import_markdown.py`.
|
||||||
|
- Kantenbildung (V2-Logic): `app/core/derive_edges.py`.
|
||||||
|
- Smart Chunking & Traffic Control: `app/core/chunker.py` & `app/services/llm_service.py`.
|
||||||
|
- Typ-Registry: `config/types.yaml` & `TYPE_REGISTRY_MANUAL.md`.
|
||||||
|
- Retriever-Scoring & Explanation: `app/core/retriever.py`.
|
||||||
|
- Persönlichkeit & Chat: `config/prompts.yaml` & `app/routers/chat.py`.
|
||||||
|
- Decision Engine: `config/decision_engine.yaml`.
|
||||||
|
- Logging Service: `app/services/feedback_service.py`.
|
||||||
|
- Frontend UI: `app/frontend/ui.py`.
|
||||||
|
- Intelligence Logic: `app/services/discovery.py`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 16) Workpackage Status (v2.6.0)
|
||||||
|
|
||||||
|
Aktueller Implementierungsstand der Module.
|
||||||
|
|
||||||
|
| WP | Titel | Status | Anmerkung |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **WP01** | Knowledge Design | 🟢 Live | Typen, Frontmatter definiert. |
|
||||||
|
| **WP02** | Chunking Strategy | 🟢 Live | Profilbasiertes Chunking aktiv. |
|
||||||
|
| **WP03** | Edge Logic / Import | 🟢 Live | Neue Importer-Pipeline mit Provenance. |
|
||||||
|
| **WP04a**| Retriever Scoring | 🟢 Live | Hybrider Score (Semantik + Graph). |
|
||||||
|
| **WP04b**| Explanation Layer | 🟢 Live | API liefert Reasons & Breakdown. |
|
||||||
|
| **WP04c**| Feedback Loop | 🟢 Live | Logging (JSONL) & Traceability aktiv. |
|
||||||
|
| **WP05** | Persönlichkeit / Chat | 🟢 Live | RAG-Integration mit Context Enrichment. |
|
||||||
|
| **WP06** | Decision Engine | 🟢 Live | Hybrid Router, Strategic Retrieval. |
|
||||||
|
| **WP07** | Interview Assistent | 🟢 Live | **One-Shot Extractor & Schemas aktiv.** |
|
||||||
|
| **WP08** | Self-Tuning | 🔴 Geplant | Auto-Adjustment der Gewichte. |
|
||||||
|
| **WP10** | Chat Interface | 🟢 Live | Web-Interface (Streamlit). |
|
||||||
|
| **WP10a**| Draft Editor | 🟢 Live | **Interaktives UI & Healing Parser.** |
|
||||||
|
| **WP11** | Backend Intelligence | 🟢 Live | **Async Ingestion, Nomic Embeddings, Matrix Logic.** |
|
||||||
|
| **WP15** | Smart Edge Allocation | 🟢 Live | **LLM-Filter & Traffic Control aktiv.** |
|
||||||
|
| **WP16** | Auto-Discovery | 🟡 Geplant | UX & Retrieval Tuning. |
|
||||||
|
| **WP17** | Conversational Memory | 🟡 Geplant | Dialog-Gedächtnis. |
|
||||||
@@ -0,0 +1,450 @@
|
|||||||
|
# Mindnet v2.6 – Technische Architektur
|
||||||
|
**Datei:** `docs/mindnet_technical_architecture_v2.6.md`
|
||||||
|
**Stand:** 2025-12-12
|
||||||
|
**Status:** **FINAL** (Integrierter Stand WP01–WP15: Smart Edges & Traffic Control)
|
||||||
|
**Quellen:** `Programmplan_V2.6.md`, `Handbuch.md`, `chunking_strategy.md`, `wp04_retriever_scoring.md`.
|
||||||
|
|
||||||
|
> **Ziel dieses Dokuments:**
|
||||||
|
> Vollständige Beschreibung der technischen Architektur inkl. Graph-Datenbank, Retrieval-Logik, der **RAG-Komponenten (Decision Engine & Hybrid Router)**, des **Traffic Control Systems** und dem **Frontend (Streamlit)**.
|
||||||
|
|
||||||
|
---
|
||||||
|
<details>
|
||||||
|
<summary>📖 <b>Inhaltsverzeichnis (Klicken zum Öffnen)</b></summary>
|
||||||
|
|
||||||
|
- [Mindnet v2.6 – Technische Architektur](#mindnet-v26--technische-architektur)
|
||||||
|
- [](#)
|
||||||
|
- [1. Systemüberblick](#1-systemüberblick)
|
||||||
|
- [1.1 Architektur-Zielbild](#11-architektur-zielbild)
|
||||||
|
- [1.2 Verzeichnisstruktur \& Komponenten (Post-WP15)](#12-verzeichnisstruktur--komponenten-post-wp15)
|
||||||
|
- [2. Datenmodell \& Collections (Qdrant)](#2-datenmodell--collections-qdrant)
|
||||||
|
- [2.1 Notes Collection (`<prefix>_notes`)](#21-notes-collection-prefix_notes)
|
||||||
|
- [2.2 Chunks Collection (`<prefix>_chunks`)](#22-chunks-collection-prefix_chunks)
|
||||||
|
- [2.3 Edges Collection (`<prefix>_edges`)](#23-edges-collection-prefix_edges)
|
||||||
|
- [3. Konfiguration](#3-konfiguration)
|
||||||
|
- [3.1 Typ-Registry (`config/types.yaml`)](#31-typ-registry-configtypesyaml)
|
||||||
|
- [3.2 Retriever-Config (`config/retriever.yaml`)](#32-retriever-config-configretrieveryaml)
|
||||||
|
- [3.3 Decision Engine (`config/decision_engine.yaml`)](#33-decision-engine-configdecision_engineyaml)
|
||||||
|
- [3.4 Prompts (`config/prompts.yaml`)](#34-prompts-configpromptsyaml)
|
||||||
|
- [3.5 Environment (`.env`)](#35-environment-env)
|
||||||
|
- [4. Import-Pipeline (Markdown → Qdrant)](#4-import-pipeline-markdown--qdrant)
|
||||||
|
- [4.1 Verarbeitungsschritte (Async + Smart)](#41-verarbeitungsschritte-async--smart)
|
||||||
|
- [5. Retriever-Architektur \& Scoring](#5-retriever-architektur--scoring)
|
||||||
|
- [5.1 Betriebsmodi](#51-betriebsmodi)
|
||||||
|
- [5.2 Scoring-Formel (WP04a)](#52-scoring-formel-wp04a)
|
||||||
|
- [5.3 Explanation Layer (WP04b)](#53-explanation-layer-wp04b)
|
||||||
|
- [5.4 Graph-Expansion](#54-graph-expansion)
|
||||||
|
- [6. RAG \& Chat Architektur (WP06 Hybrid Router + WP07 Interview)](#6-rag--chat-architektur-wp06-hybrid-router--wp07-interview)
|
||||||
|
- [6.1 Architektur-Pattern: Intent Router v5](#61-architektur-pattern-intent-router-v5)
|
||||||
|
- [6.2 Traffic Control (Priorisierung)](#62-traffic-control-priorisierung)
|
||||||
|
- [6.3 Schritt 1: Intent Detection (Question vs. Action)](#63-schritt-1-intent-detection-question-vs-action)
|
||||||
|
- [6.4 Schritt 2: Strategy Resolution](#64-schritt-2-strategy-resolution)
|
||||||
|
- [6.5 Schritt 3: Retrieval vs. Extraction](#65-schritt-3-retrieval-vs-extraction)
|
||||||
|
- [6.6 Schritt 4: Generation \& Response](#66-schritt-4-generation--response)
|
||||||
|
- [7. Frontend Architektur (WP10)](#7-frontend-architektur-wp10)
|
||||||
|
- [7.1 Kommunikation](#71-kommunikation)
|
||||||
|
- [7.2 Features \& UI-Logik](#72-features--ui-logik)
|
||||||
|
- [7.3 Draft-Editor \& Healing Parser (Neu in WP10a/v2.5)](#73-draft-editor--healing-parser-neu-in-wp10av25)
|
||||||
|
- [7.4 State Management (Resurrection Pattern)](#74-state-management-resurrection-pattern)
|
||||||
|
- [7.5 Deployment Ports](#75-deployment-ports)
|
||||||
|
- [8. Feedback \& Logging Architektur (WP04c)](#8-feedback--logging-architektur-wp04c)
|
||||||
|
- [8.1 Komponenten](#81-komponenten)
|
||||||
|
- [8.2 Log-Dateien](#82-log-dateien)
|
||||||
|
- [8.3 Traceability](#83-traceability)
|
||||||
|
- [9. Indizes \& Performance](#9-indizes--performance)
|
||||||
|
- [10. Offene Punkte / Known Limitations](#10-offene-punkte--known-limitations)
|
||||||
|
|
||||||
|
|
||||||
|
</details>
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Systemüberblick
|
||||||
|
|
||||||
|
### 1.1 Architektur-Zielbild
|
||||||
|
Mindnet ist ein **lokales RAG-System (Retrieval Augmented Generation)** mit Web-Interface.
|
||||||
|
1. **Source:** Markdown-Notizen in einem Vault (Obsidian-kompatibel).
|
||||||
|
2. **Pipeline:** Ein Python-Importer transformiert diese in **Notes**, **Chunks** und **Edges**.
|
||||||
|
* **Neu in v2.6:** Intelligente Kanten-Zuweisung durch lokale LLMs (**Smart Edge Allocation**).
|
||||||
|
3. **Storage:**
|
||||||
|
* **Qdrant:** Vektor-Datenbank für Graph und Semantik (Collections: notes, chunks, edges).
|
||||||
|
* **Local Files (JSONL):** Append-Only Logs für Feedback und Search-History (Data Flywheel).
|
||||||
|
4. **Backend:** Eine FastAPI-Anwendung stellt Endpunkte für **Semantische** und **Hybride Suche** sowie **Feedback** bereit.
|
||||||
|
* **Update v2.6:** Der Core arbeitet nun vollständig **asynchron (AsyncIO)** mit **Traffic Control** (Semaphore zur Lastverteilung).
|
||||||
|
5. **Frontend:** Streamlit-App (`ui.py`) für Interaktion und Visualisierung inkl. **Draft Editor**, **Active Intelligence** und **Healing Parser**.
|
||||||
|
6. **Inference:** Lokales LLM (Ollama: Phi-3 Mini) für RAG-Chat und Antwortgenerierung. Embedding via `nomic-embed-text`.
|
||||||
|
|
||||||
|
Das System arbeitet **deterministisch** (stabile IDs) und ist **konfigurationsgetrieben** (`types.yaml`, `retriever.yaml`, `decision_engine.yaml`, `prompts.yaml`).
|
||||||
|
|
||||||
|
### 1.2 Verzeichnisstruktur & Komponenten (Post-WP15)
|
||||||
|
|
||||||
|
/mindnet/
|
||||||
|
├── app/
|
||||||
|
│ ├── main.py # FastAPI Einstiegspunkt
|
||||||
|
│ ├── core/
|
||||||
|
│ │ ├── ingestion.py # NEU: Async Ingestion mit Change Detection
|
||||||
|
│ │ ├── qdrant.py # Client-Factory & Connection
|
||||||
|
│ │ ├── qdrant_points.py # Low-Level Point Operations (Upsert/Delete)
|
||||||
|
│ │ ├── note_payload.py # Bau der Note-Objekte
|
||||||
|
│ │ ├── chunk_payload.py # Bau der Chunk-Objekte
|
||||||
|
│ │ ├── chunker.py # Smart Chunker Orchestrator (WP15)
|
||||||
|
│ │ ├── edges.py # Edge-Datenstrukturen
|
||||||
|
│ │ ├── derive_edges.py # Logik der Kantenableitung (WP03)
|
||||||
|
│ │ ├── graph_adapter.py # Subgraph & Reverse-Lookup (WP04b)
|
||||||
|
│ │ └── retriever.py # Scoring, Expansion & Explanation (WP04a/b)
|
||||||
|
│ ├── models/ # Pydantic DTOs
|
||||||
|
│ │ └── dto.py # Zentrale DTO-Definition
|
||||||
|
│ ├── routers/
|
||||||
|
│ │ ├── query.py # Such-Endpunkt
|
||||||
|
│ │ ├── ingest.py # NEU: API für Save & Analyze (WP11)
|
||||||
|
│ │ ├── chat.py # Hybrid Router v5 & Interview Logic (WP06/07)
|
||||||
|
│ │ ├── feedback.py # Feedback-Endpunkt (WP04c)
|
||||||
|
│ │ └── ...
|
||||||
|
│ ├── services/
|
||||||
|
│ │ ├── llm_service.py # Ollama Chat Client mit Traffic Control (v2.8.0)
|
||||||
|
│ │ ├── semantic_analyzer.py# NEU: LLM-Filter für Edges (WP15)
|
||||||
|
│ │ ├── embeddings_client.py# NEU: Async Embeddings (HTTPX)
|
||||||
|
│ │ ├── feedback_service.py # Logging (JSONL Writer)
|
||||||
|
│ │ └── discovery.py # NEU: Intelligence Logic (WP11)
|
||||||
|
│ ├── frontend/ # NEU (WP10)
|
||||||
|
│ │ └── ui.py # Streamlit Application inkl. Healing Parser
|
||||||
|
│ └── main.py # Entrypoint der API
|
||||||
|
├── config/ # YAML-Konfigurationen (Single Source of Truth)
|
||||||
|
│ ├── types.yaml # Import-Regeln & Smart-Edge Config
|
||||||
|
│ ├── prompts.yaml # LLM Prompts & Interview Templates (WP06/07)
|
||||||
|
│ ├── decision_engine.yaml # Router-Strategien (Actions only)
|
||||||
|
│ └── retriever.yaml # Scoring-Regeln & Kantengewichte
|
||||||
|
├── data/
|
||||||
|
│ └── logs/ # Lokale Logs (search_history.jsonl, feedback.jsonl)
|
||||||
|
├── scripts/ # CLI-Tools (Import, Diagnose, Reset)
|
||||||
|
│ ├── import_markdown.py # Haupt-Importer CLI (Async)
|
||||||
|
│ ├── payload_dryrun.py # Diagnose: JSON-Generierung ohne DB
|
||||||
|
│ └── edges_full_check.py # Diagnose: Graph-Integrität
|
||||||
|
├── tests/ # Pytest Suite & Smoke Scripts
|
||||||
|
└── vault/ # Dein lokaler Markdown-Content (Git-ignored)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Datenmodell & Collections (Qdrant)
|
||||||
|
|
||||||
|
Das Datenmodell verteilt sich auf drei Collections, definiert durch `COLLECTION_PREFIX` (Standard: `mindnet`).
|
||||||
|
|
||||||
|
### 2.1 Notes Collection (`<prefix>_notes`)
|
||||||
|
Repräsentiert die Metadaten einer Datei.
|
||||||
|
* **Zweck:** Filterung, Metadaten-Haltung, Vererbung von Eigenschaften an Chunks.
|
||||||
|
* **Schema (Payload):**
|
||||||
|
|
||||||
|
| Feld | Datentyp | Beschreibung | Herkunft |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `note_id` | Keyword | Stabile ID (UUIDv5 oder Slug). | Frontmatter |
|
||||||
|
| `title` | Text | Titel der Notiz. | Frontmatter |
|
||||||
|
| `type` | Keyword | Logischer Typ (z.B. `concept`). | `types.yaml` Resolver |
|
||||||
|
| `retriever_weight` | Float | Wichtigkeit im Retrieval. | `types.yaml` |
|
||||||
|
| `chunk_profile` | Keyword | Genutztes Chunking-Profil. | `types.yaml` |
|
||||||
|
| `edge_defaults` | List[Str] | Aktive Default-Relationen. | `types.yaml` |
|
||||||
|
| `tags` | List[Kw] | Tags zur Filterung. | Frontmatter |
|
||||||
|
| `updated` | Integer | Zeitstempel (z.B. YYYYMMDD...). | File Stats |
|
||||||
|
| `fulltext` | Text | Gesamter Inhalt (für Export/Rekonstruktion). | Body |
|
||||||
|
|
||||||
|
### 2.2 Chunks Collection (`<prefix>_chunks`)
|
||||||
|
Die atomaren Sucheinheiten.
|
||||||
|
* **Zweck:** Vektorsuche (Embeddings), Granulares Ergebnis.
|
||||||
|
* **Update v2.4:** Vektor-Dimension ist jetzt **768** (für `nomic-embed-text`).
|
||||||
|
* **Schema (Payload):**
|
||||||
|
|
||||||
|
| Feld | Datentyp | Beschreibung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `chunk_id` | Keyword | Deterministisch: `{note_id}#c{index:02d}`. |
|
||||||
|
| `note_id` | Keyword | Referenz zur Note. |
|
||||||
|
| `type` | Keyword | **Kopie des Note-Typs** (Denormalisiert für Filter). |
|
||||||
|
| `text` | Text | **Reiner Inhalt** (ohne Overlap). Anzeige-Text. |
|
||||||
|
| `window` | Text | **Kontext-Fenster** (mit Overlap). Embedding-Basis. |
|
||||||
|
| `ord` | Integer | Sortierreihenfolge (1..N). |
|
||||||
|
| `retriever_weight` | Float | Vererbt von Note. |
|
||||||
|
| `chunk_profile` | Keyword | Vererbt von Note. |
|
||||||
|
| `neighbors_prev` | List[Str] | ID des Vorgänger-Chunks. |
|
||||||
|
| `neighbors_next` | List[Str] | ID des Nachfolger-Chunks. |
|
||||||
|
|
||||||
|
### 2.3 Edges Collection (`<prefix>_edges`)
|
||||||
|
Gerichtete Kanten. Massiv erweitert in WP03 für Provenienz-Tracking.
|
||||||
|
* **Zweck:** Graph-Traversal, Kontext-Anreicherung.
|
||||||
|
* **Schema (Payload):**
|
||||||
|
|
||||||
|
| Feld | Datentyp | Beschreibung | Wertebereich (Bsp.) |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `edge_id` | Keyword | Hash aus (src, dst, kind). | |
|
||||||
|
| `source_id` | Keyword | ID des Start-Chunks. | |
|
||||||
|
| `target_id` | Keyword | ID des Ziel-Chunks (oder Note-Titel). | |
|
||||||
|
| `note_id` | Keyword | Note, die diese Kante definiert. | |
|
||||||
|
| `kind` | Keyword | Art der Beziehung. | `references`, `depends_on`, `next` |
|
||||||
|
| `scope` | Keyword | Geltungsbereich. | Immer `"chunk"` (v2.2). |
|
||||||
|
| `rule_id` | Keyword | Herkunftsregel. | `explicit:wikilink`, `inline:rel` |
|
||||||
|
| `confidence` | Float | Vertrauenswürdigkeit (0.0-1.0). | 1.0, 0.95, 0.7 |
|
||||||
|
| `provenance` | Keyword | Quelle der Kante (Neu in v2.6). | `explicit`, `rule`, `smart` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Konfiguration
|
||||||
|
|
||||||
|
Die Logik ist ausgelagert in YAML-Dateien.
|
||||||
|
|
||||||
|
### 3.1 Typ-Registry (`config/types.yaml`)
|
||||||
|
Steuert den Import-Prozess.
|
||||||
|
* **Priorität:** Frontmatter > Pfad > Default.
|
||||||
|
* **Neu in v2.6:**
|
||||||
|
* `enable_smart_edge_allocation`: (Bool) Aktiviert den LLM-Filter für diesen Typ.
|
||||||
|
* `detection_keywords`: (List) Keywords für den Hybrid Router ("Objekterkennung").
|
||||||
|
* **Inhalt (Beispiel):**
|
||||||
|
|
||||||
|
types:
|
||||||
|
concept:
|
||||||
|
chunk_profile: sliding_standard
|
||||||
|
edge_defaults: ["references", "related_to"]
|
||||||
|
retriever_weight: 0.60
|
||||||
|
experience:
|
||||||
|
chunk_profile: sliding_smart_edges
|
||||||
|
enable_smart_edge_allocation: true
|
||||||
|
detection_keywords: ["erfahrung", "erlebt"]
|
||||||
|
|
||||||
|
### 3.2 Retriever-Config (`config/retriever.yaml`)
|
||||||
|
Steuert das Scoring zur Laufzeit (WP04a).
|
||||||
|
* **Inhalt (Beispiel):**
|
||||||
|
|
||||||
|
scoring:
|
||||||
|
semantic_weight: 1.0
|
||||||
|
edge_weight: 0.7
|
||||||
|
centrality_weight: 0.5
|
||||||
|
|
||||||
|
### 3.3 Decision Engine (`config/decision_engine.yaml`)
|
||||||
|
**Neu in WP06/07:** Steuert den Intent-Router.
|
||||||
|
* Definiert Strategien (`DECISION`, `INTERVIEW`, etc.).
|
||||||
|
* **Update v2.6:** Enthält nur noch **Handlungs-Keywords** (Verben wie "neu", "erstellen"). Objektnamen ("Projekt") werden nun über `types.yaml` aufgelöst.
|
||||||
|
* Definiert LLM-Router-Settings (`llm_fallback_enabled`).
|
||||||
|
|
||||||
|
### 3.4 Prompts (`config/prompts.yaml`)
|
||||||
|
Steuert die LLM-Persönlichkeit und Templates.
|
||||||
|
* Enthält Templates für alle Strategien inkl. `interview_template` und neu `router_prompt`.
|
||||||
|
|
||||||
|
### 3.5 Environment (`.env`)
|
||||||
|
Erweiterung für LLM-Steuerung und Embedding-Modell:
|
||||||
|
|
||||||
|
MINDNET_LLM_MODEL=phi3:mini
|
||||||
|
MINDNET_EMBEDDING_MODEL=nomic-embed-text # NEU in v2.3.10
|
||||||
|
MINDNET_OLLAMA_URL=http://127.0.0.1:11434
|
||||||
|
MINDNET_LLM_TIMEOUT=300.0 # Neu: Erhöht für CPU-Inference Cold-Starts
|
||||||
|
MINDNET_API_TIMEOUT=300.0 # Neu: Timeout für Frontend-API (Smart Edges brauchen Zeit)
|
||||||
|
MINDNET_DECISION_CONFIG="config/decision_engine.yaml"
|
||||||
|
MINDNET_VAULT_ROOT="./vault" # Neu: Pfad für Write-Back
|
||||||
|
MINDNET_LLM_BACKGROUND_LIMIT=2 # Neu: Limit für parallele Hintergrund-Jobs (Traffic Control)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Import-Pipeline (Markdown → Qdrant)
|
||||||
|
|
||||||
|
Das Skript `scripts/import_markdown.py` orchestriert den Prozess.
|
||||||
|
**Neu in v2.6:** Der Import nutzt `asyncio` und **Traffic Control**, um Ollama nicht zu überlasten.
|
||||||
|
|
||||||
|
### 4.1 Verarbeitungsschritte (Async + Smart)
|
||||||
|
|
||||||
|
1. **Discovery & Parsing:** Hash-Vergleich zur Erkennung von Änderungen.
|
||||||
|
2. **Typauflösung:** Bestimmung des `type` via `types.yaml`.
|
||||||
|
3. **Config Check:** Laden des `chunk_profile` und `enable_smart_edge_allocation`.
|
||||||
|
4. **Chunking & Smart Edges (WP15):**
|
||||||
|
* Zerlegung des Textes via `chunker.py`.
|
||||||
|
* Wenn Smart Edges aktiv: Der `SemanticAnalyzer` sendet Chunks an das LLM.
|
||||||
|
* **Traffic Control:** Der Request nutzt `priority="background"`. Die Semaphore (Limit: 2) drosselt die Parallelität.
|
||||||
|
5. **Kantenableitung (Edge Derivation):**
|
||||||
|
* `derive_edges.py` erzeugt Inline-, Callout- und Default-Edges.
|
||||||
|
6. **Embedding (Async):**
|
||||||
|
* Der `EmbeddingsClient` (`app/services/embeddings_client.py`) sendet Text-Chunks asynchron an Ollama.
|
||||||
|
* Modell: `nomic-embed-text` (768d).
|
||||||
|
7. **Upsert:**
|
||||||
|
* Schreiben in Qdrant. Nutzung von `--purge-before-upsert`.
|
||||||
|
* **Strict Mode:** Der Prozess bricht ab, wenn Embeddings leer sind oder Dimension `0` haben.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Retriever-Architektur & Scoring
|
||||||
|
|
||||||
|
Der Retriever (`app/core/retriever.py`) unterstützt zwei Modi. Für den Chat wird **zwingend** der Hybrid-Modus genutzt.
|
||||||
|
|
||||||
|
### 5.1 Betriebsmodi
|
||||||
|
* **Semantic:** Reine Vektorsuche (768d).
|
||||||
|
* **Hybrid:** Vektorsuche + Graph-Expansion (Tiefe N) + Re-Ranking.
|
||||||
|
|
||||||
|
### 5.2 Scoring-Formel (WP04a)
|
||||||
|
Die Relevanzberechnung ist nun eine gewichtete Summe:
|
||||||
|
|
||||||
|
$$
|
||||||
|
TotalScore = (W_{sem} \cdot S_{sem} \cdot \max(W_{type}, 0)) + (W_{edge} \cdot B_{edge}) + (W_{cent} \cdot B_{cent})
|
||||||
|
$$
|
||||||
|
|
||||||
|
* **Komponenten:**
|
||||||
|
* $S_{sem}$: Semantic Score (Cosine Similarity).
|
||||||
|
* $W_{type}$: `retriever_weight` (aus Note/Chunk Payload).
|
||||||
|
* $B_{edge}$: Edge-Bonus (Summe der Konfidenzen eingehender relevanter Kanten).
|
||||||
|
* $B_{cent}$: Centrality-Bonus (im lokalen Subgraphen).
|
||||||
|
* **Gewichte ($W$):** Stammen aus `retriever.yaml`.
|
||||||
|
|
||||||
|
### 5.3 Explanation Layer (WP04b)
|
||||||
|
Der Retriever ist keine Blackbox mehr. Er liefert auf Wunsch (`explain=True`) eine strukturierte Begründung (`Explanation`-Objekt).
|
||||||
|
|
||||||
|
**Die "Warum"-Logik:**
|
||||||
|
1. **Semantik:** Prüfung der Cosine-Similarity ("Sehr hohe textuelle Übereinstimmung").
|
||||||
|
2. **Typ:** Prüfung des `retriever_weight` ("Bevorzugt, da Entscheidung").
|
||||||
|
3. **Graph (Kontext):**
|
||||||
|
* **Hub (Outgoing):** Worauf verweist dieser Treffer? ("Verweist auf Qdrant").
|
||||||
|
* **Authority (Incoming):** Wer verweist auf diesen Treffer? ("Wird referenziert von Projekt Alpha").
|
||||||
|
|
||||||
|
Die API gibt diese Analysen als menschenlesbare Sätze (`reasons`) und als Datenstruktur (`score_breakdown`) zurück.
|
||||||
|
|
||||||
|
### 5.4 Graph-Expansion
|
||||||
|
Der Hybrid-Modus lädt dynamisch die Nachbarschaft der Top-K Vektor-Treffer ("Seeds") über `graph_adapter.expand`. Dies baut einen temporären `NetworkX`-artigen Graphen im Speicher (Klasse `Subgraph`), auf dem Boni berechnet werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. RAG & Chat Architektur (WP06 Hybrid Router + WP07 Interview)
|
||||||
|
|
||||||
|
Der Flow für eine Chat-Anfrage (`/chat`) wurde in WP06 auf eine **Configuration-Driven Architecture** umgestellt und in WP15 (v2.6) verfeinert.
|
||||||
|
|
||||||
|
### 6.1 Architektur-Pattern: Intent Router v5
|
||||||
|
Die Behandlung einer Anfrage ist nicht mehr hartkodiert, sondern wird dynamisch zur Laufzeit entschieden.
|
||||||
|
* **Input:** User Message.
|
||||||
|
* **Config:** `decision_engine.yaml` (Strategien) + `types.yaml` (Objekte).
|
||||||
|
* **Komponenten:**
|
||||||
|
* **Traffic Control:** `LLMService` priorisiert Chat-Anfragen.
|
||||||
|
* **Question Detection:** Unterscheidung Frage vs. Befehl.
|
||||||
|
|
||||||
|
### 6.2 Traffic Control (Priorisierung)
|
||||||
|
Der `LLMService` implementiert zwei Spuren basierend auf `app/services/llm_service.py` (v2.8.0):
|
||||||
|
* **Realtime (Chat):** `priority="realtime"`. Umgeht die Semaphore. Antwortet sofort.
|
||||||
|
* **Background (Import/Analyse):** `priority="background"`. Wartet in der Semaphore (`asyncio.Semaphore`), die lazy mit `MINDNET_LLM_BACKGROUND_LIMIT` initialisiert wird.
|
||||||
|
|
||||||
|
### 6.3 Schritt 1: Intent Detection (Question vs. Action)
|
||||||
|
Der Router ermittelt die Absicht (`Intent`) des Nutzers.
|
||||||
|
1. **Frage-Check:** Wenn der Input ein `?` enthält oder mit W-Wörtern beginnt, wird der **RAG-Modus** erzwungen (oder LLM-Entscheidung). Interviews werden hier unterdrückt.
|
||||||
|
2. **Keyword Scan (Fast Path):**
|
||||||
|
* Prüfung auf `trigger_keywords` (Handlung) in `decision_engine.yaml`.
|
||||||
|
* Prüfung auf `detection_keywords` (Objekt) in `types.yaml`.
|
||||||
|
* Treffer -> **INTERVIEW Modus** (Erfassen).
|
||||||
|
3. **LLM Fallback (Slow Path):**
|
||||||
|
* Greift, wenn keine Keywords passen. Sendet Query an LLM Router.
|
||||||
|
|
||||||
|
### 6.4 Schritt 2: Strategy Resolution
|
||||||
|
Basierend auf dem Intent lädt der Router die Parameter:
|
||||||
|
* **Bei RAG (FACT/DECISION):** `inject_types` für Strategic Retrieval.
|
||||||
|
* **Bei INTERVIEW (WP07):** `schemas` (Pflichtfelder) basierend auf der erkannten Ziel-Entität (`_detect_target_type`).
|
||||||
|
|
||||||
|
### 6.5 Schritt 3: Retrieval vs. Extraction
|
||||||
|
Der Router verzweigt hier:
|
||||||
|
|
||||||
|
**A) RAG Modus (FACT, DECISION, EMPATHY):**
|
||||||
|
1. **Primary Retrieval:** Hybride Suche nach der User-Query.
|
||||||
|
2. **Strategic Retrieval (Conditional):** Wenn `inject_types` definiert sind, erfolgt eine zweite Suche, die explizit auf diese Typen filtert.
|
||||||
|
3. **Merge:** Ergebnisse werden dedupliziert zusammengeführt.
|
||||||
|
|
||||||
|
**B) Interview Modus (INTERVIEW):**
|
||||||
|
1. **Kein Retrieval:** Der Kontext ist der Chat-Verlauf (oder initial die Query).
|
||||||
|
2. **Schema Injection:** Das Schema für den erkannten Typ (z.B. "Project") wird geladen.
|
||||||
|
3. **Prompt Assembly:** Der `interview_template` Prompt wird mit der Schema-Definition ("Ziel", "Status") gefüllt.
|
||||||
|
|
||||||
|
### 6.6 Schritt 4: Generation & Response
|
||||||
|
* **Templating:** Das LLM erhält den Prompt basierend auf dem gewählten Template.
|
||||||
|
* **Execution:** Der `LLMService` führt den Call mit `priority="realtime"` aus.
|
||||||
|
* **Response:** Rückgabe enthält Antworttext (im Interview-Modus: Markdown Codeblock), Quellenliste und den erkannten `intent`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Frontend Architektur (WP10)
|
||||||
|
|
||||||
|
Das Frontend ist eine **Streamlit-Anwendung** (`app/frontend/ui.py`), die als separater Prozess läuft und via HTTP mit dem Backend kommuniziert.
|
||||||
|
|
||||||
|
### 7.1 Kommunikation
|
||||||
|
* **Backend-URL:** Konfiguriert via `MINDNET_API_URL` (Default: `http://localhost:8002`).
|
||||||
|
* **Endpoints:**
|
||||||
|
* `/chat` (Interaktion)
|
||||||
|
* `/feedback` (Bewertungen)
|
||||||
|
* `/ingest/analyze` (Active Intelligence / Link-Vorschläge)
|
||||||
|
* `/ingest/save` (Persistence / Speichern im Vault)
|
||||||
|
* **Resilienz:** Das Frontend nutzt `MINDNET_API_TIMEOUT` (300s), um auf langsame Backend-Prozesse (Smart Edges) zu warten.
|
||||||
|
|
||||||
|
### 7.2 Features & UI-Logik
|
||||||
|
* **State Management:** Session-State speichert Chat-Verlauf und `query_id`.
|
||||||
|
* **Visualisierung:**
|
||||||
|
* **Intent Badges:** Zeigt Router-Entscheidung (`DECISION`, `INTERVIEW`, etc.).
|
||||||
|
* **Source Expanders:** Zeigt verwendete Chunks inkl. Score und "Why"-Explanation.
|
||||||
|
* **Sidebar:** Zeigt Suchhistorie (Log-basiert) und Konfiguration.
|
||||||
|
|
||||||
|
### 7.3 Draft-Editor & Healing Parser (Neu in WP10a/v2.5)
|
||||||
|
Wenn der Intent `INTERVIEW` ist, rendert die UI statt einer Textblase den **Draft-Editor**.
|
||||||
|
|
||||||
|
1. **Parsing:** Die Funktion `parse_markdown_draft` extrahiert den Codeblock aus der LLM-Antwort.
|
||||||
|
* **Healing:** Erkennt und repariert defekte YAML-Frontmatter (z.B. fehlendes schließendes `---`), falls das LLM unter Last Fehler macht.
|
||||||
|
2. **Sanitization (`normalize_meta_and_body`):**
|
||||||
|
* Prüft den YAML-Frontmatter auf unerlaubte Felder (Halluzinationen des LLMs).
|
||||||
|
* Verschiebt ungültige Felder (z.B. "Situation") in den Body der Notiz.
|
||||||
|
3. **Editor Widget:** `st.text_area` erlaubt das Bearbeiten des Inhalts vor dem Speichern.
|
||||||
|
4. **Save Action:** Speichert über `/ingest/save` atomar in Vault und DB. Erzeugt intelligente Dateinamen via `slugify`.
|
||||||
|
|
||||||
|
### 7.4 State Management (Resurrection Pattern)
|
||||||
|
Um Datenverlust bei Tab-Wechseln (Chat <-> Editor) zu verhindern, nutzt `ui.py` ein Persistenz-Muster:
|
||||||
|
* Daten liegen in `st.session_state[data_key]`.
|
||||||
|
* Widgets liegen in `st.session_state[widget_key]`.
|
||||||
|
* Callbacks (`on_change`) synchronisieren Widget -> Data.
|
||||||
|
* Beim Neu-Rendern wird Widget-State aus Data-State wiederhergestellt.
|
||||||
|
|
||||||
|
### 7.5 Deployment Ports
|
||||||
|
Zur sauberen Trennung von Prod und Dev laufen Frontend und Backend auf dedizierten Ports:
|
||||||
|
|
||||||
|
| Umgebung | Backend (FastAPI) | Frontend (Streamlit) |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Production** | 8001 | 8501 |
|
||||||
|
| **Development** | 8002 | 8502 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Feedback & Logging Architektur (WP04c)
|
||||||
|
|
||||||
|
Mindnet implementiert ein "Data Flywheel" zur späteren Optimierung (Self-Tuning).
|
||||||
|
|
||||||
|
### 8.1 Komponenten
|
||||||
|
* **Feedback Service (`app/services/feedback_service.py`):** Kapselt die Schreibzugriffe.
|
||||||
|
* **Storage:** Lokales Dateisystem (`data/logs/`), Format JSONL (Line-delimited JSON).
|
||||||
|
|
||||||
|
### 8.2 Log-Dateien
|
||||||
|
1. **`search_history.jsonl`**:
|
||||||
|
* Speichert jede Anfrage an `/query` und `/chat`.
|
||||||
|
* Enthält: `query_id`, `query_text`, `timestamp`, `hits` (inkl. `score_breakdown` Snapshots).
|
||||||
|
* Zweck: Trainingsdaten ("Was hat das System gesehen?").
|
||||||
|
2. **`feedback.jsonl`**:
|
||||||
|
* Speichert User-Reaktionen an `/feedback`.
|
||||||
|
* Enthält: `query_id`, `node_id`, `score` (1-5), `comment`.
|
||||||
|
* **Granularität:** Kann sich auf `generated_answer` (Global) oder eine spezifische `node_id` (Quelle) beziehen.
|
||||||
|
* Zweck: Labels ("War es gut?").
|
||||||
|
|
||||||
|
### 8.3 Traceability
|
||||||
|
Die `query_id` (UUIDv4) wird im `/query` Response generiert und muss vom Client beim `/feedback` Aufruf mitgesendet werden. Dies ermöglicht den Join zwischen Snapshot und Bewertung.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Indizes & Performance
|
||||||
|
|
||||||
|
Damit Qdrant performant bleibt, sind Payload-Indizes essenziell.
|
||||||
|
|
||||||
|
**Erforderliche Indizes:**
|
||||||
|
* **Notes:** `note_id`, `type`, `tags`.
|
||||||
|
* **Chunks:** `note_id`, `chunk_id`, `type`.
|
||||||
|
* **Edges:** `source_id`, `target_id`, `kind`, `scope`, `note_id`.
|
||||||
|
|
||||||
|
Validierung erfolgt über `tests/ensure_indexes_and_show.py`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Offene Punkte / Known Limitations
|
||||||
|
|
||||||
|
1. **Multi-Target Inline-Relations:**
|
||||||
|
* `rel: similar_to [[A]] [[B]]` wird aktuell parser-seitig nicht unterstützt.
|
||||||
|
* Workaround: Zwei separate Inline-Links `[[rel:similar_to A]] [[rel:similar_to B]]`.
|
||||||
|
2. **Unresolved Targets:**
|
||||||
|
* Kanten zu Notizen, die noch nicht existieren, werden mit `target_id="Titel"` angelegt.
|
||||||
|
* Heilung durch `scripts/resolve_unresolved_references.py` möglich.
|
||||||
|
3. **Hardware-Last bei Smart Import:**
|
||||||
|
* Der "Smart Edge" Import ist rechenintensiv. Trotz Traffic Control kann die Antwortzeit im Chat leicht steigen, wenn die GPU am VRAM-Limit arbeitet.
|
||||||
@@ -0,0 +1,291 @@
|
|||||||
|
# mindnet v2.4 – Pipeline Playbook
|
||||||
|
**Datei:** `docs/mindnet_pipeline_playbook_v2.6.md`
|
||||||
|
**Stand:** 2025-12-12
|
||||||
|
**Status:** **FINAL** (Inkl. Smart Edges & Traffic Control)
|
||||||
|
**Quellen:** `mindnet_v2_implementation_playbook.md`, `Handbuch.md`, `chunking_strategy.md`, `docs_mindnet_retriever.md`, `mindnet_admin_guide_v2.4.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
<details>
|
||||||
|
<summary>📖 <b>Inhaltsverzeichnis (Klicken zum Öffnen)</b></summary>
|
||||||
|
|
||||||
|
- [mindnet v2.4 – Pipeline Playbook](#mindnet-v24--pipeline-playbook)
|
||||||
|
- [](#)
|
||||||
|
- [1. Zweck \& Einordnung](#1-zweck--einordnung)
|
||||||
|
- [2. Die Import-Pipeline (Runbook)](#2-die-import-pipeline-runbook)
|
||||||
|
- [2.1 Der 13-Schritte-Prozess (Async + Smart)](#21-der-13-schritte-prozess-async--smart)
|
||||||
|
- [2.2 Standard-Betrieb (Inkrementell)](#22-standard-betrieb-inkrementell)
|
||||||
|
- [2.3 Deployment \& Restart (Systemd)](#23-deployment--restart-systemd)
|
||||||
|
- [2.4 Full Rebuild (Clean Slate)](#24-full-rebuild-clean-slate)
|
||||||
|
- [3. Chunking \& Payload-Aufbau](#3-chunking--payload-aufbau)
|
||||||
|
- [3.1 Chunk-Profile](#31-chunk-profile)
|
||||||
|
- [3.2 Payload-Felder](#32-payload-felder)
|
||||||
|
- [4. Edge-Erzeugung (Die V2-Logik)](#4-edge-erzeugung-die-v2-logik)
|
||||||
|
- [4.1 Prioritäten \& Provenance](#41-prioritäten--provenance)
|
||||||
|
- [4.2 Smart Edge Allocation (WP15)](#42-smart-edge-allocation-wp15)
|
||||||
|
- [4.3 Typ-Defaults](#43-typ-defaults)
|
||||||
|
- [5. Retriever, Chat \& Generation (RAG Pipeline)](#5-retriever-chat--generation-rag-pipeline)
|
||||||
|
- [5.1 Retrieval (Hybrid)](#51-retrieval-hybrid)
|
||||||
|
- [5.2 Intent Router (WP06/07)](#52-intent-router-wp0607)
|
||||||
|
- [5.3 Context Enrichment](#53-context-enrichment)
|
||||||
|
- [5.4 Generation (LLM) mit Traffic Control](#54-generation-llm-mit-traffic-control)
|
||||||
|
- [5.5 Active Intelligence Pipeline (Neu in v2.4)](#55-active-intelligence-pipeline-neu-in-v24)
|
||||||
|
- [6. Feedback \& Lernen (WP04c)](#6-feedback--lernen-wp04c)
|
||||||
|
- [7. Quality Gates \& Tests](#7-quality-gates--tests)
|
||||||
|
- [7.1 Pflicht-Tests vor Commit](#71-pflicht-tests-vor-commit)
|
||||||
|
- [7.2 Smoke-Test (E2E)](#72-smoke-test-e2e)
|
||||||
|
- [8. Ausblick \& Roadmap (Technische Skizzen)](#8-ausblick--roadmap-technische-skizzen)
|
||||||
|
- [8.1 WP-08: Self-Tuning (Skizze)](#81-wp-08-self-tuning-skizze)
|
||||||
|
- [16. Workpackage Status (v2.6.0)](#16-workpackage-status-v260)
|
||||||
|
|
||||||
|
</details>
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Zweck & Einordnung
|
||||||
|
|
||||||
|
Dieses Playbook ist das zentrale operative Handbuch für die **mindnet-Pipeline**. Es beschreibt, wie Daten vom Markdown-Vault in den Wissensgraphen (Qdrant) gelangen, wie der Retriever betrieben wird und wie die **RAG-Generierung** (inkl. Decision Engine & Interviewer) funktioniert.
|
||||||
|
|
||||||
|
**Zielgruppe:** Dev/Ops, Tech-Leads.
|
||||||
|
**Scope:**
|
||||||
|
* **Ist-Stand (WP01–WP15):** Async Import, Smart Chunking, Edge-Erzeugung, Hybrider Retriever, RAG-Chat (Hybrid Router), Feedback Loop, Frontend, Draft Editor, Active Intelligence.
|
||||||
|
* **Roadmap (Ausblick):** Technische Skizze für Self-Tuning (WP08).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Die Import-Pipeline (Runbook)
|
||||||
|
|
||||||
|
Der Import ist der kritischste Prozess ("Data Ingestion"). Er muss **deterministisch** und **idempotent** sein. Wir nutzen `scripts/import_markdown.py` als zentralen Entrypoint.
|
||||||
|
|
||||||
|
### 2.1 Der 13-Schritte-Prozess (Async + Smart)
|
||||||
|
Seit v2.6 läuft der Import vollständig asynchron, nutzt intelligente Kantenvalidierung (Smart Edges) und drosselt sich selbst ("Traffic Control").
|
||||||
|
|
||||||
|
1. **Markdown lesen:** Rekursives Scannen des Vaults.
|
||||||
|
2. **Frontmatter extrahieren:** Validierung von Pflichtfeldern (`id`, `type`, `title`).
|
||||||
|
3. **Typauflösung:** Bestimmung des `type` via `types.yaml` (Prio: Frontmatter > Pfad > Default).
|
||||||
|
4. **Note-Payload generieren:** Erstellen des JSON-Objekts für `mindnet_notes`.
|
||||||
|
5. **Chunking anwenden:** Zerlegung des Textes basierend auf dem `chunk_profile` des Typs (z.B. `sliding_smart_edges`).
|
||||||
|
6. **Smart Edge Allocation (Neu in WP15):**
|
||||||
|
* Wenn in `types.yaml` aktiviert (`enable_smart_edge_allocation`):
|
||||||
|
* Der `SemanticAnalyzer` sendet jeden Chunk an das LLM.
|
||||||
|
* **Resilienz & Traffic Control:**
|
||||||
|
* **Priority:** Der Request nutzt `priority="background"`.
|
||||||
|
* **Semaphore:** Eine globale Semaphore (Limit: 2, konfigurierbar) verhindert System-Überlastung.
|
||||||
|
* **Retry & Backoff:** Bei Fehlern (Timeouts) wird bis zu 5-mal mit exponentieller Wartezeit wiederholt.
|
||||||
|
* **JSON Repair:** Der Analyzer erkennt fehlerhaftes JSON (z.B. Dict statt Liste) und repariert es automatisch.
|
||||||
|
* **Safety Fallback:** Schlagen alle Versuche fehl, werden die Kanten *allen* Chunks zugewiesen, um Datenverlust zu vermeiden.
|
||||||
|
* Ergebnis: Das LLM filtert irrelevante Links aus dem Chunk ("Broadcasting" verhindern).
|
||||||
|
7. **Inline-Kanten finden:** Parsing von `[[rel:...]]` im Fließtext.
|
||||||
|
8. **Callout-Kanten finden:** Parsing von `> [!edge]` Blöcken.
|
||||||
|
9. **Default-Edges erzeugen:** Anwendung der `edge_defaults` aus der Typ-Registry.
|
||||||
|
10. **Strukturkanten erzeugen:** `belongs_to`, `next`, `prev` (Sequenz).
|
||||||
|
11. **Embedding & Upsert (Async):**
|
||||||
|
* Generierung der Vektoren via `nomic-embed-text` (768 Dim).
|
||||||
|
12. **Strict Mode:** Der Prozess bricht sofort ab, wenn ein Embedding leer ist oder die Dimension `0` hat.
|
||||||
|
13. **Diagnose:** Automatischer Check der Integrität nach dem Lauf.
|
||||||
|
|
||||||
|
### 2.2 Standard-Betrieb (Inkrementell)
|
||||||
|
Für regelmäßige Updates (z.B. Cronjob). Erkennt Änderungen via Hash.
|
||||||
|
|
||||||
|
export QDRANT_URL="http://localhost:6333"
|
||||||
|
export COLLECTION_PREFIX="mindnet"
|
||||||
|
|
||||||
|
# Import starten (Apply = Schreiben, Purge = Sauberer Upsert)
|
||||||
|
# Nutzt das Venv der Produktionsumgebung
|
||||||
|
/home/llmadmin/mindnet/.venv/bin/python3 -m scripts.import_markdown \
|
||||||
|
--vault ./vault \
|
||||||
|
--prefix "$COLLECTION_PREFIX" \
|
||||||
|
--apply \
|
||||||
|
--purge-before-upsert \
|
||||||
|
--sync-deletes
|
||||||
|
|
||||||
|
* `--apply`: Ohne dieses Flag läuft ein Dry-Run (nur Simulation).
|
||||||
|
* `--purge-before-upsert`: Löscht vor dem Schreiben einer Note ihre alten Chunks/Edges. Essentiell, um "Geister-Chunks" zu vermeiden, wenn Text gekürzt wurde.
|
||||||
|
* `--sync-deletes`: Entfernt Notizen aus Qdrant, die im Vault gelöscht wurden.
|
||||||
|
|
||||||
|
### 2.3 Deployment & Restart (Systemd)
|
||||||
|
Nach einem Import oder Code-Update müssen die API-Prozesse neu gestartet werden.
|
||||||
|
|
||||||
|
# Neustart des Produktions-Services (API + UI)
|
||||||
|
sudo systemctl restart mindnet-prod
|
||||||
|
sudo systemctl restart mindnet-ui-prod
|
||||||
|
|
||||||
|
# Prüfung
|
||||||
|
sudo systemctl status mindnet-prod
|
||||||
|
|
||||||
|
### 2.4 Full Rebuild (Clean Slate)
|
||||||
|
Notwendig bei Änderungen an `types.yaml` (z.B. Smart Edges an/aus) oder beim Wechsel des Embedding-Modells.
|
||||||
|
|
||||||
|
**WICHTIG:** Vorher das Modell pullen, sonst schlägt der Import fehl!
|
||||||
|
|
||||||
|
# 0. Modell sicherstellen (WICHTIG für v2.4+)
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
|
||||||
|
# 1. Qdrant Collections löschen und neu anlegen (Wipe inkl. Schema 768d)
|
||||||
|
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
||||||
|
|
||||||
|
# 2. Vollständiger Import aller Dateien
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Chunking & Payload-Aufbau
|
||||||
|
|
||||||
|
Das Chunking ist profilbasiert und typgesteuert.
|
||||||
|
|
||||||
|
### 3.1 Chunk-Profile
|
||||||
|
In `types.yaml` definiert. Standard-Profile (in `chunk_config.py` implementiert):
|
||||||
|
* `sliding_short`: Max 128 Tokens (z.B. für Logs, Chats).
|
||||||
|
* `sliding_standard`: Max 512 Tokens (Standard für Massendaten).
|
||||||
|
* `sliding_smart_edges`: Sliding Window, optimiert für LLM-Analyse (Fließtext).
|
||||||
|
* `structured_smart_edges`: Trennt strikt an Überschriften (für strukturierte Daten).
|
||||||
|
|
||||||
|
### 3.2 Payload-Felder
|
||||||
|
Jeder Chunk erhält zwei Text-Felder:
|
||||||
|
* `text`: Der reine Inhalt des Chunks (ohne Overlap). Wird dem Nutzer angezeigt.
|
||||||
|
* `window`: Der Inhalt plus Overlap zu Vorgänger/Nachfolger. Wird für das Embedding genutzt (besserer Kontext).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Edge-Erzeugung (Die V2-Logik)
|
||||||
|
|
||||||
|
In v2.6 entstehen Kanten nach strenger Priorität.
|
||||||
|
|
||||||
|
### 4.1 Prioritäten & Provenance
|
||||||
|
Der Importer setzt `provenance`, `rule_id` und `confidence` automatisch:
|
||||||
|
|
||||||
|
| Priorität | Quelle | Syntax (Bsp.) | Rule ID | Confidence |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **1** | Inline | `[[rel:depends_on X]]` | `inline:rel` | ~0.95 |
|
||||||
|
| **2** | Callout | `> [!edge] related_to: [[X]]` | `callout:edge` | ~0.90 |
|
||||||
|
| **3** | Wikilink | `[[X]]` | `explicit:wikilink` | 1.00 |
|
||||||
|
| **4** | Smart | *(via LLM Filter)* | `smart:llm_filter` | 0.90 |
|
||||||
|
| **5** | Default | *(via types.yaml)* | `edge_defaults:...` | ~0.70 |
|
||||||
|
| **6** | Struktur | *(automatisch)* | `structure:...` | 1.00 |
|
||||||
|
|
||||||
|
### 4.2 Smart Edge Allocation (WP15)
|
||||||
|
Dieser Mechanismus löst das Problem, dass Chunks sonst alle Links der Note erben.
|
||||||
|
* **Prozess:** Der `SemanticAnalyzer` prüft jeden Chunk: "Ist Link X im Kontext von Chunk Y relevant?"
|
||||||
|
* **Ergebnis:** Kanten werden präzise an den Chunk gebunden, nicht global an die Note.
|
||||||
|
* **Steuerung:** Das Feature wird in `types.yaml` per Typ aktiviert (`enable_smart_edge_allocation: true`).
|
||||||
|
|
||||||
|
### 4.3 Typ-Defaults
|
||||||
|
Wenn in `types.yaml` für einen Typ `edge_defaults` definiert sind, werden diese **additiv** zu expliziten Links erzeugt.
|
||||||
|
* *Beispiel:* Note Typ `project` verlinkt `[[Tool A]]`.
|
||||||
|
* *Ergebnis:* Kante `references` (explizit) UND Kante `depends_on` (Default).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Retriever, Chat & Generation (RAG Pipeline)
|
||||||
|
|
||||||
|
Der Datenfluss endet nicht beim Finden. Er geht weiter bis zur Antwort.
|
||||||
|
|
||||||
|
### 5.1 Retrieval (Hybrid)
|
||||||
|
Der `/chat` Endpunkt nutzt **Hybrid Retrieval** (Semantic + Graph), um auch logisch verbundene, aber textlich unterschiedliche Notizen zu finden (z.B. Decisions zu einem Projekt).
|
||||||
|
|
||||||
|
### 5.2 Intent Router (WP06/07)
|
||||||
|
Der Request durchläuft den **Hybrid Router v5**:
|
||||||
|
1. **Question Detection:** Ist es eine Frage (`?`, W-Wörter)? -> RAG Modus. Interviews werden hier blockiert.
|
||||||
|
2. **Keyword Scan:** Enthält es Keywords aus `types.yaml` (Objekt, z.B. "Projekt") oder `decision_engine.yaml` (Action, z.B. "erstellen")? -> INTERVIEW Modus.
|
||||||
|
3. **LLM Fallback:** Wenn unklar, entscheidet das LLM.
|
||||||
|
|
||||||
|
### 5.3 Context Enrichment
|
||||||
|
Der Router (`chat.py`) reichert die gefundenen Chunks mit Metadaten an:
|
||||||
|
* **Typ-Injection:** `[DECISION]`, `[PROJECT]`.
|
||||||
|
* **Reasoning-Infos:** `(Score: 0.75)`.
|
||||||
|
|
||||||
|
### 5.4 Generation (LLM) mit Traffic Control
|
||||||
|
* **Engine:** Ollama (lokal).
|
||||||
|
* **Modell:** `phi3:mini` (Standard).
|
||||||
|
* **Prompting:** Template wird basierend auf Intent gewählt (`decision_template`, `interview_template` etc.).
|
||||||
|
* **Traffic Control:** Der `LLMService` unterscheidet:
|
||||||
|
* **Chat-Requests** (`priority="realtime"`) -> Sofortige Ausführung.
|
||||||
|
* **Import-Requests** (`priority="background"`) -> Gedrosselt durch Semaphore (Standard: 2).
|
||||||
|
|
||||||
|
### 5.5 Active Intelligence Pipeline (Neu in v2.4)
|
||||||
|
Ein paralleler Datenfluss im Frontend ("Draft Editor") zur Unterstützung des Autors.
|
||||||
|
1. **Trigger:** User klickt "Analyse starten" oder tippt.
|
||||||
|
2. **Service:** `ingest/analyze` (Backend).
|
||||||
|
3. **Discovery:**
|
||||||
|
* **Sliding Window:** Zerlegt Text in Abschnitte.
|
||||||
|
* **Embedding:** Vektorisiert Abschnitte via Nomic (Async).
|
||||||
|
* **Exact Match:** Sucht nach Aliases ("KI-Gedächtnis").
|
||||||
|
* **Matrix Logic:** Bestimmt Kanten-Typ (`experience` -> `based_on` -> `value`).
|
||||||
|
4. **Feedback:** UI zeigt Vorschläge (`[[rel:...]]`) zum Einfügen an.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Feedback & Lernen (WP04c)
|
||||||
|
|
||||||
|
Das System schreibt kontinuierlich Logs ("Data Flywheel"):
|
||||||
|
* `data/logs/search_history.jsonl`: Trainingsdaten (Query + Ergebnisse + Breakdown).
|
||||||
|
* `data/logs/feedback.jsonl`: Labels (User-Rating zur `query_id`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Quality Gates & Tests
|
||||||
|
|
||||||
|
Diese Tests garantieren die Stabilität der Pipeline.
|
||||||
|
|
||||||
|
### 7.1 Pflicht-Tests vor Commit
|
||||||
|
|
||||||
|
1. **Payload Dryrun (Schema-Check):**
|
||||||
|
Simuliert Import, prüft JSON-Schema Konformität.
|
||||||
|
|
||||||
|
python3 -m scripts.payload_dryrun --vault ./test_vault
|
||||||
|
|
||||||
|
2. **Full Edge Check (Graph-Integrität):**
|
||||||
|
Prüft Invarianten (z.B. `next` muss reziprok zu `prev` sein).
|
||||||
|
|
||||||
|
python3 -m scripts.edges_full_check
|
||||||
|
|
||||||
|
### 7.2 Smoke-Test (E2E)
|
||||||
|
Prüft am laufenden System (Prod oder Dev), ob Semantik, Graph und Feedback funktionieren.
|
||||||
|
|
||||||
|
# Retriever Test
|
||||||
|
python scripts/test_retriever_smoke.py --mode hybrid --top-k 5
|
||||||
|
|
||||||
|
# Intelligence Test (WP11)
|
||||||
|
curl -X POST "http://localhost:8002/ingest/analyze" -d '{"text": "mindnet", "type": "journal"}'
|
||||||
|
|
||||||
|
# Decision Engine Test (WP06)
|
||||||
|
python tests/test_wp06_decision.py -p 8002 -e EMPATHY -q "Alles ist grau"
|
||||||
|
|
||||||
|
# Feedback Test
|
||||||
|
python tests/test_feedback_smoke.py --url http://localhost:8001/query
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Ausblick & Roadmap (Technische Skizzen)
|
||||||
|
|
||||||
|
Wie entwickeln wir die Pipeline weiter?
|
||||||
|
|
||||||
|
### 8.1 WP-08: Self-Tuning (Skizze)
|
||||||
|
**Ziel:** Die Gewichte in `retriever.yaml` basierend auf `feedback.jsonl` optimieren.
|
||||||
|
**Ansatz:** Ein Offline-Learning-Skript `scripts/optimize_weights.py`.
|
||||||
|
1. **Load:** Liest `search_history.jsonl` und joint mit `feedback.jsonl` via `query_id`.
|
||||||
|
2. **Analyze:** Korrelation Scores vs. User-Rating.
|
||||||
|
3. **Optimize:** Vorschlag neuer Gewichte für `retriever.yaml`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 16. Workpackage Status (v2.6.0)
|
||||||
|
|
||||||
|
Aktueller Implementierungsstand der Module.
|
||||||
|
|
||||||
|
| WP | Titel | Status | Anmerkung |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **WP01** | Knowledge Design | 🟢 Live | Typen, Frontmatter definiert. |
|
||||||
|
| **WP02** | Chunking Strategy | 🟢 Live | Profilbasiertes Chunking aktiv. |
|
||||||
|
| **WP03** | Edge Logic / Import | 🟢 Live | Neue Importer-Pipeline mit Provenance. |
|
||||||
|
| **WP04a**| Retriever Scoring | 🟢 Live | Hybrider Score (Semantik + Graph). |
|
||||||
|
| **WP04b**| Explanation Layer | 🟢 Live | API liefert Reasons & Breakdown. |
|
||||||
|
| **WP04c**| Feedback Loop | 🟢 Live | Logging (JSONL) & Traceability aktiv. |
|
||||||
|
| **WP05** | Persönlichkeit / Chat | 🟢 Live | RAG-Integration mit Context Enrichment. |
|
||||||
|
| **WP06** | Decision Engine | 🟢 Live | Hybrid Router, Strategic Retrieval. |
|
||||||
|
| **WP07** | Interview Assistent | 🟢 Live | **One-Shot Extractor & Schemas aktiv.** |
|
||||||
|
| **WP08** | Self-Tuning | 🔴 Geplant | Auto-Adjustment der Gewichte. |
|
||||||
|
| **WP10** | Chat Interface | 🟢 Live | Web-Interface (Streamlit). |
|
||||||
|
| **WP10a**| Draft Editor | 🟢 Live | **Interaktives UI für WP07 Drafts.** |
|
||||||
|
| **WP11** | Backend Intelligence | 🟢 Live | **Async Ingestion, Nomic Embeddings, Matrix Logic.** |
|
||||||
|
| **WP15** | Smart Edge Allocation | 🟢 Live | **LLM-Filter & Traffic Control aktiv.** |
|
||||||
|
| **WP16** | Auto-Discovery | 🟡 Geplant | UX & Retrieval Tuning. |
|
||||||
|
| **WP17** | Conversational Memory | 🟡 Geplant | Dialog-Gedächtnis. |
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
# Mindnet v2.4 – User Guide
|
||||||
|
**Datei:** `docs/mindnet_user_guide_v2.6.md`
|
||||||
|
**Stand:** 2025-12-12
|
||||||
|
**Status:** **FINAL** (Inkl. Smart Edges, Hybrid Router v5 & Healing UI)
|
||||||
|
**Quellen:** `knowledge_design.md`, `wp04_retriever_scoring.md`, `Programmplan_V2.2.md`, `Handbuch.md`.
|
||||||
|
|
||||||
|
> **Willkommen bei Mindnet.**
|
||||||
|
> Dies ist dein persönliches Wissensnetzwerk und dein Digitaler Zwilling. Es hilft dir beim Erinnern, beim Entscheiden, beim Reflektieren und beim **Erstellen von Inhalten**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Was Mindnet für dich tut
|
||||||
|
|
||||||
|
Mindnet ist ein **assoziatives Gedächtnis** mit Persönlichkeit. Es unterscheidet sich von einer reinen Suche (wie Google) dadurch, dass es **kontextsensitiv** agiert.
|
||||||
|
|
||||||
|
### 1.1 Das Gedächtnis (Der Graph)
|
||||||
|
Wenn du nach "Projekt Alpha" suchst, findet Mindnet nicht nur das Dokument. Es findet auch:
|
||||||
|
* **Abhängigkeiten:** "Technologie X wird benötigt".
|
||||||
|
* **Entscheidungen:** "Warum nutzen wir X?".
|
||||||
|
* **Ähnliches:** "Projekt Beta war ähnlich".
|
||||||
|
* **Neu in v2.6 (Smart Edges):** Mindnet zeigt dir präzise Verknüpfungen an, die für den spezifischen Textabschnitt relevant sind, statt pauschal alle Links der Notiz anzuzeigen.
|
||||||
|
|
||||||
|
### 1.2 Der Zwilling (Die Personas)
|
||||||
|
Mindnet passt seinen Charakter dynamisch an deine Frage an:
|
||||||
|
1. **Der Bibliothekar (FACT):** Liefert präzise Fakten und Definitionen.
|
||||||
|
2. **Der Berater (DECISION):** Hilft dir beim Abwägen, basierend auf deinen Werten und Zielen.
|
||||||
|
3. **Der Spiegel (EMPATHY):** Hört zu und antwortet basierend auf deinen Erfahrungen ("Ich"-Perspektive).
|
||||||
|
4. **Der Analyst (INTERVIEW):** Hilft dir, neue Notizen zu entwerfen und strukturiert zu erfassen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Die Oberfläche (Web UI)
|
||||||
|
|
||||||
|
Seit Version 2.3.1 bedienst du Mindnet über eine grafische Oberfläche im Browser.
|
||||||
|
|
||||||
|
### 2.1 Der Chat-Bereich
|
||||||
|
* **Eingabe:** Unten findest du das Textfeld.
|
||||||
|
* **Intent-Badge:** Über jeder Antwort zeigt ein kleines Label (z.B. **⚖️ Intent: DECISION**), in welchem Modus das System arbeitet und ob dies durch ein Schlüsselwort oder die KI erkannt wurde.
|
||||||
|
* **Quellen-Karten:** Unter der Antwort findest du ausklappbare Karten ("Expanders").
|
||||||
|
* **Grüner Punkt:** Hohe Relevanz (Score > 0.8).
|
||||||
|
* **Gelber Punkt:** Mittlere Relevanz.
|
||||||
|
* **Klick darauf:** Zeigt den Textauszug und die **Begründung** ("Warum wurde das gefunden?").
|
||||||
|
|
||||||
|
### 2.2 Die Sidebar (Einstellungen & Verlauf)
|
||||||
|
* **Modus-Wahl:** Umschalten zwischen "💬 Chat" und "📝 Manueller Editor".
|
||||||
|
* *Neu in v2.4:* Der manuelle Editor speichert deine Eingaben auch beim Wechseln der Tabs ("State Resurrection").
|
||||||
|
* **Verlauf:** Die letzten Suchanfragen sind hier gelistet. Ein Klick führt die Suche erneut aus.
|
||||||
|
* **Settings:**
|
||||||
|
* **Top-K:** Wie viele Quellen sollen gelesen werden? (Standard: 5).
|
||||||
|
* **Explanation Layer:** Schaltet die "Warum"-Erklärungen an/aus.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Den Chat steuern (Intents)
|
||||||
|
|
||||||
|
Du steuerst die Persönlichkeit von Mindnet durch deine Wortwahl. Das System nutzt einen **Hybrid Router v5**, der intelligent zwischen Frage und Befehl unterscheidet.
|
||||||
|
|
||||||
|
### 3.1 Frage-Modus (Wissen abrufen)
|
||||||
|
Sobald du ein Fragezeichen `?` benutzt oder Wörter wie "Wer", "Wie", "Was", "Soll ich" verwendest, sucht Mindnet nach Antworten (**RAG**).
|
||||||
|
|
||||||
|
* **Entscheidung ("Soll ich?"):** Mindnet lädt deine **Werte** (`type: value`) und **Ziele** (`type: goal`) in den Kontext und prüft die Fakten dagegen.
|
||||||
|
* *Beispiel:* "Soll ich Tool X nutzen?" -> "Nein, Tool X speichert Daten in den USA. Das verstößt gegen dein Prinzip 'Privacy First' und dein Ziel 'Digitale Autarkie'."
|
||||||
|
* **Empathie ("Ich fühle..."):** Mindnet lädt deine **Erfahrungen** (`type: experience`) und **Glaubenssätze** (`type: belief`). Es antwortet verständnisvoll und zitiert deine eigenen Lektionen.
|
||||||
|
* *Beispiel:* "Ich bin frustriert." -> "Das erinnert mich an Projekt Y, da ging es uns ähnlich..."
|
||||||
|
|
||||||
|
### 3.2 Befehls-Modus (Wissen erfassen / Interview)
|
||||||
|
Wenn du keine Frage stellst, sondern eine Absicht äußerst, wechselt Mindnet in den **Interview-Modus**.
|
||||||
|
|
||||||
|
* **Auslöser:** "Neues Projekt", "Notiz erstellen", "Ich will etwas festhalten", "Neue Entscheidung dokumentieren".
|
||||||
|
* **Was passiert:** Mindnet sucht nicht im Archiv, sondern öffnet den **Draft-Editor**.
|
||||||
|
* **Beispiel:** "Neue Erfahrung: Streit am Recyclinghof." -> Das System erstellt sofort eine strukturierte Notiz mit den Feldern "Situation", "Reaktion" und "Learning".
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Ergebnisse interpretieren (Explanation Layer)
|
||||||
|
|
||||||
|
Mindnet liefert nicht einfach nur Treffer. Es liefert eine **Begründung** (Explanation), warum es etwas gefunden hat.
|
||||||
|
|
||||||
|
### 4.1 Die Gründe ("Reasons")
|
||||||
|
Öffne eine Quellen-Karte, um zu sehen:
|
||||||
|
* *"Hohe textuelle Übereinstimmung."* (Semantik)
|
||||||
|
* *"Bevorzugt aufgrund des Typs 'decision'."* (Wichtigkeit)
|
||||||
|
* *"Verweist auf 'Projekt X' via 'depends_on'."* (Graph-Kontext)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Feedback & Lernen
|
||||||
|
|
||||||
|
Mindnet wird schlauer, wenn du es pflegst. Nutze die Feedback-Funktionen im Chat:
|
||||||
|
|
||||||
|
### 5.1 Globales Feedback (Antwort-Qualität)
|
||||||
|
* **Wie:** Klicke auf die **Sterne (1-5)** unter der Antwort.
|
||||||
|
* **Bedeutung:** Bewertet, wie gut die generierte Antwort war (Prompting, Tonfall).
|
||||||
|
|
||||||
|
### 5.2 Granulares Feedback (Quellen-Relevanz)
|
||||||
|
* **Wie:** Klicke innerhalb einer Quellen-Karte auf die **Smileys (Faces)**.
|
||||||
|
* **Bedeutung:**
|
||||||
|
* 😞 (Sad): Diese Quelle ist irrelevant/falsch. (Senkt zukünftig das Gewicht).
|
||||||
|
* 😐 (Neutral): Okay, aber nicht entscheidend.
|
||||||
|
* 😀 (Grin): Das ist der perfekte Treffer! (Stärkt diesen Typ/Kante).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Neues Wissen beisteuern (Authoring)
|
||||||
|
|
||||||
|
Mindnet lebt von deinem Input. Du musst kein Techniker sein, um gutes Wissen zu designen. Siehe dazu das **Knowledge Design Manual** für Details.
|
||||||
|
|
||||||
|
### 6.1 Die Goldene Regel: "Verlinke semantisch"
|
||||||
|
Statt einfach nur `[[Link]]` zu schreiben, versuche zu sagen, *wie* es zusammenhängt.
|
||||||
|
* Hängt es davon ab? -> `[[rel:depends_on Ziel]]`
|
||||||
|
* Ist es ähnlich? -> `[[rel:similar_to Ziel]]`
|
||||||
|
|
||||||
|
### 6.2 Typen nutzen (Wichtig!)
|
||||||
|
Setze im Frontmatter deiner Notizen den richtigen Typ. Das ist der wichtigste Hebel für den Chat:
|
||||||
|
* Willst du, dass Mindnet etwas als **Regel** nutzt? -> `type: principle`
|
||||||
|
* Willst du, dass Mindnet dich an eine **Lektion** erinnert? -> `type: experience`
|
||||||
|
|
||||||
|
### 6.3 Der Interview-Assistent (Drafting)
|
||||||
|
Mindnet kann dir helfen, Markdown-Notizen zu schreiben.
|
||||||
|
|
||||||
|
1. **Start:** Schreibe im Chat: *"Ich möchte ein neues Projekt 'Apollo' starten, Ziel ist die Mondlandung."*
|
||||||
|
2. **Generierung:** Mindnet erkennt den Wunsch (`INTERVIEW`), analysiert den Satz und erstellt **sofort** einen Entwurf.
|
||||||
|
3. **Editor:** Die UI wechselt von der Chat-Blase zu einem **Draft-Editor**.
|
||||||
|
* Du siehst das generierte Frontmatter (`type: project`, `status: draft`).
|
||||||
|
* **Healing UI (v2.5):** Falls das LLM Syntax-Fehler gemacht hat (z.B. fehlendes `---`), hat der Editor das bereits automatisch repariert.
|
||||||
|
* Du siehst den Body-Text mit Platzhaltern (`[TODO]`), wo Infos fehlten (z.B. Stakeholder).
|
||||||
|
4. **Finalisierung:** Ergänze die fehlenden Infos direkt im Editor und klicke auf **Download** oder **Kopieren**.
|
||||||
|
5. **Speichern:** Klicke auf "💾 Speichern". Die Notiz landet sofort im Vault und im Index.
|
||||||
|
|
||||||
|
### 6.4 Der Intelligence-Workflow (Neu in v2.4)
|
||||||
|
Wenn du Texte im **manuellen Editor** schreibst, unterstützt dich Mindnet aktiv bei der Vernetzung:
|
||||||
|
|
||||||
|
1. **Schreiben:** Tippe deinen Text im Tab **"✏️ Inhalt"**.
|
||||||
|
2. **Analysieren:** Wechsle zum Tab **"🧠 Intelligence"** und klicke auf **"🔍 Analyse starten"**. Das System scannt deinen Text (Vektor-Suche & Exact Match).
|
||||||
|
3. **Vorschläge nutzen:**
|
||||||
|
* **Exakte Treffer:** Das System erkennt Begriffe wie "KI-Gedächtnis" automatisch als Alias für "Mindnet (System)".
|
||||||
|
* **Semantische Treffer:** Das System findet inhaltlich verwandte Notizen.
|
||||||
|
* **Klick auf "➕ Einfügen":** Fügt den Link (z.B. `[[rel:related_to Mindnet]]`) an der Cursor-Position oder am Ende ein.
|
||||||
|
4. **Speichern:** Klicke auf "💾 Speichern & Indizieren". Der Text wird sofort in den Vault geschrieben und in Qdrant indiziert.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Architecture Snapshot v2.2.1
|
||||||
|
**Stand:** Nach Abschluss von WP-04c
|
||||||
|
**Kontext:** Wichtig für WP-05 Entwicklung.
|
||||||
|
|
||||||
|
## 1. Neue Komponenten (Seit v2.2.0)
|
||||||
|
|
||||||
|
### A. Feedback Service (`app/services/feedback_service.py`)
|
||||||
|
- **Zweck:** Logging von Trainingsdaten für späteres Self-Tuning (WP-08).
|
||||||
|
- **Storage:** Lokale JSONL-Dateien in `data/logs/` (Append-Only).
|
||||||
|
- `search_history.jsonl`: Query + Snapshot der Ergebnisse (Scores).
|
||||||
|
- `feedback.jsonl`: User-Rating zu spezifischer `node_id`.
|
||||||
|
|
||||||
|
### B. Explanation Layer (`app/core/retriever.py`)
|
||||||
|
- **Logik:** Der Retriever berechnet nicht nur Scores, sondern generiert `Explanation`-Objekte.
|
||||||
|
- **Graph:** `Subgraph` (in `graph_adapter.py`) führt jetzt auch `reverse_adj` (Incoming Edges), um zu erklären, warum ein Knoten wichtig ist ("Referenziert von...").
|
||||||
|
|
||||||
|
### C. DTOs (`app/models/dto.py`)
|
||||||
|
Das Datenmodell wurde massiv erweitert. Wichtige Klassen für WP-05:
|
||||||
|
- `QueryResponse`: Enthält jetzt `query_id` (UUID).
|
||||||
|
- `QueryHit`: Enthält optional `explanation` (Typ `Explanation`).
|
||||||
|
- `FeedbackRequest`: Für den Feedback-Loop.
|
||||||
|
|
||||||
|
## 2. Implikationen für WP-05 (Chat)
|
||||||
|
|
||||||
|
1. **Logging:** Auch der neue `/chat` Endpoint sollte idealerweise die `query_id` loggen oder nutzen, um Konsistenz zu wahren.
|
||||||
|
2. **DTO-Nutzung:** Der Chat-Service wird intern den Retriever aufrufen. Er muss mit den `QueryHit`-Objekten arbeiten, um den Kontext für das LLM zu bauen.
|
||||||
|
3. **Config:** Die Persönlichkeit wird in `config/prompts.yaml` definiert (Late Binding), nicht im Python-Code hardcodiert.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Changelog — WP-03 Type-Registry (2025-11-08)
|
||||||
|
|
||||||
|
## Added
|
||||||
|
- `app/core/type_registry.py` — Loader & Helper (cached), robust Fallbacks.
|
||||||
|
- `config/types.yaml` — Beispiel-Registry (version 1.0).
|
||||||
|
- `scripts/import_markdown.py` v3.8.0 — Registry-Integration:
|
||||||
|
- typvalidierung (unbekannt → `concept`, Warnung)
|
||||||
|
- `chunk_profile` → an `make_chunk_payloads(...)`
|
||||||
|
- `retriever_weight` → persistiert im Note-Payload
|
||||||
|
- `edge_defaults["references"]` schaltet Note-Scope-Refs additiv ein
|
||||||
|
- `app/core/chunk_payload.py` v2.3.0 — optionales `chunk_profile` für
|
||||||
|
synthetische Overlaps (keine Schemaänderung).
|
||||||
|
- `app/core/derive_edges.py` v1.5.0 — Type-Registry aktiviert note-scope
|
||||||
|
References/Backlinks additiv.
|
||||||
|
|
||||||
|
## Changed
|
||||||
|
- Keine Breaking Changes. Alle CLI-Flags, ENV-Variablen und Collection-
|
||||||
|
Prefix-Logik bleiben unverändert.
|
||||||
|
|
||||||
|
## Removed
|
||||||
|
- N/A
|
||||||
@@ -0,0 +1,349 @@
|
|||||||
|
# 📘 Mindnet Skript-Handbuch (aktualisiert)
|
||||||
|
|
||||||
|
Dieses Handbuch dokumentiert die Skripte und Tests für das Projekt **mindnet Wissensnetzwerk**.
|
||||||
|
Es beschreibt Zweck, Parameter, typische Aufrufe sowie aktuelle Verhaltensweisen (Hash-Modi, Parser-Robustheit, `window`/`text`-Trennung in Chunks, Export-Fixes).
|
||||||
|
Alle Beispiele sind so formatiert, dass sie direkt kopierbar sind. **Code/CLI-Beispiele sind eingerückt**, damit die Markdown-Darstellung nicht abbricht.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0) Umgebung & Konfiguration
|
||||||
|
|
||||||
|
**Wichtige ENV-Variablen**
|
||||||
|
|
||||||
|
- `QDRANT_URL` – z. B. `http://localhost:6333`
|
||||||
|
- `QDRANT_API_KEY` – API-Key (falls aktiviert)
|
||||||
|
- `COLLECTION_PREFIX` – Prefix der drei Collections, Standard: `mindnet` → `mindnet_notes`, `mindnet_chunks`, `mindnet_edges`
|
||||||
|
- `VECTOR_DIM` – Embedding-Dimension (Chunks), Standard: `384`
|
||||||
|
|
||||||
|
**Hash-Vergleich & Änderungserkennung**
|
||||||
|
|
||||||
|
- `MINDNET_HASH_COMPARE` – steuert, **welcher Anteil** für „changed“ verglichen wird
|
||||||
|
Werte: `Body` (Standard), `Frontmatter`, `Full`
|
||||||
|
- `MINDNET_HASH_SOURCE` – Quelle: `parsed` (Standard), `raw`, `file`
|
||||||
|
- `MINDNET_HASH_NORMALIZE` – Normalisierung: `canonical` (Standard) oder `none`
|
||||||
|
|
||||||
|
**Beispiel (nur Body berücksichtigen, kanonisch, geparst):**
|
||||||
|
|
||||||
|
export MINDNET_HASH_COMPARE=Body
|
||||||
|
export MINDNET_HASH_SOURCE=parsed
|
||||||
|
export MINDNET_HASH_NORMALIZE=canonical
|
||||||
|
source .venv/bin/activate
|
||||||
|
|
||||||
|
**Baseline-Signaturen (mehrere Modi):**
|
||||||
|
Der Importer kann **Signaturen aller Modi** (Body/Frontmatter/Full) vorhalten, damit spätere Moduswechsel deterministisch sind (keine „Mass-Changes“). Siehe `--baseline-modes` unter **Importer**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1) Vault anlegen (für Tests)
|
||||||
|
|
||||||
|
### `scripts/make_test_vault.py`
|
||||||
|
|
||||||
|
**Zweck:**
|
||||||
|
Erstellt einen kleinen, nachvollziehbaren Test-Vault mit Markdown-Dateien.
|
||||||
|
Szenarien: offene Links, nachträgliche Anlage fehlender Notes, geänderte Chunk-Grenzen.
|
||||||
|
|
||||||
|
**Parameter:**
|
||||||
|
- `--out PATH` : Zielverzeichnis (Default: `./test_vault`)
|
||||||
|
- `--force` : Existierenden Ordner löschen und neu anlegen
|
||||||
|
- `--with-missing` : Optional – auch die `missing-note` gleich anlegen
|
||||||
|
|
||||||
|
**Hinweise für Tests**
|
||||||
|
1. Erster Import (dry-run oder `--apply`): Es gibt einen „leeren“ Link `[[missing-note]]`.
|
||||||
|
2. Lege danach eine Datei für „missing-note“ an (mit gleicher `id` im YAML) und importiere erneut:
|
||||||
|
→ Erwartung: Edges für ehemals leeren Link werden korrekt nachgezogen (`references` + `backlink`).
|
||||||
|
3. Ändere den Body von `exp-one.md` so, dass andere Chunk-Grenzen entstehen und importiere erneut:
|
||||||
|
→ Erwartung: Chunks/Edges/Note werden für betroffene Noten aktualisiert.
|
||||||
|
|
||||||
|
**Kompatibilität:**
|
||||||
|
- `note.schema.json`: `created`/`updated` sind Strings.
|
||||||
|
|
||||||
|
**Beispiele:**
|
||||||
|
|
||||||
|
python3 -m scripts.make_test_vault --out ./test_vault --force
|
||||||
|
python3 -m scripts.make_test_vault --out ./test_vault --force --with-missing
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2) Import in Qdrant
|
||||||
|
|
||||||
|
### `scripts/import_markdown.py`
|
||||||
|
|
||||||
|
**Zweck:**
|
||||||
|
Importiert Notes/Chunks/Edges aus einem Vault nach Qdrant.
|
||||||
|
- validiert Frontmatter
|
||||||
|
- chunked Inhalte + Embeddings
|
||||||
|
- erzeugt Edges (`references`, `references_at`, `backlink`, `next`, `prev`, `belongs_to`)
|
||||||
|
- erkennt geänderte Dateien **modusgesteuert** (Body/Frontmatter/Full)
|
||||||
|
- optional: Purge der alten Chunks/Edges pro Note
|
||||||
|
|
||||||
|
**Parameter:**
|
||||||
|
- `--vault PATH` : (Pflicht) Vault-Verzeichnis
|
||||||
|
- `--apply` : Änderungen wirklich durchführen (ohne: Dry-Run)
|
||||||
|
- `--purge-before-upsert` : Vor Upsert alte Chunks/Edges **nur der geänderten Notes** löschen
|
||||||
|
- `--prefix STR` : überschreibt `COLLECTION_PREFIX`
|
||||||
|
- `--note-id ID` : nur eine bestimmte Note importieren
|
||||||
|
- `--note-scope-refs` : zusätzlich **note-weite** `references` erzeugen (nicht nur chunk-weise)
|
||||||
|
- `--baseline-modes` : berechne & speichere Hash-Signaturen für **alle** Modi (`Body`, `Frontmatter`, `Full`) als Baseline
|
||||||
|
|
||||||
|
**Erwartetes Verhalten:**
|
||||||
|
- Unveränderte Notes → `"changed": false`, Entscheidung: `apply-skip-unchanged` (bei `--apply`)
|
||||||
|
- Geänderte Notes → `"changed": true` (abhängig von `MINDNET_HASH_COMPARE`)
|
||||||
|
- Idempotenz: mehrfacher Lauf ohne Änderungen erzeugt **keine** neuen Punkte
|
||||||
|
- Baseline: Bei `--baseline-modes` erscheinen Felder wie `hash_signature`, `hash_fulltext`, ggf. `hash_frontmatter` und `needs_baseline_for_mode: false` bei Folgeläufen.
|
||||||
|
|
||||||
|
**Beispiele:**
|
||||||
|
|
||||||
|
# Dry-Run (zeigt Änderungen, schreibt NICHT)
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix mindnet
|
||||||
|
|
||||||
|
# Apply + gezielte Vorreinigung pro geänderter Note
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix mindnet --apply --purge-before-upsert
|
||||||
|
|
||||||
|
# Baseline-Signaturen aller Modi vorhalten
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --apply --baseline-modes
|
||||||
|
|
||||||
|
**Hash-Modi in der Praxis:**
|
||||||
|
- `MINDNET_HASH_COMPARE=Body` → Änderungen im Body werden erkannt; reine Frontmatter-Änderungen bleiben **ohne Effekt**.
|
||||||
|
- `MINDNET_HASH_COMPARE=Frontmatter` → nur Frontmatter maßgeblich.
|
||||||
|
- `MINDNET_HASH_COMPARE=Full` → beide Anteile zählen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3) Konsistenzprüfungen
|
||||||
|
|
||||||
|
### `scripts/audit_vault_vs_qdrant.py`
|
||||||
|
|
||||||
|
**Zweck:**
|
||||||
|
Vergleicht Vault-Inhalte mit Qdrant.
|
||||||
|
- Zählt Notes/Chunks/Edges
|
||||||
|
- Verifiziert Anzahl Wikilinks vs. Edges
|
||||||
|
- Meldet Deltas (z. B. `references` im Vault vs. in Qdrant)
|
||||||
|
|
||||||
|
**Parameter:**
|
||||||
|
- `--vault PATH` : Vault-Verzeichnis
|
||||||
|
- `--prefix STR` : Prefix für Qdrant-Collections (Default: `mindnet`)
|
||||||
|
|
||||||
|
**Beispiel:**
|
||||||
|
|
||||||
|
python3 -m scripts.audit_vault_vs_qdrant --vault ./vault --prefix mindnet
|
||||||
|
|
||||||
|
### `scripts/validate_edges.py`
|
||||||
|
|
||||||
|
**Zweck:**
|
||||||
|
Prüft die Edges-Collection in Qdrant.
|
||||||
|
- Zählt Edges pro Typ (`references`, `references_at`, `backlink`, `next`, `prev`, `belongs_to`)
|
||||||
|
- Kontrolliert Invarianten (z. B. jede `references` hat einen `backlink`)
|
||||||
|
- Listet `unresolved` Edges auf
|
||||||
|
|
||||||
|
**Parameter:**
|
||||||
|
- `--prefix STR` : Prefix für Qdrant-Collections
|
||||||
|
- `--details` : Detailausgabe mit Beispielen
|
||||||
|
|
||||||
|
**Beispiel:**
|
||||||
|
|
||||||
|
python3 -m scripts.validate_edges --prefix mindnet --details
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4) Export Qdrant → Markdown (Vault)
|
||||||
|
|
||||||
|
### `scripts/export_markdown.py`
|
||||||
|
|
||||||
|
**Zweck:**
|
||||||
|
Exportiert Notes + rekonstruierten Body in einen Zielordner.
|
||||||
|
- Pfade werden **relativ** aus `note.payload.path` abgeleitet (führende `/` entfernt, Backslashes → Slashes; Unicode-NFC empfohlen)
|
||||||
|
- **Body-Rekonstruktion** priorisiert:
|
||||||
|
1. `fulltext` (falls in Note-Payload vorhanden)
|
||||||
|
2. sonst **Chunks**: Sortierung `seq` → `chunk_index` → Nummer in `chunk_id`; **nur `text`** (Overlap bereits entfernt)
|
||||||
|
- `--prefix` (CLI) wird unterstützt (oder ENV `COLLECTION_PREFIX`)
|
||||||
|
|
||||||
|
**Parameter:**
|
||||||
|
- `--out PATH` : Ziel-Root (muss existieren)
|
||||||
|
- `--overwrite` : vorhandene Dateien überschreiben
|
||||||
|
- `--note-id ID` : nur eine bestimmte Note exportieren
|
||||||
|
- `--prefix STR` : überschreibt `COLLECTION_PREFIX`
|
||||||
|
- `--include-edges {none,footer,yaml}` *(optional, falls aktiviert)*: Edges als YAML-Liste im Frontmatter oder im Footer beilegen
|
||||||
|
|
||||||
|
**Beispiele:**
|
||||||
|
|
||||||
|
export COLLECTION_PREFIX="mindnet"
|
||||||
|
python3 -m scripts.export_markdown --out ./_exportVault
|
||||||
|
|
||||||
|
# Nur eine bestimmte Note:
|
||||||
|
python3 -m scripts.export_markdown --out ./_exportVault --note-id 20250821-architektur-ki-trainerassistent-761cfe
|
||||||
|
|
||||||
|
# Existierende Dateien überschreiben:
|
||||||
|
python3 -m scripts.export_markdown --out ./_exportVault --overwrite
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5) Qdrant zurücksetzen
|
||||||
|
|
||||||
|
### `scripts/reset_qdrant.py`
|
||||||
|
|
||||||
|
**Zweck:**
|
||||||
|
Setzt die Qdrant-Collections zurück.
|
||||||
|
- `wipe`: löscht Collections komplett (inkl. Schema)
|
||||||
|
- `truncate`: löscht nur Inhalte, behält Collections
|
||||||
|
- `truncate-edges`: löscht nur Punkte in `*_edges`
|
||||||
|
|
||||||
|
**Parameter:**
|
||||||
|
- `--mode {wipe,truncate,truncate-edges}`
|
||||||
|
- `--prefix STR` : Prefix der Collections (Default: `mindnet`)
|
||||||
|
- `--yes` : Automatische Bestätigung
|
||||||
|
- `--dry-run` : Nur anzeigen, nicht ausführen
|
||||||
|
|
||||||
|
**Beispiele:**
|
||||||
|
|
||||||
|
python3 -m scripts.reset_qdrant --mode truncate-edges --prefix mindnet
|
||||||
|
python3 -m scripts.reset_qdrant --mode truncate --prefix mindnet --yes
|
||||||
|
python3 -m scripts.reset_qdrant --mode wipe --prefix mindnet --yes
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6) Diagnose & Tools
|
||||||
|
|
||||||
|
### `scripts/diagnose_changed.py`
|
||||||
|
|
||||||
|
**Zweck:**
|
||||||
|
Prüft, ob Datei-Hashes (`sha256`) mit gespeicherten `hash_*` in Qdrant übereinstimmen.
|
||||||
|
Hilft, wenn der Importer zu viele Dateien als „changed“ erkennt oder Moduswechsel geplant sind.
|
||||||
|
|
||||||
|
**Parameter:**
|
||||||
|
- `--vault PATH` : Vault-Verzeichnis
|
||||||
|
- `--prefix STR` : Prefix (Default: `mindnet`)
|
||||||
|
- `--note-id ID` : Nur bestimmte Note prüfen
|
||||||
|
- `--all` : Alle Notes prüfen
|
||||||
|
|
||||||
|
**Beispiel:**
|
||||||
|
|
||||||
|
python3 -m scripts.diagnose_changed --vault ./vault --prefix mindnet --all
|
||||||
|
|
||||||
|
### `scripts/resolve_unresolved_references.py`
|
||||||
|
|
||||||
|
**Zweck:**
|
||||||
|
Prüft offene Wikilinks (`status=unresolved`) und fügt Edges nach, wenn inzwischen passende Notizen existieren.
|
||||||
|
Ersetzt `unresolved` durch gültige `references`/`backlink`.
|
||||||
|
|
||||||
|
**Parameter:**
|
||||||
|
- `--prefix STR` : Prefix für Qdrant-Collections
|
||||||
|
- `--apply` : Änderungen wirklich ausführen (sonst nur Vorschau)
|
||||||
|
|
||||||
|
**Beispiele:**
|
||||||
|
|
||||||
|
python3 -m scripts.resolve_unresolved_references --prefix mindnet
|
||||||
|
python3 -m scripts.resolve_unresolved_references --prefix mindnet --apply
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7) Parser-Verhalten (robust & abwärtskompatibel)
|
||||||
|
|
||||||
|
- Der Parser liest Markdown **fehlertolerant** (UTF-8 mit Fallbacks), extrahiert YAML-Frontmatter und Body.
|
||||||
|
- Keine harten Abhängigkeiten von alten Regex-Symbolen (`FRONTMATTER_RE` entfällt zugunsten interner Marker).
|
||||||
|
- `read_markdown(path)` gibt `(frontmatter_dict, body_str)` zurück.
|
||||||
|
- **Sonderfälle aus Fremd-Tools** (z. B. Silverbullet-Dateien wie `CONFIG.md`, `index.md`) werden **nicht importiert**, sofern sie nicht zum Vault gehören.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8) Chunk-Payload (Fenster vs. Kern)
|
||||||
|
|
||||||
|
- **`window`** = kontextualisierter Fenster-Text (mit linkem Overlap)
|
||||||
|
- **`text`** = **Kerntext** ohne das vom vorherigen Chunk übernommene Overlap
|
||||||
|
- Felder: `start`, `end`, `overlap_left`, `overlap_right`, `chunk_index`, `seq`, `path`, `section_title`, `section_path`, `token_count` (falls vorhanden)
|
||||||
|
- **Fallback (synthetisch):** Falls der Chunker **keinen** Overlap-Fenstertext liefert, erzeugt die Payload-Schicht Fenster mit typgerechtem Overlap aus `chunk_config.get_sizes(type)['overlap']` (unterer Wert).
|
||||||
|
- **Edges** werden aus `window` abgeleitet (um Links an Chunk-Grenzen nicht zu verlieren); der **Export** rekonstruiert den Body aus `text` (Overlap-frei).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9) Edge-Modell & IDs
|
||||||
|
|
||||||
|
- Collections:
|
||||||
|
`*_notes` (optional Vektor / Nullvektor), `*_chunks` (384-d Embeddings), `*_edges` (1-d Dummy-Vektor)
|
||||||
|
- **Deterministische IDs** (UUIDv5 / stabile Keys):
|
||||||
|
- `note_id` stabil aus Frontmatter/Slug
|
||||||
|
- `chunk_id` i. d. R. `note_id#<n>`
|
||||||
|
- `edge_id` stabil aus `(kind, source_id, target_id, seq)`
|
||||||
|
- Kantenarten: `references`, `references_at`, `backlink`, `next`, `prev`, `belongs_to`
|
||||||
|
- `unresolved` wird gekennzeichnet und kann per Resolver später aufgelöst werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10) Tests & Qualitätssicherung
|
||||||
|
|
||||||
|
**Tests unter `tests/`**
|
||||||
|
|
||||||
|
- `check_chunks_window_vs_text.py` – vergleicht je Chunk `window` vs. `text`, schätzt Overlap
|
||||||
|
- `compare_vaults.py` – rekursiver Vault-Vergleich (Body/Frontmatter/All, Key: auto/id/title/filename), Unicode-NFC-robust
|
||||||
|
- `verify_chunks_integrity.py` – prüft, ob Rekonstruktion aus Chunks (`text`) zu `fulltext` bzw. zum Vault-Body passt
|
||||||
|
- `list_md_seen_by_importer.py` – zeigt, welche `.md` der Importer sieht (inkl. Gründe/Filter)
|
||||||
|
- `inspect_one_note.py` – Parser-Diagnose für eine konkrete Datei
|
||||||
|
- `run_e2e_roundtrip.sh` – End-to-End: Reset → Import → Audit → (optional) Hash-Reporter → Export → Vergleich
|
||||||
|
|
||||||
|
**Typische Aufrufe:**
|
||||||
|
|
||||||
|
# Overlap-Qualität (Fenster vs. Kern)
|
||||||
|
python3 tests/check_chunks_window_vs_text.py --prefix "$COLLECTION_PREFIX"
|
||||||
|
|
||||||
|
# Roundtrip-Vergleich (rekursiv)
|
||||||
|
python3 tests/compare_vaults.py --src ./vault --dst ./_exportVault --focus body
|
||||||
|
|
||||||
|
# Chunks-Rekonstruktion (gegen Vault-Body)
|
||||||
|
python3 tests/verify_chunks_integrity.py --prefix "$COLLECTION_PREFIX" --vault ./vault
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11) Typische Workflows
|
||||||
|
|
||||||
|
**A) Clean-Start mit Test-Vault**
|
||||||
|
|
||||||
|
python3 -m scripts.make_test_vault --out ./test_vault --force
|
||||||
|
python3 -m scripts.reset_qdrant --mode truncate --prefix mindnet --yes
|
||||||
|
python3 -m scripts.import_markdown --vault ./test_vault --prefix mindnet
|
||||||
|
python3 -m scripts.import_markdown --vault ./test_vault --prefix mindnet --apply --purge-before-upsert
|
||||||
|
python3 -m scripts.audit_vault_vs_qdrant --vault ./test_vault --prefix mindnet
|
||||||
|
python3 -m scripts.validate_edges --prefix mindnet --details
|
||||||
|
export COLLECTION_PREFIX="mindnet"
|
||||||
|
python3 -m scripts.export_markdown --out ./_exportVault
|
||||||
|
|
||||||
|
**B) Änderungs-Propagation & Idempotenz**
|
||||||
|
|
||||||
|
python3 -m scripts.import_markdown --vault ./test_vault --prefix mindnet
|
||||||
|
python3 -m scripts.import_markdown --vault ./test_vault --prefix mindnet --apply --purge-before-upsert
|
||||||
|
python3 -m scripts.audit_vault_vs_qdrant --vault ./test_vault --prefix mindnet
|
||||||
|
python3 -m scripts.validate_edges --prefix mindnet --details
|
||||||
|
python3 -m scripts.import_markdown --vault ./test_vault --prefix mindnet
|
||||||
|
|
||||||
|
**C) Unresolved Links lösen**
|
||||||
|
|
||||||
|
python3 -m scripts.import_markdown --vault ./test_vault --apply --prefix mindnet
|
||||||
|
python3 -m scripts.resolve_unresolved_references --prefix mindnet --apply
|
||||||
|
python3 -m scripts.validate_edges --prefix mindnet --details
|
||||||
|
|
||||||
|
**D) Export & Roundtrip (Produkt-Vault)**
|
||||||
|
|
||||||
|
export COLLECTION_PREFIX="mindnet"
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --apply --purge-before-upsert --prefix "$COLLECTION_PREFIX"
|
||||||
|
python3 -m scripts.export_markdown --out ./_exportVault --prefix "$COLLECTION_PREFIX"
|
||||||
|
python3 tests/compare_vaults.py --src ./vault --dst ./_exportVault --focus body
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12) Troubleshooting (kurz)
|
||||||
|
|
||||||
|
- **Importer markiert alle als changed (Moduswechsel):**
|
||||||
|
→ `--baseline-modes` einmalig laufen lassen; sicherstellen: `MINDNET_HASH_COMPARE` passt zum Ziel.
|
||||||
|
- **Edges verschwinden / nur 1 Edge sichtbar:**
|
||||||
|
→ `app/core/qdrant_points.py` muss Edge-Payload normalisieren (Schema Alt/Neu) und `edge_id` eindeutig bilden.
|
||||||
|
- **Export ohne Body / falsches Zielverzeichnis:**
|
||||||
|
→ Exporter nutzt relativierte Pfade und rekonstruiert Body aus `fulltext` oder Chunks (`text`). ENV/CLI `--prefix` beachten.
|
||||||
|
- **Parser-Fehler (UTF-8):**
|
||||||
|
→ Neuer Parser arbeitet mit Fallbacks; mit `tests/inspect_one_note.py` prüfen, was ankommt.
|
||||||
|
- **„Fehlende“ Dateien im Vergleich:**
|
||||||
|
→ Prüfe, ob Dateien **wirklich zum Vault gehören** (z. B. Silverbullet-Artefakte `CONFIG.md`, `index.md` ausblenden).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13) Hinweise zu Silverbullet-Dateien
|
||||||
|
|
||||||
|
- Dateien wie `CONFIG.md` oder `index.md`, die **nicht** zum inhaltlichen Vault gehören, werden **nicht importiert** und erscheinen daher nicht im Export-Roundtrip.
|
||||||
|
- Diese Dateien bitte vom produktiven Vault trennen oder im Vergleich (`tests/compare_vaults.py
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# Kurzhandbuch — Type-Registry (WP-03)
|
||||||
|
|
||||||
|
## Zweck
|
||||||
|
Die Type-Registry macht den `type:`-Wert im Frontmatter maschinenlesbar
|
||||||
|
und steuert:
|
||||||
|
- Chunk-Profile (indirekt über Overlap bei fensterlosen Chunks),
|
||||||
|
- typabhängige Default-Kanten (hier: Aktivierung von Note-Scope-References),
|
||||||
|
- optionale Retriever-Gewichtungen (`retriever_weight`) für WP‑04.
|
||||||
|
|
||||||
|
## Aktivierung
|
||||||
|
1. Legen Sie `config/types.yaml` an (siehe Beispiel in diesem Paket).
|
||||||
|
2. Starten Sie Import/Server neu. Die Registry wird beim Prozessstart
|
||||||
|
geladen und gecached.
|
||||||
|
|
||||||
|
Fehlt die Datei oder ist sie defekt, bleibt das System voll funktionsfähig
|
||||||
|
(der Typ `concept` wird genutzt; Warnhinweis im Log).
|
||||||
|
|
||||||
|
## Schema (Beispiel)
|
||||||
|
```yaml
|
||||||
|
version: 1.0
|
||||||
|
types:
|
||||||
|
concept:
|
||||||
|
chunk_profile: long
|
||||||
|
edge_defaults: ["references", "related_to"]
|
||||||
|
retriever_weight: 1.0
|
||||||
|
task:
|
||||||
|
chunk_profile: short
|
||||||
|
edge_defaults: ["depends_on", "belongs_to"]
|
||||||
|
retriever_weight: 0.8
|
||||||
|
experience:
|
||||||
|
chunk_profile: medium
|
||||||
|
edge_defaults: ["derived_from", "inspired_by"]
|
||||||
|
retriever_weight: 0.9
|
||||||
|
project:
|
||||||
|
chunk_profile: medium
|
||||||
|
edge_defaults: ["references", "depends_on"]
|
||||||
|
retriever_weight: 0.95
|
||||||
|
```
|
||||||
|
|
||||||
|
## Verhalten
|
||||||
|
- **Chunking**: Die eigentliche Chunk-Länge bleibt weiterhin typabhängig über
|
||||||
|
`chunk_config.get_sizes(type)` gesteuert. Falls der Chunker keine Fenster
|
||||||
|
mit Overlap liefert, werden in `chunk_payload` synthetische Fenster erzeugt.
|
||||||
|
Hier greift das `chunk_profile` mit folgenden Overlap-Empfehlungen:
|
||||||
|
- short → (20,30), medium → (40,60), long → (60,80).
|
||||||
|
- **Edges**: Enthält `edge_defaults` den Eintrag `references`, werden Note-
|
||||||
|
Scope-References/Backlinks additiv aktiviert (kein Abbruch, keine Duplikate).
|
||||||
|
Weitere Kantenarten bleiben unverändert.
|
||||||
|
- **Retriever**: `retriever_weight` wird in der Note gespeichert und kann von
|
||||||
|
WP‑04 im Ranking/Scoring berücksichtigt werden.
|
||||||
|
|
||||||
|
## Tests / Validierung
|
||||||
|
- Dry-Run:
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.import_markdown --vault ./test_vault
|
||||||
|
```
|
||||||
|
- Vollimport + Purge:
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.import_markdown --vault ./test_vault --apply --purge-before-upsert --prefix "$COLLECTION_PREFIX"
|
||||||
|
```
|
||||||
|
- Chunks-Qualität (Window vs Text):
|
||||||
|
```bash
|
||||||
|
python3 tests/check_chunks_window_vs_text.py --prefix "$COLLECTION_PREFIX"
|
||||||
|
```
|
||||||
|
- Roundtrip:
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.export_markdown --out ./_exportVault --prefix "$COLLECTION_PREFIX"
|
||||||
|
python3 tests/compare_vaults.py --src ./test_vault --dst ./_exportVault --focus body
|
||||||
|
```
|
||||||
|
|
||||||
|
## Fallbacks & Robustheit
|
||||||
|
- Registry nicht vorhanden/ungültig → `concept`, Warnung, keine Abbrüche.
|
||||||
|
- Alle bestehenden ENV/Flags bleiben identisch.
|
||||||
|
- Keine Änderungen an Punkt-IDs, Feldern oder Vektoren.
|
||||||
File renamed without changes.
@@ -0,0 +1,96 @@
|
|||||||
|
# mindnet Retriever (WP-04 / Step 4a) – Kurz-Dokumentation
|
||||||
|
|
||||||
|
## 1. Überblick
|
||||||
|
|
||||||
|
Der Retriever besteht aus:
|
||||||
|
|
||||||
|
- **Semantic Retriever** (`semantic_retrieve`)
|
||||||
|
- **Hybrid Retriever** (`hybrid_retrieve`)
|
||||||
|
- Qdrant-Backend (`*_chunks`, `*_edges`)
|
||||||
|
- optionaler Edge-Expansion über `graph_adapter.expand`
|
||||||
|
|
||||||
|
Die API nutzt das bestehende `/query`-Endpoint (FastAPI), das `QueryRequest` und `QueryResponse` aus `app.models.dto` verwendet.
|
||||||
|
|
||||||
|
## 2. Scoring-Formel
|
||||||
|
|
||||||
|
Pro Treffer werden folgende Komponenten geführt:
|
||||||
|
|
||||||
|
- `semantic_score` – direkt aus Qdrant (Cosine/Euclidean, je nach Collection)
|
||||||
|
- `retriever_weight` – aus Chunk-Payload (`types.yaml` / Frontmatter)
|
||||||
|
- `edge_bonus` – Bonus aus dem Subgraph (z. B. Zahl der eingehenden/ausgehenden Edges, Beziehungstypen)
|
||||||
|
- `centrality_bonus` – Bonus aus einer einfachen Zentralitäts-Heuristik im Subgraph
|
||||||
|
|
||||||
|
Aktuelle Formel (Step 4a):
|
||||||
|
|
||||||
|
```text
|
||||||
|
total_score = semantic_score * max(retriever_weight, 0.0)
|
||||||
|
+ edge_bonus
|
||||||
|
+ centrality_bonus
|
||||||
|
```
|
||||||
|
|
||||||
|
Die Sortierung der Ergebnisse erfolgt absteigend nach `total_score`.
|
||||||
|
|
||||||
|
## 3. Modi
|
||||||
|
|
||||||
|
### 3.1 Semantic Mode
|
||||||
|
|
||||||
|
- Funktion: `semantic_retrieve`
|
||||||
|
- Request-Feld `mode = "semantic"`
|
||||||
|
- Keine Edge-Expansion, kein Graph-Call.
|
||||||
|
- Kandidaten nur aus Vektorsuche in `<prefix>_chunks`.
|
||||||
|
|
||||||
|
### 3.2 Hybrid Mode
|
||||||
|
|
||||||
|
- Funktion: `hybrid_retrieve`
|
||||||
|
- Request-Feld `mode = "hybrid"`
|
||||||
|
- Schritte:
|
||||||
|
1. Semantische Chunk-Suche wie im Semantic Mode
|
||||||
|
2. Falls `expand.depth > 0` gesetzt ist:
|
||||||
|
- Seeds = `chunk_id` (Fallback: `note_id`) der Treffer
|
||||||
|
- Aufruf `graph_adapter.expand(client, prefix, seed_ids, depth, edge_types)`
|
||||||
|
- Ergebnis-Subgraph liefert `edge_bonus` und `centrality_bonus` pro Node
|
||||||
|
3. Scores werden nach obiger Formel kombiniert.
|
||||||
|
|
||||||
|
## 4. Request-Struktur (JSON)
|
||||||
|
|
||||||
|
Beispiel-Hybrid-Request:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mode": "hybrid",
|
||||||
|
"query": "embeddings und qdrant",
|
||||||
|
"top_k": 10,
|
||||||
|
"expand": {
|
||||||
|
"depth": 1,
|
||||||
|
"edge_types": ["references", "depends_on"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Minimaler Semantic-Request:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mode": "semantic",
|
||||||
|
"query": "karate trainingsplan",
|
||||||
|
"top_k": 5
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5. Smoke-Test
|
||||||
|
|
||||||
|
Für einen schnellen End-to-End-Test kann folgendes Skript verwendet werden:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python scripts/test_retriever_smoke.py --query "karate" --mode hybrid --expand-depth 1 --top-k 5
|
||||||
|
```
|
||||||
|
|
||||||
|
Das Skript ruft `/query` auf, wertet Statuscode und JSON-Antwort aus und zeigt die Scores der Top-K-Treffer an.
|
||||||
|
|
||||||
|
## 6. Tests
|
||||||
|
|
||||||
|
Die wichtigsten Tests für den Retriever sind:
|
||||||
|
|
||||||
|
- `tests/test_retriever_basic.py` – Basisfunktion (Semantic + Hybrid)
|
||||||
|
- `tests/test_retriever_weight.py` – Einfluss von `retriever_weight` auf das Ranking
|
||||||
|
- `tests/test_retriever_edges.py` – Einfluss von Edge-/Centrality-Boni im Hybrid-Modus
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
# mindnet v2.2 – Knowledge Design Manual
|
||||||
|
**Datei:** `docs/mindnet_knowledge_design_manual_v2.2.md`
|
||||||
|
**Stand:** 2025-12-09
|
||||||
|
**Status:** **FINAL** (Integrierter Stand WP01–WP06)
|
||||||
|
**Quellen:** `knowledge_design.md`, `TYPE_REGISTRY_MANUAL.md`, `chunking_strategy.md`, `mindnet_functional_architecture.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ⚡ Die 5 Goldenen Regeln (TL;DR)
|
||||||
|
|
||||||
|
Damit Mindnet als dein Digitaler Zwilling funktioniert, beachte beim Schreiben diese Grundsätze:
|
||||||
|
|
||||||
|
1. **Atomare Gedanken:** Eine Notiz = Ein Thema. Wenn du über zwei Projekte schreibst, mach zwei Notizen draus.
|
||||||
|
2. **Explizite Typen:** Setze immer den `type` im Frontmatter. Mindnet behandelt eine `decision` ("Wir machen X") völlig anders als ein `concept` ("Was ist X").
|
||||||
|
3. **Semantische Links:** Schreibe nicht nur `[[Link]]`, sondern `[[rel:depends_on Link]]`. Sag dem System *wie* Dinge zusammenhängen.
|
||||||
|
4. **Werte & Ziele definieren:** Damit die **Decision Engine** dich beraten kann, musst du deine Kriterien (`type: value`, `type: goal`) explizit als Notizen anlegen.
|
||||||
|
5. **Emotionales Bridging:** Damit die **Empathie** funktioniert, nutze in Erfahrungsberichten (`type: experience`) emotionale Schlüsselwörter ("Krise", "Freude", "Angst"), damit der Vektor-Retriever sie bei Gefühls-Anfragen findet.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Zweck & Scope
|
||||||
|
|
||||||
|
Dieses Handbuch ist die **primäre Arbeitsanweisung** für dich als Mindmaster (Owner) und alle Autoren, die Inhalte im mindnet-Vault erstellen.
|
||||||
|
|
||||||
|
### 1.1 Zielsetzung
|
||||||
|
Mindnet ist mehr als eine Dokumentablage. Es ist ein vernetztes System, das deine Persönlichkeit, Entscheidungen und Erfahrungen abbildet.
|
||||||
|
Seit Version 2.3.1 verfügt Mindnet über:
|
||||||
|
* **Hybrid Router:** Das System erkennt, ob du Fakten, Entscheidungen oder Empathie brauchst.
|
||||||
|
* **Context Intelligence:** Das System lädt je nach Situation unterschiedliche Notiz-Typen (z.B. Werte bei Entscheidungen).
|
||||||
|
|
||||||
|
### 1.2 Der Vault als „Source of Truth“
|
||||||
|
Die Markdown-Dateien in deinem Vault sind die **einzige Quelle der Wahrheit**.
|
||||||
|
* Mindnet importiert diesen Zustand deterministisch in die Datenbank (Qdrant).
|
||||||
|
* Änderungen an IDs, Typen oder Inhalten müssen **immer** im Markdown erfolgen, niemals direkt in der Datenbank.
|
||||||
|
* Was nicht im Markdown steht (z. B. implizites Wissen im Kopf), existiert für das System nicht.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Note-Struktur & Frontmatter
|
||||||
|
|
||||||
|
Jede Notiz benötigt einen YAML-Header (Frontmatter) am Dateianfang. Dieser Block macht die Notiz maschinenlesbar.
|
||||||
|
|
||||||
|
### 2.1 Pflichtfelder
|
||||||
|
Jede Datei muss mindestens folgende Felder enthalten, um korrekt verarbeitet zu werden:
|
||||||
|
|
||||||
|
---
|
||||||
|
id: 20251110-projekt-alpha-8a9b2c # Eindeutige Kennung (YYYYMMDD-slug)
|
||||||
|
title: Projekt Alpha # Sprechender Titel (wird in Suchergebnissen angezeigt)
|
||||||
|
type: project # Steuert Verarbeitung & Vernetzung (siehe Kap. 3)
|
||||||
|
status: active # Status (z.B. draft, active, archived)
|
||||||
|
created: 2025-11-10 # Erstellungsdatum (ISO 8601 oder YYYY-MM-DD)
|
||||||
|
updated: 2025-12-07 # Letzte Änderung
|
||||||
|
tags: [ki, entwicklung] # Taxonomie für Filterung
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.2 Optionale Felder
|
||||||
|
Diese Felder sind technisch nicht zwingend, aber für bestimmte Typen sinnvoll:
|
||||||
|
|
||||||
|
lang: de # Sprache (Default: de)
|
||||||
|
aliases: [Alpha Projekt, Project A] # Synonyme für die Suche
|
||||||
|
visibility: internal # internal (default), public, private
|
||||||
|
|
||||||
|
> **Hinweis:** Felder wie `retriever_weight` oder `chunk_profile` sollten **nicht** mehr manuell im Frontmatter gesetzt werden. Diese werden zentral über den `type` gesteuert (siehe Kap. 3), um die Wartbarkeit zu sichern.
|
||||||
|
|
||||||
|
### 2.3 Empfehlungen für IDs und Pfade
|
||||||
|
|
||||||
|
**Die ID (Identifikator):**
|
||||||
|
* Muss global eindeutig und **stabil** sein.
|
||||||
|
* Darf sich nicht ändern, wenn die Datei umbenannt oder verschoben wird.
|
||||||
|
* **Empfehlung:** `YYYYMMDD-slug-hash` (z. B. `20231027-vektor-db-a1b2`). Dies garantiert Eindeutigkeit und Chronologie.
|
||||||
|
|
||||||
|
**Dateinamen & Pfade:**
|
||||||
|
* Pfade dienen der menschlichen Ordnung (Ordnerstruktur), sind für Mindnet aber sekundär.
|
||||||
|
* Dateinamen sollten dem Titel entsprechen (`Projekt Alpha.md`) oder dem Slug (`projekt-alpha.md`).
|
||||||
|
* Sonderzeichen vermeiden (außer Bindestrich und Unterstrich).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Note-Typen & Typ-Registry
|
||||||
|
|
||||||
|
Der `type` ist der wichtigste Hebel im Knowledge Design. Er steuert nicht nur das Gewicht bei der Suche, sondern seit WP-06 auch, **wann** eine Notiz aktiv in den Chat geholt wird ("Strategic Retrieval").
|
||||||
|
|
||||||
|
### 3.1 Übersicht der Kern-Typen
|
||||||
|
|
||||||
|
Mindnet unterscheidet verschiedene Wissensarten. Wähle den Typ, der die **Rolle** der Notiz am besten beschreibt:
|
||||||
|
|
||||||
|
| Typ | Beschreibung & Einsatzzweck | Rolle im Chat (Intent) |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **`concept`** | Fachbegriffe, Theorien. Zeitloses Wissen. | **FACT** (Basiswissen) |
|
||||||
|
| **`project`** | Ein Vorhaben mit Ziel, Dauer und Aufgaben. | **FACT / DECISION** (Kontext) |
|
||||||
|
| **`experience`** | Persönliche Erfahrung, Lektion oder Erkenntnis. | **EMPATHY** (Spiegelung) |
|
||||||
|
| **`decision`** | Eine bewusst getroffene Entscheidung (ADR). | **DECISION** (Begründung "Warum") |
|
||||||
|
| **`value`** | Ein persönlicher Wert oder ein Prinzip. | **DECISION** (Moralischer Kompass) |
|
||||||
|
| **`goal`** | Ein strategisches Ziel (kurz- oder langfristig). | **DECISION** (Abgleich) |
|
||||||
|
| **`person`** | Eine reale Person (Netzwerk, Autor). | **FACT** |
|
||||||
|
| **`journal`** | Zeitbezogener Log-Eintrag, Daily Note. | **FACT** (Historie) |
|
||||||
|
| **`source`** | Externe Quelle (Buch, PDF, Artikel). | **FACT** (Faktenbasis) |
|
||||||
|
|
||||||
|
### 3.2 Zusammenspiel mit `types.yaml`
|
||||||
|
|
||||||
|
Der `type` steuert im Hintergrund drei technische Mechanismen:
|
||||||
|
|
||||||
|
1. **`retriever_weight` (Wichtigkeit):**
|
||||||
|
* Ein `concept` (0.6) wiegt weniger als ein `project` (0.97) oder eine `decision` (1.0).
|
||||||
|
* **Warum?** Bei einer Suche nach "Datenbank" soll Mindnet bevorzugt deine *Entscheidung* ("Warum wir X nutzen") anzeigen.
|
||||||
|
2. **`chunk_profile` (Textzerlegung):**
|
||||||
|
* `journal` (short): Wird fein zerlegt.
|
||||||
|
* `project` (long): Längere Kontext-Fenster.
|
||||||
|
3. **`edge_defaults` (Automatische Vernetzung):**
|
||||||
|
* Mindnet ergänzt automatisch Kanten.
|
||||||
|
* Beispiel: Ein Link in einem `project` wird automatisch als `depends_on` (Abhängigkeit) interpretiert.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Edges & Referenzen in Notes
|
||||||
|
|
||||||
|
Um aus isolierten Dateien ein **Netzwerk** zu machen, nutzen wir Verlinkungen. In Version 2.2 sind diese Verlinkungen die Basis für den **Hybrid Retriever** (Suche über Nachbarn).
|
||||||
|
|
||||||
|
### 4.1 Wikilinks (Die Basis-Referenz)
|
||||||
|
Der klassische Obsidian-Link.
|
||||||
|
|
||||||
|
Wir nutzen [[Qdrant]] als Vektordatenbank.
|
||||||
|
|
||||||
|
* **Bedeutung:** "Diese Notiz erwähnt Qdrant."
|
||||||
|
* **Edge-Typ:** `references`
|
||||||
|
|
||||||
|
### 4.2 Inline-Relationen (Semantische Verknüpfung)
|
||||||
|
Dies ist die **mächtigste** Methode. Du sagst dem System explizit, **wie** Dinge zusammenhängen.
|
||||||
|
|
||||||
|
Daher [[rel:depends_on Qdrant]].
|
||||||
|
Dieses Konzept ist [[rel:similar_to Pinecone]].
|
||||||
|
|
||||||
|
* **Syntax:** `[[rel:RELATION ZIEL]]`.
|
||||||
|
* **Gültige Relationen:**
|
||||||
|
* `depends_on`: Hängt ab von / Benötigt. (Trigger für hohe Graph-Relevanz).
|
||||||
|
* `similar_to`: Ähnelt / Ist vergleichbar mit.
|
||||||
|
* `related_to`: Hat zu tun mit (allgemein).
|
||||||
|
* `caused_by`: Wurde verursacht durch.
|
||||||
|
* `solves`: Löst (Problem).
|
||||||
|
|
||||||
|
### 4.3 Callout-Edges (Kuratierte Listen)
|
||||||
|
Für Zusammenfassungen oder "Siehe auch"-Blöcke am Ende einer Notiz.
|
||||||
|
|
||||||
|
> [!edge] related_to: [[Vector Embeddings]] [[AI Agents]]
|
||||||
|
|
||||||
|
* **Funktion:** Erzeugt `related_to`-Kanten zu allen genannten Zielen in dieser Zeile.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Schreiben für den KI-Zwilling (New in v2.3)
|
||||||
|
|
||||||
|
Damit der **RAG-Chat (WP05/06)** nicht nur dumm Fakten wiedergibt, sondern dich berät, musst du "Futter" für die Decision Engine und das Empathie-Modul liefern.
|
||||||
|
|
||||||
|
### 5.1 Futter für die Decision Engine (`DECISION`)
|
||||||
|
Das System soll abwägen: "Passt Tool X zu mir?". Dazu muss es wissen, was "Du" bist.
|
||||||
|
|
||||||
|
**Best Practice: Werte definieren**
|
||||||
|
Erstelle Notizen mit `type: value`.
|
||||||
|
|
||||||
|
---
|
||||||
|
type: value
|
||||||
|
title: Prinzip: Datensparsamkeit
|
||||||
|
---
|
||||||
|
# Prinzip: Datensparsamkeit
|
||||||
|
Wir speichern nur das Minimum an Daten. Cloud-Uploads persönlicher Daten sind verboten, es sei denn, sie sind E2E-verschlüsselt.
|
||||||
|
|
||||||
|
**Best Practice: Ziele definieren**
|
||||||
|
Erstelle Notizen mit `type: goal`.
|
||||||
|
|
||||||
|
---
|
||||||
|
type: goal
|
||||||
|
title: Ziel: Unabhängigkeit 2026
|
||||||
|
---
|
||||||
|
# Ziel: Unabhängigkeit 2026
|
||||||
|
Bis Ende 2026 wollen wir alle SaaS-Abos durch Self-Hosted Lösungen ersetzt haben.
|
||||||
|
|
||||||
|
*Effekt:* Wenn du fragst "Soll ich Notion nutzen?", lädt die Engine diese beiden Notizen und antwortet: *"Nein, Notion ist SaaS und nicht E2E-verschlüsselt. Das verletzt dein Prinzip der Datensparsamkeit und dein Ziel der Unabhängigkeit."*
|
||||||
|
|
||||||
|
### 5.2 Futter für den Empathie-Modus (`EMPATHY`)
|
||||||
|
Das System soll dich verstehen, wenn du sagst: "Alles ist grau." Dazu braucht es deine Resonanzerfahrungen.
|
||||||
|
|
||||||
|
**Best Practice: Erfahrungen & Bridging**
|
||||||
|
Erstelle Notizen mit `type: experience`. Nutze im Text **emotionale Brückenwörter**, damit der Retriever auch bei abstrakten Gefühlen ("grau") einen Treffer landet.
|
||||||
|
|
||||||
|
---
|
||||||
|
type: experience
|
||||||
|
title: Erfahrung: Der Durchbruch nach der Krise
|
||||||
|
tags: [krise, hoffnung, grau, angst]
|
||||||
|
---
|
||||||
|
# Erfahrung: Der Durchbruch nach der Krise
|
||||||
|
Es gibt Projektphasen, da wirkt alles **sinnlos** und **grau**.
|
||||||
|
Ich habe gelernt: Das ist oft das Zeichen kurz vor dem Durchbruch.
|
||||||
|
Mein Mantra in solchen Zeiten: "Einfach weitermachen, der Nebel lichtet sich."
|
||||||
|
|
||||||
|
*Effekt:* Wenn du im Chat jammerst ("Alles ist sinnlos"), findet das System diese Notiz und spiegelt dir deine eigene Erfahrung zurück.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Best Practices & Beispiele (Klassik)
|
||||||
|
|
||||||
|
### 6.1 Beispiel: Projekt-Notiz
|
||||||
|
Projekte profitieren von `depends_on`, um Abhängigkeiten zu klären.
|
||||||
|
|
||||||
|
---
|
||||||
|
id: 20251115-proj-mindnet
|
||||||
|
title: Mindnet Implementierung
|
||||||
|
type: project
|
||||||
|
status: active
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet Implementierung
|
||||||
|
|
||||||
|
Wir bauen ein persönliches Wissensnetz.
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
Wir nutzen [[rel:depends_on Qdrant]] für die Vektorsuche und [[rel:depends_on FastAPI]] für das Backend.
|
||||||
|
|
||||||
|
## Architektur
|
||||||
|
Das Konzept basiert auf [[RAG Architecture]]. (Automatisch 'depends_on' durch Typ-Default).
|
||||||
|
|
||||||
|
### 6.2 Beispiel: Entscheidung (Decision Record)
|
||||||
|
Entscheidungen sind hoch gewichtet (`retriever_weight: 1.0`).
|
||||||
|
|
||||||
|
---
|
||||||
|
id: 20251120-adr-vektordb
|
||||||
|
title: ADR: Wahl von Qdrant
|
||||||
|
type: decision
|
||||||
|
status: final
|
||||||
|
tags: [architektur, db]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Entscheidung: Qdrant
|
||||||
|
|
||||||
|
Wir haben uns für Qdrant entschieden.
|
||||||
|
|
||||||
|
## Alternativen
|
||||||
|
Wir haben auch [[rel:similar_to Pinecone]] und [[rel:similar_to Weaviate]] betrachtet.
|
||||||
|
|
||||||
|
## Begründung
|
||||||
|
Qdrant erlaubt lokalen Betrieb und [[rel:solves Payload Filtering Requirements]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Langfristige Stabilität & Virtual Schema Layer
|
||||||
|
|
||||||
|
Mindnet ist auf Langlebigkeit ausgelegt.
|
||||||
|
|
||||||
|
### 7.1 Das "Virtual Schema" Prinzip
|
||||||
|
Wir vermeiden es, Logik in den Markdown-Dateien hart zu kodieren.
|
||||||
|
* Statt in jeder Notiz zu schreiben `chunk_size: 500`, schreiben wir nur `type: essay`.
|
||||||
|
* Wie groß ein Chunk für ein Essay ist, definieren wir in der Konfiguration (`types.yaml`).
|
||||||
|
|
||||||
|
### 7.2 Was bedeutet das für dich?
|
||||||
|
* Du kannst dich auf den Inhalt konzentrieren.
|
||||||
|
* Wenn wir in Zukunft (WP08) basierend auf Feedback lernen, dass "Projekte" noch wichtiger sind, ändern wir **eine Zeile** in der Konfiguration, und das gesamte System passt sich beim nächsten Import an.
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
# mindnet v2 – Implementierungs-Playbook & Handover (Side‑by‑Side zu v1)
|
||||||
|
*Stand:* 2025-11-10 08:03
|
||||||
|
*Autor:* ChatGPT (Projekt‑Handover)
|
||||||
|
*Zweck:* Vollständige, ausführbare Anleitung zur Weiterentwicklung von **mindnet** auf eine versionierte, testbare v2‑Architektur (neben v1), inklusive Prompt für den Folgethread, Akzeptanzkriterien, Dateiliste, Test‑ und Rollback‑Pläne.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0) Kontext & Zielbild (kurz)
|
||||||
|
- **Mission:** Persönliches Wissensnetz, das langfristig die eigene Persönlichkeit, Erfahrungen und Entscheidungslogik abbildet; später nachvollziehbare Erklärungen für Familie/Nachwelt.
|
||||||
|
- **Heutiger Stand (v1):** `mindnet_notes` in Qdrant vorhanden; **Chunks** und **Edges** bisher nur teilweise/nicht konsistent; Edge‑Defaults („1 Dot“) vorhanden, aber Ziele teils nicht materialisiert. Importskripte: `import_markdown.py`, `edges.py` (historisch).
|
||||||
|
- **Ziel (v2):**
|
||||||
|
- **Collections:** `mindnet_notes_v2`, `mindnet_chunks_v2`, `mindnet_edges_v2` (saubere Payload‑Schemata + Indizes).
|
||||||
|
- **Chunker v2:** Block/Heading‑aware, Ziel 900–1200 Zeichen, Überlappung 120–180, deterministische `chunk_id`s.
|
||||||
|
- **Edge‑Builder v2:** Reihenfolge: **explicit → rule → default_resolved → default**; saubere `provenance`.
|
||||||
|
- **Importer‑Pipeline v2:** Parse → Chunk → Edge → Embeddings → Batch‑Upsert + Payload‑Indexpflege + Snapshots.
|
||||||
|
- **Policies:** Privacy/Recency/Type‑Gewichte als **Konfiguration** (YAML + JSON‑Schema), nicht hart im Code.
|
||||||
|
- **Observability:** FastAPI + OpenTelemetry (Tracing/Metrics); Import‑Reports (CSV/JSON).
|
||||||
|
- **Side‑by‑Side:** v2 **parallel** zu v1; kein Big‑Bang.
|
||||||
|
|
||||||
|
> **Warum so?** Qdrant‑Payload‑Indizes/Filter → schnelle, erklärbare Selektionen; Snapshots → betriebssicheres Rollback; OTel → Nachvollziehbarkeit; YAML/JSON‑Schema → Validierbarkeit & Stabilität.
|
||||||
|
|
||||||
|
### 0.1 Aktueller Implementierungsstand (2025-11-18)
|
||||||
|
|
||||||
|
- Es existiert eine produktive mindnet-Instanz mit den Collections:
|
||||||
|
- `${prefix}_notes`
|
||||||
|
- `${prefix}_chunks`
|
||||||
|
- `${prefix}_edges`
|
||||||
|
- Import-Pipeline:
|
||||||
|
- `scripts/import_markdown.py` erzeugt Notes, Chunks und Edges vollständig.
|
||||||
|
- `types.yaml` definiert per Note-Typ:
|
||||||
|
- `retriever_weight`
|
||||||
|
- `chunk_profile`
|
||||||
|
- `edge_defaults` (z. B. `depends_on`, `related_to`).
|
||||||
|
- Edges:
|
||||||
|
- Strukturkanten: `belongs_to`, `next`, `prev`
|
||||||
|
- Explizite Kanten aus Wikilinks: `kind="references"`, `rule_id="explicit:wikilink"`
|
||||||
|
- Typbasierte Default-Kanten aus `edge_defaults`: `rule_id="edge_defaults:<type>:<relation>"`
|
||||||
|
- Inline-Kanten im Format `[[rel:<relation> <Zielnote>]]` mit `rule_id="inline:rel"`
|
||||||
|
- alle Edges tragen eine `confidence` im Bereich `[0,1]` als Hinweis für spätere Ranking-Logiken.
|
||||||
|
- Tests:
|
||||||
|
- `tests/test_edges_smoke.py`, `tests/test_edges_all.py` und `scripts/edges_full_check.py` validieren Counts, Konsistenz (`belongs_to == chunks`, `next/prev`-Ketten, keine Duplikate) und Provenienz-Zählungen (`explicit`, `defaults`, `inline`, `structure`).
|
||||||
|
- Offene Punkte:
|
||||||
|
- Mehrere Ziele in einer Inline-Relation (`rel: similar_to [[A]] [[B]]`) sind noch nicht implementiert.
|
||||||
|
- Retrieval-Service nutzt die neuen Edges und Weights bisher nur teilweise; ein edge-bewusster Retriever ist als nächster Schritt geplant.
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1) Datenmodelle (Schemata, v2)
|
||||||
|
Die tatsächlichen JSON‑Schemata (2020‑12) werden im Repo abgelegt und in CI validiert.
|
||||||
|
|
||||||
|
### 1.1 note.schema.json
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
|
"$id": "https://example.org/mindnet/note.schema.json",
|
||||||
|
"type": "object",
|
||||||
|
"required": ["id", "title", "type", "privacy", "created", "hash_body"],
|
||||||
|
"properties": {
|
||||||
|
"id": { "type": "string", "pattern": "^[a-zA-Z0-9_-]+$" },
|
||||||
|
"title": { "type": "string", "minLength": 1 },
|
||||||
|
"type": { "type": "string" },
|
||||||
|
"privacy": { "type": "string", "enum": ["public","internal","private"] },
|
||||||
|
"created": { "type": "string", "format": "date-time" },
|
||||||
|
"modified": { "type": "string", "format": "date-time" },
|
||||||
|
"tags": { "type": "array", "items": { "type": "string" } },
|
||||||
|
"lang": { "type": "string", "default": "de" },
|
||||||
|
"source_path": { "type": "string" },
|
||||||
|
"source_collection": { "type": "string" },
|
||||||
|
"hash_body": { "type": "string" },
|
||||||
|
"hash_frontmatter": { "type": "string" },
|
||||||
|
"token_count": { "type": "integer", "minimum": 0 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.2 chunk.schema.json
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
|
"$id": "https://example.org/mindnet/chunk.schema.json",
|
||||||
|
"type": "object",
|
||||||
|
"required": ["chunk_id","note_id","text","ord"],
|
||||||
|
"properties": {
|
||||||
|
"chunk_id": { "type": "string", "pattern": "^[a-zA-Z0-9_-]+#c\d{4}$" },
|
||||||
|
"note_id": { "type": "string" },
|
||||||
|
"text": { "type": "string" },
|
||||||
|
"ord": { "type": "integer", "minimum": 0 },
|
||||||
|
"span_char_start": { "type": "integer", "minimum": 0 },
|
||||||
|
"span_char_end": { "type": "integer", "minimum": 0 },
|
||||||
|
"heading_path": { "type": "array", "items": { "type": "string" } },
|
||||||
|
"section_title": { "type": "string" },
|
||||||
|
"tokens_start": { "type": "integer", "minimum": 0 },
|
||||||
|
"tokens_end": { "type": "integer", "minimum": 0 },
|
||||||
|
"embeddings_version": { "type": "string" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.3 edge.schema.json
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
|
"$id": "https://example.org/mindnet/edge.schema.json",
|
||||||
|
"type": "object",
|
||||||
|
"required": ["edge_id","src_note_id","relation","provenance"],
|
||||||
|
"properties": {
|
||||||
|
"edge_id": { "type": "string" },
|
||||||
|
"src_note_id": { "type": "string" },
|
||||||
|
"src_chunk_id": { "type": "string" },
|
||||||
|
"dst_note_id": { "type": "string" },
|
||||||
|
"dst_chunk_id": { "type": "string" },
|
||||||
|
"relation": { "type": "string" },
|
||||||
|
"evidence_spans":{ "type": "array", "items": {"type":"object","properties":{"chunk_id":{"type":"string"},"span":[{"type":"integer"},{"type":"integer"}]]} },
|
||||||
|
"provenance": { "type": "string", "enum": ["explicit","rule","default_resolved","default"] },
|
||||||
|
"rule_id": { "type": "string" },
|
||||||
|
"confidence": { "type": "number", "minimum": 0, "maximum": 1 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.4 default_edge.schema.json
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
|
"$id": "https://example.org/mindnet/default_edge.schema.json",
|
||||||
|
"type": "object",
|
||||||
|
"required": ["src_note_id","relation","target_kind"],
|
||||||
|
"properties": {
|
||||||
|
"src_note_id": { "type": "string" },
|
||||||
|
"relation": { "type": "string" },
|
||||||
|
"target_kind": { "type": "string" },
|
||||||
|
"when": { "type": "string" },
|
||||||
|
"strength_hint":{ "type": "number", "minimum": 0, "maximum": 1 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2) Qdrant: Collections & Indizes (v2)
|
||||||
|
Anlegen **neben** v1:
|
||||||
|
- `mindnet_notes_v2` (Payload‑Index: `type, privacy, created, modified, tags, source_path`)
|
||||||
|
- `mindnet_chunks_v2` (Payload‑Index: `note_id, ord, heading_path`)
|
||||||
|
- `mindnet_edges_v2` (Payload‑Index: `src_note_id, dst_note_id, relation, provenance`)
|
||||||
|
|
||||||
|
> Snapshots für Backups/Restore einplanen (Runbook siehe unten).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3) Import‑Pipeline v2 – Module & Flags
|
||||||
|
- **Chunker v2** (`chunking/block_chunker.py`): `target_len=1000`, `overlap=150`, `respect_headings=True`, `min_chunk_len=600`, `max_chunk_len=1400`, `chunk_id = f\"{note_id}#c{ordinal:04d}\"`
|
||||||
|
- **Edge‑Builder v2** (`graph/edge_builder_v2.py`): Reihenfolge **explicit → rule → default_resolved → default**, `provenance` korrekt setzen.
|
||||||
|
- **Importer** (`scripts/import_markdown.py` erweitern oder `scripts/import_markdown_v2.py`):
|
||||||
|
Flags: `--schema v2`, `--chunker v2`, `--edges v2`, `--dry-run`, `--apply`, `--prefix "$COLLECTION_PREFIX"`.
|
||||||
|
|
||||||
|
**Beispiel‑Run (dry‑run):**
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.import_markdown_v2 --vault ./vault --schema v2 --chunker v2 --edges v2 --dry-run --prefix "$COLLECTION_PREFIX"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Apply:**
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.import_markdown_v2 --vault ./vault --schema v2 --chunker v2 --edges v2 --apply --prefix "$COLLECTION_PREFIX"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4) Policies (konfigurierbar, kein Hard‑Code)
|
||||||
|
- `policies/retrieval.schema.json` (JSON‑Schema) und `policies/retrieval.yaml`, z. B.:
|
||||||
|
```yaml
|
||||||
|
privacy_order: [private, internal, public]
|
||||||
|
recency_boost_half_life_days: 90
|
||||||
|
type_priority:
|
||||||
|
person: 1.2
|
||||||
|
event: 1.1
|
||||||
|
concept: 1.0
|
||||||
|
max_chunks_per_note: 8
|
||||||
|
edge_provenance_weights:
|
||||||
|
explicit: 1.0
|
||||||
|
rule: 0.8
|
||||||
|
default_resolved: 0.6
|
||||||
|
default: 0.2
|
||||||
|
rule_sets:
|
||||||
|
- id: "rules:types-v1"
|
||||||
|
enabled: true
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5) Observability & Reports
|
||||||
|
- **FastAPI + OpenTelemetry**: Traces um Phasen *parse/chunk/edge/upsert*; Metriken (Counter/Histogramme) pro Phase.
|
||||||
|
- **Import‑Report** je Lauf (CSV/JSON): counts für Notes/Chunks/Edges, Fehler, Dauer, Embedding‑Version.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6) Teststrategie
|
||||||
|
- **Gold‑Notizen** (3–5 repräsentative .md) mit erwarteten *Chunk‑Counts* und *Edge‑Sets*.
|
||||||
|
- **Regression:** fixer Soll‑Count (z. B. 171 ± 15 %) über Gesamt‑Vault; keine Duplikate `(src,relation,dst)`.
|
||||||
|
- **Dry‑Run vs Apply**: identische Counts, nur ohne Upserts.
|
||||||
|
- **Filter‑Smoke‑Tests:** Qdrant‑Filter nach `privacy`, `type`, `tags`, `created` funktionieren performant.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7) Akzeptanzkriterien (KPI)
|
||||||
|
1. **Chunk‑Qualität:** ≥ 90 % der Chunks enden an semantischen Grenzen; Ziel‑Länge 900–1200 Zeichen; deterministische IDs.
|
||||||
|
2. **Edge‑Kohärenz:** Keine Duplikate gleicher `(src,relation,dst)`; ≥ 95 % der expliziten Links materialisiert; `default` nur, wenn kein Ziel existiert.
|
||||||
|
3. **Filterbarkeit:** Queries nach `privacy/type/tags/created` performant (Payload‑Index vorhanden).
|
||||||
|
4. **Betriebsfestigkeit:** Telemetrie aktiv; fehlertoleranter Import; Qdrant‑Snapshot nach erfolgreichem Lauf.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8) Roadmap in kleinen, testbaren Schritten
|
||||||
|
|
||||||
|
### Step 0 – Safeguards
|
||||||
|
- Qdrant‑Snapshot v1 erstellen + Restore‑Probe.
|
||||||
|
- ENV: `MINDNET_SCHEMA_VERSION=2` (Importer wird v2 schreiben, v1 bleibt unberührt).
|
||||||
|
|
||||||
|
### Step 1 – Schemata (nur Dateien)
|
||||||
|
- Ablage: `/schemas/note.schema.json`, `/schemas/chunk.schema.json`, `/schemas/edge.schema.json`, `/schemas/default_edge.schema.json`
|
||||||
|
- CI‑Job: `make schema-validate` (jsonschema).
|
||||||
|
- **Abnahme:** Validator grün auf 3 Gold‑Notizen.
|
||||||
|
|
||||||
|
### Step 2 – Qdrant v2‑Collections (Optional)
|
||||||
|
- Anlegen der 3 v2‑Collections + Payload‑Indizes.
|
||||||
|
- **Abnahme:** Filter‑Query liefert erwartbare Ergebnisse.
|
||||||
|
|
||||||
|
### Step 2a – Edge-Pipeline v1 stabilisieren (ERLEDIGT)
|
||||||
|
- Ziel: Vollständige Generierung von Struktur-, expliziten, typbasierten und Inline-Kanten in den bestehenden Collections `${prefix}_notes`, `${prefix}_chunks`, `${prefix}_edges`.
|
||||||
|
- Status: Implementiert und durch `tests/test_edges_smoke.py`, `tests/test_edges_all.py` und `scripts/edges_full_check.py` verifiziert.
|
||||||
|
|
||||||
|
|
||||||
|
### Step 3 – Chunker v2
|
||||||
|
- Implementierung & Flag `--chunker v2`.
|
||||||
|
- **Abnahme:** Chunk‑Counts ~ alt (≈171 ± 15 %), semantische Schnitte.
|
||||||
|
|
||||||
|
### Step 4 – Edge‑Builder v2
|
||||||
|
- Reihenfolge & `provenance` strikt umsetzen, `default_resolved` integrieren.
|
||||||
|
- **Abnahme:** erwartete Relationensätze auf Gold‑Notizen, keine Duplikate.
|
||||||
|
|
||||||
|
### Step 4a – Edge-bewusster Retriever
|
||||||
|
- Implementiere einen Retrieval-Service, der:
|
||||||
|
- Chunks über Vektor-Suche aus `${prefix}_chunks` holt,
|
||||||
|
- dazu passende Nachbar-Chunks (`next/prev`) und typrelevante Notizen (`edge_defaults`, Inline-Relationen, Wikilinks) über `${prefix}_edges` ergänzt,
|
||||||
|
- `retriever_weight` und `confidence` beim Scoring berücksichtigt.
|
||||||
|
- Liefere einen API-Endpoint `/mindnet/query` mit einem einfachen JSON-Response (Chunks + Begründung).
|
||||||
|
- Akzeptanz:
|
||||||
|
- mindestens ein Testfall mit dem Relations-Showcase-Vault,
|
||||||
|
- sichtbarer Einfluss von `edge_defaults` und Inline-Relationen auf die Ergebnisliste.
|
||||||
|
|
||||||
|
|
||||||
|
### Step 5 – Importer‑Pipeline v2
|
||||||
|
- `--schema v2` Side‑by‑Side; Batch‑Upserts; vollständige Payloads; Recency‑Boost Konfig **nur** in Policy.
|
||||||
|
- **Abnahme:** Dry‑Run/Apply‑Parität, Reports, Telemetrie‑Ereignisse sichtbar.
|
||||||
|
|
||||||
|
### Step 6 – Observability
|
||||||
|
- OTel‑Instrumentierung + `/import/status` + Reports.
|
||||||
|
- **Abnahme:** Traces & Metriken vorhanden.
|
||||||
|
|
||||||
|
### Step 7 – Snapshots & Runbook
|
||||||
|
- Snapshot nach Erfolg; Restore‑Dokument.
|
||||||
|
- **Abnahme:** Restore‑Probe erfolgreich.
|
||||||
|
|
||||||
|
### Step 8 – Policies
|
||||||
|
- `policies/retrieval.yaml` + JSON‑Schema; A/B‑Test (Policy ändern → Retrieval ändert sich ohne Reimport).
|
||||||
|
- **Abnahme:** Sichtbarer Effekt laut Testfall.
|
||||||
|
|
||||||
|
### Step 9 – Umschalten
|
||||||
|
- Abnahme‑Doku, KPI‑Delta dokumentiert; Alias/Flag‑Switch auf v2.
|
||||||
|
- **Abnahme:** Funktionale Gleichwertigkeit + Qualitätsgewinn.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9) Dateien (neu/ändern)
|
||||||
|
**Neu:**
|
||||||
|
- `schemas/note.schema.json`
|
||||||
|
- `schemas/chunk.schema.json`
|
||||||
|
- `schemas/edge.schema.json`
|
||||||
|
- `schemas/default_edge.schema.json`
|
||||||
|
- `policies/retrieval.schema.json`
|
||||||
|
- `policies/retrieval.yaml`
|
||||||
|
- `chunking/block_chunker.py`
|
||||||
|
- `graph/edge_builder_v2.py`
|
||||||
|
- `docs/OPERATIONS.md` (Snapshots/Restore/Runbook)
|
||||||
|
- `tests/gold_notes/manifest.yaml` (+ 3–5 Notizen Kopien)
|
||||||
|
|
||||||
|
**Änderungen:**
|
||||||
|
- `scripts/import_markdown.py` **oder** `scripts/import_markdown_v2.py` neu (Flags `--schema/--chunker/--edges`).
|
||||||
|
- `edges.py` (falls weiterverwendet): auf **v2‑Edge‑Builder** migrieren oder auslaufen lassen.
|
||||||
|
- `types.yaml`: Regel‑Definitionen klarisieren (IDs, Bedingungen), **nicht** hart in Code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10) Beispiel‑Kommandos
|
||||||
|
```bash
|
||||||
|
# Step 2: Collections prüfen
|
||||||
|
curl -s http://127.0.0.1:6333/collections | jq
|
||||||
|
|
||||||
|
# Step 3: Chunker v2 (dry-run)
|
||||||
|
python3 -m scripts.import_markdown_v2 --vault ./vault --schema v2 --chunker v2 --edges v2 --dry-run --prefix "$COLLECTION_PREFIX"
|
||||||
|
|
||||||
|
# Step 5: Apply + Report
|
||||||
|
python3 -m scripts.import_markdown_v2 --vault ./vault --schema v2 --chunker v2 --edges v2 --apply --prefix "$COLLECTION_PREFIX" --report ./reports/import_$(date +%F_%H%M).json
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11) Rollback
|
||||||
|
- v2‑Collections droppen (wenn Side‑by‑Side).
|
||||||
|
- Aus Snapshot wiederherstellen (v1).
|
||||||
|
- Flags zurück auf v1.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12) Referenzen (offizielle Quellen)
|
||||||
|
- Qdrant – Collections, Payload‑Index, Filter: <https://qdrant.tech/documentation/>
|
||||||
|
- Qdrant – Snapshots/Backup: <https://qdrant.tech/documentation/guides/backup/>
|
||||||
|
- OpenTelemetry (Python/FastAPI): <https://opentelemetry.io/docs/instrumentation/python/>
|
||||||
|
- JSON‑Schema 2020‑12: <https://json-schema.org/>
|
||||||
|
- YAML 1.2: <https://yaml.org/spec/1.2.2/>
|
||||||
|
- Obsidian Frontmatter: <https://help.obsidian.md/Editing+and+formatting/Properties>
|
||||||
|
- Ollama CLI/API (lokale Modelle): <https://github.com/ollama/ollama>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13) **PROMPT für den neuen Chat (bitte exakt so einfügen)**
|
||||||
|
```
|
||||||
|
Rolle: Du bist mein Senior‑Entwickler & Architekt für mindnet. Arbeite strikt in kleinen, testbaren Schritten (Side‑by‑Side v2 neben v1). Liefere komplette Dateien als Downloads. Frage immer zuerst nach den **aktuellsten** Projektdateien, wenn du sie brauchst (z. B. import_markdown.py, edges.py, types.yaml), ändere keine Systemfunktion „workaround‑artig“ ohne die Gesamtwirkung zu prüfen.
|
||||||
|
|
||||||
|
Kontext (Kurzfassung):
|
||||||
|
- v1 hat nur mindnet_notes zuverlässig. Chunks/Edges sind inkonsistent/teilweise leer. Ziel: v2 mit drei Collections (notes/chunks/edges), neuem Chunker v2, Edge‑Builder v2 (explicit → rule → default_resolved → default), Policies (YAML), Observability (OTel), Snapshots. Kein Big‑Bang; v2 parallel zu v1.
|
||||||
|
- Siehe angehängte Datei **mindnet_v2_implementation_playbook.md** (Pfad/Download im Chat). Alles daraus ist verbindlich.
|
||||||
|
|
||||||
|
Deine ersten Aufgaben (Step‑by‑Step):
|
||||||
|
1) **Schemata anlegen (Step 1)**
|
||||||
|
- Erstelle die Dateien:
|
||||||
|
- schemas/note.schema.json
|
||||||
|
- schemas/chunk.schema.json
|
||||||
|
- schemas/edge.schema.json
|
||||||
|
- schemas/default_edge.schema.json
|
||||||
|
- Nutze die in der Playbook‑Datei vorgegebenen Strukturen als Basis.
|
||||||
|
- Liefere zusätzlich ein einfaches `Makefile`‑Ziel `schema-validate` (jsonschema via Python), plus `requirements.txt`.
|
||||||
|
- Output: komplette Dateien als Downloads + kurze Testanleitung.
|
||||||
|
|
||||||
|
2) **Qdrant v2‑Collections (Step 2)**
|
||||||
|
- Erzeuge die Collections + Payload‑Indizes.
|
||||||
|
- Liefere ein kleines Python‑Skript `tools/qdrant_bootstrap_v2.py`, das diese Anlage idempotent durchführt (inkl. Prüf‑Output).
|
||||||
|
|
||||||
|
3) **Chunker v2 (Step 3)**
|
||||||
|
- Implementiere `chunking/block_chunker.py` mit den im Playbook genannten Parametern.
|
||||||
|
- Teste gegen 3 Gold‑Notizen (liefere mini Test‑Harness in `tests/gold_notes/…`).
|
||||||
|
|
||||||
|
Arbeitsweise:
|
||||||
|
- Jede Aufgabe einzeln, mit klaren Akzeptanzkriterien (aus Playbook) und Download‑Artefakten.
|
||||||
|
- Keine parallelen Großumbauten.
|
||||||
|
- Immer deterministische IDs, idempotente Upserts.
|
||||||
|
|
||||||
|
Dateien, die ich dir anfänglich bereitstelle:
|
||||||
|
- **mindnet_v2_implementation_playbook.md** (diese Datei)
|
||||||
|
- **import_markdown.py** (aktuelle Version aus dem Projekt)
|
||||||
|
- **edges.py** (aktuelle Version aus dem Projekt)
|
||||||
|
- **types.yaml** (aktuelle Version)
|
||||||
|
|
||||||
|
Sage mir jeweils, welche Datei du als Nächstes brauchst. Beginne jetzt mit Aufgabe 1 (Schemata).
|
||||||
|
```
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
# WP-04 / Step 4a – Retriever Scoring & Konfiguration
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt den aktuellen Stand (2025-11-30) der Scoring-Logik des mindnet-Retrievers in WP-04 / Step 4a.
|
||||||
|
Es dient als Referenz für:
|
||||||
|
|
||||||
|
- Nachvollziehbarkeit des Rankings
|
||||||
|
- Konfiguration und Feintuning (ohne Codeänderungen)
|
||||||
|
- spätere Automatisierung / „Selbstjustierung“ des Retrievers
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Überblick
|
||||||
|
|
||||||
|
Der Retriever kombiniert drei Signalquellen zu einem einheitlichen Score:
|
||||||
|
|
||||||
|
1. **Semantik** – Vektorsuche über `mindnet_chunks`
|
||||||
|
2. **Typ-Gewichtung** – `retriever_weight` pro Note/Chunk (aus `types.yaml`)
|
||||||
|
3. **Graph-Boni** – `edge_bonus` und `centrality_bonus` aus dem Subgraph (Edges)
|
||||||
|
|
||||||
|
Die Berechnung erfolgt in `app/core/retriever.py` und ist über `config/retriever.yaml` konfigurierbar.
|
||||||
|
Die API stellt die Funktionalität über den `/query`-Endpoint (FastAPI) bereit.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Datenbasis (Kurzüberblick)
|
||||||
|
|
||||||
|
### 2.1 Notes (`<prefix>_notes`)
|
||||||
|
|
||||||
|
Relevante Felder:
|
||||||
|
|
||||||
|
- note_id: keyword
|
||||||
|
- title: text
|
||||||
|
- type: keyword
|
||||||
|
- retriever_weight: float
|
||||||
|
- chunk_profile: keyword
|
||||||
|
- edge_defaults: keyword[]
|
||||||
|
- tags: keyword[]
|
||||||
|
- path: text
|
||||||
|
- fulltext: text
|
||||||
|
|
||||||
|
### 2.2 Chunks (`<prefix>_chunks`)
|
||||||
|
|
||||||
|
Relevante Felder:
|
||||||
|
|
||||||
|
- note_id: keyword
|
||||||
|
- chunk_id: keyword
|
||||||
|
- text: text
|
||||||
|
- window: text
|
||||||
|
- retriever_weight: float
|
||||||
|
- type: keyword
|
||||||
|
- path: text
|
||||||
|
- section: text
|
||||||
|
- neighbors_prev / neighbors_next
|
||||||
|
- chunk_profile: keyword
|
||||||
|
|
||||||
|
### 2.3 Edges (`<prefix>_edges`)
|
||||||
|
|
||||||
|
Relevante Felder:
|
||||||
|
|
||||||
|
- kind: keyword
|
||||||
|
- source_id: keyword
|
||||||
|
- target_id: keyword
|
||||||
|
- note_id: keyword
|
||||||
|
- confidence: float
|
||||||
|
- rule_id, provenance, edge_id, scope, relation, ref_text
|
||||||
|
|
||||||
|
Edges stammen stets aus der Import-/Edge-Pipeline (WP-03) und bilden die graphbasierte Grundlage des Retrievers.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Scoring-Formel (Retriever)
|
||||||
|
|
||||||
|
### 3.1 Eingangsgrößen
|
||||||
|
|
||||||
|
Für jeden Treffer gelten:
|
||||||
|
|
||||||
|
semantic_score – aus der Vektorsuche (Qdrant)
|
||||||
|
retriever_weight – typabhängiges Gewicht (aus types.yaml)
|
||||||
|
edge_bonus – aggregierter Graph-Bonus
|
||||||
|
centrality_bonus – Zentralitätsbonus aus dem Subgraph
|
||||||
|
|
||||||
|
### 3.2 Globale Gewichte (aus retriever.yaml)
|
||||||
|
|
||||||
|
Datei: `config/retriever.yaml`
|
||||||
|
Beispiel:
|
||||||
|
|
||||||
|
version: 1.0
|
||||||
|
|
||||||
|
scoring:
|
||||||
|
semantic_weight: 1.0 # W_sem
|
||||||
|
edge_weight: 0.7 # W_edge
|
||||||
|
centrality_weight: 0.5 # W_cent
|
||||||
|
|
||||||
|
Falls diese Datei fehlt, greifen ENV-basierte Defaults (`RETRIEVER_W_*`).
|
||||||
|
|
||||||
|
### 3.3 Formel
|
||||||
|
|
||||||
|
total_score =
|
||||||
|
W_sem * semantic_score * max(retriever_weight, 0.0)
|
||||||
|
+ W_edge * edge_bonus
|
||||||
|
+ W_cent * centrality_bonus
|
||||||
|
|
||||||
|
Bemerkungen:
|
||||||
|
|
||||||
|
- Negative `retriever_weight` werden abgefangen.
|
||||||
|
- Die rohen `edge_bonus` und `centrality_bonus` werden im API-/Smoke-Output angezeigt.
|
||||||
|
- Die Gewichte aus `retriever.yaml` beeinflussen **nur den total_score**, nicht die Anzeige.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Konfigurationsdateien
|
||||||
|
|
||||||
|
### 4.1 Typen-Registry (`types.yaml`)
|
||||||
|
|
||||||
|
Beispielauszug:
|
||||||
|
|
||||||
|
defaults:
|
||||||
|
retriever_weight: 1.0
|
||||||
|
chunk_profile: default
|
||||||
|
|
||||||
|
types:
|
||||||
|
types:
|
||||||
|
concept:
|
||||||
|
retriever_weight: 0.60
|
||||||
|
edge_defaults: ["references", "related_to"]
|
||||||
|
|
||||||
|
project:
|
||||||
|
retriever_weight: 0.97
|
||||||
|
edge_defaults: ["references", "depends_on"]
|
||||||
|
|
||||||
|
journal:
|
||||||
|
retriever_weight: 0.80
|
||||||
|
edge_defaults: ["references", "related_to"]
|
||||||
|
|
||||||
|
source:
|
||||||
|
retriever_weight: 0.50
|
||||||
|
edge_defaults: []
|
||||||
|
|
||||||
|
Diese Werte bestimmen, wie wichtig eine Note/Chunk **prinzipiell** für den Retriever ist.
|
||||||
|
|
||||||
|
### 4.2 Retriever-Konfiguration (`retriever.yaml`)
|
||||||
|
|
||||||
|
Beispiel:
|
||||||
|
|
||||||
|
version: 1.0
|
||||||
|
|
||||||
|
scoring:
|
||||||
|
semantic_weight: 1.0
|
||||||
|
edge_weight: 0.7
|
||||||
|
centrality_weight: 0.5
|
||||||
|
|
||||||
|
# Blueprint für spätere Edge-Feinsteuerung:
|
||||||
|
edge_types:
|
||||||
|
references: 0.20
|
||||||
|
depends_on: 0.18
|
||||||
|
related_to: 0.15
|
||||||
|
similar_to: 0.12
|
||||||
|
belongs_to: 0.10
|
||||||
|
next: 0.06
|
||||||
|
prev: 0.06
|
||||||
|
|
||||||
|
Die Datei befindet sich standardmäßig unter `config/retriever.yaml`.
|
||||||
|
Override per ENV:
|
||||||
|
|
||||||
|
MINDNET_RETRIEVER_CONFIG=/pfad/zur/datei.yaml
|
||||||
|
|
||||||
|
### 4.3 Aktive Gewichte auslesen
|
||||||
|
|
||||||
|
python - << 'PY'
|
||||||
|
from app.core.retriever import _get_scoring_weights
|
||||||
|
print(_get_scoring_weights())
|
||||||
|
PY
|
||||||
|
|
||||||
|
Beispielausgabe:
|
||||||
|
|
||||||
|
(1.0, 0.7, 0.5)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Betriebsmodi
|
||||||
|
|
||||||
|
### 5.1 Semantikmodus (semantic)
|
||||||
|
|
||||||
|
Ablauf:
|
||||||
|
|
||||||
|
- Query-Vektor über embed_text()
|
||||||
|
- Qdrant-Suche über mindnet_chunks
|
||||||
|
- kein Subgraph → edge_bonus = centrality = 0
|
||||||
|
- total_score = W_sem * semantic_score * retriever_weight
|
||||||
|
|
||||||
|
### 5.2 Hybridmodus (hybrid)
|
||||||
|
|
||||||
|
Ablauf:
|
||||||
|
|
||||||
|
- Semantik wie oben
|
||||||
|
- falls expand.depth > 0:
|
||||||
|
- Subgraph-Berechnung über ga.expand()
|
||||||
|
- Ermittlung von edge_bonus und centrality_bonus
|
||||||
|
- total_score = kombinierte Formel aus Semantik + Graph
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Tests
|
||||||
|
|
||||||
|
### Ausführung (Unit & Integration)
|
||||||
|
|
||||||
|
pytest tests/test_retriever_basic.py \
|
||||||
|
tests/test_retriever_weight.py \
|
||||||
|
tests/test_retriever_edges.py
|
||||||
|
|
||||||
|
pytest tests/test_query_unit.py \
|
||||||
|
tests/test_query_text_embed_unit.py
|
||||||
|
|
||||||
|
Tests decken ab:
|
||||||
|
|
||||||
|
- Semantiktreffer
|
||||||
|
- Typ-Gewichte
|
||||||
|
- Edge-Boni
|
||||||
|
- Hybridmodus / FastAPI-Endpunkt
|
||||||
|
|
||||||
|
### Smoke-Test
|
||||||
|
|
||||||
|
python tests/test_retriever_smoke.py \
|
||||||
|
--url "http://127.0.0.1:8001/query" \
|
||||||
|
--query "embeddings" \
|
||||||
|
--mode hybrid \
|
||||||
|
--expand-depth 1 \
|
||||||
|
--top-k 5
|
||||||
|
|
||||||
|
Beispielausgabe:
|
||||||
|
|
||||||
|
[1] note_id=...retriever-design
|
||||||
|
total=1.5054 (semantic=0.4038 edge=1.5910 centrality=0.0000)
|
||||||
|
|
||||||
|
Interpretation:
|
||||||
|
|
||||||
|
- `semantic`, `edge`, `centrality` = Rohwerte
|
||||||
|
- `total` = skaliert mit `retriever.yaml`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Betriebs-Hinweise
|
||||||
|
|
||||||
|
### 7.1 Änderung der Gewichte
|
||||||
|
|
||||||
|
- retriever.yaml anpassen
|
||||||
|
- FastAPI/uvicorn neu starten
|
||||||
|
- Smoke-Test prüfen
|
||||||
|
|
||||||
|
### 7.2 Zielbild WP-04
|
||||||
|
|
||||||
|
Der jetzige Stand ermöglicht:
|
||||||
|
|
||||||
|
- transparente, konfigurierbare Score-Berechnung
|
||||||
|
- Kombination aus Semantik, Typwissen und Graphstruktur
|
||||||
|
- spätere agentenbasierte Selbstjustierung
|
||||||
|
- alternative Profile (z. B. „mehr Semantik“, „mehr Graph“)
|
||||||
|
|
||||||
|
Dieses Dokument dient als stabile Referenz für Entwickler, Tests und spätere Automatisierungsschritte.
|
||||||
|
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
# mindnet v2 — Dokumentationsreview (vollständig & konsolidiert)
|
||||||
|
|
||||||
|
Dieses Dokument fasst alle notwendigen Anpassungen der mindnet-v2 Dokumentation zusammen.
|
||||||
|
Der Fokus liegt ausschließlich auf Aspekten, die durch die aktuellen Arbeiten verändert wurden:
|
||||||
|
|
||||||
|
- neue Edge-Mechanik
|
||||||
|
- neuer Importer
|
||||||
|
- neues Verhalten von note_payload & chunk_payload
|
||||||
|
- Default-Typregeln aus `types.yaml`
|
||||||
|
- Inline- und Callout-Relations
|
||||||
|
- WP04a – Einführung der Retriever-Schicht
|
||||||
|
- neue Diagnose- und Testskripte
|
||||||
|
|
||||||
|
Es handelt sich um eine strukturelle Analyse.
|
||||||
|
Nichts davon überschreibt bestehende Inhalte — es markiert nur, **was angepasst werden muss**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 1) knowledge_design.md
|
||||||
|
## Erforderliche Anpassungen
|
||||||
|
|
||||||
|
### 1.1 Neue Edge-Arten dokumentieren
|
||||||
|
Es müssen vier neue Kategorien beschrieben werden:
|
||||||
|
|
||||||
|
1. **Inline-Edges**
|
||||||
|
|
||||||
|
Beispiel:
|
||||||
|
`[ [rel:depends_on Embeddings 101] ]`
|
||||||
|
(Leerzeichen hier zur Demonstration; im echten Dokument ohne Leerzeichen)
|
||||||
|
|
||||||
|
2. **Callout-Edges**
|
||||||
|
|
||||||
|
> [!edge] related_to: [[Vector DB Basics]] [[Embeddings 101]]
|
||||||
|
|
||||||
|
3. **Typbasierte Default-Kanten**
|
||||||
|
Aus `types.yaml` → `edge_defaults`
|
||||||
|
|
||||||
|
4. **Strukturkanten**
|
||||||
|
- belongs_to
|
||||||
|
- next
|
||||||
|
- prev
|
||||||
|
|
||||||
|
### 1.2 Neue Edge-Felder ergänzen
|
||||||
|
Jeder Edge enthält jetzt:
|
||||||
|
|
||||||
|
- `rule_id`
|
||||||
|
- `confidence`
|
||||||
|
- `scope = "chunk"`
|
||||||
|
- deterministischer `edge_id`
|
||||||
|
|
||||||
|
Diese Felder müssen vollständig erklärt werden.
|
||||||
|
|
||||||
|
### 1.3 Chunk-basierte Kanten
|
||||||
|
Neu: **Alle Kanten entstehen ausschließlich zwischen Chunks**, nie zwischen Notes.
|
||||||
|
Notes dienen nur noch als Metadatencontainer.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 2) TYPE_REGISTRY_MANUAL.md
|
||||||
|
## Erforderliche Anpassungen
|
||||||
|
|
||||||
|
### 2.1 Typauflösung dokumentieren
|
||||||
|
Die Regeln sind jetzt:
|
||||||
|
|
||||||
|
- Typ aus Frontmatter → höchste Priorität
|
||||||
|
- Falls nicht gesetzt: Typ aus Dateipfad ableiten
|
||||||
|
- Falls unbekannt: Fallback auf `types.default`
|
||||||
|
- Typ definiert:
|
||||||
|
- retriever_weight
|
||||||
|
- chunk_profile
|
||||||
|
- edge_defaults
|
||||||
|
|
||||||
|
Diese müssen klar dokumentiert werden.
|
||||||
|
|
||||||
|
### 2.2 Neue Fallback-Regeln
|
||||||
|
Wenn Werte fehlen, werden sie ersetzt durch:
|
||||||
|
|
||||||
|
types.default.retriever_weight
|
||||||
|
types.default.chunk_profile
|
||||||
|
types.default.edge_defaults
|
||||||
|
|
||||||
|
### 2.3 Beispiele aktualisieren
|
||||||
|
Alle Beispiele müssen auf die neue Inline-Syntax angepasst werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 3) wp04_retriever_scoring.md
|
||||||
|
## Erforderliche Anpassungen
|
||||||
|
|
||||||
|
### 3.1 Neue Scoring-Formel
|
||||||
|
total_score =
|
||||||
|
semantic_weight * semantic_score
|
||||||
|
+ edge_weight * edge_bonus
|
||||||
|
+ centrality_weight * centrality_bonus
|
||||||
|
+ type_weight * retriever_weight
|
||||||
|
|
||||||
|
### 3.2 Bedeutung von `confidence`
|
||||||
|
confidence wirkt multiplikativ bei edge_bonus.
|
||||||
|
Inline > Callout > Default (Standardwerte im Code hinterlegt).
|
||||||
|
|
||||||
|
### 3.3 Pfadbegründungen
|
||||||
|
Der Retriever gibt optional `paths[]` zurück:
|
||||||
|
|
||||||
|
paths: [
|
||||||
|
{
|
||||||
|
"via": "depends_on",
|
||||||
|
"confidence": 0.7,
|
||||||
|
"hops": ["Note A", "Chunk A#01", "Note B"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
Diese Funktion müssen dokumentiert werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 4) mindnet_v2_implementation_playbook.md
|
||||||
|
## Erforderliche Anpassungen
|
||||||
|
|
||||||
|
### 4.1 Neuer Import-Prozess vollständig dokumentieren
|
||||||
|
Der Importer läuft jetzt so:
|
||||||
|
|
||||||
|
1. Markdown lesen
|
||||||
|
2. Frontmatter extrahieren
|
||||||
|
3. Typauflösung via `types.yaml`
|
||||||
|
4. Note-Payload generieren
|
||||||
|
5. Chunking anwenden
|
||||||
|
6. Inline-Kanten finden
|
||||||
|
7. Callout-Kanten finden
|
||||||
|
8. Default-Edges erzeugen
|
||||||
|
9. Strukturkanten erzeugen
|
||||||
|
10. Chunks in Qdrant upserten
|
||||||
|
11. Edges upserten
|
||||||
|
12. Diagnose laufen lassen:
|
||||||
|
|
||||||
|
python3 -m scripts.payload_dryrun
|
||||||
|
python3 -m scripts.edges_full_check
|
||||||
|
|
||||||
|
### 4.2 Erweiterte Testpipeline
|
||||||
|
Neu zu dokumentieren:
|
||||||
|
|
||||||
|
tests.test_edges_all
|
||||||
|
scripts.edges_full_check
|
||||||
|
scripts.payload_dryrun
|
||||||
|
|
||||||
|
Diese Testschritte sind jetzt Standardanforderung nach jeder Änderung.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 5) mindnet_technical_architecture.md
|
||||||
|
## Erforderliche Anpassungen
|
||||||
|
|
||||||
|
### 5.1 Aktualisiertes Schema für Qdrant Collections
|
||||||
|
|
||||||
|
#### Notes:
|
||||||
|
note_id
|
||||||
|
title
|
||||||
|
type
|
||||||
|
fulltext
|
||||||
|
retriever_weight
|
||||||
|
chunk_profile
|
||||||
|
edge_defaults
|
||||||
|
tags
|
||||||
|
updated
|
||||||
|
|
||||||
|
#### Chunks:
|
||||||
|
chunk_id
|
||||||
|
note_id
|
||||||
|
text
|
||||||
|
window
|
||||||
|
ord
|
||||||
|
retriever_weight
|
||||||
|
chunk_profile
|
||||||
|
neighbors_prev
|
||||||
|
neighbors_next
|
||||||
|
|
||||||
|
#### Edges:
|
||||||
|
edge_id
|
||||||
|
source_id
|
||||||
|
target_id
|
||||||
|
kind
|
||||||
|
scope = "chunk"
|
||||||
|
rule_id
|
||||||
|
confidence
|
||||||
|
|
||||||
|
### 5.2 Dokumentation der Edge-Pipeline
|
||||||
|
Neu beschreiben:
|
||||||
|
|
||||||
|
- Inline-Parser
|
||||||
|
- Callout-Parser
|
||||||
|
- Default-Edge-Resolver
|
||||||
|
- Strukturkanten
|
||||||
|
- Normalisierung für Qdrant
|
||||||
|
- deterministische ID-Bildung
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 6) mindnet_functional_architecture.md
|
||||||
|
## Erforderliche Anpassungen
|
||||||
|
|
||||||
|
### 6.1 Inline-Relations – einzig gültige Syntax
|
||||||
|
Nur diese Syntax erzeugt Kanten:
|
||||||
|
|
||||||
|
[[rel:depends_on Embeddings 101]]
|
||||||
|
|
||||||
|
Nicht unterstützt:
|
||||||
|
|
||||||
|
rel:depends_on [[Embeddings 101]]
|
||||||
|
|
||||||
|
Dies muss klar dokumentiert werden.
|
||||||
|
|
||||||
|
### 6.2 Prioritäten der Kantenerzeugung
|
||||||
|
Gültige Reihenfolge:
|
||||||
|
|
||||||
|
1. Inline
|
||||||
|
2. Callout
|
||||||
|
3. Typdefaults
|
||||||
|
4. Strukturkanten
|
||||||
|
|
||||||
|
### 6.3 Relaunch der Chunk-zentrierten Funktionslogik
|
||||||
|
Alle Beispiele müssen angepasst werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 7) chunking_strategy.md
|
||||||
|
## Erforderliche Änderungen
|
||||||
|
|
||||||
|
### 7.1 Neues Verhalten der Chunks
|
||||||
|
- `ord` ist jetzt Sortierkriterium
|
||||||
|
- `window` wird über chunk_config erzeugt
|
||||||
|
- Chunkprofile kommen ausschließlich aus `types.yaml`
|
||||||
|
|
||||||
|
### 7.2 Best Practices erneuern
|
||||||
|
Empfehlung:
|
||||||
|
|
||||||
|
- keine manuelle Chunkprofile mehr im Frontmatter setzen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 8) docs_mindnet_retriever.md
|
||||||
|
## Erforderliche Änderungen
|
||||||
|
|
||||||
|
### 8.1 Neue Ausgabeparameter dokumentieren
|
||||||
|
Retriever liefert jetzt:
|
||||||
|
|
||||||
|
semantic_score
|
||||||
|
edge_bonus
|
||||||
|
centrality_bonus
|
||||||
|
type_score
|
||||||
|
total_score
|
||||||
|
paths[]
|
||||||
|
|
||||||
|
### 8.2 Graph-Expansion
|
||||||
|
Dokumentieren:
|
||||||
|
|
||||||
|
- Seed-Auswahl
|
||||||
|
- Depth-Limit
|
||||||
|
- Edge-Filterung
|
||||||
|
- Wirkung von `confidence` auf edge_bonus
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 9) Handbuch.md
|
||||||
|
## Erforderliche Änderungen
|
||||||
|
|
||||||
|
### 9.1 Neuer Import-Workflow
|
||||||
|
Erläuterung der Parser:
|
||||||
|
|
||||||
|
- Inline-Parser
|
||||||
|
- Callout-Parser
|
||||||
|
- Default-Kanten
|
||||||
|
- Struktur-Kanten
|
||||||
|
|
||||||
|
### 9.2 Best Practices
|
||||||
|
Ergänzen:
|
||||||
|
|
||||||
|
- Typenpflege erfolgt nur in `types.yaml`
|
||||||
|
- Tests immer nach Änderungen ausführen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Gesamtübersicht der notwendigen Anpassungen
|
||||||
|
|
||||||
|
| Dokument | Anpassungsbedarf |
|
||||||
|
|---------|------------------|
|
||||||
|
| knowledge_design.md | neue Edge-Arten, Felder, Chunk-Edges |
|
||||||
|
| TYPE_REGISTRY_MANUAL.md | Typauflösung, neue Felder, neue Fallbacks |
|
||||||
|
| wp04_retriever_scoring.md | neue Score-Formel, Pfade, confidence |
|
||||||
|
| implementation_playbook.md | neuer Importprozess, Tests |
|
||||||
|
| technical_architecture.md | aktualisierte Schemas |
|
||||||
|
| functional_architecture.md | Syntax + Prioritäten |
|
||||||
|
| chunking_strategy.md | ord, window, neue Profile |
|
||||||
|
| docs_mindnet_retriever.md | neue API-Parameter |
|
||||||
|
| Handbuch.md | Parser + Best Practices |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Empfehlung zur Umsetzung
|
||||||
|
1. Dieses Review-Dokument als Master-Referenz verwenden.
|
||||||
|
2. Jedes Dokument strikt nur an den beschriebenen Stellen anpassen.
|
||||||
|
3. Überprüfen, ob Wann/Wo Typen, Kanten und Parser erklärt werden.
|
||||||
|
4. Nach jeder Anpassung Testlauf:
|
||||||
|
|
||||||
|
python3 -m scripts.payload_dryrun
|
||||||
|
python3 -m scripts.edges_full_check
|
||||||
|
|
||||||
|
5. Danach Playbook + Programmplan updaten.
|
||||||
|
|
||||||
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user