Compare commits
69
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59bcd227f9 | ||
|
|
7f707cffb9 | ||
|
|
a50c4494c6 | ||
|
|
418612cd10 | ||
|
|
828fe1f8ce | ||
|
|
c184c3cae2 | ||
|
|
2cd3605017 | ||
|
|
0d71f41a13 | ||
|
|
f5bfb0cfb4 | ||
|
|
f7ab32ebf4 | ||
|
|
64dbd57fc5 | ||
|
|
ba46957556 | ||
|
|
33b0c83c87 | ||
|
|
5dd58f49f0 | ||
|
|
cc12dcf993 | ||
|
|
cbfdd96152 | ||
|
|
babab3167b | ||
|
|
c61d9c8236 | ||
|
|
e47241740d | ||
|
|
6db1714449 | ||
|
|
136c3bb43f | ||
|
|
2c3ee8efd6 | ||
|
|
48729e6f5d | ||
|
|
3eac646cb6 | ||
|
|
9a18f3cc8b | ||
|
|
5dd20d683f | ||
|
|
8af744fc97 | ||
|
|
342d3e5103 | ||
|
|
7f7d8c87db | ||
|
|
43f695de54 | ||
|
|
20b219d86c | ||
|
|
0ff39d7b14 | ||
|
|
e2ee5df815 | ||
|
|
77a6db7e92 | ||
|
|
d53912a8f1 | ||
|
|
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 |
No files matched your search
+6
-13
@@ -1,17 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app — mindnet API package
|
FILE: app/__init__.py
|
||||||
|
DESCRIPTION: Paket-Initialisierung.
|
||||||
Zweck:
|
VERSION: 0.1.0
|
||||||
Markiert 'app/' als Python-Paket, damit 'from app.main import create_app'
|
STATUS: Active
|
||||||
in Tests und Skripten funktioniert.
|
DEPENDENCIES: None
|
||||||
Kompatibilität:
|
LAST_ANALYSIS: 2025-12-15
|
||||||
Python 3.12+
|
|
||||||
Version:
|
|
||||||
0.1.0 (Erstanlage)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Hinweise:
|
|
||||||
Keine Logik – nur Paketinitialisierung.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__version__ = "0.1.0"
|
__version__ = "0.1.0"
|
||||||
+6
-2
@@ -1,6 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/config.py — zentrale Konfiguration
|
FILE: app/config.py
|
||||||
Version: 0.4.0 (WP-06 Complete)
|
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
|
||||||
|
|||||||
+76
-36
@@ -1,11 +1,13 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
app/core/chunk_payload.py (Mindnet V2 — types.yaml authoritative)
|
FILE: app/core/chunk_payload.py
|
||||||
- neighbors_prev / neighbors_next sind Listen ([], [id]).
|
DESCRIPTION: Baut das JSON-Objekt für 'mindnet_chunks'.
|
||||||
- retriever_weight / chunk_profile kommen aus types.yaml (Frontmatter wird ignoriert).
|
FEATURES:
|
||||||
- Fallbacks: defaults.* in types.yaml; sonst 1.0 / "default".
|
- Inkludiert Nachbarschafts-IDs (prev/next) und Titel.
|
||||||
- WP-11 Update: Injects 'title' into chunk payload for Discovery Service.
|
- FIX 3: Robuste Erkennung des Inputs (Frontmatter-Dict vs. Note-Objekt), damit Overrides ankommen.
|
||||||
|
VERSION: 2.3.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: yaml, os
|
||||||
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
@@ -36,42 +38,48 @@ def _get_defaults(reg: dict) -> dict:
|
|||||||
return {}
|
return {}
|
||||||
|
|
||||||
def _as_float(x: Any):
|
def _as_float(x: Any):
|
||||||
try:
|
try: return float(x)
|
||||||
return float(x)
|
except Exception: return None
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def _resolve_chunk_profile(note_type: str, reg: dict) -> str:
|
def _resolve_chunk_profile_from_config(note_type: str, reg: dict) -> Optional[str]:
|
||||||
|
# 1. Type Level
|
||||||
types = _get_types_map(reg)
|
types = _get_types_map(reg)
|
||||||
if isinstance(types, dict):
|
if isinstance(types, dict):
|
||||||
t = types.get(note_type, {})
|
t = types.get(note_type, {})
|
||||||
if isinstance(t, dict) and isinstance(t.get("chunk_profile"), str):
|
if isinstance(t, dict):
|
||||||
return t["chunk_profile"]
|
cp = t.get("chunking_profile") or t.get("chunk_profile")
|
||||||
|
if isinstance(cp, str) and cp: return cp
|
||||||
|
# 2. Defaults Level
|
||||||
defs = _get_defaults(reg)
|
defs = _get_defaults(reg)
|
||||||
if isinstance(defs, dict) and isinstance(defs.get("chunk_profile"), str):
|
if isinstance(defs, dict):
|
||||||
return defs["chunk_profile"]
|
cp = defs.get("chunking_profile") or defs.get("chunk_profile")
|
||||||
return "default"
|
if isinstance(cp, str) and cp: return cp
|
||||||
|
return None
|
||||||
|
|
||||||
def _resolve_retriever_weight(note_type: str, reg: dict) -> float:
|
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)
|
types = _get_types_map(reg)
|
||||||
if isinstance(types, dict):
|
if isinstance(types, dict):
|
||||||
t = types.get(note_type, {})
|
t = types.get(note_type, {})
|
||||||
if isinstance(t, dict) and (t.get("retriever_weight") is not None):
|
if isinstance(t, dict) and (t.get("retriever_weight") is not None):
|
||||||
v = _as_float(t.get("retriever_weight"))
|
v = _as_float(t.get("retriever_weight"))
|
||||||
if v is not None:
|
if v is not None: return float(v)
|
||||||
return float(v)
|
|
||||||
|
# 2. Defaults Level
|
||||||
defs = _get_defaults(reg)
|
defs = _get_defaults(reg)
|
||||||
if isinstance(defs, dict) and (defs.get("retriever_weight") is not None):
|
if isinstance(defs, dict) and (defs.get("retriever_weight") is not None):
|
||||||
v = _as_float(defs.get("retriever_weight"))
|
v = _as_float(defs.get("retriever_weight"))
|
||||||
if v is not None:
|
if v is not None: return float(v)
|
||||||
return float(v)
|
|
||||||
return 1.0
|
return 1.0
|
||||||
|
|
||||||
def _as_list(x):
|
def _as_list(x):
|
||||||
if x is None:
|
if x is None: return []
|
||||||
return []
|
if isinstance(x, list): return x
|
||||||
if isinstance(x, list):
|
|
||||||
return x
|
|
||||||
return [x]
|
return [x]
|
||||||
|
|
||||||
def make_chunk_payloads(note: Dict[str, Any],
|
def make_chunk_payloads(note: Dict[str, Any],
|
||||||
@@ -81,18 +89,49 @@ def make_chunk_payloads(note: Dict[str, Any],
|
|||||||
note_text: str = "",
|
note_text: str = "",
|
||||||
types_cfg: Optional[dict] = None,
|
types_cfg: Optional[dict] = None,
|
||||||
file_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
file_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||||
fm = (note or {}).get("frontmatter", {}) or {}
|
"""
|
||||||
|
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:
|
||||||
|
# Fall B: Direktes Dict (so ruft ingestion.py es auf!)
|
||||||
|
fm = note or {}
|
||||||
|
|
||||||
note_type = fm.get("type") or note.get("type") or "concept"
|
note_type = fm.get("type") or note.get("type") or "concept"
|
||||||
|
|
||||||
# WP-11 FIX: Title Extraction für Discovery Service
|
# Title Extraction (Fallback Chain)
|
||||||
# Wir holen den Titel aus Frontmatter oder Fallback ID/Untitled
|
|
||||||
title = fm.get("title") or note.get("title") or fm.get("id") or "Untitled"
|
title = fm.get("title") or note.get("title") or fm.get("id") or "Untitled"
|
||||||
|
|
||||||
reg = types_cfg if isinstance(types_cfg, dict) else _load_types()
|
reg = types_cfg if isinstance(types_cfg, dict) else _load_types()
|
||||||
|
|
||||||
# types.yaml authoritative
|
# --- Profil-Ermittlung ---
|
||||||
cp = _resolve_chunk_profile(note_type, reg)
|
# Da wir 'fm' jetzt korrekt haben, funktionieren diese lookups:
|
||||||
rw = _resolve_retriever_weight(note_type, reg)
|
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 []
|
tags = fm.get("tags") or []
|
||||||
if isinstance(tags, str):
|
if isinstance(tags, str):
|
||||||
@@ -100,7 +139,7 @@ def make_chunk_payloads(note: Dict[str, Any],
|
|||||||
|
|
||||||
out: List[Dict[str, Any]] = []
|
out: List[Dict[str, Any]] = []
|
||||||
for idx, ch in enumerate(chunks_from_chunker):
|
for idx, ch in enumerate(chunks_from_chunker):
|
||||||
# Attribute oder Keys (Chunk-Objekt oder Dict)
|
# Attribute extrahieren
|
||||||
cid = getattr(ch, "id", None) or (ch.get("id") if isinstance(ch, dict) else None)
|
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"))
|
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)
|
index = getattr(ch, "index", None) or (ch.get("index") if isinstance(ch, dict) else idx)
|
||||||
@@ -112,7 +151,7 @@ def make_chunk_payloads(note: Dict[str, Any],
|
|||||||
pl: Dict[str, Any] = {
|
pl: Dict[str, Any] = {
|
||||||
"note_id": nid,
|
"note_id": nid,
|
||||||
"chunk_id": cid,
|
"chunk_id": cid,
|
||||||
"title": title, # <--- HIER: Titel in Payload einfügen
|
"title": title,
|
||||||
"index": int(index),
|
"index": int(index),
|
||||||
"ord": int(index) + 1,
|
"ord": int(index) + 1,
|
||||||
"type": note_type,
|
"type": note_type,
|
||||||
@@ -125,9 +164,10 @@ def make_chunk_payloads(note: Dict[str, Any],
|
|||||||
"path": note_path,
|
"path": note_path,
|
||||||
"source_path": file_path or note_path,
|
"source_path": file_path or note_path,
|
||||||
"retriever_weight": float(rw),
|
"retriever_weight": float(rw),
|
||||||
"chunk_profile": cp,
|
"chunk_profile": cp, # Jetzt endlich mit dem Override-Wert!
|
||||||
}
|
}
|
||||||
# Aufräumen von Alt-Feldern
|
|
||||||
|
# Cleanup
|
||||||
for alias in ("chunk_num", "Chunk_Number"):
|
for alias in ("chunk_num", "Chunk_Number"):
|
||||||
pl.pop(alias, None)
|
pl.pop(alias, None)
|
||||||
|
|
||||||
|
|||||||
+135
-41
@@ -1,3 +1,13 @@
|
|||||||
|
"""
|
||||||
|
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, Any, Set
|
from typing import List, Dict, Optional, Tuple, Any, Set
|
||||||
@@ -5,8 +15,6 @@ import re
|
|||||||
import math
|
import math
|
||||||
import yaml
|
import yaml
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from markdown_it import MarkdownIt
|
|
||||||
from markdown_it.token import Token
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
@@ -93,7 +101,7 @@ class Chunk:
|
|||||||
suggested_edges: Optional[List[str]] = None
|
suggested_edges: Optional[List[str]] = None
|
||||||
|
|
||||||
# ==========================================
|
# ==========================================
|
||||||
# 3. PARSING & STRATEGIES (SYNCHRON)
|
# 3. PARSING & STRATEGIES
|
||||||
# ==========================================
|
# ==========================================
|
||||||
|
|
||||||
def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
||||||
@@ -115,7 +123,13 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
|||||||
for line in lines:
|
for line in lines:
|
||||||
stripped = line.strip()
|
stripped = line.strip()
|
||||||
if stripped.startswith('# '):
|
if stripped.startswith('# '):
|
||||||
continue
|
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, 1, section_path, current_h2))
|
||||||
|
|
||||||
elif stripped.startswith('## '):
|
elif stripped.startswith('## '):
|
||||||
if buffer:
|
if buffer:
|
||||||
content = "\n".join(buffer).strip()
|
content = "\n".join(buffer).strip()
|
||||||
@@ -125,6 +139,15 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
|||||||
current_h2 = stripped[3:].strip()
|
current_h2 = stripped[3:].strip()
|
||||||
section_path = f"/{current_h2}"
|
section_path = f"/{current_h2}"
|
||||||
blocks.append(RawBlock("heading", stripped, 2, section_path, 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))
|
||||||
|
|
||||||
elif not stripped:
|
elif not stripped:
|
||||||
if buffer:
|
if buffer:
|
||||||
content = "\n".join(buffer).strip()
|
content = "\n".join(buffer).strip()
|
||||||
@@ -141,6 +164,15 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
|||||||
|
|
||||||
return blocks, h1_title
|
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]:
|
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)
|
target = config.get("target", 400)
|
||||||
max_tokens = config.get("max", 600)
|
max_tokens = config.get("max", 600)
|
||||||
@@ -148,15 +180,6 @@ def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], not
|
|||||||
overlap = sum(overlap_val) // 2 if isinstance(overlap_val, tuple) else overlap_val
|
overlap = sum(overlap_val) // 2 if isinstance(overlap_val, tuple) else overlap_val
|
||||||
chunks = []; buf = []
|
chunks = []; buf = []
|
||||||
|
|
||||||
def _create_chunk(txt, win, sec, path):
|
|
||||||
idx = len(chunks)
|
|
||||||
chunks.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 flush_buffer():
|
def flush_buffer():
|
||||||
nonlocal buf
|
nonlocal buf
|
||||||
if not buf: return
|
if not buf: return
|
||||||
@@ -164,9 +187,14 @@ def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], not
|
|||||||
text_body = "\n\n".join([b.text for b in buf])
|
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
|
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:
|
if estimate_tokens(text_body) <= max_tokens:
|
||||||
_create_chunk(text_body, win_body, buf[-1].section_title, buf[-1].section_path)
|
_create_chunk_obj(chunks, note_id, text_body, win_body, sec, path)
|
||||||
else:
|
else:
|
||||||
|
# Fallback: Wenn Block zu groß, intern splitten (Sentence-Level)
|
||||||
sentences = split_sentences(text_body)
|
sentences = split_sentences(text_body)
|
||||||
current_chunk_sents = []
|
current_chunk_sents = []
|
||||||
current_len = 0
|
current_len = 0
|
||||||
@@ -176,7 +204,7 @@ def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], not
|
|||||||
if current_len + sent_len > target and current_chunk_sents:
|
if current_len + sent_len > target and current_chunk_sents:
|
||||||
c_txt = " ".join(current_chunk_sents)
|
c_txt = " ".join(current_chunk_sents)
|
||||||
c_win = f"{context_prefix}\n{c_txt}".strip() if context_prefix else c_txt
|
c_win = f"{context_prefix}\n{c_txt}".strip() if context_prefix else c_txt
|
||||||
_create_chunk(c_txt, c_win, buf[-1].section_title, buf[-1].section_path)
|
_create_chunk_obj(chunks, note_id, c_txt, c_win, sec, path)
|
||||||
|
|
||||||
overlap_sents = []
|
overlap_sents = []
|
||||||
ov_len = 0
|
ov_len = 0
|
||||||
@@ -197,27 +225,111 @@ def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], not
|
|||||||
if current_chunk_sents:
|
if current_chunk_sents:
|
||||||
c_txt = " ".join(current_chunk_sents)
|
c_txt = " ".join(current_chunk_sents)
|
||||||
c_win = f"{context_prefix}\n{c_txt}".strip() if context_prefix else c_txt
|
c_win = f"{context_prefix}\n{c_txt}".strip() if context_prefix else c_txt
|
||||||
_create_chunk(c_txt, c_win, buf[-1].section_title, buf[-1].section_path)
|
_create_chunk_obj(chunks, note_id, c_txt, c_win, sec, path)
|
||||||
|
|
||||||
buf = []
|
buf = []
|
||||||
|
|
||||||
for b in blocks:
|
for b in blocks:
|
||||||
if b.kind == "heading": continue
|
if b.kind == "heading":
|
||||||
|
flush_buffer()
|
||||||
|
|
||||||
current_buf_text = "\n\n".join([x.text for x in buf])
|
current_buf_text = "\n\n".join([x.text for x in buf])
|
||||||
if estimate_tokens(current_buf_text) + estimate_tokens(b.text) >= target:
|
if buf and (estimate_tokens(current_buf_text) + estimate_tokens(b.text) >= target):
|
||||||
flush_buffer()
|
flush_buffer()
|
||||||
|
|
||||||
buf.append(b)
|
buf.append(b)
|
||||||
if estimate_tokens(b.text) >= target:
|
|
||||||
flush_buffer()
|
|
||||||
|
|
||||||
flush_buffer()
|
flush_buffer()
|
||||||
return chunks
|
return chunks
|
||||||
|
|
||||||
def _strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
|
def _strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
|
||||||
return _strategy_sliding_window(blocks, config, note_id, doc_title, context_prefix=f"# {doc_title}")
|
"""
|
||||||
|
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}"
|
||||||
|
|
||||||
|
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) - WP-15 CORE
|
# 4. ORCHESTRATION (ASYNC)
|
||||||
# ==========================================
|
# ==========================================
|
||||||
|
|
||||||
async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Optional[Dict] = None) -> List[Chunk]:
|
async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Optional[Dict] = None) -> List[Chunk]:
|
||||||
@@ -245,7 +357,6 @@ async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Op
|
|||||||
return []
|
return []
|
||||||
|
|
||||||
if enable_smart_edges:
|
if enable_smart_edges:
|
||||||
# Hier rufen wir nun die Smart Edge Allocation auf
|
|
||||||
chunks = await _run_smart_edge_allocation(chunks, md_text, note_id, note_type)
|
chunks = await _run_smart_edge_allocation(chunks, md_text, note_id, note_type)
|
||||||
|
|
||||||
for i, ch in enumerate(chunks):
|
for i, ch in enumerate(chunks):
|
||||||
@@ -255,56 +366,40 @@ async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Op
|
|||||||
return chunks
|
return chunks
|
||||||
|
|
||||||
def _extract_all_edges_from_md(md_text: str, note_id: str, note_type: str) -> List[str]:
|
def _extract_all_edges_from_md(md_text: str, note_id: str, note_type: str) -> List[str]:
|
||||||
"""
|
|
||||||
Hilfsfunktion: Erstellt einen Dummy-Chunk für den gesamten Text und ruft
|
|
||||||
den Edge-Parser auf, um ALLE Kanten der Notiz zu finden.
|
|
||||||
"""
|
|
||||||
# 1. Dummy Chunk erstellen, der den gesamten Text enthält
|
|
||||||
# Das ist notwendig, da build_edges_for_note Kanten nur aus Chunks extrahiert.
|
|
||||||
dummy_chunk = {
|
dummy_chunk = {
|
||||||
"chunk_id": f"{note_id}#full",
|
"chunk_id": f"{note_id}#full",
|
||||||
"text": md_text,
|
"text": md_text,
|
||||||
"content": md_text, # Sicherstellen, dass der Parser Text findet
|
"content": md_text,
|
||||||
"window": md_text,
|
"window": md_text,
|
||||||
"type": note_type
|
"type": note_type
|
||||||
}
|
}
|
||||||
|
|
||||||
# 2. Aufruf des Parsers (Signatur-Fix!)
|
|
||||||
# derive_edges.py: build_edges_for_note(note_id, chunks, note_level_references=None, include_note_scope_refs=False)
|
|
||||||
raw_edges = build_edges_for_note(
|
raw_edges = build_edges_for_note(
|
||||||
note_id,
|
note_id,
|
||||||
[dummy_chunk],
|
[dummy_chunk],
|
||||||
note_level_references=None,
|
note_level_references=None,
|
||||||
include_note_scope_refs=False
|
include_note_scope_refs=False
|
||||||
)
|
)
|
||||||
|
|
||||||
# 3. Kanten extrahieren
|
|
||||||
all_candidates = set()
|
all_candidates = set()
|
||||||
for e in raw_edges:
|
for e in raw_edges:
|
||||||
kind = e.get("kind")
|
kind = e.get("kind")
|
||||||
target = e.get("target_id")
|
target = e.get("target_id")
|
||||||
if target and kind not in ["belongs_to", "next", "prev", "backlink"]:
|
if target and kind not in ["belongs_to", "next", "prev", "backlink"]:
|
||||||
all_candidates.add(f"{kind}:{target}")
|
all_candidates.add(f"{kind}:{target}")
|
||||||
|
|
||||||
return list(all_candidates)
|
return list(all_candidates)
|
||||||
|
|
||||||
async def _run_smart_edge_allocation(chunks: List[Chunk], full_text: str, note_id: str, note_type: str) -> List[Chunk]:
|
async def _run_smart_edge_allocation(chunks: List[Chunk], full_text: str, note_id: str, note_type: str) -> List[Chunk]:
|
||||||
analyzer = get_semantic_analyzer()
|
analyzer = get_semantic_analyzer()
|
||||||
|
|
||||||
# A. Alle potenziellen Kanten der Notiz sammeln (über den Dummy-Chunk Trick)
|
|
||||||
candidate_list = _extract_all_edges_from_md(full_text, note_id, note_type)
|
candidate_list = _extract_all_edges_from_md(full_text, note_id, note_type)
|
||||||
|
|
||||||
if not candidate_list:
|
if not candidate_list:
|
||||||
return chunks
|
return chunks
|
||||||
|
|
||||||
# B. LLM Filterung pro Chunk (Parallel)
|
|
||||||
tasks = []
|
tasks = []
|
||||||
for chunk in chunks:
|
for chunk in chunks:
|
||||||
tasks.append(analyzer.assign_edges_to_chunk(chunk.text, candidate_list, note_type))
|
tasks.append(analyzer.assign_edges_to_chunk(chunk.text, candidate_list, note_type))
|
||||||
|
|
||||||
results_per_chunk = await asyncio.gather(*tasks)
|
results_per_chunk = await asyncio.gather(*tasks)
|
||||||
|
|
||||||
# C. Injection & Fallback
|
|
||||||
assigned_edges_global = set()
|
assigned_edges_global = set()
|
||||||
|
|
||||||
for i, confirmed_edges in enumerate(results_per_chunk):
|
for i, confirmed_edges in enumerate(results_per_chunk):
|
||||||
@@ -317,7 +412,6 @@ async def _run_smart_edge_allocation(chunks: List[Chunk], full_text: str, note_i
|
|||||||
chunk.text += injection_str
|
chunk.text += injection_str
|
||||||
chunk.window += injection_str
|
chunk.window += injection_str
|
||||||
|
|
||||||
# D. Fallback: Unassigned Kanten überall hin
|
|
||||||
unassigned = set(candidate_list) - assigned_edges_global
|
unassigned = set(candidate_list) - assigned_edges_global
|
||||||
if unassigned:
|
if unassigned:
|
||||||
fallback_str = "\n" + " ".join([f"[[rel:{e.split(':')[0]}|{e.split(':')[1]}]]" for e in unassigned if ':' in e])
|
fallback_str = "\n" + " ".join([f"[[rel:{e.split(':')[0]}|{e.split(':')[1]}]]" for e in unassigned if ':' in e])
|
||||||
|
|||||||
@@ -1,26 +1,11 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
Modul: app/core/derive_edges.py
|
FILE: app/core/derive_edges.py
|
||||||
Zweck:
|
DESCRIPTION: Extrahiert Graph-Kanten aus Text. Unterstützt Wikilinks, Inline-Relations ([[rel:type|target]]) und Obsidian Callouts.
|
||||||
- Bewahrt bestehende Edgelogik (belongs_to, prev/next, references, backlink)
|
VERSION: 2.0.0
|
||||||
- Ergänzt typenbasierte Default-Kanten (edge_defaults aus config/types.yaml)
|
STATUS: Active
|
||||||
- Unterstützt "typed inline relations":
|
DEPENDENCIES: re, os, yaml, typing
|
||||||
* [[rel:KIND | Target]]
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
* [[rel:KIND Target]]
|
LAST_ANALYSIS: 2025-12-15
|
||||||
* rel: KIND [[Target]]
|
|
||||||
- Unterstützt Obsidian-Callouts:
|
|
||||||
* > [!edge] KIND: [[Target]] [[Target2]] ...
|
|
||||||
Kompatibilität:
|
|
||||||
- build_edges_for_note(...) Signatur unverändert
|
|
||||||
- rule_id Werte:
|
|
||||||
* structure:belongs_to
|
|
||||||
* structure:order
|
|
||||||
* explicit:wikilink
|
|
||||||
* inline:rel
|
|
||||||
* callout:edge
|
|
||||||
* edge_defaults:<type>:<relation>
|
|
||||||
* derived:backlink
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
@@ -1,296 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
Modul: app/core/edges.py
|
|
||||||
Version: 2.0.0 (V2‑superset, rückwärtskompatibel zu v1 vom 2025‑09‑09)
|
|
||||||
|
|
||||||
Zweck
|
|
||||||
-----
|
|
||||||
Bewahrt die bestehende Edgelogik (belongs_to, prev/next, references, backlink)
|
|
||||||
und ergänzt V2‑Felder + Typ‑Default‑Kanten gemäß config/types.yaml (edge_defaults).
|
|
||||||
Die Funktion ist **idempotent** und **rückwärtskompatibel** zur bisherigen Signatur.
|
|
||||||
|
|
||||||
Kompatibilitätsgarantien (gegenüber v1):
|
|
||||||
- **Input**: akzeptiert identische Chunk‑Payloads wie v1:
|
|
||||||
* `id` (Chunk‑ID), `note_id` (Owner), `neighbors.prev|next` (optional),
|
|
||||||
`references: [{target_id: ...}]` (optional),
|
|
||||||
alternativ: `chunk_id`, `chunk_index|ord`, `window|text`
|
|
||||||
- **Output (v1‑Felder)**: `kind`, `source_id`, `target_id`, `scope`, `note_id`, `edge_id`
|
|
||||||
- **Neu (v2‑Felder)**: `relation`, `src_note_id`, `src_chunk_id?`, `dst_note_id`, `dst_chunk_id?`,
|
|
||||||
`provenance` (`explicit|rule`), `rule_id?`, `confidence?`
|
|
||||||
|
|
||||||
Regeln
|
|
||||||
------
|
|
||||||
- Deduplizierungsschlüssel: (source_id, target_id, relation, rule_id)
|
|
||||||
- Strukturkanten:
|
|
||||||
* belongs_to: 1× pro Chunk
|
|
||||||
* next/prev: Sequenz der Chunks; nutzt bevorzugt neighbors; sonst ord/chunk_index
|
|
||||||
- Explizite Referenzen:
|
|
||||||
* aus Chunk: `references[].target_id` (falls vorhanden)
|
|
||||||
* Fallback: Wikilinks in `window|text`: [[Some Title|some-id]] oder [[some-id]]
|
|
||||||
- Note‑Scope:
|
|
||||||
* backlink immer; references nur, wenn include_note_scope_refs=True
|
|
||||||
- Typ‑Defaults (edge_defaults aus config/types.yaml des **Quell‑Notiztyps**):
|
|
||||||
* Für jede explizite Referenz wird je default‑Relation eine Regel‑Kante erzeugt
|
|
||||||
* rule_id: "type_default:{note_type}:{relation}:v1", provenance="rule"
|
|
||||||
|
|
||||||
Konfiguration
|
|
||||||
-------------
|
|
||||||
- ENV MINDNET_TYPES_FILE (Default: ./config/types.yaml)
|
|
||||||
|
|
||||||
Lizenz/Autor
|
|
||||||
------------
|
|
||||||
- Erstimplementierung v1 (2025‑09‑09) — Projekt Mindnet
|
|
||||||
- Erweiterung v2 (2025‑11‑11) — kompatible Superset‑Implementierung
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
from typing import Dict, Iterable, List, Optional, Tuple, Set
|
|
||||||
|
|
||||||
try:
|
|
||||||
import yaml # optional, nur für types.yaml
|
|
||||||
except Exception: # pragma: no cover
|
|
||||||
yaml = None
|
|
||||||
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
# Hilfen: types.yaml laden (edge_defaults)
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
|
|
||||||
def _types_path() -> str:
|
|
||||||
return os.getenv("MINDNET_TYPES_FILE") or "./config/types.yaml"
|
|
||||||
|
|
||||||
def _load_types() -> Dict[str, dict]:
|
|
||||||
p = _types_path()
|
|
||||||
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 {}
|
|
||||||
if isinstance(data, dict) and "types" in data and isinstance(data["types"], dict):
|
|
||||||
return data["types"]
|
|
||||||
return data if isinstance(data, dict) else {}
|
|
||||||
except Exception:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
def _edge_defaults_for(note_type: Optional[str]) -> List[str]:
|
|
||||||
types = _load_types()
|
|
||||||
t = (note_type or "").strip().lower()
|
|
||||||
cfg = types.get(t) or {}
|
|
||||||
defaults = cfg.get("edge_defaults") or []
|
|
||||||
if isinstance(defaults, str):
|
|
||||||
defaults = [defaults]
|
|
||||||
return [str(x) for x in defaults if isinstance(x, (str, int, float))]
|
|
||||||
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
# Wikilink‑Parser (Fallback, wenn ch["references"] fehlt)
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
|
|
||||||
_WIKILINK_RE = re.compile(r"\[\[(?:[^\|\]]+\|)?([a-zA-Z0-9_\-#:. ]+)\]\]")
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
# Utility
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
def _dedupe(edges: List[Dict]) -> List[Dict]:
|
|
||||||
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
|
|
||||||
|
|
||||||
def _first(v: dict, *keys, default=None):
|
|
||||||
for k in keys:
|
|
||||||
if k in v and v[k] is not None:
|
|
||||||
return v[k]
|
|
||||||
return default
|
|
||||||
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
# Hauptfunktion
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
|
|
||||||
def build_edges_for_note(
|
|
||||||
note_id: str,
|
|
||||||
chunk_payloads: List[Dict],
|
|
||||||
note_level_refs: Optional[List[str]] = None,
|
|
||||||
*,
|
|
||||||
include_note_scope_refs: bool = False,
|
|
||||||
) -> List[Dict]:
|
|
||||||
edges: List[Dict] = []
|
|
||||||
chunks = list(chunk_payloads or [])
|
|
||||||
# Notiztyp aus erstem Chunk ableiten (kompatibel zu existierenden Payloads)
|
|
||||||
note_type = (chunks[0].get("type") if chunks else None) or (chunks[0].get("note_type") if chunks else None)
|
|
||||||
|
|
||||||
# --- Strukturkanten ------------------------------------------------------
|
|
||||||
# belongs_to
|
|
||||||
for ch in chunks:
|
|
||||||
cid = _first(ch, "id", "chunk_id")
|
|
||||||
if not cid:
|
|
||||||
continue
|
|
||||||
owner = ch.get("note_id") or note_id
|
|
||||||
e = {
|
|
||||||
"edge_id": _mk_edge_id("belongs_to", cid, note_id, "chunk", "structure:belongs_to:v1"),
|
|
||||||
"kind": "belongs_to",
|
|
||||||
"relation": "belongs_to",
|
|
||||||
"scope": "chunk",
|
|
||||||
"source_id": cid,
|
|
||||||
"target_id": note_id,
|
|
||||||
"note_id": owner, # v1-Kompat
|
|
||||||
# v2
|
|
||||||
"src_note_id": owner,
|
|
||||||
"src_chunk_id": cid,
|
|
||||||
"dst_note_id": note_id,
|
|
||||||
"provenance": "rule",
|
|
||||||
"rule_id": "structure:belongs_to:v1",
|
|
||||||
"confidence": 1.0,
|
|
||||||
}
|
|
||||||
edges.append(e)
|
|
||||||
|
|
||||||
# next/prev — bevorzugt neighbors.prev/next; sonst via ord/chunk_index
|
|
||||||
# Map der Chunks nach Index
|
|
||||||
ordered = list(chunks)
|
|
||||||
def _idx(c):
|
|
||||||
return _first(c, "chunk_index", "ord", default=0)
|
|
||||||
ordered.sort(key=_idx)
|
|
||||||
|
|
||||||
for i, ch in enumerate(ordered):
|
|
||||||
cid = _first(ch, "id", "chunk_id")
|
|
||||||
if not cid:
|
|
||||||
continue
|
|
||||||
owner = ch.get("note_id") or note_id
|
|
||||||
nb = ch.get("neighbors") or {}
|
|
||||||
prev_id = nb.get("prev")
|
|
||||||
next_id = nb.get("next")
|
|
||||||
# Fallback-Reihenfolge
|
|
||||||
if prev_id is None and i > 0:
|
|
||||||
prev_id = _first(ordered[i-1], "id", "chunk_id")
|
|
||||||
if next_id is None and i+1 < len(ordered):
|
|
||||||
next_id = _first(ordered[i+1], "id", "chunk_id")
|
|
||||||
|
|
||||||
if prev_id:
|
|
||||||
edges.append({
|
|
||||||
"edge_id": _mk_edge_id("prev", cid, prev_id, "chunk", "structure:order:v1"),
|
|
||||||
"kind": "prev", "relation": "prev", "scope": "chunk",
|
|
||||||
"source_id": cid, "target_id": prev_id, "note_id": owner,
|
|
||||||
"src_note_id": owner, "src_chunk_id": cid,
|
|
||||||
"dst_note_id": owner, "dst_chunk_id": prev_id,
|
|
||||||
"provenance": "rule", "rule_id": "structure:order:v1", "confidence": 0.95,
|
|
||||||
})
|
|
||||||
edges.append({
|
|
||||||
"edge_id": _mk_edge_id("next", prev_id, cid, "chunk", "structure:order:v1"),
|
|
||||||
"kind": "next", "relation": "next", "scope": "chunk",
|
|
||||||
"source_id": prev_id, "target_id": cid, "note_id": owner,
|
|
||||||
"src_note_id": owner, "src_chunk_id": prev_id,
|
|
||||||
"dst_note_id": owner, "dst_chunk_id": cid,
|
|
||||||
"provenance": "rule", "rule_id": "structure:order:v1", "confidence": 0.95,
|
|
||||||
})
|
|
||||||
|
|
||||||
# --- Explizite Referenzen (Chunk‑Scope) ---------------------------------
|
|
||||||
explicit_refs: List[Dict] = []
|
|
||||||
for ch in chunks:
|
|
||||||
cid = _first(ch, "id", "chunk_id")
|
|
||||||
if not cid:
|
|
||||||
continue
|
|
||||||
owner = ch.get("note_id") or note_id
|
|
||||||
# 1) bevorzugt vorhandene ch["references"]
|
|
||||||
refs = ch.get("references") or []
|
|
||||||
targets = [r.get("target_id") for r in refs if isinstance(r, dict) and r.get("target_id")]
|
|
||||||
# 2) Fallback: Wikilinks aus Text
|
|
||||||
if not targets:
|
|
||||||
text = _first(ch, "window", "text", default="") or ""
|
|
||||||
targets = _extract_wikilinks(text)
|
|
||||||
for tid in targets:
|
|
||||||
if not isinstance(tid, str) or not tid.strip():
|
|
||||||
continue
|
|
||||||
e = {
|
|
||||||
"edge_id": _mk_edge_id("references", cid, tid, "chunk"),
|
|
||||||
"kind": "references",
|
|
||||||
"relation": "references",
|
|
||||||
"scope": "chunk",
|
|
||||||
"source_id": cid,
|
|
||||||
"target_id": tid,
|
|
||||||
"note_id": owner,
|
|
||||||
# v2
|
|
||||||
"src_note_id": owner,
|
|
||||||
"src_chunk_id": cid,
|
|
||||||
"dst_note_id": tid,
|
|
||||||
"provenance": "explicit",
|
|
||||||
"rule_id": "",
|
|
||||||
"confidence": 1.0,
|
|
||||||
}
|
|
||||||
edges.append(e)
|
|
||||||
explicit_refs.append(e)
|
|
||||||
|
|
||||||
# --- Note‑Scope: references (optional) + backlink (immer) ----------------
|
|
||||||
unique_refs = []
|
|
||||||
if note_level_refs:
|
|
||||||
seen = set()
|
|
||||||
for tid in note_level_refs:
|
|
||||||
if isinstance(tid, str) and tid.strip() and tid not in seen:
|
|
||||||
unique_refs.append(tid); seen.add(tid)
|
|
||||||
|
|
||||||
for tid in unique_refs:
|
|
||||||
if include_note_scope_refs:
|
|
||||||
edges.append({
|
|
||||||
"edge_id": _mk_edge_id("references", note_id, tid, "note"),
|
|
||||||
"kind": "references", "relation": "references", "scope": "note",
|
|
||||||
"source_id": note_id, "target_id": tid, "note_id": note_id,
|
|
||||||
"src_note_id": note_id, "dst_note_id": tid,
|
|
||||||
"provenance": "explicit", "rule_id": "", "confidence": 1.0,
|
|
||||||
})
|
|
||||||
edges.append({
|
|
||||||
"edge_id": _mk_edge_id("backlink", tid, note_id, "note", "derived:backlink:v1"),
|
|
||||||
"kind": "backlink", "relation": "backlink", "scope": "note",
|
|
||||||
"source_id": tid, "target_id": note_id, "note_id": note_id,
|
|
||||||
"src_note_id": tid, "dst_note_id": note_id,
|
|
||||||
"provenance": "rule", "rule_id": "derived:backlink:v1", "confidence": 0.9,
|
|
||||||
})
|
|
||||||
|
|
||||||
# --- Type‑Defaults je expliziter Referenz --------------------------------
|
|
||||||
defaults = [d for d in _edge_defaults_for(note_type) if d and d != "references"]
|
|
||||||
if defaults:
|
|
||||||
for e in explicit_refs + ([ ] if not include_note_scope_refs else []):
|
|
||||||
# wir nutzen die bereits erzeugten explicit‑Edges als Vorlage
|
|
||||||
src = e["source_id"]; tgt = e["target_id"]
|
|
||||||
scope = e.get("scope", "chunk")
|
|
||||||
s_note = e.get("src_note_id") or note_id
|
|
||||||
s_chunk = e.get("src_chunk_id")
|
|
||||||
t_note = e.get("dst_note_id") or tgt
|
|
||||||
for rel in defaults:
|
|
||||||
rule_id = f"type_default:{(note_type or 'unknown')}:{rel}:v1"
|
|
||||||
edges.append({
|
|
||||||
"edge_id": _mk_edge_id(rel, src, tgt, scope, rule_id),
|
|
||||||
"kind": rel, "relation": rel, "scope": scope,
|
|
||||||
"source_id": src, "target_id": tgt, "note_id": s_note,
|
|
||||||
"src_note_id": s_note, "src_chunk_id": s_chunk,
|
|
||||||
"dst_note_id": t_note,
|
|
||||||
"provenance": "rule", "rule_id": rule_id, "confidence": 0.7,
|
|
||||||
})
|
|
||||||
|
|
||||||
# --- Dedupe & Return -----------------------------------------------------
|
|
||||||
return _dedupe(edges)
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
# app/core/edges_writer.py
|
|
||||||
from __future__ import annotations
|
|
||||||
import hashlib
|
|
||||||
from typing import Dict, List, Iterable, Tuple
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Dein Modul mit der Schemadefinition und der Builder-Funktion
|
|
||||||
from app.core.edges import build_edges_for_note # noqa: F401
|
|
||||||
except Exception as e:
|
|
||||||
raise RuntimeError("Konnte app.core.edges nicht importieren. "
|
|
||||||
"Bitte sicherstellen, dass app/core/edges.py vorhanden ist.") from e
|
|
||||||
|
|
||||||
def _edge_uid(kind: str, source_id: str, target_id: str, scope: str) -> str:
|
|
||||||
"""
|
|
||||||
Deterministische, kurze ID für eine Edge.
|
|
||||||
Kollisionen sind praktisch ausgeschlossen (BLAKE2s über den Kanonischen Schlüssel).
|
|
||||||
"""
|
|
||||||
key = f"{kind}|{source_id}|{target_id}|{scope}"
|
|
||||||
return hashlib.blake2s(key.encode("utf-8"), digest_size=12).hexdigest()
|
|
||||||
|
|
||||||
def ensure_edges_collection(qdrant_client, collection: str) -> None:
|
|
||||||
"""
|
|
||||||
Legt die Edge-Collection an, falls sie nicht existiert.
|
|
||||||
Minimal: 1D-Vector (Dummy), Cosine. Payload-only-Collections sind je nach Qdrant-Version heikel.
|
|
||||||
"""
|
|
||||||
from qdrant_client.http import models as qm
|
|
||||||
|
|
||||||
existing = [c.name for c in qdrant_client.get_collections().collections]
|
|
||||||
if collection in existing:
|
|
||||||
return
|
|
||||||
|
|
||||||
qdrant_client.recreate_collection(
|
|
||||||
collection_name=collection,
|
|
||||||
vectors_config=qm.VectorParams(size=1, distance=qm.Distance.COSINE),
|
|
||||||
on_disk_payload=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
def edges_from_note(
|
|
||||||
note_id: str,
|
|
||||||
chunk_payloads: List[Dict],
|
|
||||||
note_level_refs: Iterable[str] | None,
|
|
||||||
*,
|
|
||||||
include_note_scope_refs: bool = False,
|
|
||||||
) -> List[Dict]:
|
|
||||||
"""
|
|
||||||
Ruft deinen Edge-Builder auf und gibt die (deduplizierten) Edge-Payloads zurück.
|
|
||||||
Keine Schemaänderung – exakt das aus app/core/edges.py.
|
|
||||||
"""
|
|
||||||
return build_edges_for_note(
|
|
||||||
note_id=note_id,
|
|
||||||
chunk_payloads=chunk_payloads,
|
|
||||||
note_level_refs=list(note_level_refs or []),
|
|
||||||
include_note_scope_refs=include_note_scope_refs,
|
|
||||||
)
|
|
||||||
|
|
||||||
def upsert_edges(
|
|
||||||
qdrant_client,
|
|
||||||
collection: str,
|
|
||||||
edge_payloads: List[Dict],
|
|
||||||
) -> Tuple[int, int]:
|
|
||||||
"""
|
|
||||||
Schreibt Edges als Points in Qdrant.
|
|
||||||
- id: deterministisch aus (kind, source_id, target_id, scope)
|
|
||||||
- vector: [0.0] Dummy
|
|
||||||
- payload: Edge-Dict (unverändert, siehe Schema in app/core/edges.py)
|
|
||||||
Gibt (anzahl_points, anzahl_unique_keys) zurück.
|
|
||||||
"""
|
|
||||||
from qdrant_client.models import PointStruct
|
|
||||||
|
|
||||||
if not edge_payloads:
|
|
||||||
return 0, 0
|
|
||||||
|
|
||||||
points = []
|
|
||||||
seen = set()
|
|
||||||
for e in edge_payloads:
|
|
||||||
key = (e.get("kind"), e.get("source_id"), e.get("target_id"), e.get("scope"))
|
|
||||||
if key in seen:
|
|
||||||
continue
|
|
||||||
seen.add(key)
|
|
||||||
eid = _edge_uid(*key)
|
|
||||||
points.append(
|
|
||||||
PointStruct(
|
|
||||||
id=eid,
|
|
||||||
vector=[0.0],
|
|
||||||
payload=e,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
if not points:
|
|
||||||
return 0, 0
|
|
||||||
|
|
||||||
ensure_edges_collection(qdrant_client, collection)
|
|
||||||
qdrant_client.upsert(collection_name=collection, points=points)
|
|
||||||
return len(points), len(seen)
|
|
||||||
@@ -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]
|
|
||||||
@@ -1,103 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
Datei: app/core/env_vars.py
|
|
||||||
Version: 1.1.0 (2025-11-08)
|
|
||||||
|
|
||||||
Zweck
|
|
||||||
Einheitliche Auflösung von ENV-Variablen (Prefix, Qdrant, Embeddings, Hashing)
|
|
||||||
mit Abwärtskompatibilität.
|
|
||||||
|
|
||||||
Grundsatz
|
|
||||||
- Für Qdrant-Funktionen ist 'COLLECTION_PREFIX' der Primärschlüssel.
|
|
||||||
- 'MINDNET_PREFIX' bleibt für App-/UI-/Exporter-Kontexte nutzbar.
|
|
||||||
- Fallbacks sorgen dafür, dass ältere Umgebungen weiter funktionieren.
|
|
||||||
|
|
||||||
Wichtig
|
|
||||||
- Lädt optional eine .env (wenn python-dotenv verfügbar ist).
|
|
||||||
- Überschreibt keine bereits gesetzten OS-Variablen (override=False).
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
from typing import Optional, Dict
|
|
||||||
|
|
||||||
# Optional: .env automatisch laden (ohne Hard-Fail, falls nicht vorhanden)
|
|
||||||
try:
|
|
||||||
from dotenv import load_dotenv, find_dotenv # type: ignore
|
|
||||||
_p = find_dotenv()
|
|
||||||
if _p:
|
|
||||||
load_dotenv(_p, override=False)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# -------- Prefix-Auflösung --------
|
|
||||||
|
|
||||||
def get_collection_prefix(cli_override: Optional[str] = None) -> str:
|
|
||||||
"""
|
|
||||||
Für Qdrant-relevante Funktionen:
|
|
||||||
1) CLI-Override (--prefix)
|
|
||||||
2) ENV COLLECTION_PREFIX
|
|
||||||
3) ENV MINDNET_PREFIX (Fallback)
|
|
||||||
4) 'mindnet' (Default)
|
|
||||||
"""
|
|
||||||
if cli_override and str(cli_override).strip():
|
|
||||||
return str(cli_override).strip()
|
|
||||||
return (
|
|
||||||
os.getenv("COLLECTION_PREFIX")
|
|
||||||
or os.getenv("MINDNET_PREFIX")
|
|
||||||
or "mindnet"
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_mindnet_prefix(cli_override: Optional[str] = None) -> str:
|
|
||||||
"""
|
|
||||||
Für App-/UI-/Exporter-Kontexte:
|
|
||||||
1) CLI-Override (--prefix)
|
|
||||||
2) ENV MINDNET_PREFIX
|
|
||||||
3) ENV COLLECTION_PREFIX (Fallback)
|
|
||||||
4) 'mindnet'
|
|
||||||
"""
|
|
||||||
if cli_override and str(cli_override).strip():
|
|
||||||
return str(cli_override).strip()
|
|
||||||
return (
|
|
||||||
os.getenv("MINDNET_PREFIX")
|
|
||||||
or os.getenv("COLLECTION_PREFIX")
|
|
||||||
or "mindnet"
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_prefix(cli_override: Optional[str] = None, target: str = "qdrant") -> str:
|
|
||||||
"""
|
|
||||||
Universelle Hülle (abwärtskompatibel):
|
|
||||||
target='qdrant' -> get_collection_prefix
|
|
||||||
target='app' -> get_mindnet_prefix
|
|
||||||
"""
|
|
||||||
if target.lower() == "app":
|
|
||||||
return get_mindnet_prefix(cli_override)
|
|
||||||
return get_collection_prefix(cli_override)
|
|
||||||
|
|
||||||
# -------- Qdrant / Embeddings / Hashing --------
|
|
||||||
|
|
||||||
def get_qdrant_url(default: str = "http://127.0.0.1:6333") -> str:
|
|
||||||
return os.getenv("QDRANT_URL", default)
|
|
||||||
|
|
||||||
def get_qdrant_api_key(default: str = "") -> str:
|
|
||||||
return os.getenv("QDRANT_API_KEY", default)
|
|
||||||
|
|
||||||
def get_vector_dim(default: int = 384) -> int:
|
|
||||||
try:
|
|
||||||
return int(os.getenv("VECTOR_DIM", str(default)))
|
|
||||||
except Exception:
|
|
||||||
return default
|
|
||||||
|
|
||||||
def get_embed_url(default: Optional[str] = None) -> Optional[str]:
|
|
||||||
return os.getenv("EMBED_URL", default)
|
|
||||||
|
|
||||||
def get_hash_env() -> Dict[str, str]:
|
|
||||||
"""
|
|
||||||
Liefert die Hash-Konfiguration (nur Aggregation; die Auswertung bleibt in den Skripten).
|
|
||||||
"""
|
|
||||||
return {
|
|
||||||
"MINDNET_HASH_COMPARE": os.getenv("MINDNET_HASH_COMPARE", ""),
|
|
||||||
"MINDNET_HASH_SOURCE": os.getenv("MINDNET_HASH_SOURCE", ""),
|
|
||||||
"MINDNET_HASH_NORMALIZE": os.getenv("MINDNET_HASH_NORMALIZE", ""),
|
|
||||||
}
|
|
||||||
@@ -1,17 +1,10 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
app/core/graph_adapter.py — Adjazenzaufbau & Subgraph-Expansion
|
FILE: app/core/graph_adapter.py
|
||||||
|
DESCRIPTION: Lädt Kanten aus Qdrant und baut einen In-Memory Subgraphen für Scoring (Centrality) und Explanation.
|
||||||
Zweck:
|
VERSION: 0.4.0
|
||||||
Baut aus Qdrant-Edges (Collection: *_edges) einen leichten In-Memory-Graph.
|
STATUS: Active
|
||||||
|
DEPENDENCIES: qdrant_client, app.core.qdrant
|
||||||
Kompatibilität:
|
LAST_ANALYSIS: 2025-12-15
|
||||||
- WP-04a: Liefert Scores (edge_bonus, centrality).
|
|
||||||
- WP-04b: Liefert jetzt auch Struktur-Daten für Erklärungen (Reverse-Lookup).
|
|
||||||
|
|
||||||
Version:
|
|
||||||
0.4.0 (Update für WP-04b: Reverse Adjacency für Explainability)
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
+122
-70
@@ -1,8 +1,14 @@
|
|||||||
"""
|
"""
|
||||||
app/core/ingestion.py
|
FILE: app/core/ingestion.py
|
||||||
|
DESCRIPTION: Haupt-Ingestion-Logik. Transformiert Markdown in den Graphen (Notes, Chunks, Edges).
|
||||||
Zentraler Service für die Transformation von Markdown-Dateien in Qdrant-Objekte.
|
FIX: Korrekte Priorisierung von Frontmatter für chunk_profile und retriever_weight.
|
||||||
Version: 2.5.2 (Full Feature: Change Detection + Robust IO + Clean Config)
|
Lade Chunk-Config basierend auf dem effektiven Profil, nicht nur dem Notiz-Typ.
|
||||||
|
WP-22: Integration von Content Lifecycle (Status Gate) und Edge Registry Validation.
|
||||||
|
WP-22: Multi-Hash Refresh für konsistente Change Detection.
|
||||||
|
VERSION: 2.8.6 (WP-22 Lifecycle & Registry)
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.core.parser, app.core.note_payload, app.core.chunker, app.core.derive_edges, app.core.qdrant*, app.services.embeddings_client, app.services.edge_registry
|
||||||
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
@@ -35,11 +41,13 @@ from app.core.qdrant_points import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
from app.services.embeddings_client import EmbeddingsClient
|
from app.services.embeddings_client import EmbeddingsClient
|
||||||
|
from app.services.edge_registry import registry as edge_registry
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# --- Helper ---
|
# --- Helper ---
|
||||||
def load_type_registry(custom_path: Optional[str] = None) -> dict:
|
def load_type_registry(custom_path: Optional[str] = None) -> dict:
|
||||||
|
"""Lädt die types.yaml zur Steuerung der typ-spezifischen Ingestion."""
|
||||||
import yaml
|
import yaml
|
||||||
path = custom_path or os.getenv("MINDNET_TYPES_FILE", "config/types.yaml")
|
path = custom_path or os.getenv("MINDNET_TYPES_FILE", "config/types.yaml")
|
||||||
if not os.path.exists(path): return {}
|
if not os.path.exists(path): return {}
|
||||||
@@ -48,20 +56,47 @@ def load_type_registry(custom_path: Optional[str] = None) -> dict:
|
|||||||
except Exception: return {}
|
except Exception: return {}
|
||||||
|
|
||||||
def resolve_note_type(requested: Optional[str], reg: dict) -> str:
|
def resolve_note_type(requested: Optional[str], reg: dict) -> str:
|
||||||
|
"""Bestimmt den finalen Notiz-Typ (Fallback auf 'concept')."""
|
||||||
types = reg.get("types", {})
|
types = reg.get("types", {})
|
||||||
if requested and requested in types: return requested
|
if requested and requested in types: return requested
|
||||||
return "concept"
|
return "concept"
|
||||||
|
|
||||||
def effective_chunk_profile(note_type: str, reg: dict) -> str:
|
def effective_chunk_profile_name(fm: dict, note_type: str, reg: dict) -> str:
|
||||||
t_cfg = reg.get("types", {}).get(note_type, {})
|
"""
|
||||||
if t_cfg and t_cfg.get("chunk_profile"):
|
Ermittelt den Namen des zu nutzenden Chunk-Profils.
|
||||||
return t_cfg.get("chunk_profile")
|
Priorität: 1. Frontmatter Override -> 2. Type Config -> 3. Global Default
|
||||||
return reg.get("defaults", {}).get("chunk_profile", "default")
|
"""
|
||||||
|
# 1. Frontmatter Override
|
||||||
|
override = fm.get("chunking_profile") or fm.get("chunk_profile")
|
||||||
|
if override and isinstance(override, str):
|
||||||
|
return override
|
||||||
|
|
||||||
def effective_retriever_weight(note_type: str, reg: dict) -> float:
|
# 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 effektive retriever_weight für das Scoring.
|
||||||
|
Priorität: 1. Frontmatter Override -> 2. Type Config -> 3. Global 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, {})
|
t_cfg = reg.get("types", {}).get(note_type, {})
|
||||||
if t_cfg and "retriever_weight" in t_cfg:
|
if t_cfg and "retriever_weight" in t_cfg:
|
||||||
return float(t_cfg["retriever_weight"])
|
return float(t_cfg["retriever_weight"])
|
||||||
|
|
||||||
|
# 3. Global Default
|
||||||
return float(reg.get("defaults", {}).get("retriever_weight", 1.0))
|
return float(reg.get("defaults", {}).get("retriever_weight", 1.0))
|
||||||
|
|
||||||
|
|
||||||
@@ -77,12 +112,25 @@ class IngestionService:
|
|||||||
self.registry = load_type_registry()
|
self.registry = load_type_registry()
|
||||||
self.embedder = EmbeddingsClient()
|
self.embedder = EmbeddingsClient()
|
||||||
|
|
||||||
|
# Change Detection Modus (full oder body)
|
||||||
|
self.active_hash_mode = os.getenv("MINDNET_CHANGE_DETECTION_MODE", "full")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
ensure_collections(self.client, self.prefix, self.dim)
|
ensure_collections(self.client, self.prefix, self.dim)
|
||||||
ensure_payload_indexes(self.client, self.prefix)
|
ensure_payload_indexes(self.client, self.prefix)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"DB init warning: {e}")
|
logger.warning(f"DB init warning: {e}")
|
||||||
|
|
||||||
|
def _get_chunk_config_by_profile(self, profile_name: str, note_type: str) -> Dict[str, Any]:
|
||||||
|
"""Holt die Chunker-Parameter (max, target, overlap) für ein spezifisches Profil."""
|
||||||
|
profiles = self.registry.get("chunking_profiles", {})
|
||||||
|
if profile_name in profiles:
|
||||||
|
cfg = profiles[profile_name].copy()
|
||||||
|
if "overlap" in cfg and isinstance(cfg["overlap"], list):
|
||||||
|
cfg["overlap"] = tuple(cfg["overlap"])
|
||||||
|
return cfg
|
||||||
|
return get_chunk_config(note_type)
|
||||||
|
|
||||||
async def process_file(
|
async def process_file(
|
||||||
self,
|
self,
|
||||||
file_path: str,
|
file_path: str,
|
||||||
@@ -91,72 +139,81 @@ class IngestionService:
|
|||||||
apply: bool = False,
|
apply: bool = False,
|
||||||
purge_before: bool = False,
|
purge_before: bool = False,
|
||||||
note_scope_refs: bool = False,
|
note_scope_refs: bool = False,
|
||||||
hash_mode: str = "body",
|
|
||||||
hash_source: str = "parsed",
|
hash_source: str = "parsed",
|
||||||
hash_normalize: str = "canonical"
|
hash_normalize: str = "canonical"
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Verarbeitet eine einzelne Datei (ASYNC).
|
Verarbeitet eine Markdown-Datei und schreibt sie in den Graphen.
|
||||||
Inklusive Change Detection (Hash-Check) gegen Qdrant.
|
Folgt dem 14-Schritte-Workflow.
|
||||||
"""
|
"""
|
||||||
result = {
|
result = {"path": file_path, "status": "skipped", "changed": False, "error": None}
|
||||||
"path": file_path,
|
|
||||||
"status": "skipped",
|
|
||||||
"changed": False,
|
|
||||||
"error": None
|
|
||||||
}
|
|
||||||
|
|
||||||
# 1. Parse & Frontmatter Validation
|
# 1. Parse & Frontmatter Validation
|
||||||
try:
|
try:
|
||||||
parsed = read_markdown(file_path)
|
parsed = read_markdown(file_path)
|
||||||
if not parsed:
|
if not parsed: return {**result, "error": "Empty or unreadable file"}
|
||||||
return {**result, "error": "Empty or unreadable file"}
|
|
||||||
|
|
||||||
fm = normalize_frontmatter(parsed.frontmatter)
|
fm = normalize_frontmatter(parsed.frontmatter)
|
||||||
validate_required_frontmatter(fm)
|
validate_required_frontmatter(fm)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Validation failed for {file_path}: {e}")
|
logger.error(f"Validation failed for {file_path}: {e}")
|
||||||
return {**result, "error": f"Validation failed: {str(e)}"}
|
return {**result, "error": f"Validation failed: {str(e)}"}
|
||||||
|
|
||||||
|
# --- WP-22: Content Lifecycle Gate (Teil A) ---
|
||||||
|
status = fm.get("status", "draft").lower().strip()
|
||||||
|
|
||||||
|
# Hard Skip für System- oder Archiv-Dateien
|
||||||
|
if status in ["system", "template", "archive", "hidden"]:
|
||||||
|
logger.info(f"Skipping file {file_path} (Status: {status})")
|
||||||
|
return {**result, "status": "skipped", "reason": f"lifecycle_status_{status}"}
|
||||||
|
|
||||||
# 2. Type & Config Resolution
|
# 2. Type & Config Resolution
|
||||||
note_type = resolve_note_type(fm.get("type"), self.registry)
|
note_type = resolve_note_type(fm.get("type"), self.registry)
|
||||||
fm["type"] = note_type
|
fm["type"] = note_type
|
||||||
fm["chunk_profile"] = effective_chunk_profile(note_type, self.registry)
|
|
||||||
|
|
||||||
weight = fm.get("retriever_weight")
|
effective_profile = effective_chunk_profile_name(fm, note_type, self.registry)
|
||||||
if weight is None:
|
effective_weight = effective_retriever_weight(fm, note_type, self.registry)
|
||||||
weight = effective_retriever_weight(note_type, self.registry)
|
|
||||||
fm["retriever_weight"] = float(weight)
|
|
||||||
|
|
||||||
# 3. Build Note Payload
|
fm["chunk_profile"] = effective_profile
|
||||||
|
fm["retriever_weight"] = effective_weight
|
||||||
|
|
||||||
|
# 3. Build Note Payload (Inkl. Multi-Hash für WP-22)
|
||||||
try:
|
try:
|
||||||
note_pl = make_note_payload(
|
note_pl = make_note_payload(
|
||||||
parsed,
|
parsed,
|
||||||
vault_root=vault_root,
|
vault_root=vault_root,
|
||||||
hash_mode=hash_mode,
|
|
||||||
hash_normalize=hash_normalize,
|
hash_normalize=hash_normalize,
|
||||||
hash_source=hash_source,
|
hash_source=hash_source,
|
||||||
file_path=file_path
|
file_path=file_path
|
||||||
)
|
)
|
||||||
if not note_pl.get("fulltext"):
|
# Text Body Fallback
|
||||||
note_pl["fulltext"] = getattr(parsed, "body", "") or ""
|
if not note_pl.get("fulltext"): note_pl["fulltext"] = getattr(parsed, "body", "") or ""
|
||||||
note_pl["retriever_weight"] = fm["retriever_weight"]
|
|
||||||
|
# Sicherstellen der effektiven Werte im Payload
|
||||||
|
note_pl["retriever_weight"] = effective_weight
|
||||||
|
note_pl["chunk_profile"] = effective_profile
|
||||||
|
# WP-22: Status speichern
|
||||||
|
note_pl["status"] = status
|
||||||
|
|
||||||
note_id = note_pl["note_id"]
|
note_id = note_pl["note_id"]
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Payload build failed: {e}")
|
logger.error(f"Payload build failed: {e}")
|
||||||
return {**result, "error": f"Payload build failed: {str(e)}"}
|
return {**result, "error": f"Payload build failed: {str(e)}"}
|
||||||
|
|
||||||
# 4. Change Detection (Das fehlende Stück!)
|
# 4. Change Detection
|
||||||
old_payload = None
|
old_payload = None
|
||||||
if not force_replace:
|
if not force_replace:
|
||||||
old_payload = self._fetch_note_payload(note_id)
|
old_payload = self._fetch_note_payload(note_id)
|
||||||
|
|
||||||
has_old = old_payload is not None
|
has_old = old_payload is not None
|
||||||
key_current = f"{hash_mode}:{hash_source}:{hash_normalize}"
|
# Prüfung gegen den aktuell konfigurierten Hash-Modus (body oder full)
|
||||||
old_hash = (old_payload or {}).get("hashes", {}).get(key_current)
|
check_key = f"{self.active_hash_mode}:{hash_source}:{hash_normalize}"
|
||||||
new_hash = note_pl.get("hashes", {}).get(key_current)
|
|
||||||
|
|
||||||
|
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)
|
hash_changed = (old_hash != new_hash)
|
||||||
chunks_missing, edges_missing = self._artifacts_missing(note_id)
|
chunks_missing, edges_missing = self._artifacts_missing(note_id)
|
||||||
|
|
||||||
@@ -168,18 +225,18 @@ class IngestionService:
|
|||||||
if not apply:
|
if not apply:
|
||||||
return {**result, "status": "dry-run", "changed": True, "note_id": note_id}
|
return {**result, "status": "dry-run", "changed": True, "note_id": note_id}
|
||||||
|
|
||||||
# 5. Processing (Chunking, Embedding, Edges)
|
# 5. Processing (Chunking, Embedding, Edge Generation)
|
||||||
try:
|
try:
|
||||||
body_text = getattr(parsed, "body", "") or ""
|
body_text = getattr(parsed, "body", "") or ""
|
||||||
|
|
||||||
# --- Config Loading (Clean) ---
|
# Konfiguration für das spezifische Profil laden
|
||||||
chunk_config = get_chunk_config(note_type)
|
chunk_config = self._get_chunk_config_by_profile(effective_profile, note_type)
|
||||||
# Hier greift die Logik aus types.yaml (smart=True/False)
|
|
||||||
|
|
||||||
chunks = await assemble_chunks(fm["id"], body_text, fm["type"], config=chunk_config)
|
chunks = await assemble_chunks(fm["id"], body_text, fm["type"], config=chunk_config)
|
||||||
|
|
||||||
|
# Chunks mit Metadaten anreichern
|
||||||
chunk_pls = make_chunk_payloads(fm, note_pl["path"], chunks, note_text=body_text)
|
chunk_pls = make_chunk_payloads(fm, note_pl["path"], chunks, note_text=body_text)
|
||||||
|
|
||||||
# Embedding
|
|
||||||
vecs = []
|
vecs = []
|
||||||
if chunk_pls:
|
if chunk_pls:
|
||||||
texts = [c.get("window") or c.get("text") or "" for c in chunk_pls]
|
texts = [c.get("window") or c.get("text") or "" for c in chunk_pls]
|
||||||
@@ -194,33 +251,47 @@ class IngestionService:
|
|||||||
logger.error(f"Embedding failed: {e}")
|
logger.error(f"Embedding failed: {e}")
|
||||||
raise RuntimeError(f"Embedding failed: {e}")
|
raise RuntimeError(f"Embedding failed: {e}")
|
||||||
|
|
||||||
# Edges
|
# Kanten generieren
|
||||||
try:
|
try:
|
||||||
edges = build_edges_for_note(
|
raw_edges = build_edges_for_note(
|
||||||
note_id,
|
note_id,
|
||||||
chunk_pls,
|
chunk_pls,
|
||||||
note_level_references=note_pl.get("references", []),
|
note_level_references=note_pl.get("references", []),
|
||||||
include_note_scope_refs=note_scope_refs
|
include_note_scope_refs=note_scope_refs
|
||||||
)
|
)
|
||||||
except TypeError:
|
except TypeError:
|
||||||
edges = build_edges_for_note(note_id, chunk_pls)
|
raw_edges = build_edges_for_note(note_id, chunk_pls)
|
||||||
|
|
||||||
|
# --- WP-22: Edge Registry Validation (Teil B) ---
|
||||||
|
edges = []
|
||||||
|
if raw_edges:
|
||||||
|
for edge in raw_edges:
|
||||||
|
original_kind = edge.get("kind", "related_to")
|
||||||
|
# Normalisierung über die Registry (Alias-Auflösung)
|
||||||
|
canonical_kind = edge_registry.resolve(original_kind)
|
||||||
|
edge["kind"] = canonical_kind
|
||||||
|
edges.append(edge)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Processing failed: {e}", exc_info=True)
|
logger.error(f"Processing failed: {e}", exc_info=True)
|
||||||
return {**result, "error": f"Processing failed: {str(e)}"}
|
return {**result, "error": f"Processing failed: {str(e)}"}
|
||||||
|
|
||||||
# 6. Upsert Action
|
# 6. Upsert in Qdrant
|
||||||
try:
|
try:
|
||||||
|
# Alte Fragmente löschen, um "Geister-Chunks" zu vermeiden
|
||||||
if purge_before and has_old:
|
if purge_before and has_old:
|
||||||
self._purge_artifacts(note_id)
|
self._purge_artifacts(note_id)
|
||||||
|
|
||||||
|
# Note Metadaten
|
||||||
n_name, n_pts = points_for_note(self.prefix, note_pl, None, self.dim)
|
n_name, n_pts = points_for_note(self.prefix, note_pl, None, self.dim)
|
||||||
upsert_batch(self.client, n_name, n_pts)
|
upsert_batch(self.client, n_name, n_pts)
|
||||||
|
|
||||||
|
# Chunks (Vektoren)
|
||||||
if chunk_pls and vecs:
|
if chunk_pls and vecs:
|
||||||
c_name, c_pts = points_for_chunks(self.prefix, chunk_pls, vecs)
|
c_name, c_pts = points_for_chunks(self.prefix, chunk_pls, vecs)
|
||||||
upsert_batch(self.client, c_name, c_pts)
|
upsert_batch(self.client, c_name, c_pts)
|
||||||
|
|
||||||
|
# Kanten
|
||||||
if edges:
|
if edges:
|
||||||
e_name, e_pts = points_for_edges(self.prefix, edges)
|
e_name, e_pts = points_for_edges(self.prefix, edges)
|
||||||
upsert_batch(self.client, e_name, e_pts)
|
upsert_batch(self.client, e_name, e_pts)
|
||||||
@@ -237,9 +308,8 @@ class IngestionService:
|
|||||||
logger.error(f"Upsert failed: {e}", exc_info=True)
|
logger.error(f"Upsert failed: {e}", exc_info=True)
|
||||||
return {**result, "error": f"DB Upsert failed: {e}"}
|
return {**result, "error": f"DB Upsert failed: {e}"}
|
||||||
|
|
||||||
# --- Qdrant Helper (Restored) ---
|
|
||||||
|
|
||||||
def _fetch_note_payload(self, note_id: str) -> Optional[dict]:
|
def _fetch_note_payload(self, note_id: str) -> Optional[dict]:
|
||||||
|
"""Holt das aktuelle Payload einer Note aus Qdrant."""
|
||||||
from qdrant_client.http import models as rest
|
from qdrant_client.http import models as rest
|
||||||
col = f"{self.prefix}_notes"
|
col = f"{self.prefix}_notes"
|
||||||
try:
|
try:
|
||||||
@@ -249,6 +319,7 @@ class IngestionService:
|
|||||||
except: return None
|
except: return None
|
||||||
|
|
||||||
def _artifacts_missing(self, note_id: str) -> Tuple[bool, bool]:
|
def _artifacts_missing(self, note_id: str) -> Tuple[bool, bool]:
|
||||||
|
"""Prüft, ob Chunks oder Kanten für eine Note fehlen (Integritätscheck)."""
|
||||||
from qdrant_client.http import models as rest
|
from qdrant_client.http import models as rest
|
||||||
c_col = f"{self.prefix}_chunks"
|
c_col = f"{self.prefix}_chunks"
|
||||||
e_col = f"{self.prefix}_edges"
|
e_col = f"{self.prefix}_edges"
|
||||||
@@ -260,6 +331,7 @@ class IngestionService:
|
|||||||
except: return True, True
|
except: return True, True
|
||||||
|
|
||||||
def _purge_artifacts(self, note_id: str):
|
def _purge_artifacts(self, note_id: str):
|
||||||
|
"""Löscht alle Chunks und Edges einer Note (vor dem Neu-Schreiben)."""
|
||||||
from qdrant_client.http import models as rest
|
from qdrant_client.http import models as rest
|
||||||
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
||||||
selector = rest.FilterSelector(filter=f)
|
selector = rest.FilterSelector(filter=f)
|
||||||
@@ -268,38 +340,18 @@ class IngestionService:
|
|||||||
self.client.delete(collection_name=f"{self.prefix}_{suffix}", points_selector=selector)
|
self.client.delete(collection_name=f"{self.prefix}_{suffix}", points_selector=selector)
|
||||||
except Exception: pass
|
except Exception: pass
|
||||||
|
|
||||||
async def create_from_text(
|
async def create_from_text(self, markdown_content: str, filename: str, vault_root: str, folder: str = "00_Inbox") -> Dict[str, Any]:
|
||||||
self,
|
"""Hilfsmethode zur Erstellung einer Note aus einem Textstream (Editor-Save)."""
|
||||||
markdown_content: str,
|
|
||||||
filename: str,
|
|
||||||
vault_root: str,
|
|
||||||
folder: str = "00_Inbox"
|
|
||||||
) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
WP-11 Persistence API Entrypoint.
|
|
||||||
"""
|
|
||||||
target_dir = os.path.join(vault_root, folder)
|
target_dir = os.path.join(vault_root, folder)
|
||||||
os.makedirs(target_dir, exist_ok=True)
|
os.makedirs(target_dir, exist_ok=True)
|
||||||
|
|
||||||
file_path = os.path.join(target_dir, filename)
|
file_path = os.path.join(target_dir, filename)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Robust Write: Ensure Flush & Sync
|
|
||||||
with open(file_path, "w", encoding="utf-8") as f:
|
with open(file_path, "w", encoding="utf-8") as f:
|
||||||
f.write(markdown_content)
|
f.write(markdown_content)
|
||||||
f.flush()
|
f.flush()
|
||||||
os.fsync(f.fileno())
|
os.fsync(f.fileno())
|
||||||
|
|
||||||
await asyncio.sleep(0.1)
|
await asyncio.sleep(0.1)
|
||||||
|
|
||||||
logger.info(f"Written file to {file_path}")
|
logger.info(f"Written file to {file_path}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return {"status": "error", "error": f"Disk write failed: {str(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)
|
||||||
return await self.process_file(
|
|
||||||
file_path=file_path,
|
|
||||||
vault_root=vault_root,
|
|
||||||
apply=True,
|
|
||||||
force_replace=True,
|
|
||||||
purge_before=True
|
|
||||||
)
|
|
||||||
+83
-51
@@ -1,17 +1,13 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
Modul: app/core/note_payload.py
|
FILE: app/core/note_payload.py
|
||||||
Version: 2.1.0 (WP-11 Update: Aliases support)
|
DESCRIPTION: Baut das JSON-Objekt.
|
||||||
|
FEATURES:
|
||||||
Zweck
|
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').
|
||||||
Erzeugt ein robustes Note-Payload. Werte wie `retriever_weight`, `chunk_profile`
|
VERSION: 2.3.0
|
||||||
und `edge_defaults` werden in folgender Priorität bestimmt:
|
STATUS: Active
|
||||||
1) Frontmatter (Note)
|
DEPENDENCIES: yaml, os, json, pathlib, hashlib
|
||||||
2) Typ-Registry (config/types.yaml: types.<type>.*)
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
3) Registry-Defaults (config/types.yaml: defaults.*)
|
|
||||||
4) ENV-Defaults (MINDNET_DEFAULT_RETRIEVER_WEIGHT / MINDNET_DEFAULT_CHUNK_PROFILE)
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -20,6 +16,7 @@ from typing import Any, Dict, Tuple, Optional
|
|||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
import pathlib
|
import pathlib
|
||||||
|
import hashlib
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import yaml # type: ignore
|
import yaml # type: ignore
|
||||||
@@ -37,7 +34,6 @@ def _as_dict(x) -> Dict[str, Any]:
|
|||||||
return dict(x)
|
return dict(x)
|
||||||
|
|
||||||
out: Dict[str, Any] = {}
|
out: Dict[str, Any] = {}
|
||||||
# bekannte Attribute übernehmen, sofern vorhanden
|
|
||||||
for attr in (
|
for attr in (
|
||||||
"frontmatter",
|
"frontmatter",
|
||||||
"body",
|
"body",
|
||||||
@@ -56,7 +52,6 @@ def _as_dict(x) -> Dict[str, Any]:
|
|||||||
if val is not None:
|
if val is not None:
|
||||||
out[attr] = val
|
out[attr] = val
|
||||||
|
|
||||||
# Fallback: wenn immer noch leer, raw speichern
|
|
||||||
if not out:
|
if not out:
|
||||||
out["raw"] = str(x)
|
out["raw"] = str(x)
|
||||||
|
|
||||||
@@ -64,14 +59,12 @@ def _as_dict(x) -> Dict[str, Any]:
|
|||||||
|
|
||||||
|
|
||||||
def _pick_args(*args, **kwargs) -> Tuple[Optional[str], Optional[dict]]:
|
def _pick_args(*args, **kwargs) -> Tuple[Optional[str], Optional[dict]]:
|
||||||
"""Extrahiert optionale Zusatzargumente wie path und types_cfg."""
|
|
||||||
path = kwargs.get("path") or (args[0] if args else None)
|
path = kwargs.get("path") or (args[0] if args else None)
|
||||||
types_cfg = kwargs.get("types_cfg") or kwargs.get("types") or None
|
types_cfg = kwargs.get("types_cfg") or kwargs.get("types") or None
|
||||||
return path, types_cfg
|
return path, types_cfg
|
||||||
|
|
||||||
|
|
||||||
def _env_float(name: str, default: float) -> float:
|
def _env_float(name: str, default: float) -> float:
|
||||||
"""Liest einen Float-Wert aus der Umgebung, mit robustem Fallback."""
|
|
||||||
try:
|
try:
|
||||||
return float(os.environ.get(name, default))
|
return float(os.environ.get(name, default))
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -79,7 +72,6 @@ def _env_float(name: str, default: float) -> float:
|
|||||||
|
|
||||||
|
|
||||||
def _ensure_list(x) -> list:
|
def _ensure_list(x) -> list:
|
||||||
"""Garantiert eine String-Liste."""
|
|
||||||
if x is None:
|
if x is None:
|
||||||
return []
|
return []
|
||||||
if isinstance(x, list):
|
if isinstance(x, list):
|
||||||
@@ -88,13 +80,44 @@ def _ensure_list(x) -> list:
|
|||||||
return [str(i) for i in x]
|
return [str(i) for i in x]
|
||||||
return [str(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":
|
||||||
|
fm = n.get("frontmatter") or {}
|
||||||
|
# Wichtig: Sortierte Keys für deterministisches Verhalten!
|
||||||
|
# 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
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Type-Registry laden
|
# Type-Registry laden
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
def _load_types_config(explicit_cfg: Optional[dict] = None) -> dict:
|
def _load_types_config(explicit_cfg: Optional[dict] = None) -> dict:
|
||||||
"""Lädt die Type-Registry aus YAML/JSON oder nutzt ein explizit übergebenes Dict."""
|
|
||||||
if explicit_cfg and isinstance(explicit_cfg, dict):
|
if explicit_cfg and isinstance(explicit_cfg, dict):
|
||||||
return explicit_cfg
|
return explicit_cfg
|
||||||
|
|
||||||
@@ -111,7 +134,6 @@ def _load_types_config(explicit_cfg: Optional[dict] = None) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def _cfg_for_type(note_type: str, reg: dict) -> dict:
|
def _cfg_for_type(note_type: str, reg: dict) -> dict:
|
||||||
"""Liefert die Konfiguration für einen konkreten Notiztyp aus der Registry."""
|
|
||||||
if not isinstance(reg, dict):
|
if not isinstance(reg, dict):
|
||||||
return {}
|
return {}
|
||||||
types = reg.get("types") if isinstance(reg.get("types"), dict) else reg
|
types = reg.get("types") if isinstance(reg.get("types"), dict) else reg
|
||||||
@@ -119,7 +141,6 @@ def _cfg_for_type(note_type: str, reg: dict) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def _cfg_defaults(reg: dict) -> dict:
|
def _cfg_defaults(reg: dict) -> dict:
|
||||||
"""Liefert den Default-Block aus der Registry (defaults/global)."""
|
|
||||||
if not isinstance(reg, dict):
|
if not isinstance(reg, dict):
|
||||||
return {}
|
return {}
|
||||||
for key in ("defaults", "default", "global"):
|
for key in ("defaults", "default", "global"):
|
||||||
@@ -136,21 +157,16 @@ def _cfg_defaults(reg: dict) -> dict:
|
|||||||
def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Baut das Note-Payload für mindnet_notes auf.
|
Baut das Note-Payload für mindnet_notes auf.
|
||||||
|
Inkludiert Hash-Berechnung (Body & Full) und korrigierte Config-Lookups.
|
||||||
Erwartete Felder im Payload:
|
|
||||||
- note_id: stabile ID aus Frontmatter (id) oder Note-Objekt
|
|
||||||
- title: Titel der Notiz
|
|
||||||
- type: Notiztyp (z. B. concept, project, journal, ...)
|
|
||||||
- path: Pfad im Vault
|
|
||||||
- retriever_weight: effektives Gewicht für den Retriever
|
|
||||||
- chunk_profile: Profil für Chunking (short|medium|long|default|...)
|
|
||||||
- edge_defaults: Liste von Kanten-Typen, die als Defaults gelten
|
|
||||||
- aliases: Liste von Synonymen (WP-11)
|
|
||||||
"""
|
"""
|
||||||
n = _as_dict(note)
|
n = _as_dict(note)
|
||||||
path_arg, types_cfg_explicit = _pick_args(*args, **kwargs)
|
path_arg, types_cfg_explicit = _pick_args(*args, **kwargs)
|
||||||
reg = _load_types_config(types_cfg_explicit)
|
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 = n.get("frontmatter") or {}
|
||||||
fm_type = fm.get("type") or n.get("type") or "concept"
|
fm_type = fm.get("type") or n.get("type") or "concept"
|
||||||
note_type = str(fm_type)
|
note_type = str(fm_type)
|
||||||
@@ -158,7 +174,7 @@ def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
|||||||
cfg_type = _cfg_for_type(note_type, reg)
|
cfg_type = _cfg_for_type(note_type, reg)
|
||||||
cfg_def = _cfg_defaults(reg)
|
cfg_def = _cfg_defaults(reg)
|
||||||
|
|
||||||
# --- retriever_weight: Frontmatter > Typ-Config > Registry-Defaults > ENV ---
|
# --- retriever_weight ---
|
||||||
default_rw = _env_float("MINDNET_DEFAULT_RETRIEVER_WEIGHT", 1.0)
|
default_rw = _env_float("MINDNET_DEFAULT_RETRIEVER_WEIGHT", 1.0)
|
||||||
retriever_weight = fm.get("retriever_weight")
|
retriever_weight = fm.get("retriever_weight")
|
||||||
if retriever_weight is None:
|
if retriever_weight is None:
|
||||||
@@ -171,20 +187,23 @@ def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
|||||||
except Exception:
|
except Exception:
|
||||||
retriever_weight = default_rw
|
retriever_weight = default_rw
|
||||||
|
|
||||||
# --- chunk_profile: Frontmatter > Typ-Config > Registry-Defaults > ENV ---
|
# --- chunk_profile (FIXED LOGIC) ---
|
||||||
chunk_profile = fm.get("chunk_profile")
|
# 1. Frontmatter Override (beide Schreibweisen erlaubt)
|
||||||
if chunk_profile is None:
|
chunk_profile = fm.get("chunking_profile") or fm.get("chunk_profile")
|
||||||
chunk_profile = cfg_type.get(
|
|
||||||
"chunk_profile",
|
|
||||||
cfg_def.get(
|
|
||||||
"chunk_profile",
|
|
||||||
os.environ.get("MINDNET_DEFAULT_CHUNK_PROFILE", "medium"),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
if not isinstance(chunk_profile, str):
|
|
||||||
chunk_profile = "medium"
|
|
||||||
|
|
||||||
# --- edge_defaults: Frontmatter > Typ-Config > Registry-Defaults ---
|
# 2. Type Config (Korrekter Key 'chunking_profile' aus types.yaml)
|
||||||
|
if chunk_profile is None:
|
||||||
|
chunk_profile = cfg_type.get("chunking_profile")
|
||||||
|
|
||||||
|
# 3. Default Config (Fallback auf sliding_standard statt medium)
|
||||||
|
if chunk_profile is None:
|
||||||
|
chunk_profile = cfg_def.get("chunking_profile", "sliding_standard")
|
||||||
|
|
||||||
|
# 4. Safety Fallback
|
||||||
|
if not isinstance(chunk_profile, str) or not chunk_profile:
|
||||||
|
chunk_profile = "sliding_standard"
|
||||||
|
|
||||||
|
# --- edge_defaults ---
|
||||||
edge_defaults = fm.get("edge_defaults")
|
edge_defaults = fm.get("edge_defaults")
|
||||||
if edge_defaults is None:
|
if edge_defaults is None:
|
||||||
edge_defaults = cfg_type.get(
|
edge_defaults = cfg_type.get(
|
||||||
@@ -193,7 +212,7 @@ def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
|||||||
)
|
)
|
||||||
edge_defaults = _ensure_list(edge_defaults)
|
edge_defaults = _ensure_list(edge_defaults)
|
||||||
|
|
||||||
# --- Basis-Metadaten (IDs, Titel, Pfad) ---
|
# --- Basis-Metadaten ---
|
||||||
note_id = n.get("note_id") or n.get("id") or fm.get("id")
|
note_id = n.get("note_id") or n.get("id") or fm.get("id")
|
||||||
title = n.get("title") or fm.get("title") or ""
|
title = n.get("title") or fm.get("title") or ""
|
||||||
path = n.get("path") or path_arg
|
path = n.get("path") or path_arg
|
||||||
@@ -208,29 +227,42 @@ def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
|||||||
"retriever_weight": retriever_weight,
|
"retriever_weight": retriever_weight,
|
||||||
"chunk_profile": chunk_profile,
|
"chunk_profile": chunk_profile,
|
||||||
"edge_defaults": edge_defaults,
|
"edge_defaults": edge_defaults,
|
||||||
|
"hashes": {} # Init Hash Dict
|
||||||
}
|
}
|
||||||
|
|
||||||
# Tags / Keywords übernehmen
|
# --- 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
|
||||||
|
|
||||||
|
# Tags / Keywords
|
||||||
tags = fm.get("tags") or fm.get("keywords") or n.get("tags")
|
tags = fm.get("tags") or fm.get("keywords") or n.get("tags")
|
||||||
if tags:
|
if tags:
|
||||||
payload["tags"] = _ensure_list(tags)
|
payload["tags"] = _ensure_list(tags)
|
||||||
|
|
||||||
# WP-11: Aliases übernehmen (für Discovery Service)
|
# Aliases
|
||||||
aliases = fm.get("aliases")
|
aliases = fm.get("aliases")
|
||||||
if aliases:
|
if aliases:
|
||||||
payload["aliases"] = _ensure_list(aliases)
|
payload["aliases"] = _ensure_list(aliases)
|
||||||
|
|
||||||
# Zeitliche Metadaten (sofern vorhanden)
|
# Zeit
|
||||||
for k in ("created", "modified", "date"):
|
for k in ("created", "modified", "date"):
|
||||||
v = fm.get(k) or n.get(k)
|
v = fm.get(k) or n.get(k)
|
||||||
if v:
|
if v:
|
||||||
payload[k] = str(v)
|
payload[k] = str(v)
|
||||||
|
|
||||||
# Fulltext (Fallback, falls body im Input)
|
# Fulltext
|
||||||
if "body" in n and n["body"]:
|
if "body" in n and n["body"]:
|
||||||
payload["fulltext"] = str(n["body"])
|
payload["fulltext"] = str(n["body"])
|
||||||
|
|
||||||
# JSON-Roundtrip zur harten Validierung (ASCII beibehalten)
|
# JSON Validation
|
||||||
json.loads(json.dumps(payload, ensure_ascii=False))
|
json.loads(json.dumps(payload, ensure_ascii=False))
|
||||||
|
|
||||||
return payload
|
return payload
|
||||||
+6
-39
@@ -1,43 +1,10 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
Modul: app/core/parser.py
|
FILE: app/core/parser.py
|
||||||
Version: 1.7.1 (fault-tolerant, API-kompatibel)
|
DESCRIPTION: Liest Markdown-Dateien fehlertolerant (Encoding-Fallback). Trennt Frontmatter (YAML) vom Body.
|
||||||
Datum: 2025-10-01
|
VERSION: 1.7.1
|
||||||
|
STATUS: Active
|
||||||
Zweck
|
DEPENDENCIES: yaml, re, dataclasses, json, io, os
|
||||||
-----
|
LAST_ANALYSIS: 2025-12-15
|
||||||
Fehlertolerantes Einlesen von Markdown-Dateien mit YAML-Frontmatter.
|
|
||||||
Kompatibel zur bisherigen Parser-API, aber robust gegenüber Nicht-UTF-8-Dateien:
|
|
||||||
- Versucht nacheinander: utf-8 → utf-8-sig → cp1252 → latin-1.
|
|
||||||
- Bei Fallback wird ein JSON-Warnhinweis auf stdout ausgegeben; der Import bricht NICHT ab.
|
|
||||||
- YAML-Frontmatter wird mit '---' am Anfang und '---' als Abschluss erkannt.
|
|
||||||
- extract_wikilinks() normalisiert [[id#anchor|label]] → 'id'.
|
|
||||||
|
|
||||||
Öffentliche API (kompatibel):
|
|
||||||
- class ParsedNote(frontmatter: dict, body: str, path: str)
|
|
||||||
- read_markdown(path) -> ParsedNote | None
|
|
||||||
- normalize_frontmatter(fm) -> dict
|
|
||||||
- validate_required_frontmatter(fm, required: tuple[str,...]=("id","title")) -> None
|
|
||||||
- extract_wikilinks(text) -> list[str]
|
|
||||||
- FRONTMATTER_RE (Kompatibilitäts-Konstante; Regex für '---'-Zeilen)
|
|
||||||
|
|
||||||
Beispiele
|
|
||||||
---------
|
|
||||||
from app.core.parser import read_markdown, normalize_frontmatter, validate_required_frontmatter
|
|
||||||
parsed = read_markdown("./vault/30_projects/project-demo.md")
|
|
||||||
fm = normalize_frontmatter(parsed.frontmatter)
|
|
||||||
validate_required_frontmatter(fm)
|
|
||||||
body = parsed.body
|
|
||||||
|
|
||||||
from app.core.parser import extract_wikilinks
|
|
||||||
links = extract_wikilinks(body)
|
|
||||||
|
|
||||||
Abhängigkeiten
|
|
||||||
--------------
|
|
||||||
- PyYAML (yaml)
|
|
||||||
|
|
||||||
Lizenz: MIT (projektintern)
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|||||||
+6
-24
@@ -1,28 +1,10 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
app/core/qdrant.py
|
FILE: app/core/qdrant.py
|
||||||
Version: 2.2.0 (2025-11-11)
|
DESCRIPTION: Qdrant-Client Factory und Schema-Management. Erstellt Collections und Payload-Indizes.
|
||||||
|
VERSION: 2.2.0
|
||||||
Aufgabe
|
STATUS: Active
|
||||||
-------
|
DEPENDENCIES: qdrant_client, dataclasses, os
|
||||||
- Zentraler Qdrant-Zugriff (Client, Config)
|
LAST_ANALYSIS: 2025-12-15
|
||||||
- Collection-Anlage (notes/chunks/edges)
|
|
||||||
- **Payload-Indizes sicherstellen** (idempotent)
|
|
||||||
|
|
||||||
Hinweis
|
|
||||||
-------
|
|
||||||
Diese Datei ist als Drop-in-Ersatz gedacht, falls in deinem Projekt noch keine
|
|
||||||
robuste ensure_payload_indexes()-Implementierung vorliegt. Die Signaturen
|
|
||||||
bleiben kompatibel zu scripts.import_markdown und scripts.reset_qdrant.
|
|
||||||
|
|
||||||
API-Notizen
|
|
||||||
-----------
|
|
||||||
- Payload-Indizes werden mit `create_payload_index` angelegt.
|
|
||||||
- Typen stammen aus `qdrant_client.http.models.PayloadSchemaType`:
|
|
||||||
KEYWORD | TEXT | INTEGER | FLOAT | BOOL | GEO | DATETIME
|
|
||||||
- Für häufige Filterfelder (note_id, kind, scope, type, tags, ...) legen wir
|
|
||||||
Indizes an. Das ist laut Qdrant-Doku Best Practice für performante Filter.
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|||||||
@@ -1,18 +1,10 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
app/core/qdrant_points.py - robust points helpers for Qdrant
|
FILE: app/core/qdrant_points.py
|
||||||
|
DESCRIPTION: Object-Mapper für Qdrant. Konvertiert JSON-Payloads (Notes, Chunks, Edges) in PointStructs und generiert deterministische UUIDs.
|
||||||
- Single source of truth for building PointStruct for notes/chunks/edges
|
VERSION: 1.5.0
|
||||||
- Backward-compatible payloads for edges
|
STATUS: Active
|
||||||
- Handles both Single-Vector and Named-Vector collections
|
DEPENDENCIES: qdrant_client, uuid, os
|
||||||
- Deterministic overrides via ENV to avoid auto-detection traps:
|
LAST_ANALYSIS: 2025-12-15
|
||||||
* NOTES_VECTOR_NAME, CHUNKS_VECTOR_NAME, EDGES_VECTOR_NAME
|
|
||||||
* MINDNET_VECTOR_NAME (fallback)
|
|
||||||
> Set to a concrete name (e.g. "text") to force Named-Vector with that name
|
|
||||||
> Set to "__single__" (or "single") to force Single-Vector
|
|
||||||
|
|
||||||
Version: 1.5.0 (2025-11-08)
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
import os
|
import os
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
"""
|
|
||||||
app/core/ranking.py — Kombiniertes Scoring (WP-04)
|
|
||||||
|
|
||||||
Zweck:
|
|
||||||
Zusammenführen von semantischem Score (normalisiert), Edge-Bonus und
|
|
||||||
Centrality-Bonus in einen Gesamtscore für die Ergebnisreihung.
|
|
||||||
Kompatibilität:
|
|
||||||
Python 3.12+
|
|
||||||
Version:
|
|
||||||
0.1.0 (Erstanlage)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Bezug:
|
|
||||||
WP-04 Ranking-Formel (w_sem, w_edge, w_cent)
|
|
||||||
Nutzung:
|
|
||||||
from app.core.ranking import combine_scores
|
|
||||||
Änderungsverlauf:
|
|
||||||
0.1.0 (2025-10-07) – Erstanlage.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
from typing import List, Tuple, Dict
|
|
||||||
|
|
||||||
|
|
||||||
def normalize_scores(values: List[float]) -> List[float]:
|
|
||||||
"""Min-Max-Normalisierung über die Kandidatenmenge (Fallback 0.5 bei Konstanz)."""
|
|
||||||
if not values:
|
|
||||||
return values
|
|
||||||
lo, hi = min(values), max(values)
|
|
||||||
if hi - lo < 1e-9:
|
|
||||||
return [0.5] * len(values)
|
|
||||||
return [(v - lo) / (hi - lo) for v in values]
|
|
||||||
|
|
||||||
|
|
||||||
def combine_scores(
|
|
||||||
hits: List[Tuple[str, float, dict]], # (id, semantic_score, payload)
|
|
||||||
edge_bonus_map: Dict[str, float],
|
|
||||||
centrality_map: Dict[str, float],
|
|
||||||
w_sem: float = 0.70,
|
|
||||||
w_edge: float = 0.25,
|
|
||||||
w_cent: float = 0.05,
|
|
||||||
) -> List[Tuple[str, float, float, float, float]]:
|
|
||||||
"""
|
|
||||||
Liefert Liste von (point_id, total_score, edge_bonus, centrality_bonus, raw_semantic_score),
|
|
||||||
absteigend nach total_score sortiert.
|
|
||||||
"""
|
|
||||||
sem = [h[1] for h in hits]
|
|
||||||
sem_n = normalize_scores(sem)
|
|
||||||
out = []
|
|
||||||
for (pid, s, payload), s_norm in zip(hits, sem_n):
|
|
||||||
e = edge_bonus_map.get(pid, 0.0)
|
|
||||||
c = centrality_map.get(pid, 0.0)
|
|
||||||
total = w_sem * s_norm + w_edge * e + w_cent * c
|
|
||||||
out.append((pid, total, e, c, s))
|
|
||||||
out.sort(key=lambda t: t[1], reverse=True)
|
|
||||||
return out
|
|
||||||
+190
-216
@@ -1,82 +1,63 @@
|
|||||||
"""
|
"""
|
||||||
app/core/retriever.py — Hybrider Such-Algorithmus
|
FILE: app/core/retriever.py
|
||||||
|
DESCRIPTION: Haupt-Schnittstelle für die Suche. Orchestriert Vektorsuche und Graph-Expansion.
|
||||||
Version:
|
Nutzt retriever_scoring.py für die WP-22 Logik.
|
||||||
0.5.3 (WP-06 Fix: Populate 'payload' in QueryHit for meta-data access)
|
FIX: TypeError in embed_text (model_name) behoben.
|
||||||
|
FIX: Pydantic ValidationError (Target/Source) behoben.
|
||||||
|
VERSION: 0.6.15 (WP-22 Full & Stable)
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.config, app.models.dto, app.core.qdrant*, app.core.graph_adapter, app.core.retriever_scoring
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
from functools import lru_cache
|
import logging
|
||||||
from typing import Any, Dict, List, Tuple, Iterable, Optional
|
from typing import Any, Dict, List, Tuple, Iterable, Optional
|
||||||
|
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
from app.models.dto import (
|
from app.models.dto import (
|
||||||
QueryRequest,
|
QueryRequest, QueryResponse, QueryHit,
|
||||||
QueryResponse,
|
Explanation, ScoreBreakdown, Reason, EdgeDTO
|
||||||
QueryHit,
|
|
||||||
Explanation,
|
|
||||||
ScoreBreakdown,
|
|
||||||
Reason,
|
|
||||||
EdgeDTO
|
|
||||||
)
|
)
|
||||||
import app.core.qdrant as qdr
|
import app.core.qdrant as qdr
|
||||||
import app.core.qdrant_points as qp
|
import app.core.qdrant_points as qp
|
||||||
import app.services.embeddings_client as ec
|
import app.services.embeddings_client as ec
|
||||||
import app.core.graph_adapter as ga
|
import app.core.graph_adapter as ga
|
||||||
|
|
||||||
try:
|
# Mathematische Engine importieren
|
||||||
import yaml # type: ignore[import]
|
from app.core.retriever_scoring import get_weights, compute_wp22_score
|
||||||
except Exception: # pragma: no cover
|
|
||||||
yaml = None # type: ignore[assignment]
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@lru_cache
|
# ==============================================================================
|
||||||
def _get_scoring_weights() -> Tuple[float, float, float]:
|
# 1. CORE HELPERS & CONFIG LOADERS
|
||||||
"""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]:
|
def _get_client_and_prefix() -> Tuple[Any, str]:
|
||||||
"""Liefert (QdrantClient, prefix)."""
|
"""Initialisiert Qdrant Client und lädt Collection-Prefix."""
|
||||||
cfg = qdr.QdrantConfig.from_env()
|
cfg = qdr.QdrantConfig.from_env()
|
||||||
client = qdr.get_client(cfg)
|
return qdr.get_client(cfg), cfg.prefix
|
||||||
return client, cfg.prefix
|
|
||||||
|
|
||||||
|
|
||||||
def _get_query_vector(req: QueryRequest) -> List[float]:
|
def _get_query_vector(req: QueryRequest) -> List[float]:
|
||||||
"""Liefert den Query-Vektor aus dem Request."""
|
"""
|
||||||
|
Vektorisiert die Anfrage.
|
||||||
|
FIX: Enthält try-except Block für unterschiedliche Signaturen von ec.embed_text.
|
||||||
|
"""
|
||||||
if req.query_vector:
|
if req.query_vector:
|
||||||
return list(req.query_vector)
|
return list(req.query_vector)
|
||||||
|
|
||||||
if not req.query:
|
if not req.query:
|
||||||
raise ValueError("QueryRequest benötigt entweder query oder query_vector")
|
raise ValueError("Kein Text oder Vektor für die Suche angegeben.")
|
||||||
|
|
||||||
settings = get_settings()
|
settings = get_settings()
|
||||||
model_name = settings.MODEL_NAME
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
return ec.embed_text(req.query, model_name=model_name)
|
# Versuch mit modernem Interface (WP-03 kompatibel)
|
||||||
|
return ec.embed_text(req.query, model_name=settings.MODEL_NAME)
|
||||||
except TypeError:
|
except TypeError:
|
||||||
|
# Fallback für Signaturen, die 'model_name' nicht als Keyword akzeptieren
|
||||||
|
logger.debug("ec.embed_text does not accept 'model_name' keyword. Falling back.")
|
||||||
return ec.embed_text(req.query)
|
return ec.embed_text(req.query)
|
||||||
|
|
||||||
|
|
||||||
@@ -85,138 +66,116 @@ def _semantic_hits(
|
|||||||
prefix: str,
|
prefix: str,
|
||||||
vector: List[float],
|
vector: List[float],
|
||||||
top_k: int,
|
top_k: int,
|
||||||
filters: Dict[str, Any] | None = None,
|
filters: Optional[Dict] = None
|
||||||
) -> List[Tuple[str, float, Dict[str, Any]]]:
|
) -> List[Tuple[str, float, Dict[str, Any]]]:
|
||||||
"""Führt eine semantische Suche aus."""
|
"""Führt die Vektorsuche durch und konvertiert Qdrant-Points in ein einheitliches Format."""
|
||||||
flt = filters or None
|
raw_hits = qp.search_chunks_by_vector(client, prefix, vector, top=top_k, filters=filters)
|
||||||
raw_hits = qp.search_chunks_by_vector(client, prefix, vector, top=top_k, filters=flt)
|
# Strikte Typkonvertierung für Stabilität
|
||||||
results: List[Tuple[str, float, Dict[str, Any]]] = []
|
return [(str(hit[0]), float(hit[1]), dict(hit[2] or {})) for hit in raw_hits]
|
||||||
for pid, score, payload in raw_hits:
|
|
||||||
results.append((str(pid), float(score), dict(payload or {})))
|
|
||||||
return results
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
def _compute_total_score(
|
# 2. EXPLANATION LAYER (DEBUG & VERIFIABILITY)
|
||||||
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(
|
def _build_explanation(
|
||||||
semantic_score: float,
|
semantic_score: float,
|
||||||
payload: Dict[str, Any],
|
payload: Dict[str, Any],
|
||||||
edge_bonus: float,
|
scoring_debug: Dict[str, Any],
|
||||||
cent_bonus: float,
|
|
||||||
subgraph: Optional[ga.Subgraph],
|
subgraph: Optional[ga.Subgraph],
|
||||||
node_key: Optional[str]
|
target_note_id: Optional[str],
|
||||||
|
applied_boosts: Optional[Dict[str, float]] = None
|
||||||
) -> Explanation:
|
) -> Explanation:
|
||||||
"""Erstellt ein Explanation-Objekt."""
|
"""
|
||||||
sem_w, _edge_w, _cent_w = _get_scoring_weights()
|
Transformiert mathematische Scores und Graph-Signale in eine menschenlesbare Erklärung.
|
||||||
# Scoring weights erneut laden für Reason-Details
|
Behebt Pydantic ValidationErrors durch explizite String-Sicherung.
|
||||||
_, edge_w_cfg, cent_w_cfg = _get_scoring_weights()
|
"""
|
||||||
|
_, edge_w_cfg, _ = get_weights()
|
||||||
try:
|
base_val = scoring_debug["base_val"]
|
||||||
type_weight = float(payload.get("retriever_weight", 1.0))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
type_weight = 1.0
|
|
||||||
|
|
||||||
note_type = payload.get("type", "unknown")
|
|
||||||
|
|
||||||
|
# 1. Detaillierter mathematischer Breakdown
|
||||||
breakdown = ScoreBreakdown(
|
breakdown = ScoreBreakdown(
|
||||||
semantic_contribution=(sem_w * semantic_score * type_weight),
|
semantic_contribution=base_val,
|
||||||
edge_contribution=(edge_w_cfg * edge_bonus),
|
edge_contribution=base_val * scoring_debug["edge_impact_final"],
|
||||||
centrality_contribution=(cent_w_cfg * cent_bonus),
|
centrality_contribution=base_val * scoring_debug["cent_impact_final"],
|
||||||
raw_semantic=semantic_score,
|
raw_semantic=semantic_score,
|
||||||
raw_edge_bonus=edge_bonus,
|
raw_edge_bonus=scoring_debug["edge_bonus"],
|
||||||
raw_centrality=cent_bonus,
|
raw_centrality=scoring_debug["cent_bonus"],
|
||||||
node_weight=type_weight
|
node_weight=float(payload.get("retriever_weight", 1.0)),
|
||||||
|
status_multiplier=scoring_debug["status_multiplier"],
|
||||||
|
graph_boost_factor=scoring_debug["graph_boost_factor"]
|
||||||
)
|
)
|
||||||
|
|
||||||
reasons: List[Reason] = []
|
reasons: List[Reason] = []
|
||||||
edges_dto: List[EdgeDTO] = []
|
edges_dto: List[EdgeDTO] = []
|
||||||
|
|
||||||
|
# 2. Gründe für Semantik hinzufügen
|
||||||
if semantic_score > 0.85:
|
if semantic_score > 0.85:
|
||||||
reasons.append(Reason(kind="semantic", message="Sehr hohe textuelle Übereinstimmung.", score_impact=breakdown.semantic_contribution))
|
reasons.append(Reason(kind="semantic", message="Sehr hohe textuelle Übereinstimmung.", score_impact=base_val))
|
||||||
elif semantic_score > 0.70:
|
elif semantic_score > 0.70:
|
||||||
reasons.append(Reason(kind="semantic", message="Gute textuelle Übereinstimmung.", score_impact=breakdown.semantic_contribution))
|
reasons.append(Reason(kind="semantic", message="Inhaltliche Übereinstimmung.", score_impact=base_val))
|
||||||
|
|
||||||
|
# 3. Gründe für Typ und Lifecycle
|
||||||
|
type_weight = float(payload.get("retriever_weight", 1.0))
|
||||||
if type_weight != 1.0:
|
if type_weight != 1.0:
|
||||||
msg = "Bevorzugt" if type_weight > 1.0 else "Leicht abgewertet"
|
msg = "Bevorzugt" if type_weight > 1.0 else "De-priorisiert"
|
||||||
reasons.append(Reason(kind="type", message=f"{msg} aufgrund des Typs '{note_type}'.", score_impact=(sem_w * semantic_score * (type_weight - 1.0))))
|
reasons.append(Reason(kind="type", message=f"{msg} durch Typ-Profil.", score_impact=base_val * (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"))
|
|
||||||
|
|
||||||
|
# 4. Kanten-Verarbeitung (Graph-Intelligence)
|
||||||
|
if subgraph and target_note_id and scoring_debug["edge_bonus"] > 0:
|
||||||
|
raw_edges = []
|
||||||
if hasattr(subgraph, "get_incoming_edges"):
|
if hasattr(subgraph, "get_incoming_edges"):
|
||||||
incoming = subgraph.get_incoming_edges(node_key)
|
raw_edges.extend(subgraph.get_incoming_edges(target_note_id) or [])
|
||||||
for edge in incoming:
|
if hasattr(subgraph, "get_outgoing_edges"):
|
||||||
src = edge.get("source", "Unknown")
|
raw_edges.extend(subgraph.get_outgoing_edges(target_note_id) or [])
|
||||||
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 edge in raw_edges:
|
||||||
for top_edge in all_edges[:3]:
|
# FIX: Zwingende String-Konvertierung für Pydantic-Stabilität
|
||||||
impact = edge_w_cfg * top_edge.weight
|
src = str(edge.get("source") or "note_root")
|
||||||
dir_txt = "Verweist auf" if top_edge.direction == "out" else "Referenziert von"
|
tgt = str(edge.get("target") or target_note_id or "unknown_target")
|
||||||
tgt_txt = top_edge.target if top_edge.direction == "out" else top_edge.source
|
kind = str(edge.get("kind", "related_to"))
|
||||||
reasons.append(Reason(kind="edge", message=f"{dir_txt} '{tgt_txt}' via '{top_edge.kind}'", score_impact=impact, details={"kind": top_edge.kind}))
|
prov = str(edge.get("provenance", "rule"))
|
||||||
|
conf = float(edge.get("confidence", 1.0))
|
||||||
|
|
||||||
if cent_bonus > 0.01:
|
direction = "in" if tgt == target_note_id else "out"
|
||||||
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)
|
edge_obj = EdgeDTO(
|
||||||
|
id=f"{src}->{tgt}:{kind}",
|
||||||
|
kind=kind,
|
||||||
|
source=src,
|
||||||
|
target=tgt,
|
||||||
|
weight=conf,
|
||||||
|
direction=direction,
|
||||||
|
provenance=prov,
|
||||||
|
confidence=conf
|
||||||
|
)
|
||||||
|
edges_dto.append(edge_obj)
|
||||||
|
|
||||||
|
# Die 3 wichtigsten Kanten als Begründung formulieren
|
||||||
|
top_edges = sorted(edges_dto, key=lambda e: e.confidence, reverse=True)
|
||||||
|
for e in top_edges[:3]:
|
||||||
|
peer = e.source if e.direction == "in" else e.target
|
||||||
|
prov_txt = "Bestätigte" if e.provenance == "explicit" else "KI-basierte"
|
||||||
|
boost_txt = f" [Boost x{applied_boosts.get(e.kind)}]" if applied_boosts and e.kind in applied_boosts else ""
|
||||||
|
|
||||||
def _extract_expand_options(req: QueryRequest) -> Tuple[int, List[str] | None]:
|
reasons.append(Reason(
|
||||||
"""Extrahiert depth und edge_types."""
|
kind="edge",
|
||||||
expand = getattr(req, "expand", None)
|
message=f"{prov_txt} Kante '{e.kind}'{boost_txt} von/zu '{peer}'.",
|
||||||
if not expand:
|
score_impact=edge_w_cfg * e.confidence
|
||||||
return 0, None
|
))
|
||||||
|
|
||||||
depth = 1
|
if scoring_debug["cent_bonus"] > 0.01:
|
||||||
edge_types: List[str] | None = None
|
reasons.append(Reason(kind="centrality", message="Die Notiz ist ein zentraler Informations-Hub.", score_impact=breakdown.centrality_contribution))
|
||||||
|
|
||||||
if hasattr(expand, "depth") or hasattr(expand, "edge_types"):
|
return Explanation(
|
||||||
depth = int(getattr(expand, "depth", 1) or 1)
|
breakdown=breakdown,
|
||||||
types_val = getattr(expand, "edge_types", None)
|
reasons=reasons,
|
||||||
if types_val:
|
related_edges=edges_dto if edges_dto else None,
|
||||||
edge_types = list(types_val)
|
applied_boosts=applied_boosts
|
||||||
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
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# 3. CORE RETRIEVAL PIPELINE
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
def _build_hits_from_semantic(
|
def _build_hits_from_semantic(
|
||||||
hits: Iterable[Tuple[str, float, Dict[str, Any]]],
|
hits: Iterable[Tuple[str, float, Dict[str, Any]]],
|
||||||
@@ -224,113 +183,128 @@ def _build_hits_from_semantic(
|
|||||||
used_mode: str,
|
used_mode: str,
|
||||||
subgraph: ga.Subgraph | None = None,
|
subgraph: ga.Subgraph | None = None,
|
||||||
explain: bool = False,
|
explain: bool = False,
|
||||||
|
dynamic_edge_boosts: Dict[str, float] = None
|
||||||
) -> QueryResponse:
|
) -> QueryResponse:
|
||||||
"""Baut strukturierte QueryHits."""
|
"""Wandelt semantische Roh-Treffer in hochgeladene, bewertete QueryHits um."""
|
||||||
t0 = time.time()
|
t0 = time.time()
|
||||||
enriched: List[Tuple[str, float, Dict[str, Any], float, float, float]] = []
|
enriched = []
|
||||||
|
|
||||||
for pid, semantic_score, payload in hits:
|
for pid, semantic_score, payload in hits:
|
||||||
edge_bonus = 0.0
|
edge_bonus, cent_bonus = 0.0, 0.0
|
||||||
cent_bonus = 0.0
|
target_id = payload.get("note_id")
|
||||||
node_key = payload.get("chunk_id") or payload.get("note_id")
|
|
||||||
|
|
||||||
if subgraph is not None and node_key:
|
if subgraph and target_id:
|
||||||
try:
|
try:
|
||||||
edge_bonus = float(subgraph.edge_bonus(node_key))
|
edge_bonus = float(subgraph.edge_bonus(target_id))
|
||||||
|
cent_bonus = float(subgraph.centrality_bonus(target_id))
|
||||||
except Exception:
|
except Exception:
|
||||||
edge_bonus = 0.0
|
pass
|
||||||
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)
|
# Mathematisches Scoring via WP-22 Engine
|
||||||
enriched.append((pid, float(semantic_score), payload, total, edge_bonus, cent_bonus))
|
debug_data = compute_wp22_score(
|
||||||
|
semantic_score, payload, edge_bonus, cent_bonus, dynamic_edge_boosts
|
||||||
|
)
|
||||||
|
enriched.append((pid, semantic_score, payload, debug_data))
|
||||||
|
|
||||||
enriched_sorted = sorted(enriched, key=lambda h: h[3], reverse=True)
|
# Sortierung nach finalem mathematischen Score
|
||||||
limited = enriched_sorted[: max(1, top_k)]
|
enriched_sorted = sorted(enriched, key=lambda h: h[3]["total"], reverse=True)
|
||||||
|
limited_hits = enriched_sorted[: max(1, top_k)]
|
||||||
|
|
||||||
results: List[QueryHit] = []
|
results: List[QueryHit] = []
|
||||||
for pid, semantic_score, payload, total, edge_bonus, cent_bonus in limited:
|
for pid, s_score, pl, dbg in limited_hits:
|
||||||
explanation_obj = None
|
explanation_obj = None
|
||||||
if explain:
|
if explain:
|
||||||
explanation_obj = _build_explanation(
|
explanation_obj = _build_explanation(
|
||||||
semantic_score=float(semantic_score),
|
semantic_score=float(s_score),
|
||||||
payload=payload,
|
payload=pl,
|
||||||
edge_bonus=edge_bonus,
|
scoring_debug=dbg,
|
||||||
cent_bonus=cent_bonus,
|
|
||||||
subgraph=subgraph,
|
subgraph=subgraph,
|
||||||
node_key=payload.get("chunk_id") or payload.get("note_id")
|
target_note_id=pl.get("note_id"),
|
||||||
|
applied_boosts=dynamic_edge_boosts
|
||||||
)
|
)
|
||||||
|
|
||||||
text_content = payload.get("page_content") or payload.get("text") or payload.get("content")
|
# Payload Text-Feld normalisieren
|
||||||
|
text_content = pl.get("page_content") or pl.get("text") or pl.get("content", "[Kein Text]")
|
||||||
|
|
||||||
results.append(QueryHit(
|
results.append(QueryHit(
|
||||||
node_id=str(pid),
|
node_id=str(pid),
|
||||||
note_id=payload.get("note_id"),
|
note_id=str(pl.get("note_id", "unknown")),
|
||||||
semantic_score=float(semantic_score),
|
semantic_score=float(s_score),
|
||||||
edge_bonus=edge_bonus,
|
edge_bonus=dbg["edge_bonus"],
|
||||||
centrality_bonus=cent_bonus,
|
centrality_bonus=dbg["cent_bonus"],
|
||||||
total_score=total,
|
total_score=dbg["total"],
|
||||||
paths=None,
|
|
||||||
source={
|
source={
|
||||||
"path": payload.get("path"),
|
"path": pl.get("path"),
|
||||||
"section": payload.get("section") or payload.get("section_title"),
|
"section": pl.get("section") or pl.get("section_title"),
|
||||||
"text": text_content
|
"text": text_content
|
||||||
},
|
},
|
||||||
# --- FIX: Wir füllen das payload-Feld explizit ---
|
payload=pl,
|
||||||
payload=payload,
|
|
||||||
explanation=explanation_obj
|
explanation=explanation_obj
|
||||||
))
|
))
|
||||||
|
|
||||||
dt = int((time.time() - t0) * 1000)
|
return QueryResponse(results=results, used_mode=used_mode, latency_ms=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:
|
def hybrid_retrieve(req: QueryRequest) -> QueryResponse:
|
||||||
"""Hybrid-Retriever: semantische Suche + optionale Edge-Expansion."""
|
"""
|
||||||
|
Die Haupt-Einstiegsfunktion für die hybride Suche.
|
||||||
|
Kombiniert Vektorsuche mit Graph-Expansion, Provenance-Weighting und Intent-Boosting.
|
||||||
|
"""
|
||||||
client, prefix = _get_client_and_prefix()
|
client, prefix = _get_client_and_prefix()
|
||||||
if req.query_vector:
|
vector = list(req.query_vector) if req.query_vector else _get_query_vector(req)
|
||||||
vector = list(req.query_vector)
|
top_k = req.top_k or 10
|
||||||
else:
|
|
||||||
vector = _get_query_vector(req)
|
|
||||||
|
|
||||||
top_k = req.top_k or get_settings().RETRIEVER_TOP_K
|
# 1. Semantische Seed-Suche
|
||||||
hits = _semantic_hits(client, prefix, vector, top_k=top_k, filters=req.filters)
|
hits = _semantic_hits(client, prefix, vector, top_k=top_k, filters=req.filters)
|
||||||
|
|
||||||
depth, edge_types = _extract_expand_options(req)
|
# 2. Graph Expansion Konfiguration
|
||||||
|
expand_cfg = req.expand if isinstance(req.expand, dict) else {}
|
||||||
|
depth = int(expand_cfg.get("depth", 1))
|
||||||
|
boost_edges = getattr(req, "boost_edges", {}) or {}
|
||||||
|
|
||||||
subgraph: ga.Subgraph | None = None
|
subgraph: ga.Subgraph | None = None
|
||||||
if depth and depth > 0:
|
if depth > 0 and hits:
|
||||||
seed_ids: List[str] = []
|
# Start-IDs für den Graph-Traversal sammeln
|
||||||
for _pid, _score, payload in hits:
|
seed_ids = list({h[2].get("note_id") for h in hits if h[2].get("note_id")})
|
||||||
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:
|
if seed_ids:
|
||||||
try:
|
try:
|
||||||
subgraph = ga.expand(client, prefix, seed_ids, depth=depth, edge_types=edge_types)
|
# Subgraph aus RAM/DB laden
|
||||||
except Exception:
|
subgraph = ga.expand(client, prefix, seed_ids, depth=depth, edge_types=expand_cfg.get("edge_types"))
|
||||||
|
|
||||||
|
# --- WP-22: Kanten-Gewichtung im RAM-Graphen vor Bonus-Berechnung ---
|
||||||
|
if subgraph and hasattr(subgraph, "graph"):
|
||||||
|
for _, _, data in subgraph.graph.edges(data=True):
|
||||||
|
# A. Provenance Weighting (WP-22 Bonus für Herkunft)
|
||||||
|
prov = data.get("provenance", "rule")
|
||||||
|
# Belohnung: Explizite Links (1.0) > Smart (0.9) > Rule (0.7)
|
||||||
|
prov_w = 1.0 if prov == "explicit" else (0.9 if prov == "smart" else 0.7)
|
||||||
|
|
||||||
|
# B. Intent Boost Multiplikator (Vom Router dynamisch injiziert)
|
||||||
|
kind = data.get("kind")
|
||||||
|
intent_multiplier = boost_edges.get(kind, 1.0)
|
||||||
|
|
||||||
|
# Finales Gewicht setzen (Basis * Provenance * Intent)
|
||||||
|
data["weight"] = data.get("weight", 1.0) * prov_w * intent_multiplier
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Graph Expansion failed: {e}")
|
||||||
subgraph = None
|
subgraph = None
|
||||||
|
|
||||||
return _build_hits_from_semantic(hits, top_k=top_k, used_mode="hybrid", subgraph=subgraph, explain=req.explain)
|
# 3. Scoring & Explanation Generierung
|
||||||
|
return _build_hits_from_semantic(hits, top_k, "hybrid", subgraph, req.explain, boost_edges)
|
||||||
|
|
||||||
|
|
||||||
|
def semantic_retrieve(req: QueryRequest) -> QueryResponse:
|
||||||
|
"""Standard Vektorsuche ohne Graph-Einfluss (WP-02 Fallback)."""
|
||||||
|
client, prefix = _get_client_and_prefix()
|
||||||
|
vector = _get_query_vector(req)
|
||||||
|
hits = _semantic_hits(client, prefix, vector, req.top_k or 10, req.filters)
|
||||||
|
return _build_hits_from_semantic(hits, req.top_k or 10, "semantic", explain=req.explain)
|
||||||
|
|
||||||
|
|
||||||
class Retriever:
|
class Retriever:
|
||||||
"""
|
"""Schnittstelle für die asynchrone Suche."""
|
||||||
Wrapper-Klasse für WP-05 (Chat).
|
|
||||||
"""
|
|
||||||
def __init__(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
async def search(self, request: QueryRequest) -> QueryResponse:
|
async def search(self, request: QueryRequest) -> QueryResponse:
|
||||||
|
"""Führt eine hybride Suche aus."""
|
||||||
return hybrid_retrieve(request)
|
return hybrid_retrieve(request)
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
"""app/core/retriever_config.py
|
|
||||||
---------------------------------
|
|
||||||
Zentrale Konfiguration für den mindnet-Retriever (WP-04).
|
|
||||||
|
|
||||||
Zweck:
|
|
||||||
- Lädt config/retriever.yaml (falls vorhanden) oder nutzt sinnvolle Defaults.
|
|
||||||
- Bietet einen gecachten Zugriff auf die Retriever-Config für
|
|
||||||
andere Module (z. B. graph_adapter, retriever).
|
|
||||||
|
|
||||||
Hinweis zur Weiterentwicklung (Selbstjustierung):
|
|
||||||
- Die hier definierten Parameter sind so gewählt, dass sie später
|
|
||||||
durch ein Feedback-/Learning-to-Rank-Modell überschrieben werden
|
|
||||||
können, ohne die restliche Architektur anzupassen.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from functools import lru_cache
|
|
||||||
from pathlib import Path
|
|
||||||
from typing import Dict
|
|
||||||
|
|
||||||
try:
|
|
||||||
import yaml # type: ignore
|
|
||||||
except Exception: # pragma: no cover - Fallback, falls PyYAML nicht installiert ist.
|
|
||||||
yaml = None # type: ignore
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class RetrieverConfig:
|
|
||||||
semantic_scale: float
|
|
||||||
edge_scale: float
|
|
||||||
centrality_scale: float
|
|
||||||
edge_weights: Dict[str, float]
|
|
||||||
|
|
||||||
@lru_cache
|
|
||||||
def get_retriever_config() -> RetrieverConfig:
|
|
||||||
"""Lädt die Retriever-Konfiguration (YAML + Defaults).
|
|
||||||
|
|
||||||
Reihenfolge:
|
|
||||||
1. Defaults (sinnvoll gewählte Startwerte).
|
|
||||||
2. Optional: config/retriever.yaml bzw. Pfad aus ENV
|
|
||||||
MINDNET_RETRIEVER_CONFIG überschreibt die Defaults.
|
|
||||||
|
|
||||||
Die Funktion ist bewusst gecached, da sich die Konfiguration zur
|
|
||||||
Laufzeit üblicherweise nicht ändert. Für dynamisches Nachladen
|
|
||||||
könnte der Cache explizit geleert werden.
|
|
||||||
"""
|
|
||||||
|
|
||||||
# 1) Defaults – bewusst konservativ gewählt.
|
|
||||||
semantic_scale = 1.0
|
|
||||||
edge_scale = 1.0
|
|
||||||
centrality_scale = 1.0
|
|
||||||
|
|
||||||
edge_weights: Dict[str, float] = {
|
|
||||||
# Wissens-Kanten
|
|
||||||
"depends_on": 1.0,
|
|
||||||
"related_to": 0.7,
|
|
||||||
"similar_to": 0.7,
|
|
||||||
"references": 0.5,
|
|
||||||
# Struktur-Kanten
|
|
||||||
"belongs_to": 0.2,
|
|
||||||
"next": 0.1,
|
|
||||||
"prev": 0.1,
|
|
||||||
# Sonstige / technische Kanten
|
|
||||||
"backlink": 0.2,
|
|
||||||
"references_at": 0.2,
|
|
||||||
}
|
|
||||||
|
|
||||||
# 2) Optional: YAML-Konfiguration laden
|
|
||||||
cfg_path_env = os.getenv("MINDNET_RETRIEVER_CONFIG")
|
|
||||||
if cfg_path_env:
|
|
||||||
cfg_path = Path(cfg_path_env)
|
|
||||||
else:
|
|
||||||
# Project-Root = zwei Ebenen über app/core/
|
|
||||||
cfg_path = Path(__file__).resolve().parents[2] / "config" / "retriever.yaml"
|
|
||||||
|
|
||||||
if yaml is not None and cfg_path.exists():
|
|
||||||
try:
|
|
||||||
data = yaml.safe_load(cfg_path.read_text(encoding="utf-8")) or {}
|
|
||||||
except Exception:
|
|
||||||
data = {}
|
|
||||||
|
|
||||||
retr = data.get("retriever") or {}
|
|
||||||
|
|
||||||
# Skalenwerte überschreiben, falls angegeben
|
|
||||||
try:
|
|
||||||
semantic_scale = float(retr.get("semantic_scale", semantic_scale))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
try:
|
|
||||||
edge_scale = float(retr.get("edge_scale", edge_scale))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
try:
|
|
||||||
centrality_scale = float(retr.get("centrality_scale", centrality_scale))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Edge-Gewichte je Kanten-Typ
|
|
||||||
ew_cfg = retr.get("edge_weights") or {}
|
|
||||||
if isinstance(ew_cfg, dict):
|
|
||||||
for k, v in ew_cfg.items():
|
|
||||||
try:
|
|
||||||
edge_weights[str(k)] = float(v)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
continue
|
|
||||||
|
|
||||||
return RetrieverConfig(
|
|
||||||
semantic_scale=semantic_scale,
|
|
||||||
edge_scale=edge_scale,
|
|
||||||
centrality_scale=centrality_scale,
|
|
||||||
edge_weights=edge_weights,
|
|
||||||
)
|
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/retriever_scoring.py
|
||||||
|
DESCRIPTION: Mathematische Kern-Logik für das WP-22 Scoring.
|
||||||
|
Berechnet Relevanz-Scores basierend auf Semantik, Graph-Intelligence und Content Lifecycle.
|
||||||
|
VERSION: 1.0.1 (WP-22 Full Math Engine)
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: app.config, typing
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
from functools import lru_cache
|
||||||
|
from typing import Any, Dict, Tuple, Optional
|
||||||
|
|
||||||
|
try:
|
||||||
|
import yaml
|
||||||
|
except ImportError:
|
||||||
|
yaml = None
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def get_weights() -> Tuple[float, float, float]:
|
||||||
|
"""
|
||||||
|
Liefert die Basis-Gewichtung (semantic, edge, centrality) aus der Konfiguration.
|
||||||
|
Priorität:
|
||||||
|
1. config/retriever.yaml (Scoring-Sektion)
|
||||||
|
2. Umgebungsvariablen (RETRIEVER_W_*)
|
||||||
|
3. System-Defaults (1.0, 0.0, 0.0)
|
||||||
|
"""
|
||||||
|
from app.config import get_settings
|
||||||
|
settings = get_settings()
|
||||||
|
|
||||||
|
# Defaults aus Settings laden
|
||||||
|
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))
|
||||||
|
|
||||||
|
# Optionaler Override via YAML
|
||||||
|
config_path = os.getenv("MINDNET_RETRIEVER_CONFIG", "config/retriever.yaml")
|
||||||
|
if yaml and os.path.exists(config_path):
|
||||||
|
try:
|
||||||
|
with open(config_path, "r", encoding="utf-8") as f:
|
||||||
|
data = yaml.safe_load(f) or {}
|
||||||
|
scoring = data.get("scoring", {})
|
||||||
|
sem = float(scoring.get("semantic_weight", sem))
|
||||||
|
edge = float(scoring.get("edge_weight", edge))
|
||||||
|
cent = float(scoring.get("centrality_weight", cent))
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Retriever Configuration could not be fully loaded from {config_path}: {e}")
|
||||||
|
|
||||||
|
return sem, edge, cent
|
||||||
|
|
||||||
|
def get_status_multiplier(payload: Dict[str, Any]) -> float:
|
||||||
|
"""
|
||||||
|
WP-22 A: Content Lifecycle Multiplier.
|
||||||
|
Steuert das Ranking basierend auf dem Reifegrad der Information.
|
||||||
|
|
||||||
|
- stable: 1.2 (Belohnung für verifiziertes Wissen)
|
||||||
|
- active: 1.0 (Standard-Gewichtung)
|
||||||
|
- draft: 0.5 (Bestrafung für unfertige Fragmente)
|
||||||
|
"""
|
||||||
|
status = str(payload.get("status", "active")).lower().strip()
|
||||||
|
if status == "stable":
|
||||||
|
return 1.2
|
||||||
|
if status == "draft":
|
||||||
|
return 0.5
|
||||||
|
return 1.0
|
||||||
|
|
||||||
|
def compute_wp22_score(
|
||||||
|
semantic_score: float,
|
||||||
|
payload: Dict[str, Any],
|
||||||
|
edge_bonus_raw: float = 0.0,
|
||||||
|
cent_bonus_raw: float = 0.0,
|
||||||
|
dynamic_edge_boosts: Optional[Dict[str, float]] = None
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Die zentrale mathematische Scoring-Formel der Mindnet Intelligence.
|
||||||
|
Implementiert das WP-22 Hybrid-Scoring (Semantic * Lifecycle * Graph).
|
||||||
|
|
||||||
|
FORMEL:
|
||||||
|
Score = (Similarity * StatusMult) * (1 + (TypeWeight - 1) + ((EdgeW * EB + CentW * CB) * IntentBoost))
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict mit dem finalen 'total' Score und allen mathematischen Zwischenwerten für den Explanation Layer.
|
||||||
|
"""
|
||||||
|
sem_w, edge_w_cfg, cent_w_cfg = get_weights()
|
||||||
|
status_mult = get_status_multiplier(payload)
|
||||||
|
|
||||||
|
# Retriever Weight (Type Boost aus types.yaml, z.B. 1.1 für Decisions)
|
||||||
|
node_weight = float(payload.get("retriever_weight", 1.0))
|
||||||
|
|
||||||
|
# 1. Berechnung des Base Scores (Semantik gewichtet durch Lifecycle-Status)
|
||||||
|
base_val = float(semantic_score) * status_mult
|
||||||
|
|
||||||
|
# 2. Graph Boost Factor (Teil C: Intent-spezifische Verstärkung)
|
||||||
|
# Erhöht das Gewicht des gesamten Graphen um 50%, wenn ein spezifischer Intent vorliegt.
|
||||||
|
graph_boost_factor = 1.5 if dynamic_edge_boosts and (edge_bonus_raw > 0 or cent_bonus_raw > 0) else 1.0
|
||||||
|
|
||||||
|
# 3. Einzelne Graph-Komponenten berechnen
|
||||||
|
edge_impact_final = (edge_w_cfg * edge_bonus_raw) * graph_boost_factor
|
||||||
|
cent_impact_final = (cent_w_cfg * cent_bonus_raw) * graph_boost_factor
|
||||||
|
|
||||||
|
# 4. Finales Zusammenführen (Merging)
|
||||||
|
# (node_weight - 1.0) sorgt dafür, dass ein Gewicht von 1.0 keinen Einfluss hat (neutral).
|
||||||
|
total = base_val * (1.0 + (node_weight - 1.0) + edge_impact_final + cent_impact_final)
|
||||||
|
|
||||||
|
# Sicherstellen, dass der Score niemals 0 oder negativ ist (Floor)
|
||||||
|
final_score = max(0.0001, float(total))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"total": final_score,
|
||||||
|
"edge_bonus": float(edge_bonus_raw),
|
||||||
|
"cent_bonus": float(cent_bonus_raw),
|
||||||
|
"status_multiplier": status_mult,
|
||||||
|
"graph_boost_factor": graph_boost_factor,
|
||||||
|
"type_impact": node_weight - 1.0,
|
||||||
|
"base_val": base_val,
|
||||||
|
"edge_impact_final": edge_impact_final,
|
||||||
|
"cent_impact_final": cent_impact_final
|
||||||
|
}
|
||||||
@@ -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)
|
|
||||||
@@ -1,30 +1,11 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
Modul: app/core/type_registry.py
|
FILE: app/core/type_registry.py
|
||||||
Version: 1.0.0
|
DESCRIPTION: Loader für types.yaml. Achtung: Wird in der aktuellen Pipeline meist durch lokale Loader in 'ingestion.py' oder 'note_payload.py' umgangen.
|
||||||
Datum: 2025-11-08
|
VERSION: 1.0.0
|
||||||
|
STATUS: Deprecated (Redundant)
|
||||||
Zweck
|
DEPENDENCIES: yaml, os, functools
|
||||||
-----
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
Lädt eine optionale Typ-Registry (config/types.yaml) und stellt
|
LAST_ANALYSIS: 2025-12-15
|
||||||
komfortable Zugriffsfunktionen bereit. Die Registry ist *optional*:
|
|
||||||
- Fehlt die Datei oder ist das YAML defekt, wird ein konservativer
|
|
||||||
Default (Typ "concept") verwendet und es wird eine Warnung ausgegeben.
|
|
||||||
- Änderungen an der Datei greifen nach einem Neustart des Prozesses.
|
|
||||||
|
|
||||||
Öffentliche API
|
|
||||||
---------------
|
|
||||||
- load_type_registry(path: str = "config/types.yaml") -> dict
|
|
||||||
- get_type_config(note_type: str, reg: dict) -> dict
|
|
||||||
- resolve_note_type(fm_type: str | None, reg: dict) -> str
|
|
||||||
- effective_chunk_profile(note_type: str, reg: dict) -> str | None
|
|
||||||
- profile_overlap(profile: str | None) -> tuple[int,int] # nur Overlap-Empfehlung
|
|
||||||
|
|
||||||
Hinweis
|
|
||||||
-------
|
|
||||||
Die Registry steuert KEINE Breaking Changes. Ohne Datei/Typ bleibt das
|
|
||||||
Verhalten exakt wie im Release-Stand 20251105.
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -1,3 +1,12 @@
|
|||||||
|
"""
|
||||||
|
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 streamlit as st
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,12 @@
|
|||||||
|
"""
|
||||||
|
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 requests
|
||||||
import streamlit as st
|
import streamlit as st
|
||||||
from ui_config import CHAT_ENDPOINT, INGEST_ANALYZE_ENDPOINT, INGEST_SAVE_ENDPOINT, FEEDBACK_ENDPOINT, API_TIMEOUT
|
from ui_config import CHAT_ENDPOINT, INGEST_ANALYZE_ENDPOINT, INGEST_SAVE_ENDPOINT, FEEDBACK_ENDPOINT, API_TIMEOUT
|
||||||
|
|||||||
@@ -1,3 +1,12 @@
|
|||||||
|
"""
|
||||||
|
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 streamlit as st
|
||||||
import os
|
import os
|
||||||
from ui_utils import build_markdown_doc
|
from ui_utils import build_markdown_doc
|
||||||
|
|||||||
@@ -1,3 +1,12 @@
|
|||||||
|
"""
|
||||||
|
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
|
import streamlit as st
|
||||||
from ui_api import send_chat_message, submit_feedback
|
from ui_api import send_chat_message, submit_feedback
|
||||||
from ui_editor import render_draft_editor
|
from ui_editor import render_draft_editor
|
||||||
|
|||||||
@@ -1,3 +1,12 @@
|
|||||||
|
"""
|
||||||
|
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 os
|
||||||
import hashlib
|
import hashlib
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
|
|||||||
+25
-15
@@ -1,3 +1,11 @@
|
|||||||
|
"""
|
||||||
|
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 streamlit as st
|
||||||
import uuid
|
import uuid
|
||||||
import re
|
import re
|
||||||
@@ -68,14 +76,11 @@ def render_draft_editor(msg):
|
|||||||
|
|
||||||
# --- UI LAYOUT ---
|
# --- UI LAYOUT ---
|
||||||
|
|
||||||
# Header Info (Debug Pfad anzeigen, damit wir sicher sind)
|
|
||||||
origin_fname = st.session_state.get(f"{key_base}_origin_filename")
|
origin_fname = st.session_state.get(f"{key_base}_origin_filename")
|
||||||
|
|
||||||
if origin_fname:
|
if origin_fname:
|
||||||
# Dateiname extrahieren für saubere Anzeige
|
|
||||||
display_name = str(origin_fname).split("/")[-1]
|
display_name = str(origin_fname).split("/")[-1]
|
||||||
st.success(f"📂 **Update-Modus**: `{display_name}`")
|
st.success(f"📂 **Update-Modus**: `{display_name}`")
|
||||||
# Debugging: Zeige vollen Pfad im Expander
|
|
||||||
with st.expander("Dateipfad Details", expanded=False):
|
with st.expander("Dateipfad Details", expanded=False):
|
||||||
st.code(origin_fname)
|
st.code(origin_fname)
|
||||||
st.markdown(f'<div class="draft-box" style="border-left: 5px solid #ff9f43;">', unsafe_allow_html=True)
|
st.markdown(f'<div class="draft-box" style="border-left: 5px solid #ff9f43;">', unsafe_allow_html=True)
|
||||||
@@ -165,21 +170,33 @@ def render_draft_editor(msg):
|
|||||||
save_label = "💾 Update speichern" if origin_fname else "💾 Neu anlegen & Indizieren"
|
save_label = "💾 Update speichern" if origin_fname else "💾 Neu anlegen & Indizieren"
|
||||||
|
|
||||||
if st.button(save_label, type="primary", key=f"{key_base}_save"):
|
if st.button(save_label, type="primary", key=f"{key_base}_save"):
|
||||||
with st.spinner("Speichere im Vault..."):
|
with st.spinner("Sende an Backend..."):
|
||||||
if origin_fname:
|
if origin_fname:
|
||||||
# UPDATE: Ziel ist der exakte Pfad
|
|
||||||
target_file = origin_fname
|
target_file = origin_fname
|
||||||
else:
|
else:
|
||||||
# CREATE: Neuer Dateiname
|
|
||||||
raw_title = final_meta.get("title", "draft")
|
raw_title = final_meta.get("title", "draft")
|
||||||
target_file = f"{datetime.now().strftime('%Y%m%d')}-{slugify(raw_title)[:60]}.md"
|
target_file = f"{datetime.now().strftime('%Y%m%d')}-{slugify(raw_title)[:60]}.md"
|
||||||
|
|
||||||
result = save_draft_to_vault(final_doc, filename=target_file)
|
result = save_draft_to_vault(final_doc, filename=target_file)
|
||||||
|
|
||||||
|
# --- WP-14 CHANGE START: Handling Async Response ---
|
||||||
if "error" in result:
|
if "error" in result:
|
||||||
st.error(f"Fehler: {result['error']}")
|
st.error(f"Fehler: {result['error']}")
|
||||||
else:
|
else:
|
||||||
st.success(f"Gespeichert: {result.get('file_path')}")
|
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()
|
st.balloons()
|
||||||
|
# --- WP-14 CHANGE END ---
|
||||||
|
|
||||||
with b2:
|
with b2:
|
||||||
if st.button("📋 Code anzeigen", key=f"{key_base}_btn_copy"):
|
if st.button("📋 Code anzeigen", key=f"{key_base}_btn_copy"):
|
||||||
st.code(final_doc, language="markdown")
|
st.code(final_doc, language="markdown")
|
||||||
@@ -189,25 +206,18 @@ def render_draft_editor(msg):
|
|||||||
def render_manual_editor():
|
def render_manual_editor():
|
||||||
"""
|
"""
|
||||||
Rendert den manuellen Editor.
|
Rendert den manuellen Editor.
|
||||||
PRÜFT, ob eine Edit-Anfrage aus dem Graphen vorliegt!
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
target_msg = None
|
target_msg = None
|
||||||
|
|
||||||
# 1. Prüfen: Gibt es Nachrichten im Verlauf?
|
|
||||||
if st.session_state.messages:
|
if st.session_state.messages:
|
||||||
last_msg = st.session_state.messages[-1]
|
last_msg = st.session_state.messages[-1]
|
||||||
|
|
||||||
# 2. Ist die letzte Nachricht eine Edit-Anfrage? (Erkennbar am query_id prefix 'edit_')
|
|
||||||
qid = str(last_msg.get("query_id", ""))
|
qid = str(last_msg.get("query_id", ""))
|
||||||
if qid.startswith("edit_"):
|
if qid.startswith("edit_"):
|
||||||
target_msg = last_msg
|
target_msg = last_msg
|
||||||
|
|
||||||
# 3. Fallback: Leeres Template, falls keine Edit-Anfrage vorliegt
|
|
||||||
if not target_msg:
|
if not target_msg:
|
||||||
target_msg = {
|
target_msg = {
|
||||||
"content": "---\ntype: concept\ntitle: Neue Notiz\nstatus: draft\ntags: []\n---\n# Titel\n",
|
"content": "---\ntype: concept\ntitle: Neue Notiz\nstatus: draft\ntags: []\n---\n# Titel\n",
|
||||||
"query_id": f"manual_{uuid.uuid4()}" # Eigene ID, damit neuer State entsteht
|
"query_id": f"manual_{uuid.uuid4()}"
|
||||||
}
|
}
|
||||||
|
|
||||||
render_draft_editor(target_msg)
|
render_draft_editor(target_msg)
|
||||||
@@ -1,3 +1,12 @@
|
|||||||
|
"""
|
||||||
|
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
|
import streamlit as st
|
||||||
from streamlit_agraph import agraph, Config
|
from streamlit_agraph import agraph, Config
|
||||||
from qdrant_client import models
|
from qdrant_client import models
|
||||||
|
|||||||
@@ -1,3 +1,12 @@
|
|||||||
|
"""
|
||||||
|
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
|
import streamlit as st
|
||||||
from st_cytoscape import cytoscape
|
from st_cytoscape import cytoscape
|
||||||
from qdrant_client import models
|
from qdrant_client import models
|
||||||
|
|||||||
@@ -1,3 +1,12 @@
|
|||||||
|
"""
|
||||||
|
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
|
import re
|
||||||
from qdrant_client import QdrantClient, models
|
from qdrant_client import QdrantClient, models
|
||||||
from streamlit_agraph import Node, Edge
|
from streamlit_agraph import Node, Edge
|
||||||
|
|||||||
@@ -1,3 +1,12 @@
|
|||||||
|
"""
|
||||||
|
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
|
import streamlit as st
|
||||||
from ui_utils import load_history_from_logs
|
from ui_utils import load_history_from_logs
|
||||||
from ui_config import HISTORY_FILE
|
from ui_config import HISTORY_FILE
|
||||||
|
|||||||
@@ -1,3 +1,12 @@
|
|||||||
|
"""
|
||||||
|
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 re
|
||||||
import yaml
|
import yaml
|
||||||
import unicodedata
|
import unicodedata
|
||||||
|
|||||||
@@ -1,172 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
Modul: app/graph/service.py
|
|
||||||
Version: 0.1.0
|
|
||||||
Datum: 2025-09-10
|
|
||||||
|
|
||||||
Zweck
|
|
||||||
-----
|
|
||||||
Leichtgewichtiger Graph-Layer über Qdrant:
|
|
||||||
- get_note(note_id)
|
|
||||||
- get_chunks(note_id)
|
|
||||||
- neighbors(source_id, kinds=[...], scope=['note','chunk'], depth=1)
|
|
||||||
- walk_bfs(source_id, kinds, max_depth)
|
|
||||||
- context_for_note(note_id, max_neighbors): heuristische Kontextsammlung
|
|
||||||
|
|
||||||
Hinweise
|
|
||||||
--------
|
|
||||||
- Nutzt die bestehenden Collections <prefix>_notes/_chunks/_edges.
|
|
||||||
- Edges werden über Payload-Felder (`kind`, `source_id`, `target_id`) abgefragt.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
from typing import List, Dict, Any, Optional, Iterable, Set, Tuple
|
|
||||||
from qdrant_client.http import models as rest
|
|
||||||
from app.core.qdrant import QdrantConfig, get_client
|
|
||||||
|
|
||||||
def _cols(prefix: str):
|
|
||||||
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
|
||||||
|
|
||||||
class GraphService:
|
|
||||||
def __init__(self, cfg: Optional[QdrantConfig] = None, prefix: Optional[str] = None):
|
|
||||||
self.cfg = cfg or QdrantConfig.from_env()
|
|
||||||
if prefix:
|
|
||||||
self.cfg.prefix = prefix
|
|
||||||
self.client = get_client(self.cfg)
|
|
||||||
self.notes_col, self.chunks_col, self.edges_col = _cols(self.cfg.prefix)
|
|
||||||
|
|
||||||
# ------------------------ fetch helpers ------------------------
|
|
||||||
def _scroll(self, col: str, flt: Optional[rest.Filter] = None, limit: int = 256):
|
|
||||||
out = []
|
|
||||||
nextp = None
|
|
||||||
while True:
|
|
||||||
pts, nextp = self.client.scroll(
|
|
||||||
collection_name=col,
|
|
||||||
with_payload=True,
|
|
||||||
with_vectors=False,
|
|
||||||
limit=limit,
|
|
||||||
offset=nextp,
|
|
||||||
scroll_filter=flt,
|
|
||||||
)
|
|
||||||
if not pts:
|
|
||||||
break
|
|
||||||
out.extend(pts)
|
|
||||||
if nextp is None:
|
|
||||||
break
|
|
||||||
return out
|
|
||||||
|
|
||||||
# ------------------------ public API ---------------------------
|
|
||||||
def get_note(self, note_id: str) -> Optional[Dict[str, Any]]:
|
|
||||||
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
||||||
pts, _ = self.client.scroll(self.notes_col, with_payload=True, with_vectors=False, limit=1, scroll_filter=f)
|
|
||||||
return (pts[0].payload or None) if pts else None
|
|
||||||
|
|
||||||
def get_chunks(self, note_id: str) -> List[Dict[str, Any]]:
|
|
||||||
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
||||||
pts = self._scroll(self.chunks_col, f)
|
|
||||||
# Sortierung analog Export
|
|
||||||
def key(pl):
|
|
||||||
p = pl.payload or {}
|
|
||||||
s = p.get("seq") or 0
|
|
||||||
ci = p.get("chunk_index") or 0
|
|
||||||
n = 0
|
|
||||||
cid = p.get("chunk_id") or ""
|
|
||||||
if isinstance(cid, str) and "#" in cid:
|
|
||||||
try:
|
|
||||||
n = int(cid.rsplit("#", 1)[-1])
|
|
||||||
except Exception:
|
|
||||||
n = 0
|
|
||||||
return (int(s), int(ci), n)
|
|
||||||
pts_sorted = sorted(pts, key=key)
|
|
||||||
return [p.payload or {} for p in pts_sorted]
|
|
||||||
|
|
||||||
def neighbors(self, source_id: str, kinds: Optional[Iterable[str]] = None,
|
|
||||||
scope: Optional[Iterable[str]] = None, depth: int = 1) -> Dict[str, List[Dict[str, Any]]]:
|
|
||||||
"""
|
|
||||||
Liefert eingehende & ausgehende Nachbarn (nur nach kind gefiltert).
|
|
||||||
depth==1: direkte Kanten.
|
|
||||||
"""
|
|
||||||
kinds = list(kinds) if kinds else None
|
|
||||||
must = [rest.FieldCondition(key="source_id", match=rest.MatchValue(value=source_id))]
|
|
||||||
if kinds:
|
|
||||||
must.append(rest.FieldCondition(key="kind", match=rest.MatchAny(any=kinds)))
|
|
||||||
f = rest.Filter(must=must)
|
|
||||||
edges = self._scroll(self.edges_col, f)
|
|
||||||
out = {"out": [], "in": []}
|
|
||||||
for e in edges:
|
|
||||||
out["out"].append(e.payload or {})
|
|
||||||
# Inverse Richtung (eingehend)
|
|
||||||
must_in = [rest.FieldCondition(key="target_id", match=rest.MatchValue(value=source_id))]
|
|
||||||
if kinds:
|
|
||||||
must_in.append(rest.FieldCondition(key="kind", match=rest.MatchAny(any=kinds)))
|
|
||||||
f_in = rest.Filter(must=must_in)
|
|
||||||
edges_in = self._scroll(self.edges_col, f_in)
|
|
||||||
for e in edges_in:
|
|
||||||
out["in"].append(e.payload or {})
|
|
||||||
return out
|
|
||||||
|
|
||||||
def walk_bfs(self, source_id: str, kinds: Iterable[str], max_depth: int = 2) -> Set[str]:
|
|
||||||
visited: Set[str] = {source_id}
|
|
||||||
frontier: Set[str] = {source_id}
|
|
||||||
kinds = list(kinds)
|
|
||||||
for _ in range(max_depth):
|
|
||||||
nxt: Set[str] = set()
|
|
||||||
for s in frontier:
|
|
||||||
neigh = self.neighbors(s, kinds=kinds)
|
|
||||||
for e in neigh["out"]:
|
|
||||||
t = e.get("target_id")
|
|
||||||
if isinstance(t, str) and t not in visited:
|
|
||||||
visited.add(t)
|
|
||||||
nxt.add(t)
|
|
||||||
frontier = nxt
|
|
||||||
if not frontier:
|
|
||||||
break
|
|
||||||
return visited
|
|
||||||
|
|
||||||
def context_for_note(self, note_id: str, kinds: Iterable[str] = ("references","backlink"), max_neighbors: int = 12) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Heuristischer Kontext: eigene Chunks + Nachbarn nach Kantenarten, dedupliziert.
|
|
||||||
"""
|
|
||||||
note = self.get_note(note_id) or {}
|
|
||||||
chunks = self.get_chunks(note_id)
|
|
||||||
neigh = self.neighbors(note_id, kinds=list(kinds))
|
|
||||||
targets = []
|
|
||||||
for e in neigh["out"]:
|
|
||||||
t = e.get("target_id")
|
|
||||||
if isinstance(t, str):
|
|
||||||
targets.append(t)
|
|
||||||
for e in neigh["in"]:
|
|
||||||
s = e.get("source_id")
|
|
||||||
if isinstance(s, str):
|
|
||||||
targets.append(s)
|
|
||||||
# de-dupe
|
|
||||||
seen = set()
|
|
||||||
uniq = []
|
|
||||||
for t in targets:
|
|
||||||
if t not in seen:
|
|
||||||
seen.add(t)
|
|
||||||
uniq.append(t)
|
|
||||||
uniq = uniq[:max_neighbors]
|
|
||||||
neighbor_notes = [self.get_note(t) for t in uniq]
|
|
||||||
return {
|
|
||||||
"note": note,
|
|
||||||
"chunks": chunks,
|
|
||||||
"neighbors": [n for n in neighbor_notes if n],
|
|
||||||
"edges_out": neigh["out"],
|
|
||||||
"edges_in": neigh["in"],
|
|
||||||
}
|
|
||||||
|
|
||||||
# Optional: Mini-CLI
|
|
||||||
if __name__ == "__main__": # pragma: no cover
|
|
||||||
import argparse, json
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--prefix", help="Collection-Prefix (überschreibt ENV)")
|
|
||||||
ap.add_argument("--note-id", required=True)
|
|
||||||
ap.add_argument("--neighbors", action="store_true", help="Nur Nachbarn anzeigen")
|
|
||||||
args = ap.parse_args()
|
|
||||||
svc = GraphService(prefix=args.prefix)
|
|
||||||
if args.neighbors:
|
|
||||||
out = svc.neighbors(args.note_id, kinds=["references","backlink","prev","next","belongs_to"])
|
|
||||||
else:
|
|
||||||
out = svc.context_for_note(args.note_id)
|
|
||||||
print(json.dumps(out, ensure_ascii=False, indent=2))
|
|
||||||
+11
-5
@@ -1,11 +1,17 @@
|
|||||||
"""
|
"""
|
||||||
app/main.py — mindnet API bootstrap
|
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.query import router as query_router
|
||||||
from .routers.graph import router as graph_router
|
from .routers.graph import router as graph_router
|
||||||
@@ -29,8 +35,8 @@ def create_app() -> FastAPI:
|
|||||||
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(query_router, prefix="/query", tags=["query"])
|
||||||
app.include_router(graph_router, prefix="/graph", tags=["graph"])
|
app.include_router(graph_router, prefix="/graph", tags=["graph"])
|
||||||
|
|||||||
+30
-28
@@ -1,14 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/models/dto.py — Pydantic-Modelle (DTOs) für WP-04/WP-05/WP-06
|
FILE: app/models/dto.py
|
||||||
|
DESCRIPTION: Pydantic-Modelle (DTOs) für Request/Response Bodies. Definiert das API-Schema.
|
||||||
Zweck:
|
VERSION: 0.6.6 (WP-22 Debug & Stability Update)
|
||||||
Laufzeit-Modelle für FastAPI (Requests/Responses).
|
STATUS: Active
|
||||||
WP-06 Update: Intent & Intent-Source in ChatResponse.
|
DEPENDENCIES: pydantic, typing, uuid
|
||||||
|
LAST_ANALYSIS: 2025-12-18
|
||||||
Version:
|
|
||||||
0.6.2 (WP-06: Decision Engine Transparency, Erweiterung des Feeback Request)
|
|
||||||
Stand:
|
|
||||||
2025-12-09
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -16,7 +12,8 @@ from pydantic import BaseModel, Field
|
|||||||
from typing import List, Literal, Optional, Dict, Any
|
from typing import List, Literal, Optional, Dict, Any
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
EdgeKind = Literal["references", "references_at", "backlink", "next", "prev", "belongs_to", "depends_on", "related_to", "similar_to"]
|
# Gültige Kanten-Typen gemäß Manual
|
||||||
|
EdgeKind = Literal["references", "references_at", "backlink", "next", "prev", "belongs_to", "depends_on", "related_to", "similar_to", "caused_by", "derived_from", "based_on", "solves", "blocks", "uses", "guides"]
|
||||||
|
|
||||||
|
|
||||||
# --- Basis-DTOs ---
|
# --- Basis-DTOs ---
|
||||||
@@ -44,6 +41,8 @@ class EdgeDTO(BaseModel):
|
|||||||
target: str
|
target: str
|
||||||
weight: float
|
weight: float
|
||||||
direction: Literal["out", "in", "undirected"] = "out"
|
direction: Literal["out", "in", "undirected"] = "out"
|
||||||
|
provenance: Optional[Literal["explicit", "rule", "smart", "structure"]] = "explicit"
|
||||||
|
confidence: float = 1.0
|
||||||
|
|
||||||
|
|
||||||
# --- Request Models ---
|
# --- Request Models ---
|
||||||
@@ -61,17 +60,17 @@ class QueryRequest(BaseModel):
|
|||||||
ret: Dict = {"with_paths": True, "with_notes": True, "with_chunks": True}
|
ret: Dict = {"with_paths": True, "with_notes": True, "with_chunks": True}
|
||||||
explain: bool = False
|
explain: bool = False
|
||||||
|
|
||||||
|
# WP-22: Semantic Graph Routing
|
||||||
|
boost_edges: Optional[Dict[str, float]] = None
|
||||||
|
|
||||||
|
|
||||||
class FeedbackRequest(BaseModel):
|
class FeedbackRequest(BaseModel):
|
||||||
"""
|
"""
|
||||||
User-Feedback zu einem spezifischen Treffer oder der Gesamtantwort.
|
User-Feedback zu einem spezifischen Treffer oder der Gesamtantwort (WP-08 Basis).
|
||||||
"""
|
"""
|
||||||
query_id: str = Field(..., description="ID der ursprünglichen Suche")
|
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'")
|
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) bis 5 (Perfekt)")
|
||||||
score: int = Field(..., ge=1, le=5, description="1 (Irrelevant/Falsch) bis 5 (Perfekt)")
|
|
||||||
comment: Optional[str] = None
|
comment: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
@@ -80,8 +79,7 @@ class ChatRequest(BaseModel):
|
|||||||
WP-05: Request für /chat.
|
WP-05: Request für /chat.
|
||||||
"""
|
"""
|
||||||
message: str = Field(..., description="Die Nachricht des Users")
|
message: str = Field(..., description="Die Nachricht des Users")
|
||||||
conversation_id: Optional[str] = Field(None, description="Optional: ID für Chat-Verlauf (noch nicht implementiert)")
|
conversation_id: Optional[str] = Field(None, description="ID für Chat-Verlauf")
|
||||||
# RAG Parameter (Override defaults)
|
|
||||||
top_k: int = 5
|
top_k: int = 5
|
||||||
explain: bool = False
|
explain: bool = False
|
||||||
|
|
||||||
@@ -89,7 +87,7 @@ class ChatRequest(BaseModel):
|
|||||||
# --- WP-04b Explanation Models ---
|
# --- WP-04b Explanation Models ---
|
||||||
|
|
||||||
class ScoreBreakdown(BaseModel):
|
class ScoreBreakdown(BaseModel):
|
||||||
"""Aufschlüsselung der Score-Komponenten."""
|
"""Aufschlüsselung der Score-Komponenten nach der WP-22 Formel."""
|
||||||
semantic_contribution: float
|
semantic_contribution: float
|
||||||
edge_contribution: float
|
edge_contribution: float
|
||||||
centrality_contribution: float
|
centrality_contribution: float
|
||||||
@@ -97,11 +95,14 @@ class ScoreBreakdown(BaseModel):
|
|||||||
raw_edge_bonus: float
|
raw_edge_bonus: float
|
||||||
raw_centrality: float
|
raw_centrality: float
|
||||||
node_weight: float
|
node_weight: float
|
||||||
|
# WP-22 Debug Fields für Messbarkeit
|
||||||
|
status_multiplier: float = 1.0
|
||||||
|
graph_boost_factor: float = 1.0
|
||||||
|
|
||||||
|
|
||||||
class Reason(BaseModel):
|
class Reason(BaseModel):
|
||||||
"""Ein semantischer Grund für das Ranking."""
|
"""Ein semantischer Grund für das Ranking."""
|
||||||
kind: Literal["semantic", "edge", "type", "centrality"]
|
kind: Literal["semantic", "edge", "type", "centrality", "lifecycle"]
|
||||||
message: str
|
message: str
|
||||||
score_impact: Optional[float] = None
|
score_impact: Optional[float] = None
|
||||||
details: Optional[Dict[str, Any]] = None
|
details: Optional[Dict[str, Any]] = None
|
||||||
@@ -112,6 +113,9 @@ class Explanation(BaseModel):
|
|||||||
breakdown: ScoreBreakdown
|
breakdown: ScoreBreakdown
|
||||||
reasons: List[Reason]
|
reasons: List[Reason]
|
||||||
related_edges: Optional[List[EdgeDTO]] = None
|
related_edges: Optional[List[EdgeDTO]] = None
|
||||||
|
# WP-22 Debug: Verifizierung des Routings
|
||||||
|
applied_intent: Optional[str] = None
|
||||||
|
applied_boosts: Optional[Dict[str, float]] = None
|
||||||
|
|
||||||
|
|
||||||
# --- Response Models ---
|
# --- Response Models ---
|
||||||
@@ -119,14 +123,14 @@ class Explanation(BaseModel):
|
|||||||
class QueryHit(BaseModel):
|
class QueryHit(BaseModel):
|
||||||
"""Einzelnes Trefferobjekt für /query."""
|
"""Einzelnes Trefferobjekt für /query."""
|
||||||
node_id: str
|
node_id: str
|
||||||
note_id: Optional[str]
|
note_id: str
|
||||||
semantic_score: float
|
semantic_score: float
|
||||||
edge_bonus: float
|
edge_bonus: float
|
||||||
centrality_bonus: float
|
centrality_bonus: float
|
||||||
total_score: float
|
total_score: float
|
||||||
paths: Optional[List[List[Dict]]] = None
|
paths: Optional[List[List[Dict]]] = None
|
||||||
source: Optional[Dict] = None
|
source: Optional[Dict] = None
|
||||||
payload: Optional[Dict] = None # Added for flexibility & WP-06 meta-data
|
payload: Optional[Dict] = None
|
||||||
explanation: Optional[Explanation] = None
|
explanation: Optional[Explanation] = None
|
||||||
|
|
||||||
|
|
||||||
@@ -150,11 +154,9 @@ class ChatResponse(BaseModel):
|
|||||||
"""
|
"""
|
||||||
WP-05/06: Antwortstruktur für /chat.
|
WP-05/06: Antwortstruktur für /chat.
|
||||||
"""
|
"""
|
||||||
query_id: str = Field(..., description="Traceability ID (dieselbe wie für Search)")
|
query_id: str = Field(..., description="Traceability ID")
|
||||||
answer: str = Field(..., description="Generierte Antwort vom LLM")
|
answer: str = Field(..., description="Generierte Antwort vom LLM")
|
||||||
sources: List[QueryHit] = Field(..., description="Die für die Antwort genutzten Quellen")
|
sources: List[QueryHit] = Field(..., description="Die genutzten Quellen")
|
||||||
latency_ms: int
|
latency_ms: int
|
||||||
intent: Optional[str] = Field("FACT", description="WP-06: Erkannter Intent (FACT/DECISION)")
|
intent: Optional[str] = Field("FACT", description="WP-06: Erkannter Intent")
|
||||||
intent_source: Optional[str] = Field("Unknown", description="WP-06: Quelle der Intent-Erkennung (Keyword vs. LLM)")
|
intent_source: Optional[str] = Field("Unknown", description="Quelle der Intent-Erkennung")
|
||||||
|
|
||||||
|
|
||||||
+6
-16
@@ -1,20 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/admin.py — Admin-/Monitoring-Endpunkte (optional)
|
FILE: app/routers/admin.py
|
||||||
|
DESCRIPTION: Monitoring-Endpunkt. Zeigt Qdrant-Collection-Counts und geladene Config.
|
||||||
Zweck:
|
VERSION: 0.1.0
|
||||||
Liefert einfache Kennzahlen zu Collections (Counts) und Config.
|
STATUS: Active (Optional)
|
||||||
Kompatibilität:
|
DEPENDENCIES: qdrant_client, app.config
|
||||||
Python 3.12+, FastAPI 0.110+, qdrant-client 1.x
|
LAST_ANALYSIS: 2025-12-15
|
||||||
Version:
|
|
||||||
0.1.0 (Erstanlage)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Bezug:
|
|
||||||
- Qdrant Collections: *_notes, *_chunks, *_edges
|
|
||||||
Nutzung:
|
|
||||||
app.include_router(admin.router, prefix="/admin", tags=["admin"])
|
|
||||||
Änderungsverlauf:
|
|
||||||
0.1.0 (2025-10-07) – Erstanlage.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
+18
-10
@@ -1,6 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/chat.py — RAG Endpunkt
|
FILE: app/routers/chat.py
|
||||||
Version: 2.5.0 (Fix: Question Detection protects against False-Positive Interviews)
|
DESCRIPTION: Haupt-Chat-Interface (RAG & Interview). Enthält Intent-Router (Keywords/LLM) und Prompt-Construction.
|
||||||
|
VERSION: 2.7.0 (WP-22 Semantic Graph Routing)
|
||||||
|
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
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from fastapi import APIRouter, HTTPException, Depends
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
@@ -183,9 +187,6 @@ async def _classify_intent(query: str, llm: LLMService) -> tuple[str, str]:
|
|||||||
return intent_name, "Keyword (Strategy)"
|
return intent_name, "Keyword (Strategy)"
|
||||||
|
|
||||||
# 2. FAST PATH B: Type Keywords (z.B. "Projekt", "Werte") -> INTERVIEW
|
# 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):
|
if not _is_question(query_lower):
|
||||||
types_cfg = get_types_config()
|
types_cfg = get_types_config()
|
||||||
types_def = types_cfg.get("types", {})
|
types_def = types_cfg.get("types", {})
|
||||||
@@ -198,7 +199,6 @@ async def _classify_intent(query: str, llm: LLMService) -> tuple[str, str]:
|
|||||||
|
|
||||||
# 3. SLOW PATH: LLM Router
|
# 3. SLOW PATH: LLM Router
|
||||||
if settings.get("llm_fallback_enabled", False):
|
if settings.get("llm_fallback_enabled", False):
|
||||||
# Nutze Prompts aus prompts.yaml (via LLM Service)
|
|
||||||
router_prompt_template = llm.prompts.get("router_prompt", "")
|
router_prompt_template = llm.prompts.get("router_prompt", "")
|
||||||
|
|
||||||
if router_prompt_template:
|
if router_prompt_template:
|
||||||
@@ -206,11 +206,9 @@ async def _classify_intent(query: str, llm: LLMService) -> tuple[str, str]:
|
|||||||
logger.info("Keywords failed (or Question detected). Asking LLM for Intent...")
|
logger.info("Keywords failed (or Question detected). Asking LLM for Intent...")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Nutze priority="realtime" für den Router, damit er nicht wartet
|
|
||||||
raw_response = await llm.generate_raw_response(prompt, priority="realtime")
|
raw_response = await llm.generate_raw_response(prompt, priority="realtime")
|
||||||
llm_output_upper = raw_response.upper()
|
llm_output_upper = raw_response.upper()
|
||||||
|
|
||||||
# Zuerst INTERVIEW prüfen
|
|
||||||
if "INTERVIEW" in llm_output_upper or "CREATE" in llm_output_upper:
|
if "INTERVIEW" in llm_output_upper or "CREATE" in llm_output_upper:
|
||||||
return "INTERVIEW", "LLM Router"
|
return "INTERVIEW", "LLM Router"
|
||||||
|
|
||||||
@@ -277,11 +275,19 @@ async def chat_endpoint(
|
|||||||
inject_types = strategy.get("inject_types", [])
|
inject_types = strategy.get("inject_types", [])
|
||||||
prepend_instr = strategy.get("prepend_instruction", "")
|
prepend_instr = strategy.get("prepend_instruction", "")
|
||||||
|
|
||||||
|
# --- WP-22: Semantic Graph Routing (Teil C) ---
|
||||||
|
# Wir laden die konfigurierten Edge-Boosts für diesen Intent
|
||||||
|
edge_boosts = strategy.get("edge_boosts", {})
|
||||||
|
if edge_boosts:
|
||||||
|
logger.info(f"[{query_id}] Applying Edge Boosts: {edge_boosts}")
|
||||||
|
|
||||||
query_req = QueryRequest(
|
query_req = QueryRequest(
|
||||||
query=request.message,
|
query=request.message,
|
||||||
mode="hybrid",
|
mode="hybrid",
|
||||||
top_k=request.top_k,
|
top_k=request.top_k,
|
||||||
explain=request.explain
|
explain=request.explain,
|
||||||
|
# WP-22: Boosts an den Retriever weitergeben
|
||||||
|
boost_edges=edge_boosts
|
||||||
)
|
)
|
||||||
retrieve_result = await retriever.search(query_req)
|
retrieve_result = await retriever.search(query_req)
|
||||||
hits = retrieve_result.results
|
hits = retrieve_result.results
|
||||||
@@ -292,7 +298,9 @@ async def chat_endpoint(
|
|||||||
mode="hybrid",
|
mode="hybrid",
|
||||||
top_k=3,
|
top_k=3,
|
||||||
filters={"type": inject_types},
|
filters={"type": inject_types},
|
||||||
explain=False
|
explain=False,
|
||||||
|
# WP-22: Boosts auch hier anwenden (Konsistenz)
|
||||||
|
boost_edges=edge_boosts
|
||||||
)
|
)
|
||||||
strategy_result = await retriever.search(strategy_req)
|
strategy_result = await retriever.search(strategy_req)
|
||||||
existing_ids = {h.node_id for h in hits}
|
existing_ids = {h.node_id for h in hits}
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/feedback.py
|
FILE: app/routers/feedback.py
|
||||||
Endpunkt für User-Feedback (WP-04c).
|
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 fastapi import APIRouter, HTTPException
|
||||||
from app.models.dto import FeedbackRequest
|
from app.models.dto import FeedbackRequest
|
||||||
|
|||||||
+6
-17
@@ -1,21 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/graph.py — Graph-Endpunkte (WP-04)
|
FILE: app/routers/graph.py
|
||||||
|
DESCRIPTION: Liefert Graph-Daten (Knoten/Kanten) für UI-Visualisierungen basierend auf einer Seed-ID. (WP4)
|
||||||
Zweck:
|
VERSION: 0.1.0
|
||||||
Liefert die Nachbarschaft einer Note/ID als JSON-Graph (Nodes/Edges/Stats).
|
STATUS: Active
|
||||||
Kompatibilität:
|
DEPENDENCIES: qdrant_client, app.models.dto, app.core.graph_adapter, app.config
|
||||||
Python 3.12+, FastAPI 0.110+, qdrant-client 1.x
|
LAST_ANALYSIS: 2025-12-15
|
||||||
Version:
|
|
||||||
0.1.0 (Erstanlage)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Bezug:
|
|
||||||
- app/core/graph_adapter.py
|
|
||||||
- app/models/dto.py
|
|
||||||
Nutzung:
|
|
||||||
app.include_router(graph.router, prefix="/graph", tags=["graph"])
|
|
||||||
Änderungsverlauf:
|
|
||||||
0.1.0 (2025-10-07) – Erstanlage.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
+55
-23
@@ -1,12 +1,17 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/ingest.py
|
FILE: app/routers/ingest.py
|
||||||
API-Endpunkte für WP-11 (Discovery & Persistence).
|
DESCRIPTION: Endpunkte für WP-11. Nimmt Markdown entgegen.
|
||||||
Delegiert an Services.
|
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 os
|
||||||
import time
|
import time
|
||||||
import logging
|
import logging
|
||||||
from fastapi import APIRouter, HTTPException
|
import asyncio
|
||||||
|
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from typing import Optional, Dict, Any
|
from typing import Optional, Dict, Any
|
||||||
|
|
||||||
@@ -16,7 +21,7 @@ from app.services.discovery import DiscoveryService
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
# Services Init (Global oder via Dependency Injection)
|
# Services Init
|
||||||
discovery_service = DiscoveryService()
|
discovery_service = DiscoveryService()
|
||||||
|
|
||||||
class AnalyzeRequest(BaseModel):
|
class AnalyzeRequest(BaseModel):
|
||||||
@@ -32,7 +37,32 @@ class SaveResponse(BaseModel):
|
|||||||
status: str
|
status: str
|
||||||
file_path: str
|
file_path: str
|
||||||
note_id: str
|
note_id: str
|
||||||
stats: Dict[str, Any]
|
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")
|
@router.post("/analyze")
|
||||||
async def analyze_draft(req: AnalyzeRequest):
|
async def analyze_draft(req: AnalyzeRequest):
|
||||||
@@ -40,7 +70,6 @@ async def analyze_draft(req: AnalyzeRequest):
|
|||||||
WP-11 Intelligence: Liefert Link-Vorschläge via DiscoveryService.
|
WP-11 Intelligence: Liefert Link-Vorschläge via DiscoveryService.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Hier rufen wir jetzt den verbesserten Service auf
|
|
||||||
result = await discovery_service.analyze_draft(req.text, req.type)
|
result = await discovery_service.analyze_draft(req.text, req.type)
|
||||||
return result
|
return result
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -48,9 +77,10 @@ async def analyze_draft(req: AnalyzeRequest):
|
|||||||
return {"suggestions": [], "error": str(e)}
|
return {"suggestions": [], "error": str(e)}
|
||||||
|
|
||||||
@router.post("/save", response_model=SaveResponse)
|
@router.post("/save", response_model=SaveResponse)
|
||||||
async def save_note(req: SaveRequest):
|
async def save_note(req: SaveRequest, background_tasks: BackgroundTasks):
|
||||||
"""
|
"""
|
||||||
WP-11 Persistence: Speichert und indiziert.
|
WP-14 Fix: Startet Ingestion im Hintergrund (Fire & Forget).
|
||||||
|
Verhindert Timeouts bei aktiver Smart-Edge-Allocation (WP-15).
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
vault_root = os.getenv("MINDNET_VAULT_ROOT", "./vault")
|
vault_root = os.getenv("MINDNET_VAULT_ROOT", "./vault")
|
||||||
@@ -61,29 +91,31 @@ async def save_note(req: SaveRequest):
|
|||||||
except: pass
|
except: pass
|
||||||
|
|
||||||
final_filename = req.filename or f"draft_{int(time.time())}.md"
|
final_filename = req.filename or f"draft_{int(time.time())}.md"
|
||||||
ingest_service = IngestionService()
|
|
||||||
|
|
||||||
# Async Call
|
# Wir geben sofort eine ID zurück (optimistisch),
|
||||||
result = await ingest_service.create_from_text(
|
# 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,
|
markdown_content=req.markdown_content,
|
||||||
filename=final_filename,
|
filename=final_filename,
|
||||||
vault_root=abs_vault_root,
|
vault_root=abs_vault_root,
|
||||||
folder=req.folder
|
folder=req.folder
|
||||||
)
|
)
|
||||||
|
|
||||||
if result.get("status") == "error":
|
|
||||||
raise HTTPException(status_code=500, detail=result.get("error"))
|
|
||||||
|
|
||||||
return SaveResponse(
|
return SaveResponse(
|
||||||
status="success",
|
status="queued",
|
||||||
file_path=result.get("path", "unknown"),
|
file_path=os.path.join(req.folder, final_filename),
|
||||||
note_id=result.get("note_id", "unknown"),
|
note_id="pending",
|
||||||
|
message="Speicherung & KI-Analyse im Hintergrund gestartet.",
|
||||||
stats={
|
stats={
|
||||||
"chunks": result.get("chunks_count", 0),
|
"chunks": -1, # Indikator für Async
|
||||||
"edges": result.get("edges_count", 0)
|
"edges": -1
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
except HTTPException as he: raise he
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Save failed: {e}", exc_info=True)
|
logger.error(f"Save dispatch failed: {e}", exc_info=True)
|
||||||
raise HTTPException(status_code=500, detail=f"Save failed: {str(e)}")
|
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}
|
|
||||||
+7
-18
@@ -1,23 +1,12 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/query.py — Query-Endpunkte (WP-04)
|
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
|
||||||
|
"""
|
||||||
|
|
||||||
Zweck:
|
|
||||||
Stellt POST /query bereit und ruft den passenden Retriever-Modus auf.
|
|
||||||
Kompatibilität:
|
|
||||||
Python 3.12+, FastAPI 0.110+
|
|
||||||
Version:
|
|
||||||
0.1.0 (Erstanlage)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Bezug:
|
|
||||||
- app/core/retriever.py
|
|
||||||
- app/models/dto.py
|
|
||||||
Nutzung:
|
|
||||||
app.include_router(query.router, prefix="/query", tags=["query"])
|
|
||||||
Änderungsverlauf:
|
|
||||||
0.2.0 (2025-12-07) - Update für WP04c Feedback
|
|
||||||
0.1.0 (2025-10-07) – Erstanlage.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
||||||
from app.models.dto import QueryRequest, QueryResponse
|
from app.models.dto import QueryRequest, QueryResponse
|
||||||
|
|||||||
+6
-17
@@ -1,21 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/routers/tools.py — Tool-Definitionen für Ollama/n8n/MCP (read-only)
|
FILE: app/routers/tools.py
|
||||||
|
DESCRIPTION: Liefert JSON-Schemas für die Integration als 'Tools' in Agents (Ollama/OpenAI). Read-Only.
|
||||||
Zweck:
|
VERSION: 0.1.1
|
||||||
Liefert Funktions-Schemas (OpenAI-/Ollama-kompatibles Tool-JSON) für:
|
STATUS: Active
|
||||||
- mindnet_query -> POST /query
|
DEPENDENCIES: fastapi
|
||||||
- mindnet_subgraph -> GET /graph/{note_id}
|
LAST_ANALYSIS: 2025-12-15
|
||||||
Kompatibilität:
|
|
||||||
Python 3.12+, FastAPI 0.110+
|
|
||||||
Version:
|
|
||||||
0.1.1 (query ODER query_vector möglich)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Nutzung:
|
|
||||||
app.include_router(tools.router, prefix="/tools", tags=["tools"])
|
|
||||||
Änderungsverlauf:
|
|
||||||
0.1.1 (2025-10-07) – mindnet_query: oneOf(query, query_vector).
|
|
||||||
0.1.0 (2025-10-07) – Erstanlage.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
"""
|
"""
|
||||||
app/services/discovery.py
|
FILE: app/services/discovery.py
|
||||||
Service für Link-Vorschläge und Knowledge-Discovery (WP-11).
|
DESCRIPTION: Service für WP-11. Analysiert Texte, findet Entitäten und schlägt typisierte Verbindungen vor ("Matrix-Logic").
|
||||||
|
VERSION: 0.6.0
|
||||||
Features:
|
STATUS: Active
|
||||||
- Sliding Window Analyse für lange Texte.
|
DEPENDENCIES: app.core.qdrant, app.models.dto, app.core.retriever
|
||||||
- Footer-Scan für Projekt-Referenzen.
|
EXTERNAL_CONFIG: config/types.yaml
|
||||||
- 'Matrix-Logic' für intelligente Kanten-Typen (Experience -> Value = based_on).
|
LAST_ANALYSIS: 2025-12-15
|
||||||
- Async & Nomic-Embeddings kompatibel.
|
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/services/edge_registry.py
|
||||||
|
DESCRIPTION: Single Source of Truth für Kanten-Typen.
|
||||||
|
FIX: Regex angepasst auf Format **`canonical`** (Bold + Backticks).
|
||||||
|
VERSION: 0.6.10 (Regex Precision Update)
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
import os
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from typing import Dict, Optional, Set
|
||||||
|
|
||||||
|
print(">>> MODULE_LOAD: edge_registry.py initialized <<<", flush=True)
|
||||||
|
|
||||||
|
from app.config import get_settings
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class EdgeRegistry:
|
||||||
|
_instance = None
|
||||||
|
|
||||||
|
def __new__(cls, *args, **kwargs):
|
||||||
|
if cls._instance is None:
|
||||||
|
cls._instance = super(EdgeRegistry, cls).__new__(cls)
|
||||||
|
cls._instance.initialized = False
|
||||||
|
return cls._instance
|
||||||
|
|
||||||
|
def __init__(self, vault_root: Optional[str] = None):
|
||||||
|
if self.initialized:
|
||||||
|
return
|
||||||
|
|
||||||
|
settings = get_settings()
|
||||||
|
env_vocab_path = os.getenv("MINDNET_VOCAB_PATH")
|
||||||
|
env_vault_root = os.getenv("MINDNET_VAULT_ROOT") or getattr(settings, "MINDNET_VAULT_ROOT", "./vault")
|
||||||
|
|
||||||
|
if env_vocab_path:
|
||||||
|
self.full_vocab_path = os.path.abspath(env_vocab_path)
|
||||||
|
else:
|
||||||
|
self.full_vocab_path = os.path.abspath(
|
||||||
|
os.path.join(env_vault_root, "01_User_Manual", "01_edge_vocabulary.md")
|
||||||
|
)
|
||||||
|
|
||||||
|
self.unknown_log_path = "data/logs/unknown_edges.jsonl"
|
||||||
|
self.canonical_map: Dict[str, str] = {}
|
||||||
|
self.valid_types: Set[str] = set()
|
||||||
|
|
||||||
|
self._load_vocabulary()
|
||||||
|
self.initialized = True
|
||||||
|
|
||||||
|
def _load_vocabulary(self):
|
||||||
|
"""Parst die Markdown-Tabelle im Vault."""
|
||||||
|
print(f">>> CHECK: Loading Vocabulary from {self.full_vocab_path}", flush=True)
|
||||||
|
|
||||||
|
if not os.path.exists(self.full_vocab_path):
|
||||||
|
print(f"!!! [DICT-ERROR] File not found: {self.full_vocab_path} !!!", flush=True)
|
||||||
|
return
|
||||||
|
|
||||||
|
# WP-22 Precision Regex:
|
||||||
|
# Sucht nach | **`typ`** | oder | **typ** |
|
||||||
|
# Die Backticks `? sind jetzt optional enthalten.
|
||||||
|
pattern = re.compile(r"\|\s*\*\*`?([a-zA-Z0-9_-]+)`?\*\*\s*\|\s*([^|]+)\|")
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(self.full_vocab_path, "r", encoding="utf-8") as f:
|
||||||
|
c_types, c_aliases = 0, 0
|
||||||
|
for line in f:
|
||||||
|
match = pattern.search(line)
|
||||||
|
if match:
|
||||||
|
canonical = match.group(1).strip().lower()
|
||||||
|
aliases_str = match.group(2).strip()
|
||||||
|
|
||||||
|
self.valid_types.add(canonical)
|
||||||
|
self.canonical_map[canonical] = canonical
|
||||||
|
c_types += 1
|
||||||
|
|
||||||
|
if aliases_str and "Kein Alias" not in aliases_str:
|
||||||
|
# Aliase säubern (entfernt Backticks auch hier)
|
||||||
|
aliases = [a.strip() for a in aliases_str.split(",") if a.strip()]
|
||||||
|
for alias in aliases:
|
||||||
|
clean_alias = alias.replace("`", "").lower().strip().replace(" ", "_")
|
||||||
|
self.canonical_map[clean_alias] = canonical
|
||||||
|
c_aliases += 1
|
||||||
|
|
||||||
|
if c_types == 0:
|
||||||
|
print("!!! [DICT-WARN] Pattern mismatch! Ensure types are **`canonical`** or **canonical**. !!!", flush=True)
|
||||||
|
else:
|
||||||
|
print(f"=== [DICT-SUCCESS] Registered {c_types} Canonical Types and {c_aliases} Aliases ===", flush=True)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"!!! [DICT-FATAL] Error reading file: {e} !!!", flush=True)
|
||||||
|
|
||||||
|
def resolve(self, edge_type: str) -> str:
|
||||||
|
"""Normalisiert Kanten-Typen via Registry oder loggt Unbekannte."""
|
||||||
|
if not edge_type: return "related_to"
|
||||||
|
clean_type = edge_type.lower().strip().replace(" ", "_").replace("-", "_")
|
||||||
|
|
||||||
|
if clean_type in self.canonical_map:
|
||||||
|
return self.canonical_map[clean_type]
|
||||||
|
|
||||||
|
self._log_unknown(clean_type)
|
||||||
|
return clean_type
|
||||||
|
|
||||||
|
def _log_unknown(self, edge_type: str):
|
||||||
|
try:
|
||||||
|
os.makedirs(os.path.dirname(self.unknown_log_path), exist_ok=True)
|
||||||
|
entry = {"unknown_type": edge_type, "status": "new"}
|
||||||
|
with open(self.unknown_log_path, "a", encoding="utf-8") as f:
|
||||||
|
f.write(json.dumps(entry) + "\n")
|
||||||
|
except Exception: pass
|
||||||
|
|
||||||
|
registry = EdgeRegistry()
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/services/embeddings_client.py — Text→Embedding Service
|
FILE: app/services/embeddings_client.py
|
||||||
|
DESCRIPTION: Unified Embedding Client. Nutzt Ollama API (HTTP). Ersetzt lokale sentence-transformers.
|
||||||
Zweck:
|
VERSION: 2.5.0
|
||||||
Einheitlicher Client für Embeddings via Ollama (Nomic).
|
STATUS: Active
|
||||||
Stellt sicher, dass sowohl Async (Ingestion) als auch Sync (Retriever)
|
DEPENDENCIES: httpx, requests, app.config
|
||||||
denselben Vektorraum (768 Dim) nutzen.
|
LAST_ANALYSIS: 2025-12-15
|
||||||
|
|
||||||
Version: 2.5.0 (Unified Ollama)
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
import os
|
import os
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/services/feedback_service.py
|
FILE: app/services/feedback_service.py
|
||||||
Service zum Loggen von Suchanfragen und Feedback (WP-04c).
|
DESCRIPTION: Schreibt Search- und Feedback-Logs in JSONL-Dateien.
|
||||||
Speichert Daten als JSONL für späteres Self-Tuning (WP-08).
|
VERSION: 1.1
|
||||||
|
STATUS: Active
|
||||||
Version: 1.1 (Chat-Support)
|
DEPENDENCIES: app.models.dto
|
||||||
|
LAST_ANALYSIS: 2025-12-15
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
|||||||
@@ -1,88 +0,0 @@
|
|||||||
"""
|
|
||||||
app/services/llm_ollama.py — Ollama-Integration & Prompt-Bau (WP-04)
|
|
||||||
|
|
||||||
Zweck:
|
|
||||||
Prompt-Template & (optionaler) lokaler Aufruf von Ollama. Der Aufruf ist
|
|
||||||
bewusst gekapselt und kann gefahrlos deaktiviert bleiben, bis ihr ein
|
|
||||||
konkretes Modell konfigurieren wollt.
|
|
||||||
Kompatibilität:
|
|
||||||
Python 3.12+
|
|
||||||
Version:
|
|
||||||
0.1.0 (Erstanlage)
|
|
||||||
Stand:
|
|
||||||
2025-10-07
|
|
||||||
Bezug:
|
|
||||||
WP-04/05 Kontextbereitstellung für LLM
|
|
||||||
Nutzung:
|
|
||||||
from app.services.llm_ollama import build_prompt, call_ollama
|
|
||||||
Änderungsverlauf:
|
|
||||||
0.1.0 (2025-10-07) – Erstanlage.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
from typing import List, Dict, Optional
|
|
||||||
import subprocess
|
|
||||||
import json
|
|
||||||
|
|
||||||
PROMPT_TEMPLATE = """System: You are a helpful expert.
|
|
||||||
User: {question}
|
|
||||||
|
|
||||||
Context (ranked):
|
|
||||||
{contexts}
|
|
||||||
|
|
||||||
Task: Answer precisely. At the end, list sources (note title + section) and important edge paths.
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
def build_context_block(items: List[Dict]) -> str:
|
|
||||||
"""Formatiert Top-K-Kontexte (Chunks) für den Prompt."""
|
|
||||||
lines = []
|
|
||||||
for i, it in enumerate(items, 1):
|
|
||||||
note = it.get("note_title", "") or it.get("note_id", "")
|
|
||||||
sec = it.get("section", "") or it.get("section_title", "")
|
|
||||||
sc = it.get("score", 0)
|
|
||||||
txt = it.get("text", "") or it.get("body", "") or ""
|
|
||||||
lines.append(f"{i}) {note} — {sec} [score={sc:.2f}]\n{txt}\n")
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def build_prompt(question: str, contexts: List[Dict]) -> str:
|
|
||||||
"""Setzt Frage + Kontexte in ein konsistentes Template."""
|
|
||||||
return PROMPT_TEMPLATE.format(question=question, contexts=build_context_block(contexts))
|
|
||||||
|
|
||||||
|
|
||||||
def call_ollama(prompt: str, model: str = "llama3.1:8b", timeout_s: int = 120) -> Optional[str]:
|
|
||||||
"""
|
|
||||||
Optionaler lokaler Aufruf von `ollama run`.
|
|
||||||
Rückgabe: generierter Text oder None bei Fehler/Abbruch.
|
|
||||||
Hinweis: Nur nutzen, wenn Ollama lokal installiert/konfiguriert ist.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
proc = subprocess.run(
|
|
||||||
["ollama", "run", model],
|
|
||||||
input=prompt.encode("utf-8"),
|
|
||||||
stdout=subprocess.PIPE,
|
|
||||||
stderr=subprocess.PIPE,
|
|
||||||
timeout=timeout_s,
|
|
||||||
check=False,
|
|
||||||
)
|
|
||||||
out = proc.stdout.decode("utf-8", errors="replace")
|
|
||||||
# viele ollama Builds streamen JSON-Zeilen; robust extrahieren:
|
|
||||||
try:
|
|
||||||
# Falls JSONL, letztes "response" zusammenfassen
|
|
||||||
texts = []
|
|
||||||
for line in out.splitlines():
|
|
||||||
line = line.strip()
|
|
||||||
if not line:
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
obj = json.loads(line)
|
|
||||||
if "response" in obj:
|
|
||||||
texts.append(obj["response"])
|
|
||||||
except Exception:
|
|
||||||
texts.append(line)
|
|
||||||
return "".join(texts).strip()
|
|
||||||
except Exception:
|
|
||||||
return out.strip()
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
@@ -1,6 +1,11 @@
|
|||||||
"""
|
"""
|
||||||
app/services/llm_service.py — LLM Client
|
FILE: app/services/llm_service.py
|
||||||
Version: 2.8.0 (Configurable Concurrency Limit)
|
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 httpx
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
app/services/semantic_analyzer.py — Edge Validation & Filtering
|
FILE: app/services/semantic_analyzer.py
|
||||||
Version: 2.0 (Update: Background Priority for Batch Jobs)
|
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 json
|
||||||
@@ -17,6 +21,34 @@ class SemanticAnalyzer:
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.llm = LLMService()
|
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]:
|
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.
|
Sendet einen Chunk und eine Liste potenzieller Kanten an das LLM.
|
||||||
@@ -55,14 +87,13 @@ class SemanticAnalyzer:
|
|||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 4. LLM Call mit Traffic Control (NEU: priority="background")
|
# 4. LLM Call mit Traffic Control
|
||||||
# Wir nutzen die "Slow Lane", damit der User im Chat nicht warten muss.
|
|
||||||
response_json = await self.llm.generate_raw_response(
|
response_json = await self.llm.generate_raw_response(
|
||||||
prompt=final_prompt,
|
prompt=final_prompt,
|
||||||
force_json=True,
|
force_json=True,
|
||||||
max_retries=5,
|
max_retries=5,
|
||||||
base_delay=5.0,
|
base_delay=5.0,
|
||||||
priority="background" # <--- WICHTIG: Drosselung aktivieren
|
priority="background"
|
||||||
)
|
)
|
||||||
|
|
||||||
# LOG: Raw Response Preview
|
# LOG: Raw Response Preview
|
||||||
@@ -87,30 +118,38 @@ class SemanticAnalyzer:
|
|||||||
valid_edges = []
|
valid_edges = []
|
||||||
|
|
||||||
# 6. Robuste Validierung (List vs Dict)
|
# 6. Robuste Validierung (List vs Dict)
|
||||||
|
# Wir sammeln erst alle Strings ein
|
||||||
|
raw_candidates = []
|
||||||
|
|
||||||
if isinstance(data, list):
|
if isinstance(data, list):
|
||||||
# Standardfall: ["kind:target", ...]
|
raw_candidates = data
|
||||||
valid_edges = [str(e) for e in data if isinstance(e, str) and ":" in e]
|
|
||||||
|
|
||||||
elif isinstance(data, dict):
|
elif isinstance(data, dict):
|
||||||
# Abweichende Formate behandeln
|
|
||||||
logger.info(f"ℹ️ [SemanticAnalyzer] LLM lieferte Dict statt Liste. Versuche Reparatur. Keys: {list(data.keys())}")
|
logger.info(f"ℹ️ [SemanticAnalyzer] LLM lieferte Dict statt Liste. Versuche Reparatur. Keys: {list(data.keys())}")
|
||||||
|
|
||||||
for key, val in data.items():
|
for key, val in data.items():
|
||||||
# Fall A: {"edges": ["kind:target"]}
|
# Fall A: {"edges": ["kind:target"]}
|
||||||
if key.lower() in ["edges", "results", "kanten", "matches"] and isinstance(val, list):
|
if key.lower() in ["edges", "results", "kanten", "matches"] and isinstance(val, list):
|
||||||
valid_edges.extend([str(e) for e in val if isinstance(e, str) and ":" in e])
|
raw_candidates.extend(val)
|
||||||
|
|
||||||
# Fall B: {"kind": "target"}
|
# Fall B: {"kind": "target"} (Beziehung als Key)
|
||||||
elif isinstance(val, str):
|
elif isinstance(val, str):
|
||||||
valid_edges.append(f"{key}:{val}")
|
raw_candidates.append(f"{key}:{val}")
|
||||||
|
|
||||||
# Fall C: {"kind": ["target1", "target2"]}
|
# Fall C: {"kind": ["target1", "target2"]}
|
||||||
elif isinstance(val, list):
|
elif isinstance(val, list):
|
||||||
for target in val:
|
for target in val:
|
||||||
if isinstance(target, str):
|
if isinstance(target, str):
|
||||||
valid_edges.append(f"{key}:{target}")
|
raw_candidates.append(f"{key}:{target}")
|
||||||
|
|
||||||
# Safety: Filtere nur Kanten, die halbwegs valide aussehen
|
# 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]
|
final_result = [e for e in valid_edges if ":" in e]
|
||||||
|
|
||||||
# LOG: Ergebnis
|
# LOG: Ergebnis
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# config/decision_engine.yaml
|
# config/decision_engine.yaml
|
||||||
# Steuerung der Decision Engine (Intent Recognition)
|
# Steuerung der Decision Engine (Intent Recognition & Graph Routing)
|
||||||
# Version: 2.4.0 (Clean Architecture: Generic Intents only)
|
# Version: 2.5.0 (WP-22: Semantic Graph Routing)
|
||||||
|
|
||||||
version: 1.4
|
version: 2.5
|
||||||
|
|
||||||
settings:
|
settings:
|
||||||
llm_fallback_enabled: true
|
llm_fallback_enabled: true
|
||||||
@@ -37,6 +37,12 @@ strategies:
|
|||||||
description: "Reine Wissensabfrage."
|
description: "Reine Wissensabfrage."
|
||||||
trigger_keywords: []
|
trigger_keywords: []
|
||||||
inject_types: []
|
inject_types: []
|
||||||
|
# WP-22: Definitionen & Hierarchien bevorzugen
|
||||||
|
edge_boosts:
|
||||||
|
part_of: 2.0
|
||||||
|
composed_of: 2.0
|
||||||
|
similar_to: 1.5
|
||||||
|
caused_by: 0.5
|
||||||
prompt_template: "rag_template"
|
prompt_template: "rag_template"
|
||||||
prepend_instruction: null
|
prepend_instruction: null
|
||||||
|
|
||||||
@@ -53,6 +59,12 @@ strategies:
|
|||||||
- "abwägung"
|
- "abwägung"
|
||||||
- "vergleich"
|
- "vergleich"
|
||||||
inject_types: ["value", "principle", "goal", "risk"]
|
inject_types: ["value", "principle", "goal", "risk"]
|
||||||
|
# WP-22: Risiken und Konsequenzen hervorheben
|
||||||
|
edge_boosts:
|
||||||
|
blocks: 2.5
|
||||||
|
solves: 2.0
|
||||||
|
depends_on: 1.5
|
||||||
|
risk_of: 2.5
|
||||||
prompt_template: "decision_template"
|
prompt_template: "decision_template"
|
||||||
prepend_instruction: |
|
prepend_instruction: |
|
||||||
!!! ENTSCHEIDUNGS-MODUS !!!
|
!!! ENTSCHEIDUNGS-MODUS !!!
|
||||||
@@ -71,6 +83,12 @@ strategies:
|
|||||||
- "überfordert"
|
- "überfordert"
|
||||||
- "müde"
|
- "müde"
|
||||||
inject_types: ["experience", "belief", "profile"]
|
inject_types: ["experience", "belief", "profile"]
|
||||||
|
# WP-22: Weiche Assoziationen & Erfahrungen stärken
|
||||||
|
edge_boosts:
|
||||||
|
based_on: 2.0
|
||||||
|
related_to: 2.0
|
||||||
|
experienced_in: 2.5
|
||||||
|
blocks: 0.1
|
||||||
prompt_template: "empathy_template"
|
prompt_template: "empathy_template"
|
||||||
prepend_instruction: null
|
prepend_instruction: null
|
||||||
|
|
||||||
@@ -88,6 +106,11 @@ strategies:
|
|||||||
- "yaml"
|
- "yaml"
|
||||||
- "bash"
|
- "bash"
|
||||||
inject_types: ["snippet", "reference", "source"]
|
inject_types: ["snippet", "reference", "source"]
|
||||||
|
# WP-22: Technische Abhängigkeiten
|
||||||
|
edge_boosts:
|
||||||
|
uses: 2.5
|
||||||
|
depends_on: 2.0
|
||||||
|
implemented_in: 3.0
|
||||||
prompt_template: "technical_template"
|
prompt_template: "technical_template"
|
||||||
prepend_instruction: null
|
prepend_instruction: null
|
||||||
|
|
||||||
@@ -108,9 +131,9 @@ strategies:
|
|||||||
- "idee speichern"
|
- "idee speichern"
|
||||||
- "draft"
|
- "draft"
|
||||||
inject_types: []
|
inject_types: []
|
||||||
|
edge_boosts: {}
|
||||||
prompt_template: "interview_template"
|
prompt_template: "interview_template"
|
||||||
prepend_instruction: null
|
prepend_instruction: null
|
||||||
|
|
||||||
# Schemas: Hier nur der Fallback.
|
# Schemas: Hier nur der Fallback.
|
||||||
# Spezifische Schemas (Project, Experience) kommen jetzt aus types.yaml!
|
# Spezifische Schemas (Project, Experience) kommen jetzt aus types.yaml!
|
||||||
schemas:
|
schemas:
|
||||||
|
|||||||
+72
-58
@@ -1,4 +1,4 @@
|
|||||||
version: 2.4.0 # Optimized for Async Intelligence & Hybrid Router
|
version: 2.6.0 # Final WP-15 Config: Smart Edges & Strict/Soft Chunking
|
||||||
|
|
||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
# 1. CHUNKING PROFILES
|
# 1. CHUNKING PROFILES
|
||||||
@@ -7,7 +7,6 @@ version: 2.4.0 # Optimized for Async Intelligence & Hybrid Router
|
|||||||
chunking_profiles:
|
chunking_profiles:
|
||||||
|
|
||||||
# A. SHORT & FAST
|
# A. SHORT & FAST
|
||||||
# Für Glossar, Tasks, Risiken. Kleine Schnipsel.
|
|
||||||
sliding_short:
|
sliding_short:
|
||||||
strategy: sliding_window
|
strategy: sliding_window
|
||||||
enable_smart_edge_allocation: false
|
enable_smart_edge_allocation: false
|
||||||
@@ -16,7 +15,6 @@ chunking_profiles:
|
|||||||
overlap: [30, 50]
|
overlap: [30, 50]
|
||||||
|
|
||||||
# B. STANDARD & FAST
|
# B. STANDARD & FAST
|
||||||
# Der "Traktor": Robust für Quellen, Journal, Daily Logs.
|
|
||||||
sliding_standard:
|
sliding_standard:
|
||||||
strategy: sliding_window
|
strategy: sliding_window
|
||||||
enable_smart_edge_allocation: false
|
enable_smart_edge_allocation: false
|
||||||
@@ -24,10 +22,8 @@ chunking_profiles:
|
|||||||
max: 650
|
max: 650
|
||||||
overlap: [50, 100]
|
overlap: [50, 100]
|
||||||
|
|
||||||
# C. SMART FLOW (Performance-Safe Mode)
|
# C. SMART FLOW (Text-Fluss)
|
||||||
# Für Konzepte, Projekte, Erfahrungen.
|
# Nutzt Sliding Window, aber mit LLM-Kanten-Analyse.
|
||||||
# HINWEIS: 'enable_smart_edge_allocation' ist vorerst FALSE, um Ollama
|
|
||||||
# bei der Generierung nicht zu überlasten. Später wieder aktivieren.
|
|
||||||
sliding_smart_edges:
|
sliding_smart_edges:
|
||||||
strategy: sliding_window
|
strategy: sliding_window
|
||||||
enable_smart_edge_allocation: true
|
enable_smart_edge_allocation: true
|
||||||
@@ -35,12 +31,38 @@ chunking_profiles:
|
|||||||
max: 600
|
max: 600
|
||||||
overlap: [50, 80]
|
overlap: [50, 80]
|
||||||
|
|
||||||
# D. SMART STRUCTURE
|
# D. SMART STRUCTURE (Soft Split)
|
||||||
# Für Profile, Werte, Prinzipien. Trennt hart an Überschriften (H2).
|
# Trennt bevorzugt an H2, fasst aber kleine Abschnitte zusammen ("Soft Mode").
|
||||||
structured_smart_edges:
|
structured_smart_edges:
|
||||||
strategy: by_heading
|
strategy: by_heading
|
||||||
enable_smart_edge_allocation: true
|
enable_smart_edge_allocation: true
|
||||||
split_level: 2
|
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
|
max: 600
|
||||||
target: 400
|
target: 400
|
||||||
overlap: [50, 80]
|
overlap: [50, 80]
|
||||||
@@ -59,24 +81,13 @@ defaults:
|
|||||||
|
|
||||||
types:
|
types:
|
||||||
|
|
||||||
# --- KERNTYPEN (Hoch priorisiert & Smart) ---
|
# --- KERNTYPEN ---
|
||||||
|
|
||||||
experience:
|
experience:
|
||||||
chunking_profile: sliding_smart_edges
|
chunking_profile: sliding_smart_edges
|
||||||
retriever_weight: 0.90
|
retriever_weight: 0.90
|
||||||
edge_defaults: ["derived_from", "references"]
|
edge_defaults: ["derived_from", "references"]
|
||||||
# Hybrid Classifier: Wenn diese Worte fallen, ist es eine Experience
|
detection_keywords: ["passiert", "erlebt", "gefühl", "situation", "reaktion"]
|
||||||
detection_keywords:
|
|
||||||
- "passiert"
|
|
||||||
- "erlebt"
|
|
||||||
- "gefühl"
|
|
||||||
- "situation"
|
|
||||||
- "stolz"
|
|
||||||
- "geärgert"
|
|
||||||
- "reaktion"
|
|
||||||
- "moment"
|
|
||||||
- "konflikt"
|
|
||||||
# Ghostwriter Schema: Sprechende Anweisungen für besseren Textfluss
|
|
||||||
schema:
|
schema:
|
||||||
- "Situation (Was ist passiert?)"
|
- "Situation (Was ist passiert?)"
|
||||||
- "Meine Reaktion (Was habe ich getan?)"
|
- "Meine Reaktion (Was habe ich getan?)"
|
||||||
@@ -87,48 +98,37 @@ types:
|
|||||||
chunking_profile: sliding_smart_edges
|
chunking_profile: sliding_smart_edges
|
||||||
retriever_weight: 0.97
|
retriever_weight: 0.97
|
||||||
edge_defaults: ["references", "depends_on"]
|
edge_defaults: ["references", "depends_on"]
|
||||||
detection_keywords:
|
detection_keywords: ["projekt", "vorhaben", "ziel ist", "planen", "starten"]
|
||||||
- "projekt"
|
|
||||||
- "vorhaben"
|
|
||||||
- "ziel ist"
|
|
||||||
- "meilenstein"
|
|
||||||
- "planen"
|
|
||||||
- "starten"
|
|
||||||
- "mission"
|
|
||||||
schema:
|
schema:
|
||||||
- "Mission & Zielsetzung"
|
- "Mission & Zielsetzung"
|
||||||
- "Aktueller Status & Blockaden"
|
- "Aktueller Status & Blockaden"
|
||||||
- "Nächste konkrete Schritte"
|
- "Nächste konkrete Schritte"
|
||||||
- "Stakeholder & Ressourcen"
|
|
||||||
|
|
||||||
decision:
|
decision:
|
||||||
chunking_profile: structured_smart_edges
|
# Strict, damit jede Entscheidung atomar bleibt
|
||||||
retriever_weight: 1.00 # MAX: Entscheidungen sind Gesetz
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
retriever_weight: 1.00
|
||||||
edge_defaults: ["caused_by", "references"]
|
edge_defaults: ["caused_by", "references"]
|
||||||
detection_keywords:
|
detection_keywords: ["entschieden", "wahl", "optionen", "alternativen", "adr"]
|
||||||
- "entschieden"
|
|
||||||
- "wahl"
|
|
||||||
- "optionen"
|
|
||||||
- "alternativen"
|
|
||||||
- "beschluss"
|
|
||||||
- "adr"
|
|
||||||
schema:
|
schema:
|
||||||
- "Kontext & Problemstellung"
|
- "Kontext & Problemstellung"
|
||||||
- "Betrachtete Optionen (Alternativen)"
|
- "Betrachtete Optionen"
|
||||||
- "Die Entscheidung"
|
- "Die Entscheidung"
|
||||||
- "Begründung (Warum diese Wahl?)"
|
- "Begründung"
|
||||||
|
|
||||||
# --- PERSÖNLICHKEIT & IDENTITÄT ---
|
# --- PERSÖNLICHKEIT & IDENTITÄT ---
|
||||||
|
|
||||||
value:
|
value:
|
||||||
chunking_profile: structured_smart_edges
|
# Strict, damit Werte nicht verschwimmen
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
retriever_weight: 1.00
|
retriever_weight: 1.00
|
||||||
edge_defaults: ["related_to"]
|
edge_defaults: ["related_to"]
|
||||||
detection_keywords: ["wert", "wichtig ist", "moral", "ethik"]
|
detection_keywords: ["wert", "wichtig ist", "moral", "ethik"]
|
||||||
schema: ["Definition", "Warum mir das wichtig ist", "Leitsätze für den Alltag"]
|
schema: ["Definition", "Warum mir das wichtig ist", "Leitsätze"]
|
||||||
|
|
||||||
principle:
|
principle:
|
||||||
chunking_profile: structured_smart_edges
|
# L3 Strict für P3/P3a und Tier2/MP1 Logik
|
||||||
|
chunking_profile: structured_smart_edges_strict_L3
|
||||||
retriever_weight: 0.95
|
retriever_weight: 0.95
|
||||||
edge_defaults: ["derived_from", "references"]
|
edge_defaults: ["derived_from", "references"]
|
||||||
detection_keywords: ["prinzip", "regel", "grundsatz", "leitlinie"]
|
detection_keywords: ["prinzip", "regel", "grundsatz", "leitlinie"]
|
||||||
@@ -138,11 +138,11 @@ types:
|
|||||||
chunking_profile: sliding_short
|
chunking_profile: sliding_short
|
||||||
retriever_weight: 0.90
|
retriever_weight: 0.90
|
||||||
edge_defaults: ["related_to"]
|
edge_defaults: ["related_to"]
|
||||||
detection_keywords: ["glaube", "überzeugung", "denke dass", "meinung"]
|
|
||||||
schema: ["Der Glaubenssatz", "Ursprung & Reflexion"]
|
schema: ["Der Glaubenssatz", "Ursprung & Reflexion"]
|
||||||
|
|
||||||
profile:
|
profile:
|
||||||
chunking_profile: structured_smart_edges
|
# Strict: Jede Rolle (H2) muss ein eigener Chunk sein
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
retriever_weight: 0.70
|
retriever_weight: 0.70
|
||||||
edge_defaults: ["references", "related_to"]
|
edge_defaults: ["references", "related_to"]
|
||||||
schema: ["Rolle / Identität", "Fakten & Daten", "Historie"]
|
schema: ["Rolle / Identität", "Fakten & Daten", "Historie"]
|
||||||
@@ -159,8 +159,8 @@ types:
|
|||||||
chunking_profile: sliding_short
|
chunking_profile: sliding_short
|
||||||
retriever_weight: 0.85
|
retriever_weight: 0.85
|
||||||
edge_defaults: ["related_to", "blocks"]
|
edge_defaults: ["related_to", "blocks"]
|
||||||
detection_keywords: ["risiko", "gefahr", "bedrohung", "problem", "angst"]
|
detection_keywords: ["risiko", "gefahr", "bedrohung"]
|
||||||
schema: ["Beschreibung des Risikos", "Mögliche Auswirkungen", "Gegenmaßnahmen"]
|
schema: ["Beschreibung des Risikos", "Auswirkungen", "Gegenmaßnahmen"]
|
||||||
|
|
||||||
# --- BASIS & WISSEN ---
|
# --- BASIS & WISSEN ---
|
||||||
|
|
||||||
@@ -168,10 +168,7 @@ types:
|
|||||||
chunking_profile: sliding_smart_edges
|
chunking_profile: sliding_smart_edges
|
||||||
retriever_weight: 0.60
|
retriever_weight: 0.60
|
||||||
edge_defaults: ["references", "related_to"]
|
edge_defaults: ["references", "related_to"]
|
||||||
schema:
|
schema: ["Definition", "Kontext", "Verwandte Konzepte"]
|
||||||
- "Definition"
|
|
||||||
- "Kontext & Hintergrund"
|
|
||||||
- "Verwandte Konzepte"
|
|
||||||
|
|
||||||
task:
|
task:
|
||||||
chunking_profile: sliding_short
|
chunking_profile: sliding_short
|
||||||
@@ -183,19 +180,36 @@ types:
|
|||||||
chunking_profile: sliding_standard
|
chunking_profile: sliding_standard
|
||||||
retriever_weight: 0.80
|
retriever_weight: 0.80
|
||||||
edge_defaults: ["references", "related_to"]
|
edge_defaults: ["references", "related_to"]
|
||||||
schema: ["Log-Eintrag", "Gedanken & Erkenntnisse"]
|
schema: ["Log-Eintrag", "Gedanken"]
|
||||||
|
|
||||||
source:
|
source:
|
||||||
chunking_profile: sliding_standard
|
chunking_profile: sliding_standard
|
||||||
retriever_weight: 0.50
|
retriever_weight: 0.50
|
||||||
edge_defaults: []
|
edge_defaults: []
|
||||||
schema:
|
schema: ["Metadaten", "Zusammenfassung", "Zitate"]
|
||||||
- "Metadaten (Autor, URL, Datum)"
|
|
||||||
- "Kernaussage / Zusammenfassung"
|
|
||||||
- "Zitate & Notizen"
|
|
||||||
|
|
||||||
glossary:
|
glossary:
|
||||||
chunking_profile: sliding_short
|
chunking_profile: sliding_short
|
||||||
retriever_weight: 0.40
|
retriever_weight: 0.40
|
||||||
edge_defaults: ["related_to"]
|
edge_defaults: ["related_to"]
|
||||||
schema: ["Begriff", "Definition"]
|
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"]
|
||||||
@@ -58,6 +58,7 @@ Das Repository ist in **logische Domänen** unterteilt.
|
|||||||
| Datei | Inhalt & Zweck |
|
| Datei | Inhalt & Zweck |
|
||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| `05_developer_guide.md` | **Workflow.** Hardware-Setup (Win/Pi/Beelink), Git-Flow, Test-Befehle, Modul-Interna. |
|
| `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
|
### 📂 06_Roadmap & 99_Archive
|
||||||
*Zielgruppe: Projektleitung*
|
*Zielgruppe: Projektleitung*
|
||||||
|
|||||||
@@ -2,41 +2,40 @@
|
|||||||
doc_type: glossary
|
doc_type: glossary
|
||||||
audience: all
|
audience: all
|
||||||
status: active
|
status: active
|
||||||
version: 2.6
|
version: 2.7.0
|
||||||
context: "Definitionen zentraler Begriffe und Entitäten im Mindnet-System."
|
context: "Zentrales Glossar für Mindnet v2.7. Definitionen von Entitäten, WP-22 Scoring-Konzepten und der Edge Registry."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Mindnet Glossar
|
# Mindnet Glossar
|
||||||
|
|
||||||
**Quellen:** `appendix.md`, `Overview.md`
|
**Quellen:** `01_edge_vocabulary.md`, `retriever_scoring.py`, `edge_registry.py`
|
||||||
|
|
||||||
## Kern-Entitäten
|
## Kern-Entitäten
|
||||||
|
|
||||||
* **Note:** Repräsentiert eine Markdown-Datei. Die fachliche Haupteinheit.
|
* **Note:** Repräsentiert eine Markdown-Datei. Die fachliche Haupteinheit. Verfügt über einen **Status** (stable, draft, system), der das Scoring beeinflusst.
|
||||||
* **Chunk:** Ein Textabschnitt einer Note (meist 512 Tokens). Die technische Sucheinheit (Vektor).
|
* **Chunk:** Ein Textabschnitt einer Note. Die technische Sucheinheit (Vektor).
|
||||||
* **Edge:** Eine gerichtete Verbindung zwischen zwei Knoten (Chunks oder Notes).
|
* **Edge:** Eine gerichtete Verbindung zwischen zwei Knoten. Wird in WP-22 durch die Registry validiert.
|
||||||
* **Vault:** Der lokale Ordner mit den Markdown-Dateien (Source of Truth).
|
* **Vault:** Der lokale Ordner mit den Markdown-Dateien (Source of Truth).
|
||||||
* **Frontmatter:** Der YAML-Header am Anfang einer Notiz (enthält `id`, `type`, `title`).
|
* **Frontmatter:** Der YAML-Header am Anfang einer Notiz (enthält `id`, `type`, `title`, `status`).
|
||||||
|
|
||||||
## Komponenten
|
## Komponenten
|
||||||
|
|
||||||
* **Importer:** Das Python-Skript (`ingestion.py`), das Markdown liest und in Qdrant schreibt.
|
* **Edge Registry:** Der zentrale Dienst (SSOT), der Kanten-Typen validiert und Aliase in kanonische Typen auflöst. Nutzt `01_edge_vocabulary.md` als Basis.
|
||||||
* **Retriever:** Die Komponente, die sucht. Nutzt hybrides Scoring (Semantik + Graph).
|
* **Retriever:** Besteht in v2.7 aus der Orchestrierung (`retriever.py`) und der mathematischen Scoring-Engine (`retriever_scoring.py`).
|
||||||
* **Decision Engine:** Teil des Routers, der entscheidet, wie auf eine Anfrage reagiert wird (z.B. Strategie wählen).
|
* **Decision Engine:** Teil des Routers, der Intents erkennt und entsprechende **Boost-Faktoren** für das Retrieval injiziert.
|
||||||
* **Hybrid Router v5:** Die Logik, die erkennt, ob der User eine Frage stellt (`RAG`) oder einen Befehl gibt (`INTERVIEW`).
|
* **Traffic Control:** Verwaltet Prioritäten und drosselt Hintergrund-Tasks (z.B. Smart Edges) mittels Semaphoren.
|
||||||
* **Draft Editor:** Die Web-UI-Komponente, in der generierte Notizen bearbeitet werden.
|
* **Unknown Edges Log:** Die Datei `unknown_edges.jsonl`, in der das System Kanten-Typen protokolliert, die nicht im Dictionary gefunden wurden.
|
||||||
* **Traffic Control:** Ein Mechanismus im `LLMService`, der Chat-Anfragen priorisiert und Hintergrund-Jobs (wie Import) drosselt.
|
|
||||||
|
|
||||||
## Konzepte & Features
|
## Konzepte & Features
|
||||||
|
|
||||||
* **Active Intelligence:** Feature im Web-Editor, das während des Schreibens automatisch Links vorschlägt.
|
* **Canonical Type:** Der standardisierte System-Name einer Kante (z.B. `based_on`), der in der Datenbank gespeichert wird.
|
||||||
* **Smart Edge Allocation (WP15):** Ein KI-Verfahren, das prüft, ob ein Link in einer Notiz für einen spezifischen Textabschnitt relevant ist.
|
* **Alias (Edge):** Ein nutzerfreundliches Synonym (z.B. `basiert_auf`), das während der Ingestion automatisch zum Canonical Type aufgelöst wird.
|
||||||
* **Healing Parser:** UI-Funktion, die fehlerhaften Output des LLMs (z.B. defektes YAML) automatisch repariert.
|
* **Lifecycle Scoring (WP-22):** Ein Mechanismus, der die Relevanz einer Notiz basierend auf ihrem Status gewichtet (z.B. Bonus für `stable`, Malus für `draft`).
|
||||||
* **Explanation Layer:** Die Schicht, die dem Nutzer erklärt, *warum* ein Suchergebnis gefunden wurde (z.B. "Weil Projekt X davon abhängt").
|
* **Intent Boosting:** Dynamische Erhöhung der Kanten-Gewichte basierend auf der Nutzerfrage (z.B. Fokus auf `caused_by` bei "Warum"-Fragen).
|
||||||
* **Provenance:** Die Herkunft einer Kante.
|
* **Provenance Weighting:** Gewichtung einer Kante nach ihrer Herkunft:
|
||||||
* `explicit`: Vom Mensch geschrieben.
|
* `explicit`: Vom Mensch gesetzt (Prio 1).
|
||||||
* `smart`: Vom LLM validiert.
|
* `smart`: Von der KI validiert (Prio 2).
|
||||||
* `rule`: Durch Config-Regel erzeugt.
|
* `rule`: Durch System-Regeln/Matrix erzeugt (Prio 3).
|
||||||
* **Matrix Logic:** Regelwerk, das den Typ einer Kante basierend auf Quell- und Ziel-Typ bestimmt (z.B. Erfahrung -> Wert = `based_on`).
|
* **Smart Edge Allocation:** KI-Verfahren zur Relevanzprüfung von Links für spezifische Textabschnitte.
|
||||||
* **Idempotenz:** Die Eigenschaft des Importers, bei mehrfacher Ausführung dasselbe Ergebnis zu liefern ohne Duplikate.
|
* **Strict Heading Split:** Chunking-Strategie mit harten Grenzen an Überschriften und integriertem "Safety Net" gegen zu große Chunks.
|
||||||
* **Resurrection Pattern:** UI-Technik, um User-Eingaben beim Tab-Wechsel zu erhalten.
|
* **Matrix Logic:** Bestimmung des Kanten-Typs basierend auf Quell- und Ziel-Entität (z.B. Erfahrung -> Wert = `based_on`).
|
||||||
@@ -3,13 +3,13 @@ doc_type: user_manual
|
|||||||
audience: user, author
|
audience: user, author
|
||||||
scope: vault, markdown, schema
|
scope: vault, markdown, schema
|
||||||
status: active
|
status: active
|
||||||
version: 2.6
|
version: 2.7.0
|
||||||
context: "Regelwerk für das Erstellen von Notizen im Vault. Die 'Source of Truth' für Autoren."
|
context: "Regelwerk für das Erstellen von Notizen im Vault. Die 'Source of Truth' für Autoren."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Knowledge Design Manual
|
# Knowledge Design Manual
|
||||||
|
|
||||||
**Quellen:** `knowledge_design.md`, `TYPE_REGISTRY_MANUAL.md`
|
**Quellen:** `knowledge_design.md`, `types.yaml`
|
||||||
|
|
||||||
## ⚡ Die 5 Goldenen Regeln (TL;DR)
|
## ⚡ Die 5 Goldenen Regeln (TL;DR)
|
||||||
|
|
||||||
@@ -46,29 +46,63 @@ tags: [ki, entwicklung] # Taxonomie
|
|||||||
---
|
---
|
||||||
```
|
```
|
||||||
|
|
||||||
**Optionale Felder:**
|
### 2.1 Advanced Overrides: Die KI-Steuerung übernehmen
|
||||||
* `aliases`: [Alpha Projekt] – Wichtig für "Active Intelligence" (Exact Match).
|
|
||||||
* `visibility`: internal (default) / public.
|
|
||||||
|
|
||||||
> **Wichtig:** Felder wie `retriever_weight` oder `chunk_profile` werden zentral über `types.yaml` gesteuert und müssen nicht mehr manuell gesetzt werden (Virtual Schema Layer).
|
In 95% der Fälle setzt der `type` (z.B. "concept") automatisch die richtigen Einstellungen. In Spezialfällen kannst du diese manuell im Frontmatter überschreiben, um das Verhalten der KI zu erzwingen.
|
||||||
|
|
||||||
|
#### A. `retriever_weight`: Die Sichtbarkeit steuern
|
||||||
|
Dieser Faktor (Default: 1.0) ist ein Multiplikator für das Ranking in der Vektorsuche. Er entscheidet, welche Notiz "gewinnt", wenn zwei Texte inhaltlich ähnlich sind.
|
||||||
|
|
||||||
|
* **Standard (1.0):** Normale Wichtigkeit.
|
||||||
|
* **Boost (1.2 - 2.0):** "Das hier ist die Wahrheit."
|
||||||
|
* *Einsatz:* Finale Entscheidungen, Kernprinzipien, die "Single Source of Truth".
|
||||||
|
* *Effekt:* Verdrängt weniger wichtige Notizen (z.B. Meeting-Protokolle) aus dem Kontext-Fenster der KI.
|
||||||
|
* **Deboost (0.5 - 0.8):** "Nur Kontext, keine Fakten."
|
||||||
|
* *Einsatz:* Glossare, externe Quellen (`source`), reine Datensammlungen.
|
||||||
|
* *Effekt:* Die Notiz wird nur gefunden, wenn man sehr spezifisch danach sucht.
|
||||||
|
|
||||||
|
#### B. `chunking_profile`: Die Zerstückelung steuern
|
||||||
|
Das Profil bestimmt, wie der Text für die Datenbank zerschnitten wird. Falsches Chunking zerreißt den Kontext. Wähle das Profil basierend auf der **Struktur** deines Textes.
|
||||||
|
|
||||||
|
| Profil-Name | Strategie | Einsatzzweck & Wirkung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **`sliding_standard`** | Sliding Window | **Der Allrounder.** Für Fließtexte (Tagebuch, Artikel). Der Text wird in überlappende Fenster geschnitten. Gut, wenn der Inhalt von oben nach unten fließt. |
|
||||||
|
| **`sliding_short`** | Sliding Window (Klein) | **Für Dichte.** Für Texte mit sehr hoher Informationsdichte (Glossare, Task-Listen), wo jeder Satz wichtig ist. Erzeugt viele kleine Chunks. |
|
||||||
|
| **`sliding_smart_edges`** | Sliding + AI | **Der Intelligente.** Wie Standard, aber das LLM analysiert jeden Chunk zusätzlich auf implizite Querverweise. Standard für `concept` und `project`. |
|
||||||
|
| **`structured_smart_edges`** | Heading Split (Soft) | **Für Strukturierte Texte.** Trennt an Überschriften (H2). *Besonderheit:* Wenn ein Abschnitt sehr kurz ist, wird er mit dem nächsten verschmolzen ("Soft Mode"), um den Kontext zu wahren. |
|
||||||
|
| **`structured_smart_edges_strict`** | Heading Split (Hard) | **Für Listen & Kataloge.** Trennt *zwingend* an jeder H2-Überschrift. Verhindert das Verschmelzen. <br>**Wichtig für:** `decision` (Option A darf nicht mit Option B verschmelzen), `value`, `profile`. |
|
||||||
|
|
||||||
|
**Beispiel für ein Override:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
title: Sammlung meiner Passwörter-Regeln
|
||||||
|
type: list
|
||||||
|
# Wir erzwingen eine strikte Trennung, damit Regel 1 nicht mit Regel 2 vermischt wird.
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
# Extrem wichtig, soll immer beachtet werden.
|
||||||
|
retriever_weight: 1.5
|
||||||
|
---
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Typ-Referenz & Verhalten
|
## 3. Typ-Referenz & Verhalten
|
||||||
|
|
||||||
Wähle den Typ, der die **Rolle** der Notiz am besten beschreibt. Der Typ steuert Chunking, Gewichtung und Kanten-Logik.
|
Wähle den Typ, der die **Rolle** der Notiz am besten beschreibt. Der Typ setzt die Defaults für die oben genannten Parameter.
|
||||||
|
|
||||||
| Typ | Beschreibung & Einsatzzweck | Rolle im Chat (Intent) | Matrix-Logik |
|
| Typ | Default Profil | Default Gewicht | Einsatzzweck |
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| **`concept`** | Fachbegriffe, Theorien. Zeitloses Wissen. | **FACT** | Ziel für `uses` |
|
| **`concept`** | `sliding_smart_edges` | 0.60 | Fachbegriffe, Theorien. Zeitloses Wissen. |
|
||||||
| **`project`** | Ein Vorhaben mit Ziel, Dauer und Aufgaben. | **FACT / DECISION** | Quelle für `depends_on` |
|
| **`project`** | `sliding_smart_edges` | 0.97 | Aktive Vorhaben mit Ziel und Status. |
|
||||||
| **`experience`** | Persönliche Erfahrung, Lektion oder Erkenntnis. | **EMPATHY** | Quelle für `based_on` |
|
| **`experience`**| `sliding_smart_edges` | 0.90 | Persönliche Lektionen (für Empathie). |
|
||||||
| **`decision`** | Eine bewusst getroffene Entscheidung (ADR). | **DECISION** | Quelle für `caused_by` |
|
| **`decision`** | **`structured_..._strict`** | **1.00** | Entscheidungen. Muss atomar getrennt sein (Optionen vs. Ergebnis). |
|
||||||
| **`value`** | Ein persönlicher Wert oder ein Prinzip. | **DECISION** | Ziel für `based_on` |
|
| **`value`** | **`structured_..._strict`** | **1.00** | Werte/Prinzipien. |
|
||||||
| **`principle`** | Handlungsleitlinie. | **DECISION** | Quelle für `derived_from` |
|
| **`principle`**| `structured_..._strict_L3`| 0.95 | Handlungsleitlinien (Trennt bis Ebene H3). |
|
||||||
| **`goal`** | Ein strategisches Ziel. | **DECISION** | Ziel für `related_to` |
|
| **`goal`** | `sliding_smart_edges` | 0.95 | Strategische Ziele. |
|
||||||
| **`risk`** | Ein identifiziertes Risiko. | **DECISION** | Quelle für `blocks` |
|
| **`risk`** | `sliding_short` | 0.85 | Risiken (kurz und prägnant). |
|
||||||
| **`journal`** | Zeitbezogener Log-Eintrag. | **FACT** | - |
|
| **`journal`** | `sliding_standard` | 0.80 | Zeitbezogene Logs. |
|
||||||
|
| **`source`** | `sliding_standard` | 0.50 | Externe Quellen (niedrig gewichtet). |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -136,11 +170,9 @@ Ich habe gelernt: Das ist oft das Zeichen kurz vor dem Durchbruch.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6. Best Practices & Beispiele (Klassik)
|
## 6. Best Practices & Beispiele
|
||||||
|
|
||||||
Hier sind vollständige Vorlagen für häufige Typen.
|
### 6.1 Beispiel: Projekt-Notiz (Standard)
|
||||||
|
|
||||||
### 6.1 Beispiel: Projekt-Notiz
|
|
||||||
Projekte profitieren von `depends_on`, um Abhängigkeiten zu klären.
|
Projekte profitieren von `depends_on`, um Abhängigkeiten zu klären.
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
@@ -159,11 +191,11 @@ Wir bauen ein persönliches Wissensnetz.
|
|||||||
Wir nutzen [[rel:depends_on Qdrant]] für die Vektorsuche und [[rel:depends_on FastAPI]] für das Backend.
|
Wir nutzen [[rel:depends_on Qdrant]] für die Vektorsuche und [[rel:depends_on FastAPI]] für das Backend.
|
||||||
|
|
||||||
## Architektur
|
## Architektur
|
||||||
Das Konzept basiert auf [[RAG Architecture]]. (Automatisch 'depends_on' durch Typ-Default, falls konfiguriert).
|
Das Konzept basiert auf [[RAG Architecture]].
|
||||||
```
|
```
|
||||||
|
|
||||||
### 6.2 Beispiel: Entscheidung (Decision Record)
|
### 6.2 Beispiel: Advanced Tuning (Manuelles Override)
|
||||||
Entscheidungen sind hoch gewichtet (`retriever_weight: 1.0`).
|
Hier zwingen wir das System, eine Entscheidung extrem kleinteilig (`strict`) zu zerlegen und in der Suche maximal zu priorisieren.
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
---
|
---
|
||||||
@@ -172,6 +204,11 @@ title: ADR: Wahl von Qdrant
|
|||||||
type: decision
|
type: decision
|
||||||
status: final
|
status: final
|
||||||
tags: [architektur, db]
|
tags: [architektur, db]
|
||||||
|
# OVERRIDES: Wir wollen diese Notiz extrem wichtig machen und strikt trennen.
|
||||||
|
# Da "strict" genutzt wird, landet "Alternativen" in einem eigenen Chunk
|
||||||
|
# und vermischt sich nicht mit der Entscheidung selbst.
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
retriever_weight: 1.5
|
||||||
---
|
---
|
||||||
|
|
||||||
# Entscheidung: Qdrant
|
# Entscheidung: Qdrant
|
||||||
@@ -180,13 +217,11 @@ Wir haben uns für Qdrant entschieden.
|
|||||||
|
|
||||||
## Alternativen
|
## Alternativen
|
||||||
Wir haben auch [[rel:similar_to Pinecone]] und [[rel:similar_to Weaviate]] betrachtet.
|
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
|
## 7. Virtual Schema Layer
|
||||||
|
|
||||||
Wir nutzen das Prinzip des **Virtual Schema Layers**. Wir kodieren keine Logik (wie `chunk_size`) in die Notizen. Das wird zentral in der `types.yaml` verwaltet. Das bedeutet für dich: Du kannst dich rein auf den Inhalt konzentrieren. Wenn wir die Chunking-Strategie ändern, müssen wir nicht 1000 Markdown-Dateien anfassen.
|
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.
|
||||||
@@ -3,13 +3,13 @@ doc_type: concept
|
|||||||
audience: architect, product_owner
|
audience: architect, product_owner
|
||||||
scope: graph, logic, provenance
|
scope: graph, logic, provenance
|
||||||
status: active
|
status: active
|
||||||
version: 2.6
|
version: 2.7.0
|
||||||
context: "Fachliche Beschreibung des Wissensgraphen: Knoten, Kanten, Provenance und Matrix-Logik."
|
context: "Fachliche Beschreibung des Wissensgraphen: Knoten, Kanten, Provenance, Matrix-Logik und WP-22 Scoring-Prinzipien."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Konzept: Die Graph-Logik
|
# Konzept: Die Graph-Logik
|
||||||
|
|
||||||
**Quellen:** `mindnet_functional_architecture.md`, `chunking_strategy.md`
|
**Quellen:** `mindnet_functional_architecture.md`, `chunking_strategy.md`, `01_edge_vocabulary.md`, `retriever_scoring.py`, `03_tech_retrieval_scoring.md`
|
||||||
|
|
||||||
Mindnet ist keine reine Dokumentablage, sondern ein **semantischer Graph**. Dieses Dokument beschreibt, wie aus statischen Textdateien ein vernetztes Wissensobjekt wird.
|
Mindnet ist keine reine Dokumentablage, sondern ein **semantischer Graph**. Dieses Dokument beschreibt, wie aus statischen Textdateien ein vernetztes Wissensobjekt wird.
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@ Der Graph besteht aus zwei Ebenen von Knoten.
|
|||||||
|
|
||||||
### 1.1 Die Note (Das Fachobjekt)
|
### 1.1 Die Note (Das Fachobjekt)
|
||||||
Eine Note repräsentiert ein atomares Konzept (z.B. "Projekt Alpha").
|
Eine Note repräsentiert ein atomares Konzept (z.B. "Projekt Alpha").
|
||||||
* **Eigenschaften:** Titel, Typ, Tags, Erstellungsdatum.
|
* **Eigenschaften:** Titel, Typ, Tags, Erstellungsdatum sowie der **Status** (Lifecycle).
|
||||||
* **Rolle:** Sie ist der Container für Metadaten und steuert via `type`, wie der Inhalt verarbeitet wird (siehe `types.yaml`).
|
* **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.
|
* **Identität:** Definiert durch eine deterministische UUIDv5.
|
||||||
|
|
||||||
@@ -29,71 +29,97 @@ Da LLMs (Large Language Models) nicht unendlich viel Text auf einmal lesen könn
|
|||||||
* **Rolle:** Dies sind die eigentlichen Treffer bei einer Suche.
|
* **Rolle:** Dies sind die eigentlichen Treffer bei einer Suche.
|
||||||
* **Hierarchie:** Jeder Chunk gehört streng zu einer Note (`belongs_to`).
|
* **Hierarchie:** Jeder Chunk gehört streng zu einer Note (`belongs_to`).
|
||||||
|
|
||||||
|
### 1.3 Content Lifecycle & Status (WP-22)
|
||||||
|
Seit v2.7 beeinflusst der `status` einer Note direkt deren Gewichtung im Retrieval (Lifecycle Scoring).
|
||||||
|
* **Stable:** Notizen mit `status: stable` erhalten einen positiven Modifier (Standard: 1.0), da sie geprüftes Wissen repräsentieren.
|
||||||
|
* **Draft:** Notizen mit `status: draft` werden durch einen Malus (Standard: 0.5 - 0.8) herabgestuft, um "Rauschen" durch unfertige Gedanken zu reduzieren.
|
||||||
|
* **System/Template:** Diese Status-Typen führen zu einem vollständigen Ausschluss aus dem Index.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Die Kanten (Edges)
|
## 2. Die Kanten (Edges)
|
||||||
|
|
||||||
Kanten machen aus isolierten Informationen Wissen. Mindnet nutzt gerichtete Kanten mit semantischer Bedeutung.
|
Kanten machen aus isolierten Informationen Wissen. Mindnet nutzt gerichtete Kanten mit semantischer Bedeutung, die durch die **Edge Registry** validiert werden.
|
||||||
|
|
||||||
### 2.1 Semantische Typen
|
### 2.1 Kanonische Typen & Aliase
|
||||||
|
Um eine konsistente mathematische Gewichtung zu garantieren, werden alle Kanten auf **kanonische Typen** normalisiert.
|
||||||
|
|
||||||
| Kanten-Typ | Frage, die er beantwortet | Beispiel |
|
| Kanonischer Typ | Aliase (Beispiele) | Bedeutung |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| `references` | Worüber wird gesprochen? | Text erwähnt "Python". |
|
| `caused_by` | `ausgelöst_durch`, `wegen` | Kausalität: A löst B aus. |
|
||||||
| `depends_on` | Was ist Voraussetzung? | Projekt braucht "Budget". |
|
| `derived_from` | `abgeleitet_von`, `quelle` | Herkunft: A stammt von B. |
|
||||||
| `caused_by` | Warum ist das passiert? | Bug durch "Commit X". |
|
| `based_on` | `basiert_auf`, `fundament` | Fundament: B baut auf A auf. |
|
||||||
| `blocks` | Was steht im Weg? | Risiko blockiert "Release". |
|
| `solves` | `löst`, `fix_für` | Lösung: A ist Lösung für Problem B. |
|
||||||
| `based_on` | Worauf fußt das? | Erfahrung basiert auf "Wert Y". |
|
| `part_of` | `teil_von`, `cluster` | Hierarchie: Kind -> Eltern. |
|
||||||
| `derived_from` | Woher kommt das? | Prinzip stammt aus "Buch Z". |
|
| `depends_on` | `braucht`, `requires` | Abhängigkeit: A braucht B. |
|
||||||
| `related_to` | Was ist ähnlich? | "Hund" ist verwandt mit "Wolf". |
|
| `blocks` | `blockiert`, `risiko_für` | Blocker: A verhindert B. |
|
||||||
| `solves` | Was ist die Lösung? | "Qdrant" löst "Vektorsuche". |
|
| `related_to` | `siehe_auch`, `kontext` | Lose Assoziation. |
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### 2.2 Provenance (Herkunft & Vertrauen)
|
### 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.
|
Nicht alle Kanten sind gleich viel wert. Mindnet unterscheidet drei Qualitätsstufen (**Provenance**), um bei der Berechnung des Edge-Bonus Prioritäten zu setzen.
|
||||||
|
|
||||||
**1. Explicit (Der Mensch hat es gesagt)**
|
**1. Explicit (Der Mensch hat es gesagt)**
|
||||||
* *Quelle:* Inline-Links (`[[rel:...]]`) oder Wikilinks im Text.
|
* *Quelle:* Inline-Links (`[[rel:...]]`) oder Wikilinks im Text.
|
||||||
* *Vertrauen:* **Hoch (1.0)**.
|
* *Vertrauen:* **Hoch (1.0)**.
|
||||||
* *Bedeutung:* Dies ist hartes Faktenwissen. "Ich habe diesen Link bewusst gesetzt."
|
* *Bedeutung:* Hartes Faktenwissen. Die explizite menschliche Intention wird im Scoring am stärksten gewichtet.
|
||||||
|
|
||||||
**2. Smart (Die KI hat es bestätigt)**
|
**2. Smart (Die KI hat es bestätigt)**
|
||||||
* *Quelle:* Smart Edge Allocation (WP15).
|
* *Quelle:* Smart Edge Allocation (WP15).
|
||||||
* *Vertrauen:* **Mittel (0.9)**.
|
* *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).
|
* *Bedeutung:* Ein LLM hat die Relevanz des Links im Kontext geprüft. Dies filtert irrelevante Links (z.B. aus Navigationsleisten) heraus.
|
||||||
|
|
||||||
**3. Rule (Die Regel hat es vermutet)**
|
**3. Rule (Die Regel hat es vermutet)**
|
||||||
* *Quelle:* `types.yaml` Defaults.
|
* *Quelle:* `types.yaml` Defaults oder Matrix-Logik.
|
||||||
* *Vertrauen:* **Niedrig (0.7)**.
|
* *Vertrauen:* **Niedrig (0.7)**.
|
||||||
* *Bedeutung:* Eine Heuristik. "Weil es ein Projekt ist, nehmen wir an, dass es von allen erwähnten Technologien abhängt."
|
* *Bedeutung:* Systemseitige Heuristik. Diese Verbindungen dienen der Entdeckung neuer Pfade, haben aber weniger Gewicht als explizite Links.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Matrix-Logik (Kontext-Sensitivität)
|
## 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").
|
Die Matrix-Logik bestimmt Kanten-Typen dynamisch anhand der Quell- und Ziel-Typen der verknüpften Notizen.
|
||||||
|
|
||||||
**Logik-Beispiele:**
|
**Logik-Beispiele:**
|
||||||
|
* **Quelle `experience` → Ziel `value`**: Wird zu `based_on` (Erfahrungen fußen auf Werten).
|
||||||
* **Quelle `experience` → Ziel `value`**
|
* **Quelle `principle` → Ziel `source`**: Wird zu `derived_from` (Prinzipien stammen aus Quellen).
|
||||||
* *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
|
## 4. Semantisch bezogene Booster & Scoring-Logik
|
||||||
|
|
||||||
|
Das Scoring in Mindnet v2.7 folgt einer hybriden Logik, bei der semantische Ähnlichkeit durch kontextuelle Faktoren modifiziert wird.
|
||||||
|
|
||||||
|
### 4.1 Semantische Modifikatoren (Type & Status)
|
||||||
|
Bevor der Graph-Bonus berechnet wird, durchläuft die semantische Ähnlichkeit (Cosine Similarity) zwei Filter:
|
||||||
|
1. **Type-Weight ($W_{type}$):** Bestimmt die "Wichtigkeit" einer Notizklasse. Ein Wert von 1.0 (z. B. für `decision`) lässt die volle semantische Stärke durch. Ein Wert von 0.4 (z. B. für `glossary`) dämpft den Treffer massiv ab, es sei denn, die Frage passt exakt auf den Text.
|
||||||
|
2. **Status-Modifier:** Agiert als Qualitätsfilter. `draft` markierte Inhalte werden herabgestuft, damit `stable` Inhalte bei gleicher semantischer Passung immer oben stehen.
|
||||||
|
|
||||||
|
### 4.2 Graph-Boosting (Additive Boni)
|
||||||
|
Der Graph-Bonus wird auf den modifizierten semantischen Score addiert. Dies ermöglicht es Inhalten, im Ranking nach oben zu steigen, wenn sie stark mit anderen relevanten Treffern vernetzt sind.
|
||||||
|
|
||||||
|
| Parameter-Gruppe | Wertebereich | Logik |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Notiz-Gewichte** | 0.1 - 1.0 | Multiplikativ. Dient als Relevanz-Filter für Informationstypen. |
|
||||||
|
| **Kanten-Boosts** | 0.1 - 3.0+ | Additiv. Hebt vernetztes Wissen über isolierte Texttreffer. |
|
||||||
|
| **Status-Malus** | 0.5 - 0.9 | Multiplikativ. Bestraft unfertiges Wissen (Drafts). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Dynamic Intent Boosting (WP-22)
|
||||||
|
|
||||||
|
In v2.7 ist die Graph-Gewichtung nicht mehr statisch, sondern hängt vom **Intent** der Nutzerfrage ab (Query-Time Boosting).
|
||||||
|
|
||||||
|
Der Intent-Router injiziert spezifische Multiplikatoren für kanonische Typen:
|
||||||
|
* **Intent `EMPATHY`**: Boostet `based_on` (Fokus auf Werte).
|
||||||
|
* **Intent `WHY`**: Boostet `caused_by` (Fokus auf Ursachenforschung).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Idempotenz & Konsistenz
|
||||||
|
|
||||||
Das System garantiert fachliche Konsistenz auch bei mehrfachen Importen.
|
Das System garantiert fachliche Konsistenz auch bei mehrfachen Importen.
|
||||||
* **Stabile IDs:** Importiert man dieselbe Datei zweimal, ändern sich die IDs der Knoten nicht.
|
* **Stabile IDs:** Deterministische IDs verhindern Duplikate bei Re-Imports.
|
||||||
* **Keine Duplikate:** Kanten werden dedupliziert. Die "stärkere" Quelle (Explicit > Smart > Rule) gewinnt.
|
* **Deduplizierung:** Kanten werden anhand ihrer Identität erkannt. Die "stärkere" Provenance gewinnt.
|
||||||
* **Lösch-Garantie:** Wenn eine Notiz gelöscht wird, verschwinden auch alle ihre Chunks und ausgehenden Kanten (via `--sync-deletes`).
|
|
||||||
@@ -1,19 +1,19 @@
|
|||||||
---
|
---
|
||||||
doc_type: technical_reference
|
doc_type: technical_reference
|
||||||
audience: developer, admin
|
audience: developer, admin
|
||||||
scope: configuration, env
|
scope: configuration, env, registry, scoring
|
||||||
status: active
|
status: active
|
||||||
version: 2.6
|
version: 2.7.2
|
||||||
context: "Referenztabellen für Umgebungsvariablen und YAML-Konfigurationen."
|
context: "Umfassende Referenztabellen für Umgebungsvariablen, YAML-Konfigurationen und die Edge Registry Struktur."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Konfigurations-Referenz
|
# Konfigurations-Referenz
|
||||||
|
|
||||||
Dieses Dokument beschreibt die Steuerungsdateien von Mindnet.
|
Dieses Dokument beschreibt alle Steuerungsdateien von Mindnet. In der Version 2.7 wurde die Konfiguration professionalisiert, um die Edge Registry und dynamische Scoring-Parameter (Lifecycle & Intent) zu unterstützen.
|
||||||
|
|
||||||
## 1. Environment Variablen (`.env`)
|
## 1. Environment Variablen (`.env`)
|
||||||
|
|
||||||
Diese Variablen steuern die Infrastruktur, Timeouts und Feature-Flags.
|
Diese Variablen steuern die Infrastruktur, Pfade und globale Timeouts.
|
||||||
|
|
||||||
| Variable | Default | Beschreibung |
|
| Variable | Default | Beschreibung |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
@@ -21,6 +21,8 @@ Diese Variablen steuern die Infrastruktur, Timeouts und Feature-Flags.
|
|||||||
| `QDRANT_API_KEY` | *(leer)* | Optionaler Key für Absicherung. |
|
| `QDRANT_API_KEY` | *(leer)* | Optionaler Key für Absicherung. |
|
||||||
| `COLLECTION_PREFIX` | `mindnet` | Namensraum für Collections (erzeugt `{prefix}_notes` etc). |
|
| `COLLECTION_PREFIX` | `mindnet` | Namensraum für Collections (erzeugt `{prefix}_notes` etc). |
|
||||||
| `VECTOR_DIM` | `768` | **Muss 768 sein** (für Nomic Embeddings). |
|
| `VECTOR_DIM` | `768` | **Muss 768 sein** (für Nomic Embeddings). |
|
||||||
|
| `MINDNET_VOCAB_PATH` | *(Pfad)* | **Neu (WP-22):** Absoluter Pfad zur `01_edge_vocabulary.md`. Definiert den Ort des Dictionarys. |
|
||||||
|
| `MINDNET_VAULT_ROOT` | `./vault` | Basis-Pfad für Datei-Operationen. Dient als Fallback-Basis, falls `MINDNET_VOCAB_PATH` nicht gesetzt ist. |
|
||||||
| `MINDNET_TYPES_FILE` | `config/types.yaml` | Pfad zur Typ-Registry. |
|
| `MINDNET_TYPES_FILE` | `config/types.yaml` | Pfad zur Typ-Registry. |
|
||||||
| `MINDNET_RETRIEVER_CONFIG`| `config/retriever.yaml`| Pfad zur Scoring-Konfiguration. |
|
| `MINDNET_RETRIEVER_CONFIG`| `config/retriever.yaml`| Pfad zur Scoring-Konfiguration. |
|
||||||
| `MINDNET_DECISION_CONFIG` | `config/decision_engine.yaml` | Pfad zur Router & Intent Config. |
|
| `MINDNET_DECISION_CONFIG` | `config/decision_engine.yaml` | Pfad zur Router & Intent Config. |
|
||||||
@@ -30,10 +32,8 @@ Diese Variablen steuern die Infrastruktur, Timeouts und Feature-Flags.
|
|||||||
| `MINDNET_OLLAMA_URL` | `http://127.0.0.1:11434`| URL zum LLM-Server. |
|
| `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_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_API_TIMEOUT` | `300.0` | Frontend Timeout (Erhöht für Smart Edge Wartezeiten). |
|
||||||
| `MINDNET_LLM_BACKGROUND_LIMIT`| `2` | **Traffic Control:** Max. parallele Import-Tasks. |
|
| `MINDNET_LLM_BACKGROUND_LIMIT`| `2` | **Traffic Control:** Max. parallele Hintergrund-Tasks (Semaphore). |
|
||||||
| `MINDNET_VAULT_ROOT` | `./vault` | Pfad für Write-Back Operationen (Drafts). |
|
| `MINDNET_CHANGE_DETECTION_MODE` | `full` | `full` (Text + Meta) oder `body` (nur Text). |
|
||||||
| `MINDNET_HASH_COMPARE` | `Body` | Import-Strategie: `Body`, `Frontmatter` oder `Full`. |
|
|
||||||
| `MINDNET_HASH_SOURCE` | `parsed` | Hash-Quelle: `parsed`, `raw` oder `file`. |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -41,92 +41,121 @@ Diese Variablen steuern die Infrastruktur, Timeouts und Feature-Flags.
|
|||||||
|
|
||||||
Steuert das Import-Verhalten, Chunking und die Kanten-Logik pro Typ.
|
Steuert das Import-Verhalten, Chunking und die Kanten-Logik pro Typ.
|
||||||
|
|
||||||
**Referenztabelle (Stand v2.6):**
|
### 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.
|
||||||
|
2. **Type Config:** Der Standardwert für den `type` aus `types.yaml`.
|
||||||
|
3. **Global Default:** Fallback aus `defaults` in `types.yaml`.
|
||||||
|
|
||||||
| Typ (`type`) | Chunk Profile | Retriever Weight | Smart Edges? | Beschreibung |
|
### 2.2 Typ-Referenztabelle (Vollständig)
|
||||||
|
|
||||||
|
| Typ (`type`) | Chunk Profile (Standard) | Retriever Weight ($W_{type}$) | Smart Edges? | Beschreibung |
|
||||||
| :--- | :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
| **concept** | `sliding_smart_edges` | 0.60 | Ja | Abstrakte Begriffe. |
|
| **decision** | `structured_strict` | 1.00 | Ja | Entscheidungen. Atomar. |
|
||||||
| **project** | `sliding_smart_edges` | 0.97 | Ja | Aktive Vorhaben. |
|
| **value** | `structured_strict` | 1.00 | Ja | Werte/Prinzipien. Atomar. |
|
||||||
| **decision** | `structured_smart_edges` | 1.00 | Ja | Entscheidungen (ADRs). |
|
| **project** | `sliding_smart` | 0.97 | Ja | Aktive Vorhaben. |
|
||||||
| **experience** | `sliding_smart_edges` | 0.90 | Ja | Persönliche Learnings. |
|
| **experience** | `sliding_smart` | 0.90 | Ja | Persönliche Learnings. |
|
||||||
| **journal** | `sliding_standard` | 0.80 | Nein | Logs / Dailies. |
|
| **concept** | `sliding_smart` | 0.60 | Ja | Abstrakte Begriffe. |
|
||||||
| **value** | `structured_smart_edges` | 1.00 | Ja | Werte/Prinzipien. |
|
| **principle** | `structured_L3` | 0.95 | Nein | Prinzipien (Tiefer Split). |
|
||||||
|
| **belief** | `sliding_short` | 0.90 | Nein | Glaubenssätze. |
|
||||||
| **risk** | `sliding_short` | 0.90 | Nein | Risiken. |
|
| **risk** | `sliding_short` | 0.90 | Nein | Risiken. |
|
||||||
|
| **journal** | `sliding_standard` | 0.80 | Nein | Logs / Dailies. |
|
||||||
| **person** | `sliding_standard` | 0.50 | Nein | Profile. |
|
| **person** | `sliding_standard` | 0.50 | Nein | Profile. |
|
||||||
| **source** | `sliding_standard` | 0.50 | Nein | Externe Quellen. |
|
| **source** | `sliding_standard` | 0.50 | Nein | Externe Quellen. |
|
||||||
| **event** | `sliding_standard` | 0.60 | Nein | Meetings. |
|
| **glossary** | `sliding_short` | 0.40 | Nein | Begriffsdefinitionen. |
|
||||||
| **goal** | `sliding_standard` | 0.95 | Nein | Strategische Ziele. |
|
| **default** | `sliding_standard` | 1.00 | Nein | Fallback für alle anderen. |
|
||||||
| **belief** | `sliding_short` | 0.90 | Nein | Glaubenssätze. |
|
|
||||||
| **default** | `sliding_standard` | 1.00 | Nein | Fallback. |
|
|
||||||
|
|
||||||
*Hinweis: `Smart Edges?` entspricht dem YAML-Key `enable_smart_edge_allocation: true`.*
|
*Richtwert für $W_{type}$: 0.1 (minimale Relevanz/Filter) bis 1.0 (maximale Relevanz).*
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Retriever Config (`retriever.yaml`)
|
## 3. Retriever Config (`retriever.yaml`)
|
||||||
|
|
||||||
Steuert die Gewichtung der Scoring-Formel (WP04a).
|
Steuert die Gewichtung der Scoring-Formel und die neuen Lifecycle-Modifier.
|
||||||
|
|
||||||
**Beispielkonfiguration:**
|
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
scoring:
|
scoring:
|
||||||
semantic_weight: 1.0 # Basis-Relevanz (Cosine Similarity)
|
semantic_weight: 1.0 # Basis-Relevanz (Cosine Similarity)
|
||||||
edge_weight: 0.7 # Einfluss des Graphen (Bonus)
|
edge_weight: 0.7 # Einfluss des Graphen (Bonus)
|
||||||
centrality_weight: 0.5 # Einfluss von Hubs
|
centrality_weight: 0.5 # Einfluss von Hubs (Zentralität)
|
||||||
|
|
||||||
|
# WP-22 Lifecycle Modifier (Multiplikativ auf Semantik)
|
||||||
|
lifecycle_weights:
|
||||||
|
stable: 1.2 # Bonus: Geprüftes Wissen wird 20% höher gewichtet
|
||||||
|
draft: 0.5 # Malus: Entwürfe werden auf 50% gedämpft
|
||||||
|
system: 0.0 # Ausschluss aus dem Index
|
||||||
|
|
||||||
|
# Kanten-spezifische Basis-Gewichtung (Ohne Intent-Boost)
|
||||||
edge_weights:
|
edge_weights:
|
||||||
# Multiplikatoren für den Edge-Bonus
|
|
||||||
depends_on: 1.5 # Harte Abhängigkeiten stark gewichten
|
depends_on: 1.5 # Harte Abhängigkeiten stark gewichten
|
||||||
blocks: 1.5 # Risiken stark gewichten
|
blocks: 1.5 # Blocker/Risiken stark gewichten
|
||||||
caused_by: 1.2 # Kausalitäten stärken
|
caused_by: 1.2 # Kausalitäten moderat stärken
|
||||||
related_to: 0.5 # Weiche Themen schwächer gewichten
|
based_on: 1.3 # Werte-Bezug stärken
|
||||||
|
related_to: 0.5 # Weiche Assoziation schwächen
|
||||||
references: 0.8 # Standard-Referenzen
|
references: 0.8 # Standard-Referenzen
|
||||||
based_on: 1.3 # Werte-Bezug
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Edge Typen Referenz
|
## 4. Edge Typen & Registry Referenz
|
||||||
|
|
||||||
Definiert die Semantik der `kind`-Felder in der Edge-Collection.
|
Die `EdgeRegistry` ist die **Single Source of Truth** für das Vokabular.
|
||||||
|
|
||||||
| Kind | Symmetrisch? | Herkunft (Primär) | Bedeutung |
|
### 4.1 Dateistruktur & Speicherort
|
||||||
|
Die Registry erwartet eine Markdown-Datei an folgendem Ort:
|
||||||
|
* **Standard-Pfad:** `<MINDNET_VAULT_ROOT>/01_User_Manual/01_edge_vocabulary.md`.
|
||||||
|
* **Custom-Pfad:** Kann via `.env` Variable `MINDNET_VOCAB_PATH` überschrieben werden.
|
||||||
|
|
||||||
|
### 4.2 Aufbau des Dictionaries (Markdown-Schema)
|
||||||
|
Die Datei muss eine Markdown-Tabelle enthalten, die vom Regex-Parser gelesen wird.
|
||||||
|
|
||||||
|
**Erwartetes Format:**
|
||||||
|
```markdown
|
||||||
|
| System-Typ (Canonical) | Erlaubte Aliasse (User) | Beschreibung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **`based_on`** | `basiert_auf`, `fundament` | Fundament: B baut auf A auf. |
|
||||||
|
| **`caused_by`** | `ausgelöst_durch`, `wegen` | Kausalität: A löst B aus. |
|
||||||
|
```
|
||||||
|
|
||||||
|
**Regeln für die Spalten:**
|
||||||
|
1. **Canonical:** Muss fett gedruckt sein (`**type**` oder `**`type`**`). Dies ist der Wert, der in der DB landet.
|
||||||
|
2. **Aliasse:** Kommagetrennte Liste von Synonymen. Diese werden beim Import automatisch zum Canonical aufgelöst.
|
||||||
|
3. **Beschreibung:** Rein informativ für den Nutzer.
|
||||||
|
|
||||||
|
### 4.3 Verfügbare Kanten-Typen (System-Standard)
|
||||||
|
|
||||||
|
| Kind (Canonical) | Symmetrisch? | Herkunft | Bedeutung |
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| `references` | Nein | Wikilink | Standard-Verweis. "Erwähnt X". |
|
| `references` | Nein | Wikilink | Standard-Verweis ("Erwähnt X"). |
|
||||||
| `belongs_to` | Nein | Struktur | Chunk gehört zu Note. |
|
| `belongs_to` | Nein | Struktur | Chunk gehört zu Note. |
|
||||||
| `next` / `prev` | Ja | Struktur | Lesereihenfolge. |
|
| `caused_by` | Nein | Inline | Kausalität: A löst B aus. |
|
||||||
| `depends_on` | Nein | Inline / Default | Harte Abhängigkeit. |
|
| `based_on` | Nein | Matrix | Fundament: A fußt auf B. |
|
||||||
| `related_to` | Ja | Callout / Default | Thematische Nähe. |
|
| `blocks` | Nein | Inline | Blocker: A verhindert B. |
|
||||||
| `similar_to` | Ja | Inline | Inhaltliche Ähnlichkeit. |
|
| `solves` | Nein | Inline | Lösung: A ist Lösung für Problem B. |
|
||||||
| `caused_by` | Nein | Inline | Kausalität. |
|
| `next` / `prev` | Ja | Struktur | Sequenzielle Lesereihenfolge. |
|
||||||
| `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`)
|
## 5. Decision Engine (`decision_engine.yaml`)
|
||||||
|
|
||||||
Steuert den Hybrid Router (WP06). Definiert, welche Keywords welche Strategie auslösen.
|
Steuert den Hybrid Router und das dynamische Intent-Boosting (WP-22).
|
||||||
|
|
||||||
**Beispielauszug:**
|
**Beispielauszug für Intent-Boosting:**
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# Strategie-Definitionen
|
intents:
|
||||||
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:
|
EMPATHY:
|
||||||
description: "Emotionaler Support"
|
description: "Emotionaler Support / Werte-Fokus"
|
||||||
|
boost_edges:
|
||||||
|
based_on: 2.0 # Verdoppelt den Einfluss von Werte-Kanten
|
||||||
|
related_to: 1.5 # Stärkt assoziative Bezüge
|
||||||
inject_types: ["experience", "belief"]
|
inject_types: ["experience", "belief"]
|
||||||
|
|
||||||
|
WHY:
|
||||||
|
description: "Ursachenanalyse (Kausalität)"
|
||||||
|
boost_edges:
|
||||||
|
caused_by: 2.5 # Massiver Boost für Kausalitätsketten
|
||||||
|
derived_from: 1.8 # Fokus auf die Herkunft
|
||||||
```
|
```
|
||||||
|
|
||||||
|
*Richtwert für Kanten-Boosts: 0.1 (Abwertung) bis 3.0+ (Dominanz gegenüber Text-Match).*
|
||||||
@@ -3,7 +3,7 @@ doc_type: technical_reference
|
|||||||
audience: developer, architect
|
audience: developer, architect
|
||||||
scope: database, qdrant, schema
|
scope: database, qdrant, schema
|
||||||
status: active
|
status: active
|
||||||
version: 2.6
|
version: 2.7.0
|
||||||
context: "Exakte Definition der Datenmodelle (Payloads) in Qdrant und Index-Anforderungen."
|
context: "Exakte Definition der Datenmodelle (Payloads) in Qdrant und Index-Anforderungen."
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -31,13 +31,20 @@ Repräsentiert die Metadaten einer Markdown-Datei (1:1 Beziehung).
|
|||||||
"note_id": "string (keyword)", // UUIDv5 (deterministisch) oder Slug
|
"note_id": "string (keyword)", // UUIDv5 (deterministisch) oder Slug
|
||||||
"title": "string (text)", // Titel aus Frontmatter
|
"title": "string (text)", // Titel aus Frontmatter
|
||||||
"type": "string (keyword)", // Logischer Typ (z.B. 'project', 'concept')
|
"type": "string (keyword)", // Logischer Typ (z.B. 'project', 'concept')
|
||||||
"retriever_weight": "float", // Numerische Wichtigkeit (0.0-1.0), aus types.yaml
|
"retriever_weight": "float", // Effektive Wichtigkeit (Frontmatter > Type > Default)
|
||||||
"chunk_profile": "string", // Genutztes Profil (z.B. 'sliding_smart_edges')
|
"chunk_profile": "string", // Effektives Profil (Frontmatter > Type > Default)
|
||||||
"edge_defaults": ["string"], // Liste der aktiven Default-Kanten
|
"edge_defaults": ["string"], // Liste der aktiven Default-Kanten
|
||||||
"tags": ["string"], // Liste von Tags aus Frontmatter
|
"tags": ["string"], // Liste von Tags aus Frontmatter
|
||||||
|
"aliases": ["string"], // Synonyme für Discovery (WP-11)
|
||||||
"created": "string (iso-date)", // Erstellungsdatum
|
"created": "string (iso-date)", // Erstellungsdatum
|
||||||
"updated": "integer", // Timestamp (File Modification Time)
|
"updated": "integer", // Timestamp (File Modification Time)
|
||||||
"fulltext": "string (no-index)" // Gesamter Text (nur für Recovery/Export)
|
"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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -68,10 +75,12 @@ Die atomare Sucheinheit. Enthält den Vektor.
|
|||||||
"text": "string (text)", // Reintext für Anzeige (ohne Overlap)
|
"text": "string (text)", // Reintext für Anzeige (ohne Overlap)
|
||||||
"window": "string (text)", // Text + Overlap (Basis für Embedding)
|
"window": "string (text)", // Text + Overlap (Basis für Embedding)
|
||||||
"ord": "integer", // Laufende Nummer (1..N) für Sortierung
|
"ord": "integer", // Laufende Nummer (1..N) für Sortierung
|
||||||
"retriever_weight": "float", // Kopie aus Note (für Query-Speed)
|
"retriever_weight": "float", // Geerbt von Note (für schnelles Re-Ranking)
|
||||||
"chunk_profile": "string", // Vererbt von Note
|
"chunk_profile": "string", // Geerbt von Note (für Debugging/Filtering)
|
||||||
"neighbors_prev": ["string"], // ID des Vorgängers (Linked List)
|
"neighbors_prev": ["string"], // ID des Vorgängers (Linked List)
|
||||||
"neighbors_next": ["string"] // ID des Nachfolgers
|
"neighbors_next": ["string"], // ID des Nachfolgers
|
||||||
|
"section": "string", // Pfad/Überschrift, zu der der Chunk gehört
|
||||||
|
"source_path": "string" // Relativer Pfad zur Datei
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -99,7 +108,7 @@ Gerichtete Kanten zwischen Knoten. Stark erweitert in v2.6 für Provenienz-Track
|
|||||||
"note_id": "string (keyword)", // Owner Note ID (Ursprung der Kante)
|
"note_id": "string (keyword)", // Owner Note ID (Ursprung der Kante)
|
||||||
|
|
||||||
// Provenance & Quality (WP03/WP15)
|
// Provenance & Quality (WP03/WP15)
|
||||||
"provenance": "keyword", // 'explicit', 'rule', 'smart' (NEU)
|
"provenance": "keyword", // 'explicit', 'rule', 'smart', 'structure'
|
||||||
"rule_id": "string (keyword)", // Traceability: 'inline:rel', 'explicit:wikilink', 'smart:llm'
|
"rule_id": "string (keyword)", // Traceability: 'inline:rel', 'explicit:wikilink', 'smart:llm'
|
||||||
"confidence": "float" // Vertrauenswürdigkeit (0.0 - 1.0)
|
"confidence": "float" // Vertrauenswürdigkeit (0.0 - 1.0)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ doc_type: technical_reference
|
|||||||
audience: developer, frontend_architect
|
audience: developer, frontend_architect
|
||||||
scope: architecture, graph_viz, state_management
|
scope: architecture, graph_viz, state_management
|
||||||
status: active
|
status: active
|
||||||
version: 2.6
|
version: 2.7.0
|
||||||
context: "Technische Dokumentation des modularen Streamlit-Frontends, der Graph-Engines und des Editors."
|
context: "Technische Dokumentation des modularen Streamlit-Frontends, der Graph-Engines und des Editors."
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ Seit Version 2.6 ist das Frontend (`app/frontend/`) kein Monolith mehr, sondern
|
|||||||
| `ui_utils.py` | **Helper.** Markdown-Parsing (`parse_markdown_draft`) und String-Normalisierung. |
|
| `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_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_graph_cytoscape.py`| **View: Graph.** Implementierung mit `st-cytoscape` (COSE Layout). |
|
||||||
| `ui_editor.py` | **View: Editor.** Logik für Drafts und manuelles Editieren. |
|
| `ui_editor.py` | **View: Editor.** Logik für Drafts, manuelles Editieren und **Async Feedback**. |
|
||||||
|
|
||||||
### 1.2 Konfiguration (`ui_config.py`)
|
### 1.2 Konfiguration (`ui_config.py`)
|
||||||
|
|
||||||
@@ -117,7 +117,19 @@ Der `switch_to_editor_callback` in `ui_callbacks.py` implementiert folgende Kask
|
|||||||
})
|
})
|
||||||
st.session_state["sidebar_mode_selection"] = "📝 Manueller Editor"
|
st.session_state["sidebar_mode_selection"] = "📝 Manueller Editor"
|
||||||
|
|
||||||
Dies garantiert, dass der Editor immer den **echten, aktuellen Stand** der Markdown-Datei anzeigt.
|
### 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).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,38 +1,59 @@
|
|||||||
---
|
---
|
||||||
doc_type: technical_reference
|
doc_type: technical_reference
|
||||||
audience: developer, devops
|
audience: developer, devops
|
||||||
scope: backend, ingestion, smart_edges
|
scope: backend, ingestion, smart_edges, edge_registry
|
||||||
status: active
|
status: active
|
||||||
version: 2.6
|
version: 2.7.1
|
||||||
context: "Detaillierte technische Beschreibung der Import-Pipeline, Quality Gates und CLI-Befehle."
|
context: "Detaillierte technische Beschreibung der Import-Pipeline, Chunking-Strategien und CLI-Befehle."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Ingestion Pipeline & Smart Processing
|
# Ingestion Pipeline & Smart Processing
|
||||||
|
|
||||||
**Quellen:** `pipeline_playbook.md`, `Handbuch.md`
|
**Quellen:** `pipeline_playbook.md`, `Handbuch.md`, `edge_registry.py`, `01_edge_vocabulary.md`, `06_active_roadmap.md`
|
||||||
|
|
||||||
Die Ingestion transformiert Markdown in den Graphen. Entrypoint: `scripts/import_markdown.py`.
|
Die Ingestion transformiert Markdown in den Graphen. Entrypoint: `scripts/import_markdown.py` (CLI) oder `routers/ingest.py` (API). Seit v2.7 integriert dieser Prozess die **Edge Registry** zur Normalisierung des Vokabulars und beachtet den **Content Lifecycle**.
|
||||||
|
|
||||||
## 1. Der Import-Prozess (13-Schritte-Workflow)
|
## 1. Der Import-Prozess (15-Schritte-Workflow)
|
||||||
|
|
||||||
Der Prozess ist **asynchron** und **idempotent**.
|
Der Prozess ist **asynchron** und **idempotent**.
|
||||||
|
|
||||||
1. **Markdown lesen:** Rekursives Scannen des Vaults.
|
1. **Trigger & Async Dispatch:**
|
||||||
2. **Frontmatter extrahieren:** Validierung von Pflichtfeldern (`id`, `type`, `title`).
|
* **API (`/save`):** Nimmt Request entgegen, validiert und startet Background-Task ("Fire & Forget"). Antwortet sofort mit `202/Queued`.
|
||||||
3. **Typauflösung:** Bestimmung des `type` via `types.yaml`.
|
* **CLI:** Iteriert über Dateien und nutzt `asyncio.Semaphore` zur Drosselung.
|
||||||
4. **Note-Payload generieren:** Erstellen des JSON-Objekts für `mindnet_notes`.
|
2. **Markdown lesen:** Rekursives Scannen des Vaults.
|
||||||
5. **Chunking anwenden:** Zerlegung des Textes basierend auf dem `chunk_profile` (siehe unten).
|
3. **Frontmatter Check & Hard Skip (WP-22):**
|
||||||
6. **Smart Edge Allocation (WP15):**
|
* Extraktion von `status` und `type`.
|
||||||
|
* **Hard Skip Rule:** Wenn `status` in `['system', 'template']` ist, wird die Datei **sofort übersprungen**. Sie wird weder vektorisiert noch in den Graphen aufgenommen.
|
||||||
|
* Validierung der Pflichtfelder (`id`, `title`) für alle anderen Dateien.
|
||||||
|
4. **Edge Registry Initialisierung (WP-22):**
|
||||||
|
* Laden der Singleton-Instanz der `EdgeRegistry`.
|
||||||
|
* Validierung der Vokabular-Datei unter `MINDNET_VOCAB_PATH`.
|
||||||
|
5. **Config Resolution:**
|
||||||
|
* Bestimmung von `chunking_profile` und `retriever_weight`.
|
||||||
|
* **Priorität:** 1. Frontmatter (Override) -> 2. `types.yaml` (Type) -> 3. Global Default.
|
||||||
|
6. **Note-Payload generieren:**
|
||||||
|
* Erstellen des JSON-Objekts inklusive `status` (für Scoring).
|
||||||
|
* **Multi-Hash Calculation:** Berechnet Hashtabellen für `body` (nur Text) und `full` (Text + Metadaten).
|
||||||
|
7. **Change Detection:**
|
||||||
|
* Vergleich des Hashes mit Qdrant.
|
||||||
|
* Strategie wählbar via ENV `MINDNET_CHANGE_DETECTION_MODE` (`full` oder `body`).
|
||||||
|
8. **Chunking anwenden:** Zerlegung des Textes basierend auf dem ermittelten Profil (siehe Kap. 3).
|
||||||
|
9. **Smart Edge Allocation (WP15):**
|
||||||
* Wenn `enable_smart_edge_allocation: true`: Der `SemanticAnalyzer` sendet Chunks an das LLM.
|
* Wenn `enable_smart_edge_allocation: true`: Der `SemanticAnalyzer` sendet Chunks an das LLM.
|
||||||
* **Traffic Control:** Request nutzt `priority="background"`. Semaphore (Limit: 2) drosselt die Last.
|
* **Traffic Control:** Request nutzt `priority="background"`. Semaphore (Limit via `.env`) drosselt die Last.
|
||||||
* **Resilienz:** Bei Timeout (Ollama) greift ein Fallback (Broadcasting an alle Chunks).
|
* **Resilienz:** Bei Timeout (Ollama) greift ein Fallback (Broadcasting an alle Chunks).
|
||||||
7. **Inline-Kanten finden:** Parsing von `[[rel:...]]`.
|
10. **Inline-Kanten finden:** Parsing von `[[rel:...]]`.
|
||||||
8. **Callout-Kanten finden:** Parsing von `> [!edge]`.
|
11. **Alias-Auflösung & Kanonisierung (WP-22):**
|
||||||
9. **Default-Edges erzeugen:** Anwendung der `edge_defaults` aus Registry.
|
* Jede Kante wird via `edge_registry.resolve()` normalisiert.
|
||||||
10. **Strukturkanten erzeugen:** `belongs_to`, `next`, `prev`.
|
* Aliase (z.B. `basiert_auf`) werden zu kanonischen Typen (z.B. `based_on`) aufgelöst.
|
||||||
11. **Embedding (Async):** Generierung via `nomic-embed-text` (768d).
|
* Unbekannte Typen werden in `unknown_edges.jsonl` protokolliert.
|
||||||
12. **Strict Mode:** Abbruch bei leeren Embeddings oder Dimension 0.
|
12. **Callout-Kanten finden:** Parsing von `> [!edge]`.
|
||||||
13. **Diagnose:** Integritäts-Check nach dem Lauf.
|
13. **Default- & Matrix-Edges erzeugen:** Anwendung der `edge_defaults` aus Registry und Matrix-Logik.
|
||||||
|
14. **Strukturkanten erzeugen:** `belongs_to`, `next`, `prev`.
|
||||||
|
15. **Embedding (Async):** Generierung via `nomic-embed-text` (768 Dim).
|
||||||
|
16. **Diagnose:** Integritäts-Check nach dem Lauf.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -44,6 +65,8 @@ Für regelmäßige Updates (Cronjob). Erkennt Änderungen via Hash.
|
|||||||
```bash
|
```bash
|
||||||
export QDRANT_URL="http://localhost:6333"
|
export QDRANT_URL="http://localhost:6333"
|
||||||
export COLLECTION_PREFIX="mindnet"
|
export COLLECTION_PREFIX="mindnet"
|
||||||
|
# Steuert, wann eine Datei als "geändert" gilt
|
||||||
|
export MINDNET_CHANGE_DETECTION_MODE="full"
|
||||||
|
|
||||||
# Nutzt das Venv der Produktionsumgebung
|
# Nutzt das Venv der Produktionsumgebung
|
||||||
/home/llmadmin/mindnet/.venv/bin/python3 -m scripts.import_markdown \
|
/home/llmadmin/mindnet/.venv/bin/python3 -m scripts.import_markdown \
|
||||||
@@ -58,7 +81,7 @@ export COLLECTION_PREFIX="mindnet"
|
|||||||
> 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).
|
> 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)
|
### 2.2 Full Rebuild (Clean Slate)
|
||||||
Notwendig bei Änderungen an `types.yaml` oder Modell-Wechsel.
|
Notwendig bei Änderungen an `types.yaml` (z.B. neue Chunking-Profile), der Registry oder Modell-Wechsel.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 0. Modell sicherstellen
|
# 0. Modell sicherstellen
|
||||||
@@ -68,6 +91,7 @@ ollama pull nomic-embed-text
|
|||||||
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
||||||
|
|
||||||
# 2. Vollständiger Import (Force)
|
# 2. Vollständiger Import (Force)
|
||||||
|
# --force ignoriert alle Hashes und schreibt alles neu
|
||||||
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -75,47 +99,69 @@ python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --
|
|||||||
|
|
||||||
## 3. Chunking & Payload
|
## 3. Chunking & Payload
|
||||||
|
|
||||||
Das Chunking ist profilbasiert.
|
Das Chunking ist profilbasiert und in `types.yaml` konfiguriert.
|
||||||
|
|
||||||
| Profil | Max Token | Overlap | Einsatz |
|
### 3.1 Profile und Strategien (Vollständige Referenz)
|
||||||
|
|
||||||
|
| Profil | Strategie | Parameter | Einsatzgebiet |
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| `sliding_short` | 128 | 20 | Logs, Chats. |
|
| `sliding_short` | `sliding_window` | Max: 350, Target: 200 | Kurze Logs, Chats, Risiken. |
|
||||||
| `sliding_standard` | 512 | 50 | Massendaten. |
|
| `sliding_standard` | `sliding_window` | Max: 650, Target: 450 | Massendaten (Journal, Quellen). |
|
||||||
| `sliding_smart_edges`| 512 | 50 | Wichtige Inhalte (Experience, Project). |
|
| `sliding_smart_edges`| `sliding_window` | Max: 600, Target: 400 | Fließtexte mit hohem Wert (Projekte). |
|
||||||
| `structured_smart` | n/a | n/a | Trennt strikt an Headings (für ADRs). |
|
| `structured_smart_edges` | `by_heading` | `strict: false` (Soft) | Strukturierte Texte, Merging erlaubt. |
|
||||||
|
| `structured_smart_edges_strict` | `by_heading` | `strict: true` (Hard) | **Atomare Einheiten**: Entscheidungen, Werte. |
|
||||||
|
| `structured_smart_edges_strict_L3`| `by_heading` | `strict: true`, `level: 3` | Tief geschachtelte Prinzipien (Tier 2/MP1). |
|
||||||
|
|
||||||
**Payload-Felder:**
|
### 3.2 Die `by_heading` Logik (v2.9 Hybrid)
|
||||||
* `text`: Der reine Inhalt (Anzeige).
|
|
||||||
|
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 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).
|
||||||
* `window`: Inhalt plus Overlap (für Embedding).
|
* `window`: Inhalt plus Overlap (für Embedding).
|
||||||
|
* `chunk_profile`: Das effektiv genutzte Profil (zur Nachverfolgung).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Edge-Erzeugung & Prioritäten
|
## 4. Edge-Erzeugung & Prioritäten (Provenance)
|
||||||
|
|
||||||
Kanten werden nach Vertrauenswürdigkeit (`provenance`) priorisiert. Die höhere Prio gewinnt.
|
Kanten werden nach Vertrauenswürdigkeit (`provenance`) priorisiert. Die höhere Prio gewinnt.
|
||||||
|
|
||||||
| Prio | Quelle | Rule ID | Confidence |
|
| Prio | Quelle | Rule ID | Confidence | Erläuterung |
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
| **1** | Inline | `inline:rel` | 0.95 |
|
| **1** | Wikilink | `explicit:wikilink` | **1.00** | Harte menschliche Setzung. |
|
||||||
| **2** | Callout | `callout:edge` | 0.90 |
|
| **2** | Inline | `inline:rel` | **0.95** | Typisierte menschliche Kante. |
|
||||||
| **3** | Wikilink | `explicit:wikilink` | 1.00 |
|
| **3** | Callout | `callout:edge` | **0.90** | Explizite Meta-Information. |
|
||||||
| **4** | Smart Edge | `smart:llm_filter` | 0.90 |
|
| **4** | Smart Edge | `smart:llm_filter` | **0.90** | KI-validierte Verbindung. |
|
||||||
| **5** | Type Default | `edge_defaults` | 0.70 |
|
| **5** | Type Default | `edge_defaults` | **0.70** | Heuristik aus der Registry. |
|
||||||
| **6** | Struktur | `structure` | 1.00 |
|
| **6** | Struktur | `structure` | **1.00** | System-interne Verkettung. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Quality Gates & Tests
|
## 5. Quality Gates & Monitoring
|
||||||
|
|
||||||
Diese Tests garantieren die Stabilität der Pipeline.
|
In v2.7 wurden Tools zur Überwachung der Datenqualität integriert:
|
||||||
|
|
||||||
**1. Payload Dryrun (Schema-Check):**
|
**1. Registry Review:** Prüfung der `data/logs/unknown_edges.jsonl`. Administratoren sollten hier gelistete Begriffe als Aliase in die `01_edge_vocabulary.md` aufnehmen.
|
||||||
|
|
||||||
|
**2. Payload Dryrun (Schema-Check):**
|
||||||
Simuliert Import, prüft JSON-Schema Konformität.
|
Simuliert Import, prüft JSON-Schema Konformität.
|
||||||
```bash
|
```bash
|
||||||
python3 -m scripts.payload_dryrun --vault ./test_vault
|
python3 -m scripts.payload_dryrun --vault ./test_vault
|
||||||
```
|
```
|
||||||
|
|
||||||
**2. Full Edge Check (Graph-Integrität):**
|
**3. Full Edge Check (Graph-Integrität):**
|
||||||
Prüft Invarianten (z.B. `next` muss reziprok zu `prev` sein).
|
Prüft Invarianten (z.B. `next` muss reziprok zu `prev` sein).
|
||||||
```bash
|
```bash
|
||||||
python3 -m scripts.edges_full_check
|
python3 -m scripts.edges_full_check
|
||||||
|
|||||||
@@ -1,25 +1,25 @@
|
|||||||
---
|
---
|
||||||
doc_type: technical_reference
|
doc_type: technical_reference
|
||||||
audience: developer, data_scientist
|
audience: developer, data_scientist
|
||||||
scope: backend, retrieval, scoring
|
scope: backend, retrieval, scoring, modularization
|
||||||
status: active
|
status: active
|
||||||
version: 2.6
|
version: 2.7.1
|
||||||
context: "Formeln und Algorithmen des Hybrid Retrievers und Explanation Layer."
|
context: "Detaillierte Dokumentation der Scoring-Algorithmen, inklusive WP-22 Lifecycle-Modifier, Intent-Boosting und Modularisierung."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Retrieval & Scoring Algorithmen
|
# 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.
|
Der Retriever unterstützt **Semantic Search** und **Hybrid Search**. Seit v2.4 nutzt Mindnet ein gewichtetes Scoring-Modell, das Semantik, Graphentheorie und Metadaten kombiniert. Mit Version 2.7 (WP-22) wurde dieses Modell um **Lifecycle-Faktoren** und **Intent-Boosting** erweitert sowie die Architektur modularisiert.
|
||||||
|
|
||||||
## 1. Scoring Formel (WP04a)
|
## 1. Scoring Formel (v2.7.0)
|
||||||
|
|
||||||
Der Gesamtscore eines Treffers berechnet sich als gewichtete Summe. Alle Gewichte ($W$) sind in `retriever.yaml` konfigurierbar.
|
Der Gesamtscore eines Treffers berechnet sich als gewichtete Summe. Alle Gewichte ($W$) und Modifier ($M$) sind in `retriever.yaml` und `decision_engine.yaml` konfigurierbar.
|
||||||
|
|
||||||
$$
|
$$
|
||||||
TotalScore = (W_{sem} \cdot S_{sem} \cdot \max(W_{type}, 0)) + (W_{edge} \cdot B_{edge}) + (W_{cent} \cdot B_{cent})
|
TotalScore = (W_{sem} \cdot S_{sem} \cdot W_{type} \cdot M_{status}) + (W_{edge} \cdot B_{edge}) + (W_{cent} \cdot B_{cent}) + B_{intent}
|
||||||
$$
|
$$
|
||||||
|
|
||||||
### Die Komponenten
|
### Die Komponenten (Klassisch v2.4)
|
||||||
|
|
||||||
**1. Semantic Score ($S_{sem}$):**
|
**1. Semantic Score ($S_{sem}$):**
|
||||||
* **Basis:** Cosine Similarity des Vektors.
|
* **Basis:** Cosine Similarity des Vektors.
|
||||||
@@ -27,87 +27,103 @@ $$
|
|||||||
* **Wertebereich:** 0.0 bis 1.0.
|
* **Wertebereich:** 0.0 bis 1.0.
|
||||||
|
|
||||||
**2. Type Weight ($W_{type}$):**
|
**2. Type Weight ($W_{type}$):**
|
||||||
* **Herkunft:** Feld `retriever_weight` aus der Note/Chunk Payload.
|
* **Herkunft:** Feld `retriever_weight` aus der Note/Chunk Payload oder `types.yaml`.
|
||||||
* **Zweck:** Priorisierung bestimmter Dokumententypen unabhängig vom Inhalt.
|
* **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.
|
* **Beispiel:** Eine `decision` (1.0) schlägt ein `concept` (0.6) bei gleicher Ähnlichkeit.
|
||||||
|
|
||||||
**3. Edge Bonus ($B_{edge}$):**
|
**3. Edge Bonus ($B_{edge}$):**
|
||||||
* **Kontext:** Berechnet im lokalen Subgraphen (Expansion Tiefe 1).
|
* **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.
|
* **Logik:** Summe der `confidence` aller eingehenden Kanten von Knoten im aktuellen Result-Set.
|
||||||
* **Zweck:** Belohnt Chunks, die "im Thema" vernetzt sind.
|
* **Zweck:** Belohnt Chunks, die "im Thema" vernetzt sind.
|
||||||
|
|
||||||
**4. Centrality Bonus ($B_{cent}$):**
|
**4. Centrality Bonus ($B_{cent}$):**
|
||||||
* **Kontext:** Berechnet im lokalen Subgraphen.
|
* **Kontext:** Berechnet im lokalen Subgraphen.
|
||||||
* **Logik:** Eine vereinfachte PageRank-Metrik (Degree Centrality) im temporären Graphen.
|
* **Logik:** Vereinfachte PageRank-Metrik (Degree Centrality).
|
||||||
* **Zweck:** Belohnt "Hubs", die viele Verbindungen zu anderen Treffern haben.
|
* **Zweck:** Belohnt "Hubs" mit vielen Verbindungen zu anderen Treffern.
|
||||||
|
|
||||||
|
### Die WP-22 Erweiterungen (v2.7.0)
|
||||||
|
|
||||||
|
**5. Status Modifier ($M_{status}$):**
|
||||||
|
* **Herkunft:** Feld `status` aus dem Frontmatter.
|
||||||
|
* **Zweck:** Bestraft unfertiges Wissen (Drafts) oder bevorzugt stabiles Wissen.
|
||||||
|
* **Werte (Auftrag WP-22):** * `stable`: **1.2** (Bonus für Qualität).
|
||||||
|
* `draft`: **0.5** (Malus für Entwürfe).
|
||||||
|
* `system`: Exkludiert (siehe Ingestion).
|
||||||
|
|
||||||
|
**6. Intent Boost ($B_{intent}$):**
|
||||||
|
* **Herkunft:** Dynamische Injektion durch die Decision Engine basierend auf der Nutzerfrage.
|
||||||
|
* **Zweck:** Erhöhung des Scores für Knoten, die über spezifische Kanten-Typen (z.B. `caused_by` bei "Warum"-Fragen) verbunden sind.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Hybrid Retrieval Flow
|
## 2. Hybrid Retrieval Flow & Modularisierung
|
||||||
|
|
||||||
Der Hybrid-Modus ist der Standard für den Chat (`/chat`). Er läuft in drei Phasen ab:
|
In v2.7 wurde die Engine in einen Orchestrator (`retriever.py`) und eine Scoring-Engine (`retriever_scoring.py`) aufgeteilt.
|
||||||
|
|
||||||
**Phase 1: Vector Search (Seed Generation)**
|
**Phase 1: Vector Search (Seed Generation)**
|
||||||
* Suche die Top-K (z.B. 20) Kandidaten via Embeddings in Qdrant.
|
* Der Orchestrator sucht Top-K (Standard: 20) Kandidaten via Embeddings in Qdrant.
|
||||||
* Dies sind die "Seeds" für den Graphen.
|
* Diese bilden die "Seeds" für den Graphen.
|
||||||
|
|
||||||
**Phase 2: Graph Expansion**
|
**Phase 2: Graph Expansion**
|
||||||
* Nutze `graph_adapter.expand(seeds, depth=1)`.
|
* Nutze `graph_adapter.expand(seeds, depth=1)`.
|
||||||
* Lade alle direkten Nachbarn (Incoming & Outgoing) der Seeds aus der `_edges` Collection.
|
* Lade direkte Nachbarn aus der `_edges` Collection.
|
||||||
* Konstruiere einen temporären `NetworkX`-Graphen im Speicher (`Subgraph`).
|
* Konstruiere einen `NetworkX`-Graphen im Speicher.
|
||||||
|
|
||||||
**Phase 3: Re-Ranking**
|
**Phase 3: Re-Ranking (Modular)**
|
||||||
* Berechne für jeden Knoten im Subgraphen die Boni ($B_{edge}$, $B_{cent}$).
|
* Der Orchestrator übergibt den Graphen und die Seeds an die `ScoringEngine`.
|
||||||
* Wende die Scoring-Formel an.
|
* Berechne Boni ($B_{edge}$, $B_{cent}$) sowie die neuen Lifecycle- und Intent-Modifier.
|
||||||
* Sortiere die Liste neu absteigend nach `TotalScore`.
|
* Sortierung absteigend nach `TotalScore` und Limitierung auf Top-Resultate (z.B. 5).
|
||||||
* Schneide die Liste beim finalen Limit (z.B. 5) ab.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Explanation Layer (WP04b)
|
## 3. Explanation Layer (WP-22 Update)
|
||||||
|
|
||||||
Wenn der Parameter `explain=True` an die API übergeben wird, generiert der Retriever ein `Explanation` Objekt für jeden Treffer.
|
Bei `explain=True` generiert das System eine detaillierte Begründung.
|
||||||
|
|
||||||
**JSON-Struktur der Erklärung:**
|
**Erweiterte JSON-Struktur:**
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"score_breakdown": {
|
"score_breakdown": {
|
||||||
"semantic": 0.85,
|
"semantic": 0.85,
|
||||||
"type_boost": 1.0,
|
"type_boost": 1.0,
|
||||||
|
"lifecycle_modifier": 0.5,
|
||||||
"edge_bonus": 0.4,
|
"edge_bonus": 0.4,
|
||||||
|
"intent_boost": 0.5,
|
||||||
"centrality": 0.1
|
"centrality": 0.1
|
||||||
},
|
},
|
||||||
"reasons": [
|
"reasons": [
|
||||||
"Hohe textuelle Übereinstimmung (>0.85).",
|
"Hohe textuelle Übereinstimmung (>0.85).",
|
||||||
"Bevorzugt, da Typ 'decision' (Gewicht 1.0).",
|
"Status 'draft' reduziert Relevanz (Modifier 0.5).",
|
||||||
"Wird referenziert von 'Projekt Alpha' via 'depends_on'."
|
"Wird referenziert via 'caused_by' (Intent-Bonus 0.5).",
|
||||||
|
"Bevorzugt, da Typ 'decision' (Gewicht 1.0)."
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**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`)
|
## 4. Konfiguration (`retriever.yaml`)
|
||||||
|
|
||||||
Diese Datei steuert die Balance der Formel.
|
Steuert die Gewichtung der mathematischen Komponenten.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
scoring:
|
scoring:
|
||||||
semantic_weight: 1.0 # Basis-Relevanz (sollte immer ca. 1.0 sein)
|
semantic_weight: 1.0 # Basis-Relevanz
|
||||||
edge_weight: 0.7 # Einfluss des Graphen (0.5 - 1.0 empfohlen)
|
edge_weight: 0.7 # Graphen-Einfluss
|
||||||
centrality_weight: 0.5 # Einfluss der Zentralität (Hub-Bonus)
|
centrality_weight: 0.5 # Hub-Einfluss
|
||||||
|
|
||||||
# Kanten-spezifische Gewichtung für den Edge-Bonus
|
# WP-22 Lifecycle Konfiguration (Abgleich mit Auftrag)
|
||||||
|
lifecycle_weights:
|
||||||
|
stable: 1.2 # Bonus für Qualität
|
||||||
|
draft: 0.5 # Malus für Entwürfe
|
||||||
|
|
||||||
|
# Kanten-Gewichtung für den Edge-Bonus (Basis)
|
||||||
edge_weights:
|
edge_weights:
|
||||||
depends_on: 1.5 # Harte Abhängigkeiten sehr stark gewichten
|
depends_on: 1.5 # Harte Abhängigkeiten
|
||||||
blocks: 1.5 # Risiken/Blocker stark gewichten
|
blocks: 1.5 # Risiken/Blocker
|
||||||
caused_by: 1.2 # Kausalitäten moderat stärken
|
caused_by: 1.2 # Kausalitäten
|
||||||
related_to: 0.5 # Weiche Themen schwächer gewichten
|
based_on: 1.3 # Werte-Bezug
|
||||||
|
related_to: 0.5 # Weiche Themen
|
||||||
references: 0.8 # Standard-Referenzen
|
references: 0.8 # Standard-Referenzen
|
||||||
```
|
```
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
---
|
---
|
||||||
doc_type: operations_manual
|
doc_type: operations_manual
|
||||||
audience: admin, devops
|
audience: admin, devops
|
||||||
scope: deployment, maintenance, backup
|
scope: deployment, maintenance, backup, edge_registry
|
||||||
status: active
|
status: active
|
||||||
version: 2.6
|
version: 2.7.0
|
||||||
context: "Installationsanleitung, Systemd-Units und Wartungsprozesse."
|
context: "Installationsanleitung, Systemd-Units und Wartungsprozesse für Mindnet v2.7."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Admin Operations Guide
|
# Admin Operations Guide
|
||||||
@@ -58,6 +58,7 @@ User=llmadmin
|
|||||||
Group=llmadmin
|
Group=llmadmin
|
||||||
WorkingDirectory=/home/llmadmin/mindnet
|
WorkingDirectory=/home/llmadmin/mindnet
|
||||||
# Startet Uvicorn (Async Server)
|
# Startet Uvicorn (Async Server)
|
||||||
|
# Hinweis: Die .env muss MINDNET_VOCAB_PATH für die Edge Registry enthalten.
|
||||||
ExecStart=/home/llmadmin/mindnet/.venv/bin/uvicorn app.main:app --host 0.0.0.0 --port 8001 --env-file .env
|
ExecStart=/home/llmadmin/mindnet/.venv/bin/uvicorn app.main:app --host 0.0.0.0 --port 8001 --env-file .env
|
||||||
Restart=always
|
Restart=always
|
||||||
RestartSec=5
|
RestartSec=5
|
||||||
@@ -96,7 +97,7 @@ WantedBy=multi-user.target
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Wartung & Cronjobs
|
## 3. Wartung & Monitoring
|
||||||
|
|
||||||
### 3.1 Regelmäßiger Import (Cron)
|
### 3.1 Regelmäßiger Import (Cron)
|
||||||
Führt den Sync stündlich durch. Nutzt `--purge-before-upsert` für Sauberkeit.
|
Führt den Sync stündlich durch. Nutzt `--purge-before-upsert` für Sauberkeit.
|
||||||
@@ -106,7 +107,16 @@ Führt den Sync stündlich durch. Nutzt `--purge-before-upsert` für Sauberkeit.
|
|||||||
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
|
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
|
### 3.2 Monitoring der Edge Registry (WP-22)
|
||||||
|
Administratoren sollten regelmäßig das Log für unbekannte Kanten-Typen prüfen.
|
||||||
|
* **Pfad:** `data/logs/unknown_edges.jsonl`.
|
||||||
|
* **Aktion:** Wenn neue Typen häufig auftreten, sollten diese als Alias in die `01_edge_vocabulary.md` aufgenommen werden.
|
||||||
|
|
||||||
|
### 3.3 Troubleshooting Guide
|
||||||
|
|
||||||
|
**Fehler: "Registry Initialization Failure" (Neu in v2.7)**
|
||||||
|
* **Symptom:** API startet, aber Kanten werden nicht gewichtet oder Fehlermeldung im Log.
|
||||||
|
* **Lösung:** Prüfen Sie `MINDNET_VOCAB_PATH` in der `.env`. Der Pfad muss absolut sein und auf eine existierende Markdown-Tabelle zeigen.
|
||||||
|
|
||||||
**Fehler: "ModuleNotFoundError: No module named 'st_cytoscape'"**
|
**Fehler: "ModuleNotFoundError: No module named 'st_cytoscape'"**
|
||||||
* Ursache: Alte Dependencies oder falsches Paket installiert.
|
* Ursache: Alte Dependencies oder falsches Paket installiert.
|
||||||
@@ -115,8 +125,6 @@ Führt den Sync stündlich durch. Nutzt `--purge-before-upsert` für Sauberkeit.
|
|||||||
source .venv/bin/activate
|
source .venv/bin/activate
|
||||||
pip uninstall streamlit-cytoscapejs
|
pip uninstall streamlit-cytoscapejs
|
||||||
pip install st-cytoscape
|
pip install st-cytoscape
|
||||||
# Oder sicherheitshalber:
|
|
||||||
pip install -r requirements.txt
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Fehler: "Vector dimension error: expected 768, got 384"**
|
**Fehler: "Vector dimension error: expected 768, got 384"**
|
||||||
|
|||||||
@@ -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`
|
||||||
@@ -3,105 +3,296 @@ doc_type: developer_guide
|
|||||||
audience: developer
|
audience: developer
|
||||||
scope: workflow, testing, architecture, modules
|
scope: workflow, testing, architecture, modules
|
||||||
status: active
|
status: active
|
||||||
version: 2.6
|
version: 2.6.1
|
||||||
context: "Umfassender Guide für Entwickler: Architektur, Modul-Interna, Setup, Git-Workflow und Erweiterungs-Anleitungen."
|
context: "Umfassender Guide für Entwickler: Architektur, Modul-Interna (Deep Dive), Setup, Git-Workflow und Erweiterungs-Anleitungen."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Mindnet Developer Guide & Workflow
|
# Mindnet Developer Guide & Workflow
|
||||||
|
|
||||||
**Quellen:** `developer_guide.md`, `dev_workflow.md`
|
**Quellen:** `developer_guide.md`, `dev_workflow.md`, `Architecture_Audit_v2.6`
|
||||||
|
|
||||||
Dieser Guide vereint das technische Verständnis der Module mit dem operativen Workflow zwischen Windows (Dev) und Linux (Runtime).
|
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).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Die physische Architektur
|
# 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).
|
Mindnet läuft in einer verteilten Umgebung (Post-WP15 Setup).
|
||||||
|
|
||||||
* **Windows 11 (VS Code):** Hier schreibst du Code. **Nie** direkt auf `main` arbeiten!
|
* **Windows 11 (VS Code):** Entwicklungsumgebung. **Nie** direkt auf `main` arbeiten!
|
||||||
* **Raspberry Pi (Gitea):** Der "Safe". Speichert den Code und verwaltet Versionen.
|
* **Beelink (Runtime):** Der Server hostet zwei Instanzen via Systemd:
|
||||||
* **Beelink (Runtime):** Der Server. Hier läuft die Software. Wir nutzen **Systemd-Services**:
|
* **PROD:** API (Port 8001) + UI (Port 8501). Home: `~/mindnet`.
|
||||||
* **PROD:** API (8001) + UI (8501). Ordner: `~/mindnet`.
|
* **DEV:** API (Port 8002) + UI (Port 8502). Home: `~/mindnet_dev`.
|
||||||
* **DEV:** API (8002) + UI (8502). Ordner: `~/mindnet_dev`.
|
* **Gitea (Raspberry Pi):** Versionskontrolle ("Safe"). Speichert den Code.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Projektstruktur & Core-Module
|
## 4. Projektstruktur & Modul-Referenz (Deep Dive)
|
||||||
|
|
||||||
Der Code ist modular in `app` (Logik), `scripts` (CLI) und `config` (Steuerung) getrennt.
|
Das System ist modular aufgebaut. Hier ist die detaillierte Analyse aller Komponenten.
|
||||||
|
|
||||||
### 2.1 Verzeichnisbaum
|
### 4.1 Verzeichnisbaum
|
||||||
|
|
||||||
```text
|
```text
|
||||||
mindnet/
|
mindnet/
|
||||||
├── app/
|
├── app/
|
||||||
│ ├── core/ # Kernlogik
|
│ ├── core/ # Business Logic & Algorithms
|
||||||
│ │ ├── ingestion.py # Async Ingestion Service mit Change Detection
|
│ ├── routers/ # API Interface (FastAPI)
|
||||||
│ │ ├── chunker.py # Smart Chunker Orchestrator
|
│ ├── services/ # External Integrations (LLM, DB)
|
||||||
│ │ ├── derive_edges.py # Edge-Erzeugung (WP03 Logik)
|
│ ├── models/ # Pydantic DTOs
|
||||||
│ │ ├── retriever.py # Scoring & Hybrid Search
|
│ └── frontend/ # UI Logic (Streamlit)
|
||||||
│ │ └── qdrant.py # DB-Verbindung
|
├── config/ # Configuration Files (YAML)
|
||||||
│ ├── routers/ # FastAPI Endpoints
|
├── scripts/ # CLI Tools (Ops & Maintenance)
|
||||||
│ │ ├── query.py # Suche
|
└── vault/ # Local Content Storage
|
||||||
│ │ ├── 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# LLM-Filter für Edges (WP15)
|
|
||||||
│ │ ├── embeddings_client.py# Async Embeddings (HTTPX)
|
|
||||||
│ │ └── discovery.py # Intelligence Logic (WP11)
|
|
||||||
│ ├── frontend/ # UI Logic (WP19 Modularisierung)
|
|
||||||
│ │ ├── ui.py # Main Entrypoint & Routing
|
|
||||||
│ │ ├── ui_config.py # Styles & Constants
|
|
||||||
│ │ ├── ui_api.py # Backend Connector
|
|
||||||
│ │ ├── ui_callbacks.py # State Transitions
|
|
||||||
│ │ ├── ui_utils.py # Helper & Parsing
|
|
||||||
│ │ ├── ui_graph_service.py # Graph Data Logic
|
|
||||||
│ │ ├── ui_graph_cytoscape.py # Modern Graph View (St-Cytoscape)
|
|
||||||
│ │ └── ui_editor.py # Editor View
|
|
||||||
│ └── main.py # Entrypoint der API
|
|
||||||
├── config/ # YAML-Konfigurationen (Single Source of Truth)
|
|
||||||
├── scripts/ # CLI-Tools (Import, Diagnose, Reset)
|
|
||||||
├── tests/ # Pytest Suite & Smoke Scripts
|
|
||||||
└── vault/ # Dein lokaler Markdown-Content
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2.2 Modul-Details (Wie es funktioniert)
|
### 4.2 Frontend Architecture (`app/frontend/`)
|
||||||
|
|
||||||
**Das Frontend (`app.frontend`) - *Neu in v2.6***
|
Das Frontend ist eine Streamlit-App, die sich wie eine Single-Page-Application (SPA) verhält.
|
||||||
* **Router (`ui.py`):** Entscheidet, welche View geladen wird.
|
|
||||||
* **Service-Layer (`ui_graph_service.py`):** Kapselt die Qdrant-Abfragen. Liefert rohe Nodes/Edges, die dann von den Views visualisiert werden.
|
|
||||||
* **Graph Engine:** Wir nutzen `st-cytoscape` für das Layout. Die Logik zur Vermeidung von Re-Renders (Stable Keys, CSS-Selektion) ist essentiell.
|
|
||||||
* **Data Consistency:** Der Editor (`ui_editor.py`) liest Dateien bevorzugt direkt vom Dateisystem ("File System First"), um Datenverlust durch veraltete DB-Einträge zu vermeiden.
|
|
||||||
|
|
||||||
**Der Importer (`scripts.import_markdown`)**
|
| Modul | Status | Verantwortung |
|
||||||
* Das komplexeste Modul.
|
| :--- | :--- | :--- |
|
||||||
* Nutzt `app.core.chunker` und `app.services.semantic_analyzer` (Smart Edges).
|
| **`ui.py`** | 🟢 **Core** | **Main Router.** Initialisiert Session-State und entscheidet anhand der Sidebar-Auswahl, welche View gerendert wird. |
|
||||||
* **Idempotenz:** Nutzt deterministische UUIDv5 IDs. Kann beliebig oft laufen.
|
| **`ui_config.py`** | 🟢 **Config** | **Constants.** Zentraler Ort für Farben (`GRAPH_COLORS`), API-URLs und Timeouts. Änderungen am Look & Feel passieren hier. |
|
||||||
* **Robustheit:** Implementiert Change Detection (Hash) und Retry-Logik.
|
| **`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. |
|
||||||
|
|
||||||
**Der Hybrid Router (`app.routers.chat`)**
|
#### Frontend Design Patterns (Wichtig!)
|
||||||
* Hier liegt die Logik für Intent Detection (WP06).
|
|
||||||
* **Question Detection:** Prüft auf `?` und W-Wörter.
|
|
||||||
* **Priority:** Ruft `llm_service` mit `priority="realtime"` auf (umgeht Import-Warteschlange).
|
|
||||||
|
|
||||||
**Der Retriever (`app.core.retriever`)**
|
1. **Active Inspector Pattern (`ui_graph_cytoscape.py`)**
|
||||||
* Implementiert die Scoring-Formel (`Semantik + Graph + Typ`).
|
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.
|
||||||
* **Hybrid Search:** Lädt dynamisch den Subgraphen (`graph_adapter.expand`).
|
|
||||||
|
|
||||||
**Traffic Control (`app.services.llm_service`)**
|
2. **Resurrection Pattern (`ui_editor.py`)**
|
||||||
* Stellt sicher, dass der Chat responsive bleibt, auch wenn ein Import läuft.
|
Streamlit neigt dazu, Eingaben bei Re-Runs zu "vergessen". Der Editor synchronisiert seinen Inhalt aggressiv in den `session_state`.
|
||||||
* Nutzt `asyncio.Semaphore` (`MINDNET_LLM_BACKGROUND_LIMIT`), um Hintergrund-Jobs zu drosseln.
|
* 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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Lokales Setup (Development)
|
## 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.
|
**Voraussetzungen:** Python 3.10+, Docker, Ollama.
|
||||||
|
|
||||||
**Installation:**
|
**Installation:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 1. Repo & Venv
|
# 1. Repo & Venv
|
||||||
git clone <repo> mindnet
|
git clone <repo> mindnet
|
||||||
@@ -109,7 +300,7 @@ cd mindnet
|
|||||||
python3 -m venv .venv
|
python3 -m venv .venv
|
||||||
source .venv/bin/activate
|
source .venv/bin/activate
|
||||||
|
|
||||||
# 2. Dependencies (inkl. st-cytoscape)
|
# 2. Dependencies
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
|
|
||||||
# 3. Ollama (Nomic ist Pflicht!)
|
# 3. Ollama (Nomic ist Pflicht!)
|
||||||
@@ -117,96 +308,102 @@ ollama pull phi3:mini
|
|||||||
ollama pull nomic-embed-text
|
ollama pull nomic-embed-text
|
||||||
```
|
```
|
||||||
|
|
||||||
**Konfiguration (.env):**
|
**Konfiguration (`.env`):**
|
||||||
|
|
||||||
```ini
|
```ini
|
||||||
QDRANT_URL="http://localhost:6333"
|
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"
|
COLLECTION_PREFIX="mindnet_dev"
|
||||||
VECTOR_DIM=768
|
VECTOR_DIM=768
|
||||||
MINDNET_LLM_BACKGROUND_LIMIT=2
|
MINDNET_LLM_BACKGROUND_LIMIT=2
|
||||||
MINDNET_API_URL="http://localhost:8002"
|
MINDNET_API_URL="http://localhost:8002"
|
||||||
MINDNET_LLM_TIMEOUT=300.0
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Der Entwicklungs-Zyklus
|
## 7. Der Entwicklungs-Zyklus (Workflow)
|
||||||
|
|
||||||
### Phase 1: Windows (Code)
|
### Phase 1: Windows (Code)
|
||||||
1. **Basis holen:** `git checkout main && git pull`.
|
1. **Basis aktualisieren:** `git checkout main && git pull`.
|
||||||
2. **Branch:** `git checkout -b feature/mein-feature`.
|
2. **Branch erstellen:** `git checkout -b feature/mein-feature`.
|
||||||
3. **Code & Push:** `git push origin feature/mein-feature`.
|
3. **Coden & Committen.**
|
||||||
|
4. **Push:** `git push origin feature/mein-feature`.
|
||||||
|
|
||||||
### Phase 2: Beelink (Test)
|
### Phase 2: Beelink (Test / Dev)
|
||||||
1. **SSH:** `ssh user@beelink`.
|
Hier prüfst du, ob dein Code auf Linux läuft.
|
||||||
|
1. **Einloggen:** `ssh user@beelink`.
|
||||||
2. **Ordner:** `cd ~/mindnet_dev`.
|
2. **Ordner:** `cd ~/mindnet_dev`.
|
||||||
3. **Checkout:** `git fetch && git checkout feature/mein-feature && git pull`.
|
3. **Code holen:** `git fetch && git checkout feature/mein-feature && git pull`.
|
||||||
4. **Dependencies:** `pip install -r requirements.txt`.
|
4. **Dependencies:** `pip install -r requirements.txt`.
|
||||||
5. **Restart:** `sudo systemctl restart mindnet-dev`.
|
5. **Restart:** `sudo systemctl restart mindnet-dev`.
|
||||||
6. **Validierung (Smoke Tests):**
|
6. **Validierung (Smoke Tests):**
|
||||||
* **Last-Test:** Starte `python3 -m scripts.import_markdown ...` und chatte gleichzeitig im UI (Port 8502).
|
* **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" ...`
|
* **API Check:** `curl -X POST "http://localhost:8002/ingest/analyze" ...`
|
||||||
|
|
||||||
### Phase 3: Release & Deploy
|
### Phase 3: Release & Deployment (Prod)
|
||||||
|
Wenn alles getestet ist:
|
||||||
1. **Gitea:** Pull Request erstellen und mergen.
|
1. **Gitea:** Pull Request erstellen und mergen.
|
||||||
2. **Beelink (Prod):**
|
2. **Deploy auf Prod (Beelink):**
|
||||||
```bash
|
```bash
|
||||||
cd ~/mindnet
|
cd ~/mindnet
|
||||||
git pull origin main
|
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-prod
|
||||||
|
sudo systemctl restart mindnet-ui-prod
|
||||||
```
|
```
|
||||||
3. **Cleanup:** Branch löschen.
|
3. **Cleanup:** Branch löschen (lokal und remote).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Erweiterungs-Guide: "Teach-the-AI"
|
## 8. Erweiterungs-Guide: "Teach-the-AI"
|
||||||
|
|
||||||
Mindnet lernt durch Konfiguration, nicht durch Training.
|
Mindnet lernt nicht durch Training (Fine-Tuning), sondern durch **Konfiguration** und **Vernetzung**.
|
||||||
|
|
||||||
### Workflow A: Neuen Typ implementieren (z. B. `type: risk`)
|
### Workflow A: Neuen Typ implementieren (z. B. `type: risk`)
|
||||||
1. **Physik (`types.yaml`):**
|
1. **Physik (`config/types.yaml`):**
|
||||||
```yaml
|
```yaml
|
||||||
risk:
|
risk:
|
||||||
retriever_weight: 0.90
|
chunk_profile: sliding_short
|
||||||
edge_defaults: ["blocks"]
|
retriever_weight: 0.90 # Sehr wichtig
|
||||||
|
edge_defaults: ["blocks"] # Automatische Kante
|
||||||
detection_keywords: ["gefahr", "risiko"]
|
detection_keywords: ["gefahr", "risiko"]
|
||||||
```
|
```
|
||||||
2. **Strategie (`decision_engine.yaml`):**
|
2. **Strategie (`config/decision_engine.yaml`):**
|
||||||
```yaml
|
```yaml
|
||||||
DECISION:
|
DECISION:
|
||||||
inject_types: ["value", "risk"] # Füge 'risk' hinzu
|
inject_types: ["value", "risk"] # <--- "risk" hinzufügen
|
||||||
```
|
|
||||||
3. **Visualisierung (`ui_config.py`):**
|
|
||||||
Füge dem `GRAPH_COLORS` Dictionary einen Eintrag hinzu:
|
|
||||||
```python
|
|
||||||
"risk": "#ff6b6b"
|
|
||||||
```
|
```
|
||||||
|
*Ergebnis:* Wenn der Intent `DECISION` erkannt wird, sucht das System nun auch aktiv nach Risiken.
|
||||||
|
|
||||||
### Workflow B: Interview-Schema anpassen (WP07)
|
### Workflow B: Graph-Farben ändern
|
||||||
Wenn Mindnet neue Fragen stellen soll (z.B. "Budget" bei Projekten):
|
1. Öffne `app/frontend/ui_config.py`.
|
||||||
1. **Schema (`types.yaml`):**
|
2. Bearbeite das Dictionary `GRAPH_COLORS`.
|
||||||
```yaml
|
|
||||||
project:
|
```python
|
||||||
schema:
|
GRAPH_COLORS = {
|
||||||
- "Titel"
|
"project": "#FF4B4B",
|
||||||
- "Ziel"
|
"risk": "#8B0000" # Neu
|
||||||
- "Budget (Neu)"
|
}
|
||||||
```
|
```
|
||||||
2. **Kein Code nötig:** Der `One-Shot Extractor` liest dies dynamisch.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6. Tests & Debugging
|
## 9. Tests & Debugging
|
||||||
|
|
||||||
**Unit Tests:**
|
|
||||||
|
|
||||||
|
**Unit Tests (Pytest):**
|
||||||
```bash
|
```bash
|
||||||
pytest tests/test_retriever_basic.py
|
pytest tests/test_retriever_basic.py
|
||||||
pytest tests/test_chunking.py
|
pytest tests/test_chunking.py
|
||||||
```
|
```
|
||||||
|
|
||||||
**Pipeline Tests:**
|
**Pipeline Tests (Integration):**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# JSON-Schema prüfen
|
# JSON-Schema prüfen
|
||||||
python3 -m scripts.payload_dryrun --vault ./test_vault
|
python3 -m scripts.payload_dryrun --vault ./test_vault
|
||||||
@@ -216,7 +413,6 @@ python3 -m scripts.edges_full_check
|
|||||||
```
|
```
|
||||||
|
|
||||||
**E2E Smoke Tests:**
|
**E2E Smoke Tests:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Decision Engine
|
# Decision Engine
|
||||||
python tests/test_wp06_decision.py -p 8002 -e DECISION -q "Soll ich X tun?"
|
python tests/test_wp06_decision.py -p 8002 -e DECISION -q "Soll ich X tun?"
|
||||||
@@ -227,27 +423,35 @@ python tests/test_feedback_smoke.py --url http://localhost:8002/query
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 7. Troubleshooting & One-Liners
|
## 10. Troubleshooting & One-Liners
|
||||||
|
|
||||||
**DB komplett zurücksetzen (Vorsicht!):**
|
**DB komplett zurücksetzen (Vorsicht!):**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
# --yes überspringt die Bestätigung
|
||||||
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet_dev" --yes
|
python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet_dev" --yes
|
||||||
```
|
```
|
||||||
|
|
||||||
**Einen einzelnen File inspizieren (Parser-Sicht):**
|
**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
|
```bash
|
||||||
python3 tests/inspect_one_note.py --file ./vault/MeinFile.md
|
python3 tests/inspect_one_note.py --file ./vault/MeinFile.md
|
||||||
```
|
```
|
||||||
|
|
||||||
**Live-Logs sehen:**
|
**Live-Logs sehen:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
journalctl -u mindnet-dev -f
|
journalctl -u mindnet-dev -f
|
||||||
journalctl -u mindnet-ui-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:**
|
**"Read timed out" im Frontend:**
|
||||||
* Ursache: Backend braucht für Smart Edges länger als 60s.
|
* **Ursache:** Smart Edges brauchen länger als 60s.
|
||||||
* Lösung: `MINDNET_API_TIMEOUT=300.0` in `.env` setzen.
|
* **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.
|
||||||
@@ -2,18 +2,18 @@
|
|||||||
doc_type: roadmap
|
doc_type: roadmap
|
||||||
audience: product_owner, developer
|
audience: product_owner, developer
|
||||||
status: active
|
status: active
|
||||||
version: 2.6
|
version: 2.7
|
||||||
context: "Aktuelle Planung für kommende Features (ab WP16), Release-Strategie und Historie der abgeschlossenen WPs."
|
context: "Aktuelle Planung für kommende Features (ab WP16), Release-Strategie und Historie der abgeschlossenen WPs."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Mindnet Active Roadmap
|
# Mindnet Active Roadmap
|
||||||
|
|
||||||
**Aktueller Stand:** v2.6.0 (Post-WP19)
|
**Aktueller Stand:** v2.6.0 (Post-WP15/WP19)
|
||||||
**Fokus:** Visualisierung, Exploration & Deep Search.
|
**Fokus:** Visualisierung, Exploration & Intelligent Ingestion.
|
||||||
|
|
||||||
## 1. Programmstatus
|
## 1. Programmstatus
|
||||||
|
|
||||||
Wir haben mit der Implementierung des Graph Explorers (WP19) einen Meilenstein in **Phase E (Maintenance & Scaling)** erreicht. Die Architektur ist nun modular. Der nächste Schritt (WP19a) vertieft die Analyse-Fähigkeiten.
|
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 | Fokus | Status |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
@@ -40,17 +40,55 @@ Eine Übersicht der implementierten Features zum schnellen Auffinden von Funktio
|
|||||||
| **WP-05** | RAG-Chat | Integration von Ollama (`phi3`) und Context-Enrichment im Prompt. |
|
| **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-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-07** | Interview-Assistent | One-Shot Extraction: Erzeugt Markdown-Drafts aus User-Input. |
|
||||||
|
| **WP-08** | Interview-Assistent | One-Shot Extraction: Erzeugt Markdown-Drafts aus User-Input. |
|
||||||
|
| **WP-09** | Interview-Assistent | One-Shot Extraction: Erzeugt Markdown-Drafts aus User-Input. |
|
||||||
| **WP-10** | Web UI | Streamlit-Frontend als Ersatz für das Terminal. |
|
| **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-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-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). |
|
| **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. |
|
| **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. |
|
||||||
|
| **WP-20** | Cloud Hybrid Mode | Nutzung von Public LLM für schnellere Verarbeitung und bestimmte Aufgaben |
|
||||||
|
| **WP-21** | Semantic Graph Routing & Canonical Edges | Transformation des Graphen von statischen Verbindungen zu dynamischen, kontextsensitiven Pfaden. Das System soll verstehen, *welche* Art von Verbindung für die aktuelle Frage relevant ist ("Warum?" vs. "Was kommt danach?"). |
|
||||||
|
| **WP-22** | **Content Lifecycle & Registry** | **Ergebnis:** SSOT via `01_edge_vocabulary.md`, Alias-Mapping, Status-Scoring (`stable`/`draft`) und Modularisierung der Scoring-Engine. |
|
||||||
|
|
||||||
|
### 2.1 WP-22 Lessons Learned
|
||||||
|
* **Architektur:** Die Trennung von `retriever.py` und `retriever_scoring.py` war notwendig, um LLM-Context-Limits zu wahren und die Testbarkeit der mathematischen Formeln zu erhöhen.
|
||||||
|
* **Kanten-Validierung:** Die Edge Registry muss beim Start explizit initialisiert werden (Singleton), um "Lazy Loading" Probleme in der API zu vermeiden.
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Offene Workpackages (Planung)
|
## 3. Offene Workpackages (Planung)
|
||||||
|
|
||||||
Diese Features stehen als nächstes an.
|
### WP-08 – Self-Tuning v1/v2 (geplant)
|
||||||
|
Diese Features stehen als nächstes an oder befinden sich in der Umsetzung.
|
||||||
|
**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-19a – Graph Intelligence & Discovery (Sprint-Fokus)
|
### WP-19a – Graph Intelligence & Discovery (Sprint-Fokus)
|
||||||
**Status:** 🚀 Startklar
|
**Status:** 🚀 Startklar
|
||||||
@@ -59,11 +97,26 @@ Diese Features stehen als nächstes an.
|
|||||||
* **Filter-Logik:** "Zeige nur Wege, die zu `type:decision` führen".
|
* **Filter-Logik:** "Zeige nur Wege, die zu `type:decision` führen".
|
||||||
* **Chunk Inspection:** Umschaltbare Granularität (Notiz vs. Chunk) zur Validierung des Smart Chunkers.
|
* **Chunk Inspection:** Umschaltbare Granularität (Notiz vs. Chunk) zur Validierung des Smart Chunkers.
|
||||||
|
|
||||||
### WP-16 – Auto-Discovery & Enrichment
|
### 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
|
**Status:** 🟡 Geplant
|
||||||
**Ziel:** Automatisches Erkennen von fehlenden Kanten in "dummem" Text *vor* der Speicherung.
|
**Ziel:** Das System soll "dumme" Textdateien beim Import automatisch analysieren, strukturieren und anreichern, bevor sie gespeichert werden.
|
||||||
* **Problem:** Nutzer vergessen Wikilinks.
|
**Kern-Features:**
|
||||||
* **Lösung:** Ein "Enricher" scannt Text vor dem Import, findet Keywords (z.B. "Mindnet") und schlägt Links vor (`[[Mindnet]]`).
|
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)
|
### WP-17 – Conversational Memory (Gedächtnis)
|
||||||
**Status:** 🟡 Geplant
|
**Status:** 🟡 Geplant
|
||||||
@@ -77,11 +130,44 @@ Diese Features stehen als nächstes an.
|
|||||||
* **Feature:** Cronjob `check_graph_integrity.py`.
|
* **Feature:** Cronjob `check_graph_integrity.py`.
|
||||||
* **Funktion:** Findet "Dangling Edges" (Links auf gelöschte Notizen) und repariert/löscht sie.
|
* **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)
|
### WP-20 – Cloud Hybrid Mode (Optional)
|
||||||
**Status:** ⚪ Optional
|
**Status:** ⚪ Optional
|
||||||
**Ziel:** "Turbo-Modus" für Massen-Imports.
|
**Ziel:** "Turbo-Modus" für Massen-Imports.
|
||||||
* **Konzept:** Switch in `.env`, um statt Ollama (Lokal) auf Google Gemini (Cloud) umzuschalten.
|
* **Konzept:** Switch in `.env`, um statt Ollama (Lokal) auf Google Gemini (Cloud) umzuschalten.
|
||||||
|
|
||||||
|
### WP-21 – Semantic Graph Routing & Canonical Edges
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Ziel:** Transformation des Graphen von statischen Verbindungen zu dynamischen, kontextsensitiven Pfaden. Das System soll verstehen, *welche* Art von Verbindung für die aktuelle Frage relevant ist ("Warum?" vs. "Was kommt danach?").
|
||||||
|
**Problem:**
|
||||||
|
1. **Statische Gewichte:** Aktuell ist `caused_by` immer gleich wichtig (z.B. 1.2), egal ob der User nach Ursachen oder Definitionen fragt.
|
||||||
|
2. **Vokabular-Zwang:** Der Nutzer muss exakte System-Begriffe (`caused_by`) verwenden. Natürliche Synonyme (`führt_zu`, `ausgelöst_durch`) werden als unbekannte Kanten ignoriert oder nicht speziell gewichtet.
|
||||||
|
|
||||||
|
**Lösungsansätze & Kern-Features:**
|
||||||
|
1. **Canonical Edge Mapping (Middleware):**
|
||||||
|
* Einführung einer Mapping-Schicht (z.B. in `edges.yaml`).
|
||||||
|
* *Funktion:* Normalisiert User-Vokabular (`leads_to`, `triggers`, `starts`) automatisch auf System-Typen (`caused_by`).
|
||||||
|
* *Benefit:* Maximale Schreibfreiheit für den Nutzer bei gleichzeitiger System-Konsistenz.
|
||||||
|
2. **Dynamic Intent Boosting (Query-Time):**
|
||||||
|
* Erweiterung der `Decision Engine`.
|
||||||
|
* *Funktion:* Der Router erkennt den Intent der Frage (z.B. `EXPLANATION` für "Warum-Fragen") und injiziert temporäre `edge_weights` in den Retriever.
|
||||||
|
* *Beispiel:* Bei "Warum ist das passiert?" wird `caused_by` von 1.2 auf 2.5 geboostet, während `related_to` auf 0.1 sinkt.
|
||||||
|
3. **Graph Reasoning:**
|
||||||
|
* Der Retriever priorisiert Pfade, die dem semantischen Muster der Frage entsprechen, nicht nur dem Text-Match.
|
||||||
|
|
||||||
|
### WP-22 – Content Lifecycle & Meta-Configuration
|
||||||
|
**Status:** ✅ Fertig (v2.7.0)
|
||||||
|
**Ziel:** Professionalisierung der Datenhaltung durch Einführung eines Lebenszyklus und "Docs-as-Code" Konfiguration.
|
||||||
|
**Lösungsansätze:**
|
||||||
|
1. **Status-Logik (Frontmatter):** `stable` vs. `draft` Scoring Modifier.
|
||||||
|
2. **Single Source of Truth (SSOT):** Die Registry nutzt `01_edge_vocabulary.md` als führende Konfiguration.
|
||||||
|
3. **Self-Learning Loop:** Protokollierung unbekannter Kanten in `unknown_edges.jsonl`.
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Abhängigkeiten & Release-Plan
|
## 4. Abhängigkeiten & Release-Plan
|
||||||
@@ -91,4 +177,12 @@ graph TD
|
|||||||
WP19(Graph Viz) --> WP19a(Discovery)
|
WP19(Graph Viz) --> WP19a(Discovery)
|
||||||
WP19a --> WP17(Memory)
|
WP19a --> WP17(Memory)
|
||||||
WP15(Smart Edges) --> WP16(Auto-Discovery)
|
WP15(Smart Edges) --> WP16(Auto-Discovery)
|
||||||
|
WP15 --> WP14(Refactoring)
|
||||||
WP03(Import) --> WP18(Health Check)
|
WP03(Import) --> WP18(Health Check)
|
||||||
|
WP03 --> WP13(MCP)
|
||||||
|
WP04 --> WP13(MCP)
|
||||||
|
WP06(Decision Engine) --> WP21(Semantic Routing)
|
||||||
|
WP03(Import Pipeline) --> WP21
|
||||||
|
WP21 --> WP22(Lifecycle & Registry)
|
||||||
|
WP22 --> WP14
|
||||||
|
WP15(Smart Edges) --> WP21
|
||||||
@@ -0,0 +1,318 @@
|
|||||||
|
---
|
||||||
|
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.
|
||||||
|
```
|
||||||
|
|
||||||
|
## WP-21: Semantic Graph Routing
|
||||||
|
|
||||||
|
**Status:** 🟡 Geplant
|
||||||
|
**Fokus:** Graph-Logik, Retrieval-Präzision, User-Experience.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der Lead Architect für "Mindnet" (v2.7.0).
|
||||||
|
Wir starten **WP-21: Semantic Graph Routing**.
|
||||||
|
|
||||||
|
**Status Quo:**
|
||||||
|
- Edge-Gewichte sind statisch in `retriever.yaml` definiert.
|
||||||
|
- User müssen exakte Edge-Typen (`caused_by`) nutzen; Synonyme werden nicht erkannt.
|
||||||
|
- Der `HybridRouter` (WP-06) erkennt Intents, nutzt diese aber nur für Note-Typen (`inject_types`), nicht für Kanten.
|
||||||
|
|
||||||
|
**Dein Auftrag (WP-21):**
|
||||||
|
Implementiere eine semantische Steuerung für den Graphen, die (A) Schreibfreiheit erlaubt und (B) die Suche kontextabhängig macht.
|
||||||
|
|
||||||
|
**Technische Anforderungen:**
|
||||||
|
|
||||||
|
1. **Canonical Edge Mapping (Ingestion-Layer):**
|
||||||
|
- Erstelle eine neue Config `config/edge_mappings.yaml` (oder erweitere `types.yaml`).
|
||||||
|
- Definiere Mappings: `User-Synonym` -> `System-Canonical` (z.B. `["führt_zu", "resultat"]` -> `caused_by`).
|
||||||
|
- Erweitere `import_markdown.py` / `Chunker`: Mappe beim Einlesen alle Inline/Callout-Kanten auf den Canonical-Typ, *bevor* sie in Qdrant gespeichert werden. (Speichere das Original ggf. als Metadatum).
|
||||||
|
|
||||||
|
2. **Dynamic Boosting (Retrieval-Layer):**
|
||||||
|
- Erweitere die `DecisionEngine` (`app/services/decision_engine.py` und YAML).
|
||||||
|
- Füge `boost_edges` zu den Strategien hinzu (z.B. `strategy: EXPLANATION` -> `boost: {caused_by: 2.0}`).
|
||||||
|
- Passe den `Retriever` an, um diese dynamischen Gewichte im Query-Moment mit den statischen Config-Werten zu verrechnen (Multiplikator).
|
||||||
|
|
||||||
|
**Zielbild:**
|
||||||
|
- User schreibt: `[[rel:wegen Systemfehler]]`.
|
||||||
|
- System speichert: `caused_by` -> `Systemfehler`.
|
||||||
|
- User fragt: "Warum Absturz?".
|
||||||
|
- System erkennt "Warum" -> Boostet `caused_by` -> Findet die Notiz präzise.
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Abwärtskompatibilität wahren (alte Kanten müssen weiter funktionieren).
|
||||||
|
- Performance: Das Mapping muss O(1) sein (Hashmap Lookup), kein LLM-Call pro Kante!
|
||||||
|
|
||||||
|
Bitte bestätige die Übernahme, erstelle die `edge_mappings.yaml` Struktur und skizziere die Anpassung im `Retriever`.
|
||||||
|
---
|
||||||
|
|
||||||
|
### Warum diese Lösungsansätze?
|
||||||
|
|
||||||
|
1. **Warum Mapping beim Import (Ingestion) und nicht bei der Suche?**
|
||||||
|
* **Performance:** Es ist viel effizienter, die Daten *einmal* beim Schreiben zu säubern ("Canonical Form"), als bei *jeder* Suche tausende Synonyme abzufragen.
|
||||||
|
* **Konsistenz:** Der Graph in Qdrant bleibt sauber. `caused_by` ist immer `caused_by`, egal ob der User `wegen`, `durch` oder `ursache` geschrieben hat.
|
||||||
|
|
||||||
|
2. **Warum Boosting über die Decision Engine?**
|
||||||
|
* Wir haben den `HybridRouter` (aus WP-06) schon. Er "versteht" bereits, was der User will (`DECISION` vs `EMPATHY`).
|
||||||
|
* Es ist der logisch perfekte Ort, um zu sagen: "Wenn der User im Analyse-Modus ist, sind Fakten-Kanten wichtiger als Gefühls-Kanten."
|
||||||
|
|
||||||
|
Damit hast du das perfekte Paket für den nächsten Entwicklungsschritt geschnürt!
|
||||||
|
|
||||||
|
## WP-22: Content Lifecycle & Meta-Config
|
||||||
|
|
||||||
|
**Status:** 🚀 Startklar
|
||||||
|
**Fokus:** Ingestion-Filter, Scoring-Logik, Registry-Architektur.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Du bist der Lead Architect für "Mindnet" (v2.7).
|
||||||
|
Wir starten ein umfassendes Architektur-Paket: **WP-22: Graph Intelligence & Lifecycle**.
|
||||||
|
|
||||||
|
**Kontext:**
|
||||||
|
Wir professionalisieren die Datenhaltung ("Docs as Code") und machen die Suche kontextsensitiv.
|
||||||
|
Wir haben eine Markdown-Datei (`01_edge_vocabulary.md`), die als Single-Source-of-Truth für Kanten-Typen dient.
|
||||||
|
|
||||||
|
**Dein Auftrag:**
|
||||||
|
Implementiere (A) den Content-Lifecycle, (B) die Edge-Registry und (C) das Semantic Routing.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Teil A: Content Lifecycle (Ingestion Logic)
|
||||||
|
Steuerung über Frontmatter `status`:
|
||||||
|
1. **System-Dateien (No-Index):**
|
||||||
|
* Wenn `status` in `['system', 'template']`: **Hard Skip**. Datei wird nicht vektorisiert.
|
||||||
|
2. **Wissens-Status (Scoring):**
|
||||||
|
* Wenn `status` in `['draft', 'active', 'stable']`: Status wird im Payload gespeichert.
|
||||||
|
* **ToDo:** Erweitere `scoring.py`, damit `stable` Notizen einen Bonus erhalten (`x 1.2`), `drafts` einen Malus (`x 0.5`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Teil B: Central Edge Registry & Validation
|
||||||
|
1. **Registry Klasse:**
|
||||||
|
* Erstelle `EdgeRegistry` (Singleton).
|
||||||
|
* Liest beim Start `01_User_Manual/01_edge_vocabulary.md` (Regex parsing der Tabelle).
|
||||||
|
* Stellt `canonical_types` und `aliases` bereit.
|
||||||
|
2. **Rückwärtslogik (Learning):**
|
||||||
|
* Prüfe beim Import jede Kante gegen die Registry.
|
||||||
|
* Unbekannte Typen werden **nicht** verworfen, sondern in `data/logs/unknown_edges.jsonl` geloggt (für späteres Review).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Teil C: Semantic Graph Routing (Dynamic Boosting)
|
||||||
|
**Ziel:** Die Bedeutung einer Kante soll sich je nach Frage-Typ ändern ("Warum" vs. "Wie").
|
||||||
|
|
||||||
|
**Architektur-Vorgabe (WICHTIG):**
|
||||||
|
Die Gewichtung findet **Pre-Retrieval** (im Scoring-Algorithmus) statt, **nicht** im LLM-Prompt.
|
||||||
|
|
||||||
|
1. **Decision Engine (`decision_engine.yaml`):**
|
||||||
|
* Füge `boost_edges` zu Strategien hinzu.
|
||||||
|
* *Beispiel:* `EXPLANATION` (Warum-Fragen) -> Boost `caused_by: 2.5`, `derived_from: 2.0`.
|
||||||
|
* *Beispiel:* `ACTION` (Wie-Fragen) -> Boost `next: 3.0`, `depends_on: 2.0`.
|
||||||
|
2. **Scoring-Logik (`scoring.py`):**
|
||||||
|
* Der `Retriever` erhält vom Router die `boost_edges` Map.
|
||||||
|
* Berechne Score: `BaseScore * (1 + ConfigWeight + DynamicBoost)`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Deine Aufgaben:**
|
||||||
|
1. Zeige die `EdgeRegistry` Klasse (Parsing Logik).
|
||||||
|
2. Zeige die Integration in `ingestion.py` (Status-Filter & Edge-Validierung).
|
||||||
|
3. Zeige die Erweiterung in `scoring.py` (Status-Gewicht & Dynamic Edge Boosting).
|
||||||
|
|
||||||
|
Bitte bestätige die Übernahme dieses Architektur-Pakets.
|
||||||
+1
-1
@@ -34,4 +34,4 @@ streamlit>=1.39.0
|
|||||||
|
|
||||||
# Visualization (Parallelbetrieb)
|
# Visualization (Parallelbetrieb)
|
||||||
streamlit-agraph>=0.0.45
|
streamlit-agraph>=0.0.45
|
||||||
st-cytoscape>=1.0.0
|
st-cytoscape
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
{
|
|
||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
||||||
"title": "mindnet_chunk",
|
|
||||||
"type": "object",
|
|
||||||
"description": "Chunk-Payload (Qdrant). Kompatibel mit Alt-Feldern und neuen Feldern für Export/Roundtrip.",
|
|
||||||
"required": ["id", "note_id", "chunk_index", "path"],
|
|
||||||
"properties": {
|
|
||||||
"id": { "type": "string" },
|
|
||||||
"scope": { "type": "string", "enum": ["chunk"] },
|
|
||||||
"note_id": { "type": "string" },
|
|
||||||
"note_title": { "type": "string" },
|
|
||||||
"note_type": { "type": "string" },
|
|
||||||
"note_status": { "type": "string" },
|
|
||||||
"type": { "type": "string", "description": "Legacy: früherer Chunk-Typ; kann dem Note-Typ entsprechen" },
|
|
||||||
"area": { "type": "string" },
|
|
||||||
"project": { "type": "string" },
|
|
||||||
"tags": { "type": "array", "items": { "type": "string" } },
|
|
||||||
|
|
||||||
"note_path": { "type": "string" },
|
|
||||||
"path": { "type": "string" },
|
|
||||||
|
|
||||||
"chunk_index": { "type": "integer" },
|
|
||||||
"section_title":{ "type": ["string","null"] },
|
|
||||||
"section_path": { "type": ["string","null"] },
|
|
||||||
|
|
||||||
"char_start": { "type": ["integer","null"] },
|
|
||||||
"char_end": { "type": ["integer","null"] },
|
|
||||||
"char_len": { "type": "integer" },
|
|
||||||
|
|
||||||
"token_count": { "type": "integer", "description": "Legacy: frühere Token-Zahl" },
|
|
||||||
"token_est": { "type": "integer", "description": "Neue grobe Token-Schätzung (≈ len(text)/4)" },
|
|
||||||
|
|
||||||
"neighbors": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"prev": { "type": ["string","null"] },
|
|
||||||
"next": { "type": ["string","null"] }
|
|
||||||
},
|
|
||||||
"additionalProperties": false
|
|
||||||
},
|
|
||||||
|
|
||||||
"text": { "type": "string" },
|
|
||||||
"text_sha256": { "type": "string", "pattern": "^sha256:[0-9a-fA-F]{64}$" },
|
|
||||||
"lang": { "type": "string" },
|
|
||||||
|
|
||||||
"wikilinks": { "type": "array", "items": { "type": "string" } },
|
|
||||||
"external_links": {
|
|
||||||
"type": "array",
|
|
||||||
"items": {
|
|
||||||
"anyOf": [
|
|
||||||
{ "type": "string" },
|
|
||||||
{
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"href": { "type": "string" },
|
|
||||||
"label": { "type": ["string","null"] }
|
|
||||||
},
|
|
||||||
"required": ["href"],
|
|
||||||
"additionalProperties": false
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"references": {
|
|
||||||
"type": "array",
|
|
||||||
"items": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"target_id": { "type": "string" },
|
|
||||||
"kind": { "type": "string" }
|
|
||||||
},
|
|
||||||
"required": ["target_id","kind"],
|
|
||||||
"additionalProperties": true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
"embed_model": { "type": "string" },
|
|
||||||
"embed_dim": { "type": "integer" },
|
|
||||||
"embed_version": { "type": "integer" },
|
|
||||||
|
|
||||||
"created_at": { "type": "string" }
|
|
||||||
},
|
|
||||||
|
|
||||||
"allOf": [
|
|
||||||
{ "anyOf": [ { "required": ["token_count"] }, { "required": ["token_est"] } ] },
|
|
||||||
{ "anyOf": [ { "required": ["type"] }, { "required": ["note_type"] } ] }
|
|
||||||
],
|
|
||||||
|
|
||||||
"additionalProperties": true
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
{
|
|
||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
||||||
"title": "mindnet_edge",
|
|
||||||
"type": "object",
|
|
||||||
"description": "Edge-Payload (Qdrant). Unterstützt Legacy (edge_type/src_id/dst_id) und neues Schema (kind/source_id/target_id/note_id/status).",
|
|
||||||
|
|
||||||
"properties": {
|
|
||||||
"scope": { "type": "string", "enum": ["note","chunk"] },
|
|
||||||
|
|
||||||
"edge_type": { "type": "string", "description": "Legacy: z. B. references/backlink/belongs_to/prev/next" },
|
|
||||||
"src_id": { "type": "string", "description": "Legacy: source_id" },
|
|
||||||
"dst_id": { "type": "string", "description": "Legacy: target_id" },
|
|
||||||
|
|
||||||
"kind": { "type": "string", "description": "Neu: z. B. references/backlink/belongs_to/prev/next" },
|
|
||||||
"source_id": { "type": "string" },
|
|
||||||
"target_id": { "type": "string" },
|
|
||||||
"note_id": { "type": "string", "description": "Owner-Note für diesen Edge (Filter/Purge)" },
|
|
||||||
"status": { "type": "string", "description": "optional, z. B. 'unresolved'" },
|
|
||||||
|
|
||||||
"weight": { "type": "number" },
|
|
||||||
"meta": { "type": "object" },
|
|
||||||
"created_at":{ "type": "string" }
|
|
||||||
},
|
|
||||||
|
|
||||||
"anyOf": [
|
|
||||||
{ "required": ["src_id", "dst_id", "edge_type", "scope"] },
|
|
||||||
{ "required": ["source_id", "target_id", "kind", "scope"] }
|
|
||||||
],
|
|
||||||
|
|
||||||
"additionalProperties": true
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
{
|
|
||||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
||||||
"title": "mindnet note payload",
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"note_id": { "type": "string" },
|
|
||||||
"title": { "type": ["string","null"] },
|
|
||||||
"type": { "type": ["string","null"] },
|
|
||||||
"status": { "type": ["string","null"] },
|
|
||||||
"created": { "type": ["string","null"] },
|
|
||||||
"updated": { "type": ["string","null"] },
|
|
||||||
"path": { "type": ["string","null"] },
|
|
||||||
"tags": { "type": ["array","null"], "items": { "type": "string" } },
|
|
||||||
"area": { "type": ["string","null"] },
|
|
||||||
"project": { "type": ["string","null"] },
|
|
||||||
"source": { "type": ["string","null"] },
|
|
||||||
"lang": { "type": ["string","null"] },
|
|
||||||
"slug": { "type": ["string","null"] },
|
|
||||||
"aliases": { "type": ["array","null"], "items": { "type": "string" } },
|
|
||||||
|
|
||||||
"fulltext": { "type": ["string","null"] },
|
|
||||||
"references": { "type": ["array","null"], "items": { "type": "string" } },
|
|
||||||
|
|
||||||
"hash_fulltext": { "type": ["string","null"], "pattern": "^[a-f0-9]{64}$" },
|
|
||||||
"hash_signature": { "type": ["string","null"] },
|
|
||||||
|
|
||||||
"hash_body": { "type": ["string","null"], "pattern": "^[a-f0-9]{64}$" },
|
|
||||||
"hash_frontmatter": { "type": ["string","null"], "pattern": "^[a-f0-9]{64}$" },
|
|
||||||
"hash_full": { "type": ["string","null"], "pattern": "^[a-f0-9]{64}$" },
|
|
||||||
|
|
||||||
"hashes": {
|
|
||||||
"type": ["object","null"],
|
|
||||||
"description": "Mapping: <mode>:<source>:<normalize> -> sha256 hex",
|
|
||||||
"patternProperties": {
|
|
||||||
"^(body|frontmatter|full):(parsed|raw):(canonical|none)$": {
|
|
||||||
"type": "string",
|
|
||||||
"pattern": "^[a-f0-9]{64}$"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"additionalProperties": false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": ["note_id"],
|
|
||||||
"additionalProperties": true
|
|
||||||
}
|
|
||||||
@@ -3,241 +3,222 @@
|
|||||||
"""
|
"""
|
||||||
resolve_unresolved_references.py — Unaufgelöste Wikilinks in Qdrant nachträglich auflösen
|
resolve_unresolved_references.py — Unaufgelöste Wikilinks in Qdrant nachträglich auflösen
|
||||||
|
|
||||||
Version: 1.0.0 (2025-09-05)
|
Version: 1.1.0 (Fixed for v2.6 Architecture)
|
||||||
|
|
||||||
Zweck
|
Zweck
|
||||||
------
|
------
|
||||||
- Findet Edges in {prefix}_edges mit payload.status=="unresolved" und versucht, den Zielknoten
|
- Findet Edges in {prefix}_edges mit payload.status=="unresolved".
|
||||||
anhand bereits vorhandener Notes in {prefix}_notes aufzulösen.
|
- Baut einen In-Memory Index aller Notizen (Titel/Alias -> ID).
|
||||||
- Aktualisiert die Edges (setzt target_id, entfernt status, setzt resolution), und erzeugt
|
- Aktualisiert die Edges (setzt target_id, entfernt status).
|
||||||
– NUR für Note-Level 'references' – die symmetrische 'backlink'-Kante.
|
- Erzeugt symmetrische 'backlink'-Kanten für 'references'.
|
||||||
|
|
||||||
Warum?
|
|
||||||
------
|
|
||||||
- Beim ersten Import können Links auf (noch) nicht existierende Notizen zeigen.
|
|
||||||
- Sobald die Zielnotiz später existiert, kann dieses Skript die Kanten reparieren.
|
|
||||||
|
|
||||||
Aufruf
|
Aufruf
|
||||||
------
|
------
|
||||||
# Dry-Run (Standard):
|
python3 -m scripts.resolve_unresolved_references --apply
|
||||||
python3 -m scripts.resolve_unresolved_references --prefix mindnet
|
|
||||||
|
|
||||||
# Anwenden:
|
|
||||||
python3 -m scripts.resolve_unresolved_references --prefix mindnet --apply
|
|
||||||
|
|
||||||
# Optional: nur X Edges anfassen
|
|
||||||
python3 -m scripts.resolve_unresolved_references --prefix mindnet --apply --limit 500
|
|
||||||
|
|
||||||
Parameter
|
|
||||||
---------
|
|
||||||
--prefix : Collection-Prefix (Default: aus Env COLLECION_PREFIX oder "mindnet")
|
|
||||||
--apply : Änderungen tatsächlich schreiben (ohne --apply = Dry-Run)
|
|
||||||
--limit : Max. Anzahl unaufgelöster Edges, die in diesem Lauf bearbeitet werden (Default: keine Begrenzung)
|
|
||||||
--batch : Upsert-Batchgröße (Default: 512)
|
|
||||||
|
|
||||||
Voraussetzungen / Hinweise
|
|
||||||
--------------------------
|
|
||||||
- Bitte im aktivierten venv laufen lassen (deine Umgebung: `.venv`).
|
|
||||||
- Qdrant-URL/Key/Prefix/Vektor-Dim werden wie üblich aus ENV gelesen (sieh app/core/qdrant.py). # noqa
|
|
||||||
- Nutzt die vorhandenen Utilities:
|
|
||||||
- app/core/qdrant.py (Client/Collections)
|
|
||||||
- app/core/qdrant_points.py (points_for_edges/upsert_batch)
|
|
||||||
- app/core/derive_edges.py (build_note_index/resolve_target)
|
|
||||||
|
|
||||||
Änderungshistorie
|
|
||||||
-----------------
|
|
||||||
1.0.0 Erstveröffentlichung.
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
import logging
|
||||||
import json
|
import json
|
||||||
from typing import Any, Dict, List, Tuple, Iterable
|
import uuid
|
||||||
|
from typing import List, Dict, Any, Iterable
|
||||||
|
|
||||||
from qdrant_client import QdrantClient
|
from qdrant_client import models
|
||||||
from qdrant_client.http import models as rest
|
from app.core.qdrant import QdrantConfig, get_client
|
||||||
|
from app.core.qdrant_points import points_for_edges
|
||||||
from app.core.qdrant import QdrantConfig, get_client, ensure_collections, collection_names # :contentReference[oaicite:3]{index=3}
|
|
||||||
from app.core.qdrant_points import points_for_edges, upsert_batch # :contentReference[oaicite:4]{index=4}
|
|
||||||
from app.core.derive_edges import build_note_index, resolve_target # :contentReference[oaicite:5]{index=5}
|
|
||||||
|
|
||||||
|
|
||||||
def _scroll(client: QdrantClient, **kwargs):
|
|
||||||
"""
|
|
||||||
Wrapper um qdrant_client.scroll() für unterschiedliche Client-Versionen:
|
|
||||||
neuere: (points, next_offset)
|
|
||||||
ältere: (points, next_page_offset, _)
|
|
||||||
"""
|
|
||||||
res = client.scroll(**kwargs)
|
|
||||||
if isinstance(res, tuple):
|
|
||||||
if len(res) == 2:
|
|
||||||
points, next_off = res
|
|
||||||
else:
|
|
||||||
# ältere Signatur: (points, next_off, _)
|
|
||||||
points, next_off, _ = res[0], res[1], res[2]
|
|
||||||
else:
|
|
||||||
# sehr alte Clients -> konservativ behandeln
|
|
||||||
points, next_off = res, None
|
|
||||||
return points, next_off
|
|
||||||
|
|
||||||
|
|
||||||
def _load_all_notes(client: QdrantClient, notes_col: str) -> List[Dict[str, Any]]:
|
|
||||||
notes: List[Dict[str, Any]] = []
|
|
||||||
next_off = None
|
|
||||||
while True:
|
|
||||||
pts, next_off = _scroll(
|
|
||||||
client,
|
|
||||||
collection_name=notes_col,
|
|
||||||
with_payload=True,
|
|
||||||
with_vectors=False,
|
|
||||||
limit=1024,
|
|
||||||
offset=next_off,
|
|
||||||
)
|
|
||||||
for p in pts or []:
|
|
||||||
pl = getattr(p, "payload", {}) or {}
|
|
||||||
# Erwartet Felder: note_id, title, path etc. (gemäß Schema) # :contentReference[oaicite:6]{index=6}
|
|
||||||
if pl.get("note_id"):
|
|
||||||
notes.append(pl)
|
|
||||||
if not next_off:
|
|
||||||
break
|
|
||||||
return notes
|
|
||||||
|
|
||||||
|
|
||||||
def _iter_unresolved_edges(client: QdrantClient, edges_col: str) -> Iterable[rest.Record]:
|
|
||||||
"""
|
|
||||||
Liefert alle Edge-Records mit payload.status == 'unresolved' und 'target_label' (string).
|
|
||||||
"""
|
|
||||||
f = rest.Filter(
|
|
||||||
must=[
|
|
||||||
rest.FieldCondition(key="status", match=rest.MatchValue(value="unresolved")),
|
|
||||||
]
|
|
||||||
)
|
|
||||||
next_off = None
|
|
||||||
while True:
|
|
||||||
pts, next_off = _scroll(
|
|
||||||
client,
|
|
||||||
collection_name=edges_col,
|
|
||||||
scroll_filter=f,
|
|
||||||
with_payload=True,
|
|
||||||
with_vectors=False,
|
|
||||||
limit=1024,
|
|
||||||
offset=next_off,
|
|
||||||
)
|
|
||||||
for p in pts or []:
|
|
||||||
pl = getattr(p, "payload", {}) or {}
|
|
||||||
if isinstance(pl.get("target_label"), str):
|
|
||||||
yield p
|
|
||||||
if not next_off:
|
|
||||||
break
|
|
||||||
|
|
||||||
|
# Logging Setup
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
def _make_backlink(source_note_id: str, target_note_id: str, extra: Dict[str, Any]) -> Dict[str, Any]:
|
def _make_backlink(source_note_id: str, target_note_id: str, extra: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Baue eine 'backlink'-Edge-Payload source <- target (note-level).
|
Hilfsfunktion: Erzeugt die Payload für den Backlink.
|
||||||
"""
|
"""
|
||||||
e = {
|
return {
|
||||||
"kind": "backlink",
|
|
||||||
"source_id": target_note_id,
|
"source_id": target_note_id,
|
||||||
"target_id": source_note_id,
|
"target_id": source_note_id,
|
||||||
|
"kind": "backlink",
|
||||||
|
"scope": "note",
|
||||||
|
"text": f"Backlink from {extra.get('alias') or 'note'}",
|
||||||
|
"rule_id": "derived:backlink",
|
||||||
|
"confidence": 0.9
|
||||||
}
|
}
|
||||||
# Metafelder aus dem Original übernehmen (ohne status)
|
|
||||||
copy_keys = ["raw", "alias", "heading", "resolution"]
|
|
||||||
for k in copy_keys:
|
|
||||||
if k in extra:
|
|
||||||
e[k] = extra[k]
|
|
||||||
return e
|
|
||||||
|
|
||||||
|
def build_lookup_index(client, collection_name: str) -> Dict[str, str]:
|
||||||
|
"""
|
||||||
|
Lädt ALLE Notizen und baut ein Mapping:
|
||||||
|
lower(title) -> note_id
|
||||||
|
lower(alias) -> note_id
|
||||||
|
"""
|
||||||
|
logger.info("Building lookup index from existing notes...")
|
||||||
|
lookup = {}
|
||||||
|
|
||||||
|
# Scroll über alle Notizen
|
||||||
|
next_offset = None
|
||||||
|
count = 0
|
||||||
|
while True:
|
||||||
|
records, next_offset = client.scroll(
|
||||||
|
collection_name=collection_name,
|
||||||
|
limit=1000,
|
||||||
|
offset=next_offset,
|
||||||
|
with_payload=True,
|
||||||
|
with_vectors=False
|
||||||
|
)
|
||||||
|
|
||||||
|
for record in records:
|
||||||
|
pl = record.payload or {}
|
||||||
|
nid = pl.get("note_id")
|
||||||
|
if not nid: continue
|
||||||
|
|
||||||
|
# 1. Titel
|
||||||
|
title = pl.get("title")
|
||||||
|
if title:
|
||||||
|
lookup[str(title).lower().strip()] = nid
|
||||||
|
|
||||||
|
# 2. Aliases (WP-11)
|
||||||
|
aliases = pl.get("aliases", [])
|
||||||
|
if isinstance(aliases, str): aliases = [aliases]
|
||||||
|
for a in aliases:
|
||||||
|
lookup[str(a).lower().strip()] = nid
|
||||||
|
|
||||||
|
count += len(records)
|
||||||
|
if next_offset is None:
|
||||||
|
break
|
||||||
|
|
||||||
|
logger.info(f"Index built. Mapped {len(lookup)} terms to {count} unique notes.")
|
||||||
|
return lookup
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
ap = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
ap.add_argument("--prefix", help="Collection-Prefix (Default: Env/COLLECTION_PREFIX oder 'mindnet')")
|
parser.add_argument("--prefix", default=None, help="Collection prefix")
|
||||||
ap.add_argument("--apply", action="store_true", help="Änderungen schreiben (ohne Flag = Dry-Run)")
|
parser.add_argument("--apply", action="store_true", help="Write changes to DB")
|
||||||
ap.add_argument("--limit", type=int, default=0, help="Max. Anzahl unaufgelöster Edges bearbeiten (0 = alle)")
|
parser.add_argument("--limit", type=int, default=0, help="Max edges to process (0=all)")
|
||||||
ap.add_argument("--batch", type=int, default=512, help="Upsert-Batchgröße")
|
parser.add_argument("--batch", type=int, default=100, help="Upsert batch size")
|
||||||
args = ap.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
# Qdrant-Setup
|
|
||||||
cfg = QdrantConfig.from_env()
|
cfg = QdrantConfig.from_env()
|
||||||
if args.prefix:
|
if args.prefix:
|
||||||
cfg.prefix = args.prefix
|
cfg.prefix = args.prefix
|
||||||
|
|
||||||
client = get_client(cfg)
|
client = get_client(cfg)
|
||||||
ensure_collections(client, cfg.prefix, cfg.dim) # sorgt u. a. für 1D-Vektor-Collection bei Edges :contentReference[oaicite:7]{index=7}
|
edges_col = f"{cfg.prefix}_edges"
|
||||||
notes_col, _, edges_col = collection_names(cfg.prefix) # :contentReference[oaicite:8]{index=8}
|
notes_col = f"{cfg.prefix}_notes"
|
||||||
|
|
||||||
# Notes laden & Index bauen
|
# 1. Index aufbauen
|
||||||
notes = _load_all_notes(client, notes_col)
|
try:
|
||||||
idx = build_note_index(notes) # (by_id, by_slug, by_file_slug) :contentReference[oaicite:9]{index=9}
|
lookup_index = build_lookup_index(client, notes_col)
|
||||||
|
except Exception as e:
|
||||||
# Unresolved-Edges scannen
|
logger.error(f"Failed to build index: {e}")
|
||||||
to_fix: List[dict] = []
|
|
||||||
backlinks: List[dict] = []
|
|
||||||
processed = 0
|
|
||||||
resolved = 0
|
|
||||||
|
|
||||||
for rec in _iter_unresolved_edges(client, edges_col):
|
|
||||||
if args.limit and processed >= args.limit:
|
|
||||||
break
|
|
||||||
processed += 1
|
|
||||||
|
|
||||||
pl = dict(rec.payload or {})
|
|
||||||
kind = pl.get("kind") or "references"
|
|
||||||
src = pl.get("source_id")
|
|
||||||
tgt_label = pl.get("target_label") or pl.get("target_id") # Fallback
|
|
||||||
|
|
||||||
# Zielauflösung
|
|
||||||
resolved_id, how = resolve_target(str(tgt_label), idx) # :contentReference[oaicite:10]{index=10}
|
|
||||||
if not resolved_id:
|
|
||||||
continue # weiterhin unresolved
|
|
||||||
|
|
||||||
# Edge-Update
|
|
||||||
new_pl = dict(pl)
|
|
||||||
new_pl["target_id"] = resolved_id
|
|
||||||
new_pl["resolution"] = how
|
|
||||||
if "status" in new_pl:
|
|
||||||
del new_pl["status"]
|
|
||||||
# ID stabil lassen -> points_for_edges erzeugt UUID aus edge_id/Fallback :contentReference[oaicite:11]{index=11}
|
|
||||||
if "edge_id" not in new_pl:
|
|
||||||
# stabiler Key aus (kind, src, tgt, evtl. seq)
|
|
||||||
seq = new_pl.get("seq") or new_pl.get("order") or ""
|
|
||||||
new_pl["edge_id"] = f"{kind}:{src}->{resolved_id}#{seq}"
|
|
||||||
|
|
||||||
to_fix.append(new_pl)
|
|
||||||
resolved += 1
|
|
||||||
|
|
||||||
# Nur bei Note-Level references (nicht references_at) -> Backlink erzeugen
|
|
||||||
if kind == "references":
|
|
||||||
extra = {k: new_pl.get(k) for k in ("raw", "alias", "heading")}
|
|
||||||
extra["resolution"] = how
|
|
||||||
backlinks.append(_make_backlink(source_note_id=src, target_note_id=resolved_id, extra=extra))
|
|
||||||
|
|
||||||
# Ergebnis ausgeben
|
|
||||||
summary = {
|
|
||||||
"prefix": cfg.prefix,
|
|
||||||
"scanned_unresolved": processed,
|
|
||||||
"resolved": resolved,
|
|
||||||
"backlinks_to_create": len(backlinks),
|
|
||||||
"apply": bool(args.apply),
|
|
||||||
}
|
|
||||||
print(json.dumps(summary, ensure_ascii=False))
|
|
||||||
|
|
||||||
if not args.apply:
|
|
||||||
return
|
return
|
||||||
|
|
||||||
# Upserts (in Batches)
|
# 2. Unresolved Edges finden
|
||||||
def _batched(items: List[dict], n: int) -> Iterable[List[dict]]:
|
logger.info(f"Scanning for unresolved edges in {edges_col}...")
|
||||||
for i in range(0, len(items), n):
|
|
||||||
yield items[i : i + n]
|
|
||||||
|
|
||||||
# 1) Updates für reparierte Edges
|
scroll_filter = models.Filter(
|
||||||
for chunk in _batched(to_fix, args.batch):
|
must=[
|
||||||
col, pts = points_for_edges(cfg.prefix, chunk) # sorgt für Edge-UUID & Dummy-Vector :contentReference[oaicite:12]{index=12}
|
models.FieldCondition(key="status", match=models.MatchValue(value="unresolved"))
|
||||||
upsert_batch(client, col, pts)
|
]
|
||||||
|
)
|
||||||
|
|
||||||
# 2) Backlinks (nur references)
|
unresolved_edges = []
|
||||||
for chunk in _batched(backlinks, args.batch):
|
next_page = None
|
||||||
col, pts = points_for_edges(cfg.prefix, chunk)
|
while True:
|
||||||
upsert_batch(client, col, pts)
|
res, next_page = client.scroll(
|
||||||
|
collection_name=edges_col,
|
||||||
|
scroll_filter=scroll_filter,
|
||||||
|
limit=500,
|
||||||
|
with_payload=True,
|
||||||
|
offset=next_page
|
||||||
|
)
|
||||||
|
unresolved_edges.extend(res)
|
||||||
|
if next_page is None or (args.limit > 0 and len(unresolved_edges) >= args.limit):
|
||||||
|
break
|
||||||
|
|
||||||
|
if args.limit > 0:
|
||||||
|
unresolved_edges = unresolved_edges[:args.limit]
|
||||||
|
|
||||||
|
logger.info(f"Found {len(unresolved_edges)} unresolved edges.")
|
||||||
|
|
||||||
|
# 3. Auflösen
|
||||||
|
to_fix = []
|
||||||
|
backlinks = []
|
||||||
|
resolved_count = 0
|
||||||
|
|
||||||
|
for pt in unresolved_edges:
|
||||||
|
pl = pt.payload
|
||||||
|
# Der gesuchte Begriff steckt oft in 'raw_target' (wenn Parser es speichert)
|
||||||
|
# oder wir nutzen die 'target_id', falls diese temporär den Namen hält (Legacy Parser Verhalten).
|
||||||
|
# Im v2.6 Parser ist die target_id bei unresolved links oft der slug oder name.
|
||||||
|
|
||||||
|
# Strategie: Wir schauen uns das Payload an.
|
||||||
|
# Fall A: derive_edges hat target_id="[[Missing Note]]" gesetzt (selten)
|
||||||
|
# Fall B: target_id ist der Slug/Titel in Kleinbuchstaben (häufig)
|
||||||
|
# Fall C: Es gibt ein Feld 'raw' oder 'text'
|
||||||
|
|
||||||
|
candidate = pl.get("target_id")
|
||||||
|
|
||||||
|
# Versuch der Auflösung
|
||||||
|
target_nid = lookup_index.get(str(candidate).lower().strip())
|
||||||
|
|
||||||
|
if target_nid:
|
||||||
|
# TREFFER!
|
||||||
|
new_pl = pl.copy()
|
||||||
|
new_pl["target_id"] = target_nid
|
||||||
|
new_pl.pop("status", None) # Status entfernen -> ist jetzt resolved
|
||||||
|
new_pl["resolution"] = "healed_by_script"
|
||||||
|
|
||||||
|
# Neue Edge ID generieren (Clean architecture)
|
||||||
|
# Wir behalten die alte ID NICHT, da die ID oft target_id enthält und wir Duplikate vermeiden wollen.
|
||||||
|
# Alternativ: Update auf bestehender ID. Wir machen hier ein Update.
|
||||||
|
|
||||||
|
to_fix.append({
|
||||||
|
"id": pt.id,
|
||||||
|
"payload": new_pl
|
||||||
|
})
|
||||||
|
|
||||||
|
# Backlink erzeugen? Nur wenn es eine Referenz ist
|
||||||
|
if pl.get("kind") == "references":
|
||||||
|
backlinks.append(_make_backlink(
|
||||||
|
source_note_id=pl.get("source_id"),
|
||||||
|
target_note_id=target_nid,
|
||||||
|
extra={"alias": candidate}
|
||||||
|
))
|
||||||
|
|
||||||
|
resolved_count += 1
|
||||||
|
|
||||||
|
logger.info(f"Resolvable: {resolved_count}/{len(unresolved_edges)}")
|
||||||
|
|
||||||
|
if not args.apply:
|
||||||
|
logger.info("DRY RUN. Use --apply to execute.")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 4. Schreiben
|
||||||
|
if to_fix:
|
||||||
|
logger.info(f"Updating {len(to_fix)} edges...")
|
||||||
|
# Qdrant Update: Wir überschreiben den Point.
|
||||||
|
# Achtung: client.upsert erwartet PointStructs.
|
||||||
|
|
||||||
|
points_to_upsert = [
|
||||||
|
models.PointStruct(id=u["id"], payload=u["payload"], vector={})
|
||||||
|
for u in to_fix
|
||||||
|
]
|
||||||
|
|
||||||
|
# Batchweise
|
||||||
|
for i in range(0, len(points_to_upsert), args.batch):
|
||||||
|
batch = points_to_upsert[i:i+args.batch]
|
||||||
|
client.upsert(collection_name=edges_col, points=batch)
|
||||||
|
|
||||||
|
if backlinks:
|
||||||
|
logger.info(f"Creating {len(backlinks)} backlinks...")
|
||||||
|
# Hier nutzen wir den Helper aus qdrant_points für saubere IDs
|
||||||
|
col, bl_points = points_for_edges(backlinks, cfg.prefix)
|
||||||
|
# batchweise
|
||||||
|
for i in range(0, len(bl_points), args.batch):
|
||||||
|
batch = bl_points[i:i+args.batch]
|
||||||
|
client.upsert(collection_name=col, points=batch)
|
||||||
|
|
||||||
|
logger.info("Done.")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
"""
|
||||||
|
FILE: tests/test_WP22_intelligence.py
|
||||||
|
DESCRIPTION: Integrationstest für WP-22.
|
||||||
|
FIX: Erzwingt Pfad-Synchronisation für Registry & Router. Behebt Pydantic Validation Errors.
|
||||||
|
"""
|
||||||
|
import unittest
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import yaml
|
||||||
|
import asyncio
|
||||||
|
from unittest.mock import MagicMock, patch, AsyncMock
|
||||||
|
|
||||||
|
# --- Modul-Caching Fix: Wir müssen Caches leeren ---
|
||||||
|
import app.routers.chat
|
||||||
|
from app.models.dto import ChatRequest, QueryHit, QueryRequest
|
||||||
|
from app.services.edge_registry import EdgeRegistry
|
||||||
|
from app.core.retriever import _compute_total_score, _get_status_multiplier
|
||||||
|
from app.routers.chat import _classify_intent, get_decision_strategy, chat_endpoint
|
||||||
|
|
||||||
|
class TestWP22Integration(unittest.IsolatedAsyncioTestCase):
|
||||||
|
|
||||||
|
async def asyncSetUp(self):
|
||||||
|
"""Bereitet eine isolierte Test-Umgebung vor."""
|
||||||
|
# Wir simulieren hier 'vault_master' (oder venv_master) als Verzeichnis
|
||||||
|
self.test_root = os.path.abspath("tests/temp_wp22")
|
||||||
|
self.test_vault = os.path.join(self.test_root, "vault_master")
|
||||||
|
self.test_config_dir = os.path.join(self.test_root, "config")
|
||||||
|
|
||||||
|
# 1. Pfade erstellen
|
||||||
|
os.makedirs(os.path.join(self.test_vault, "01_User_Manual"), exist_ok=True)
|
||||||
|
os.makedirs(self.test_config_dir, exist_ok=True)
|
||||||
|
os.makedirs(os.path.join(self.test_root, "data/logs"), exist_ok=True)
|
||||||
|
|
||||||
|
# 2. Config Files schreiben (MOCK CONFIG)
|
||||||
|
self.decision_path = os.path.join(self.test_config_dir, "decision_engine.yaml")
|
||||||
|
self.decision_config = {
|
||||||
|
"strategies": {
|
||||||
|
"FACT": {
|
||||||
|
"trigger_keywords": ["was ist"],
|
||||||
|
"edge_boosts": {"part_of": 2.0}
|
||||||
|
},
|
||||||
|
"CAUSAL": {
|
||||||
|
"trigger_keywords": ["warum"],
|
||||||
|
"edge_boosts": {"caused_by": 3.0}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
with open(self.decision_path, "w", encoding="utf-8") as f:
|
||||||
|
yaml.dump(self.decision_config, f)
|
||||||
|
|
||||||
|
# 3. Vocabulary File am RICHTIGEN Ort relativ zum test_vault
|
||||||
|
self.vocab_path = os.path.join(self.test_vault, "01_User_Manual/01_edge_vocabulary.md")
|
||||||
|
with open(self.vocab_path, "w", encoding="utf-8") as f:
|
||||||
|
f.write("| System-Typ | Aliases |\n| :--- | :--- |\n| **caused_by** | ursache_ist |\n| **part_of** | teil_von |")
|
||||||
|
|
||||||
|
# 4. MOCKING / RESETTING GLOBAL STATE
|
||||||
|
# Zwinge get_settings, unsere Test-Pfade zurückzugeben
|
||||||
|
self.mock_settings = MagicMock()
|
||||||
|
self.mock_settings.DECISION_CONFIG_PATH = self.decision_path
|
||||||
|
self.mock_settings.MINDNET_VAULT_ROOT = self.test_vault
|
||||||
|
self.mock_settings.RETRIEVER_TOP_K = 5
|
||||||
|
self.mock_settings.MODEL_NAME = "test-model"
|
||||||
|
|
||||||
|
# Patching get_settings in allen relevanten Modulen
|
||||||
|
self.patch_settings_chat = patch('app.routers.chat.get_settings', return_value=self.mock_settings)
|
||||||
|
self.patch_settings_registry = patch('app.services.edge_registry.get_settings', return_value=self.mock_settings)
|
||||||
|
|
||||||
|
self.patch_settings_chat.start()
|
||||||
|
self.patch_settings_registry.start()
|
||||||
|
|
||||||
|
# Caches zwingend leeren
|
||||||
|
app.routers.chat._DECISION_CONFIG_CACHE = None
|
||||||
|
|
||||||
|
# Registry Singleton Reset & Force Init mit Test-Pfad
|
||||||
|
EdgeRegistry._instance = None
|
||||||
|
self.registry = EdgeRegistry(vault_root=self.test_vault)
|
||||||
|
self.registry.unknown_log_path = os.path.join(self.test_root, "data/logs/unknown.jsonl")
|
||||||
|
|
||||||
|
async def asyncTearDown(self):
|
||||||
|
self.patch_settings_chat.stop()
|
||||||
|
self.patch_settings_registry.stop()
|
||||||
|
if os.path.exists(self.test_root):
|
||||||
|
shutil.rmtree(self.test_root)
|
||||||
|
EdgeRegistry._instance = None
|
||||||
|
app.routers.chat._DECISION_CONFIG_CACHE = None
|
||||||
|
|
||||||
|
def test_registry_resolution(self):
|
||||||
|
print("\n🔵 TEST 1: Registry Pfad & Alias Resolution")
|
||||||
|
# Prüfen ob die Datei gefunden wurde
|
||||||
|
self.assertTrue(len(self.registry.valid_types) > 0, f"Registry leer! Root: {self.registry.vault_root}")
|
||||||
|
self.assertEqual(self.registry.resolve("ursache_ist"), "caused_by")
|
||||||
|
print("✅ Registry OK.")
|
||||||
|
|
||||||
|
def test_scoring_math(self):
|
||||||
|
print("\n🔵 TEST 2: Scoring Math (Lifecycle)")
|
||||||
|
with patch("app.core.retriever._get_scoring_weights", return_value=(1.0, 1.0, 0.0)):
|
||||||
|
# Stable (1.2)
|
||||||
|
self.assertEqual(_get_status_multiplier({"status": "stable"}), 1.2)
|
||||||
|
# Draft (0.5)
|
||||||
|
self.assertEqual(_get_status_multiplier({"status": "draft"}), 0.5)
|
||||||
|
|
||||||
|
# Scoring Formel Test: BaseScore * (1 + ConfigWeight + DynamicBoost)
|
||||||
|
# BaseScore = 0.5 (sem) * 1.2 (stable) = 0.6
|
||||||
|
# ConfigWeight = 1.0 (neutral) - 1.0 = 0.0
|
||||||
|
# DynamicBoost = (1.0 * 0.5) = 0.5
|
||||||
|
# Total = 0.6 * (1 + 0 + 0.5) = 0.9
|
||||||
|
total, _, _ = _compute_total_score(0.5, {"status": "stable", "retriever_weight": 1.0}, edge_bonus_raw=0.5)
|
||||||
|
self.assertAlmostEqual(total, 0.9)
|
||||||
|
print("✅ Scoring OK.")
|
||||||
|
|
||||||
|
async def test_router_intent(self):
|
||||||
|
print("\n🔵 TEST 3: Intent Classification")
|
||||||
|
mock_llm = MagicMock()
|
||||||
|
intent, _ = await _classify_intent("Warum ist das so?", mock_llm)
|
||||||
|
self.assertEqual(intent, "CAUSAL")
|
||||||
|
print("✅ Routing OK.")
|
||||||
|
|
||||||
|
async def test_full_flow(self):
|
||||||
|
print("\n🔵 TEST 4: End-to-End Pipeline & Dynamic Boosting")
|
||||||
|
mock_llm = AsyncMock()
|
||||||
|
mock_llm.prompts = {}
|
||||||
|
mock_llm.generate_raw_response.return_value = "Test Antwort"
|
||||||
|
|
||||||
|
mock_retriever = AsyncMock()
|
||||||
|
# Fix note_id für Pydantic Validation
|
||||||
|
mock_hit = QueryHit(
|
||||||
|
node_id="c1", note_id="test_note_n1", semantic_score=0.8, edge_bonus=0.0,
|
||||||
|
centrality_bonus=0.0, total_score=0.8, source={"text": "t"},
|
||||||
|
payload={"status": "active", "type": "concept"}
|
||||||
|
)
|
||||||
|
mock_retriever.search.return_value.results = [mock_hit]
|
||||||
|
|
||||||
|
req = ChatRequest(message="Warum ist das passiert?", top_k=1)
|
||||||
|
resp = await chat_endpoint(req, llm=mock_llm, retriever=mock_retriever)
|
||||||
|
|
||||||
|
# Verify Intent
|
||||||
|
self.assertEqual(resp.intent, "CAUSAL")
|
||||||
|
|
||||||
|
# Verify Boosts Reached Retriever
|
||||||
|
called_req = mock_retriever.search.call_args[0][0]
|
||||||
|
self.assertEqual(called_req.boost_edges.get("caused_by"), 3.0)
|
||||||
|
print("✅ Full Flow & Boosting OK.")
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
---
|
||||||
|
id: edge_vocabulary
|
||||||
|
title: Edge Vocabulary & Semantik
|
||||||
|
type: reference
|
||||||
|
status: system
|
||||||
|
system_role: config
|
||||||
|
context: "Zentrales Wörterbuch für Kanten-Bezeichner. Dient als Single Source of Truth für Obsidian-Skripte und Mindnet-Validierung."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Edge Vocabulary & Semantik
|
||||||
|
|
||||||
|
**Pfad:** `01_User_Manual/01_edge_vocabulary.md`
|
||||||
|
**Zweck:** Definition aller erlaubten Kanten-Typen und ihrer Aliase.
|
||||||
|
|
||||||
|
| System-Typ (Canonical) | Erlaubte Aliasse (User) | Beschreibung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **`caused_by`** | `ausgelöst_durch`, `wegen`, `ursache_ist` | Kausalität: A löst B aus. |
|
||||||
|
| **`derived_from`** | `abgeleitet_von`, `quelle`, `inspiriert_durch` | Herkunft: A stammt von B. |
|
||||||
|
| **`based_on`** | `basiert_auf`, `fundament`, `grundlage` | Fundament: B baut auf A auf. |
|
||||||
|
| **`solves`** | `löst`, `beantwortet`, `fix_für` | Lösung: A ist Lösung für Problem B. |
|
||||||
|
| **`part_of`** | `teil_von`, `gehört_zu`, `cluster` | Hierarchie: Kind -> Eltern. |
|
||||||
|
| **`depends_on`** | `hängt_ab_von`, `braucht`, `requires`, `enforced_by` | Abhängigkeit: A braucht B. |
|
||||||
|
| **`blocks`** | `blockiert`, `verhindert`, `risiko_für` | Blocker: A verhindert B. |
|
||||||
|
| **`uses`** | `nutzt`, `verwendet`, `tool` | Werkzeug: A nutzt B. |
|
||||||
|
| **`guides`** | `steuert`, `leitet`, `orientierung` | Soft-Dependency: A gibt Richtung für B. |
|
||||||
|
| **`next`** | `danach`, `folgt`, `nachfolger`, `followed_by` | Prozess: A -> B. |
|
||||||
|
| **`prev`** | `davor`, `vorgänger`, `preceded_by` | Prozess: B <- A. |
|
||||||
|
| **`related_to`** | `siehe_auch`, `kontext`, `thematisch` | Lose Assoziation. |
|
||||||
|
| **`similar_to`** | `ähnlich_wie`, `vergleichbar` | Synonym / Ähnlichkeit. |
|
||||||
|
| **`experienced_in`** | `erfahren_in`, `spezialisiert_in` | Synonym / Ähnlichkeit. |
|
||||||
|
| **`references`** | *(Kein Alias)* | Standard-Verweis (Fallback). |
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-2012
|
||||||
|
title: Leitbild 2012 – Persönliche Ausrichtung
|
||||||
|
type: experience
|
||||||
|
status: archived
|
||||||
|
created: 2012-01-01
|
||||||
|
updated: 2025-12-17
|
||||||
|
tags: [leitbild, identität, historie, erfahrung]
|
||||||
|
aliases: [Leitbild 2012, Persönliches Leitbild 2012]
|
||||||
|
lang: de
|
||||||
|
retriever_weight: 0.4
|
||||||
|
chunking_profile: structured_smart_edges
|
||||||
|
---
|
||||||
|
|
||||||
|
# Persönliches Leitbild (2012)
|
||||||
|
|
||||||
|
## Grundsatz
|
||||||
|
Ich möchte ein Mensch sein, der mit sich und seiner Umwelt im Reinen ist.
|
||||||
|
Ich strebe danach, ehrlich, verlässlich und verantwortungsbewusst zu handeln.
|
||||||
|
|
||||||
|
Meine Entscheidungen sollen von meinem Gewissen geleitet sein und nicht von kurzfristigen Vorteilen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Familie
|
||||||
|
Familie ist der wichtigste Bestandteil meines Lebens.
|
||||||
|
Ich möchte ein verlässlicher Partner und ein guter Vater sein.
|
||||||
|
|
||||||
|
Ich will präsent sein, Verantwortung übernehmen und ein stabiles Umfeld schaffen,
|
||||||
|
in dem Vertrauen, Offenheit und gegenseitiger Respekt gelebt werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Arbeit & Beruf
|
||||||
|
Ich möchte meine Fähigkeiten sinnvoll einsetzen und Verantwortung übernehmen.
|
||||||
|
Leistung bedeutet für mich nicht nur Erfolg, sondern auch Fairness und Nachhaltigkeit.
|
||||||
|
|
||||||
|
Ich strebe danach, mich kontinuierlich weiterzuentwickeln und meine Arbeit gewissenhaft auszuführen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Persönliche Entwicklung
|
||||||
|
Ich möchte lernen, reflektieren und mich weiterentwickeln.
|
||||||
|
Fehler sind Teil dieses Prozesses und bieten die Chance zu wachsen.
|
||||||
|
|
||||||
|
Ich strebe danach, meine Stärken zu nutzen und an meinen Schwächen zu arbeiten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Werte & Haltung
|
||||||
|
Mein Handeln soll geprägt sein von:
|
||||||
|
- Ehrlichkeit
|
||||||
|
- Verantwortungsbewusstsein
|
||||||
|
- Respekt
|
||||||
|
- Verlässlichkeit
|
||||||
|
|
||||||
|
Ich möchte meinen Mitmenschen offen und wertschätzend begegnen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verantwortung
|
||||||
|
Ich übernehme Verantwortung für mein Handeln und dessen Konsequenzen.
|
||||||
|
Ich stehe zu meinen Entscheidungen und lerne aus ihnen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Einordnung
|
||||||
|
Dieses Leitbild beschreibt meine **persönliche Haltung und Ausrichtung im Jahr 2012**.
|
||||||
|
|
||||||
|
> [!edge] succeeded_by
|
||||||
|
> Es wurde später **inhaltlich weiterentwickelt und systemisch ersetzt** durch das
|
||||||
|
> [[Leitbild – Identity Core (MOC)]]
|
||||||
|
> und das darauf aufbauende Leitbild 2025–2029.
|
||||||
|
|
||||||
|
Dieses Dokument dient ausschließlich der **historischen Reflexion** und der
|
||||||
|
Nachvollziehbarkeit meiner persönlichen Entwicklung.
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-2025-identitaet
|
||||||
|
title: Leitbild 2025–2029 – Persönliche Identität
|
||||||
|
type: concept
|
||||||
|
status: active
|
||||||
|
created: 2025-10-31
|
||||||
|
updated: 2025-12-17
|
||||||
|
tags: [leitbild, identität, werte, prinzipien, rollen, nordsterne]
|
||||||
|
lang: de
|
||||||
|
retriever_weight: 0.8
|
||||||
|
chunking_profile: structured_smart_edges
|
||||||
|
---
|
||||||
|
|
||||||
|
## Wer ich bin
|
||||||
|
Ich bin Lars.
|
||||||
|
Ich stehe für **Verlässlichkeit**, **klare Haltung** und **freundliche Konsequenz**.
|
||||||
|
Schicksalsschläge haben mich geerdet.
|
||||||
|
Sie haben meine Prioritäten neu geordnet.
|
||||||
|
Ich wähle bewusst: **präsent sein, fair handeln, vorleben statt fordern**.
|
||||||
|
|
||||||
|
Dieser Text ist die **narrative Klammer** und fasst die Grundlagen aus
|
||||||
|
|
||||||
|
> [!edge] summarizes
|
||||||
|
> [[Leitbild – Scope (Session 0)]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Wofür ich jeden Morgen aufstehe
|
||||||
|
Ich baue ein Zuhause, in dem meine Kinder wachsen können – sicher, gesehen und gefordert.
|
||||||
|
Ich pflege meine Partnerschaft mit Wärme, Humor und Klarheit.
|
||||||
|
Ich diene anderen als Trainer, Berater und Ausbilder: **ideenreich, integer, wirksam**.
|
||||||
|
Ich bleibe lernend – Gesundheit, Geist und Neugier sind meine Energiequellen.
|
||||||
|
|
||||||
|
> [!edge] defined_by
|
||||||
|
> [[Leitbild – Rollen & Identität]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Meine Kernwerte (kompakt)
|
||||||
|
- **Integrität** – Ich handle im Einklang mit meinen Werten. **Wort = Verpflichtung.** Wenn ich abweiche, sage ich es offen und repariere.
|
||||||
|
- **Disziplin (mit Menschlichkeit)** – Ich bin mir selbst gegenüber konsequent, besonders bei Unangenehmem. **Regeln gelten freundlich, fair, zuverlässig.**
|
||||||
|
- **Respekt** – Jeder Mensch ist wertvoll und gleichwürdig. Ich höre erst zu, bevor ich antworte. Keine Abwertung, keine Beschämung.
|
||||||
|
|
||||||
|
**Ergänzende Leitwerte:** Fürsorge & Familienbindung · Klarheit & Struktur · Lernorientierung · Großzügigkeit · Mut.
|
||||||
|
|
||||||
|
> [!edge] summarizes
|
||||||
|
> Das Leitbild basiert auf klar priorisierten Werten
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)]]
|
||||||
|
|
||||||
|
> [!edge] contextualized_by
|
||||||
|
> [[Leitbild – Wertekompass (vollständig)]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Handlungsprinzipien (Auszug)
|
||||||
|
- **Vorbild vor Anspruch.** Was ich erwarte, lebe ich zuerst.
|
||||||
|
- **Verstehen vor Antworten.** Ich kläre Wahrnehmung und Absicht, bevor ich urteile.
|
||||||
|
- **Klares Ja/Nein.** Grenzen schützen Fokus und Beziehungen.
|
||||||
|
- **Freundlich–konsequent.** Regeln werden fair erklärt, konsequent eingehalten und respektvoll durchgesetzt.
|
||||||
|
- **Repair first.** Wenn ich verletze, kläre ich zeitnah, ehrlich und ohne Ausflüchte.
|
||||||
|
- **Weniger, dafür besser.** WIP-Limit statt Übercommitment.
|
||||||
|
- **Gesundheit ist Basis.** Meditation, Bewegung, Ernährung, medizinische Checks.
|
||||||
|
- **AI-first, human-led.** Technologie erhöht meine Wirksamkeit – Verantwortung bleibt bei mir.
|
||||||
|
|
||||||
|
|
||||||
|
> [!edge] summarizes
|
||||||
|
> [[Leitbild – Handlungsprinzipien]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rollen & Missionen
|
||||||
|
# Rollen & Missionen
|
||||||
|
### Vater
|
||||||
|
Ich bin präsent, fair und verlässlich. Ich stärke Bindung und Selbstwirksamkeit meiner Söhne – jeden Tag ein kleines, echtes Gespräch und klare, nachvollziehbare Standards.
|
||||||
|
**Qualitätskriterien:** Nähe spürbar · Regeln werden verstanden und eingehalten · Ich halte Konsequenzen ohne Härte, mit Haltung.
|
||||||
|
|
||||||
|
### Partner
|
||||||
|
Ich bin ein zugewandter, klarer Partner. Ich teile Lasten, höre zu, entscheide mit – und wir schaffen Rituale für Nähe und Leichtigkeit.
|
||||||
|
|
||||||
|
### Karate- & Gewaltschutztrainer (inkl. Traineraufbau)
|
||||||
|
Ich vermittle Freude an Bewegung, Budo-Werte und Selbstwirksamkeit. Ich baue ein verlässliches Lernumfeld und entwickle neue Trainer*innen – strukturiert, achtsam, kindeswohlorientiert.
|
||||||
|
|
||||||
|
### Freund (Neuaufbau)
|
||||||
|
Ich kultiviere einen Kreis auf Augenhöhe: verlässlich, neugierig, sportlich oder intellektuell – mit echten Gesprächen, gegenseitiger Unterstützung und Nähe.
|
||||||
|
|
||||||
|
### Berufsrolle (AI-first)
|
||||||
|
Ich verbinde Research-Tiefe, IT-Kostensenkung und Ausbildung. Ich teile Wissen großzügig, baue belastbare Hypothesen und Assets, und erziele Wirkung für Kunden und Kolleg*innen – integer und transparent.
|
||||||
|
|
||||||
|
> [!edge] summarizes
|
||||||
|
> [[Leitbild – Rollen & Identität]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Nordsterne (2025–2029)
|
||||||
|
1) **Vater:** Starke Bindung, klare Standards, faire Konsequenz.
|
||||||
|
2) **Ich-Pflege:** Ruhe, Beweglichkeit, Klarheit – getragen von Ritualen.
|
||||||
|
3) **Karate & Gewaltschutz (+ Traineraufbau):** Sicheres Lernökosystem, das wächst und trägt.
|
||||||
|
4) **Partner:** Nähe, Humor, gemeinsame Entscheidungen.
|
||||||
|
5) **Freund (Neuaufbau):** Verlässliches Netzwerk mit Tiefe und Freude.
|
||||||
|
6) **Beruf (AI-first):** Wirksame Assets & Ausbildung mit messbarem Kundennutzen.
|
||||||
|
|
||||||
|
> [!edge] summarizes
|
||||||
|
> [[Leitbild – Nordsterne & Ziele]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rituale als Systeme
|
||||||
|
|
||||||
|
Ich vertraue nicht auf Willenskraft, sondern auf Systeme:
|
||||||
|
- **R1** Meditation 20′ (morgens, ruhiger Block)
|
||||||
|
- **R2** Mobility 10′ (erste 10′ des Lunch)
|
||||||
|
- **R3** Journal (bevor das Licht ausgeht)
|
||||||
|
- **R4** Familienrat light 14-tägig (So 14:00)
|
||||||
|
- **R5** Paar-Ritual Tanzen (So 17:00)
|
||||||
|
- **R6** 1:1 Rohan 5′ (nach Abendessen)
|
||||||
|
- **R7** 1:1 Rouven 20–30′ (Sa 11:00)
|
||||||
|
**Regel bei Ausfall:** Mini-Reset ≤24 h (kein „alles-egal“).
|
||||||
|
*Details & Messung siehe `leitbild-rituale-system`.*
|
||||||
|
|
||||||
|
|
||||||
|
Die Umsetzung erfolgt über
|
||||||
|
> [!edge] uses
|
||||||
|
> [[Leitbild – Rituale & Systeme]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Standards & Grenzen
|
||||||
|
|
||||||
|
- **Zuhause:** Ablagen/Böden frei, Küche morgens aufgeräumt, kein sichtbarer Dreck.
|
||||||
|
- **Zeit:** Familie geht vor zusätzlichen Vereins-/Aufgaben – keine Mehrbelastung zulasten der Bindung.
|
||||||
|
- **Konsequenzen:** Angekündigte Schritte werden umgesetzt – freundlich, fair, ohne Demütigung.
|
||||||
|
- **Nein-Liste:** Keine neuen Verpflichtungen, die Nordsterne verwässern.
|
||||||
|
- **Transparenz:** Abweichungen dokumentiere ich als **Deviation Note („Schuldschein“) – mit Begründung und Repair-Schritt**.
|
||||||
|
|
||||||
|
> [!edge] uses
|
||||||
|
> Abweichungen werden bewusst dokumentiert über [[Leitbild – Review-System]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Messung & Review
|
||||||
|
- **Weekly (20–30′):** Scoreboard füllen → kurze Reflexion → **eine** Decision Note.
|
||||||
|
- **Monthly (45–60′):** Roll-up der KPIs, Top-3 Outcomes, Risiken + Gegenmaßnahmen.
|
||||||
|
- **Quarterly (90′):** Nordsterne/Meilensteine prüfen, Kurs justieren.
|
||||||
|
|
||||||
|
> [!edge] uses
|
||||||
|
> *Templates & CSVs siehe *[[Leitbild - ReviewSystem]]*
|
||||||
|
---
|
||||||
|
|
||||||
|
## Öffentliche Haltung & privater Kern
|
||||||
|
Dieses Leitbild darf gelesen und gespiegelt werden. **Private Motive und Startpunkte bleiben bei mir.**
|
||||||
|
Ich nehme Feedback an, sofern es meine Werte schärft und die Wirkung erhöht.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Leitsatz
|
||||||
|
**Stark im Herzen. Klar im Handeln. Fair im Umgang.**
|
||||||
|
Ich bin verlässlich – für meine Familie, für mein Team, für mich.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> [!edge] part_of
|
||||||
|
> Dieses Dokument ist Teil des Identitätskerns
|
||||||
|
> [[ Leitbild – Identity Core (MOC)]].
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-prinzipien
|
||||||
|
title: Leitbild – Handlungsprinzipien
|
||||||
|
type: principle
|
||||||
|
status: active
|
||||||
|
created: 2025-10-30
|
||||||
|
updated: 2025-12-17
|
||||||
|
tags: [leitbild, prinzipien, handlungsleitlinien, decision-engine]
|
||||||
|
aliases: [Prinzipien, Handlungsleitlinien, Entscheidungsprinzipien]
|
||||||
|
lang: de
|
||||||
|
retriever_weight: 0.95
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
---
|
||||||
|
|
||||||
|
# Handlungsprinzipien
|
||||||
|
|
||||||
|
Diese Prinzipien sind **konkrete Handlungsleitlinien**. Sie sind **direkt abgeleitet** aus den verbindlichen Werten [[Leitbild – Kernwerte (Top 5)]]
|
||||||
|
und steuern das Verhalten **in allen Rollen**, insbesondere in [[Leitbild – Rollen & Identität]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## P1 – Integrität
|
||||||
|
**Leitsatz:**
|
||||||
|
*Ich spiegele jede wichtige Entscheidung am Werte-Modell und dokumentiere Abweichungen.*
|
||||||
|
|
||||||
|
Dieses Prinzip ist **direkt abgeleitet** aus dem Kernwert [[Leitbild – Kernwerte (Top 5)#Integrität]]
|
||||||
|
und wird operativ überprüft über das [[Leitbild – Review-System]].
|
||||||
|
|
||||||
|
**Signal:**
|
||||||
|
Bei Abweichung wird innerhalb von 24 Stunden eine Decision- oder Deviation-Note erstellt.
|
||||||
|
|
||||||
|
### Anti-Pattern
|
||||||
|
★ **Nachträgliche Rationalisierung**
|
||||||
|
Entscheidungen werden getroffen und erst danach mit Werten „passend gemacht“.
|
||||||
|
|
||||||
|
Weitere mögliche Anti-Pattern:
|
||||||
|
- Stille Abweichung
|
||||||
|
- Prinzipienwechsel je nach Vorteil
|
||||||
|
|
||||||
|
> [!edge] derived_from
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)#Integrität]]
|
||||||
|
|
||||||
|
> [!edge] enforced_by
|
||||||
|
> [[Leitbild – Review-System]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## P2 – Vertrauenswürdigkeit & Ehrlichkeit
|
||||||
|
**Leitsatz:**
|
||||||
|
*Ich kündige drohende Abweichungen proaktiv an und verhandle Alternativen.*
|
||||||
|
|
||||||
|
Dieses Prinzip basiert auf
|
||||||
|
[[Leitbild – Kernwerte (Top 5)#Vertrauenswürdigkeit & Ehrlichkeit]]
|
||||||
|
und schützt explizit die Vertrauensbasis in allen Rollen
|
||||||
|
[[Leitbild – Rollen & Identität]].
|
||||||
|
|
||||||
|
**Signal:**
|
||||||
|
Information erfolgt **vor** Fristende oder Regelbruch.
|
||||||
|
|
||||||
|
### Anti-Pattern
|
||||||
|
★ **Abtauchen bis zur Deadline**
|
||||||
|
|
||||||
|
Weitere mögliche Anti-Pattern:
|
||||||
|
- Scheinkommunikation
|
||||||
|
- Optimismus-Bias
|
||||||
|
|
||||||
|
> [!edge] derived_from
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)#Vertrauenswürdigkeit & Ehrlichkeit]]
|
||||||
|
|
||||||
|
> [!edge] guides
|
||||||
|
> [[Leitbild – Rollen & Identität]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## P3 – Disziplin (Selbstführung)
|
||||||
|
**Leitsatz:**
|
||||||
|
*Ich bin mir selbst konsequent; Unangenehmes gehe ich rechtzeitig an.*
|
||||||
|
|
||||||
|
Dieses Prinzip ist eine direkte Operationalisierung von
|
||||||
|
[[Leitbild – Kernwerte (Top 5)#Disziplin]]
|
||||||
|
und wird durch tägliche Systeme abgesichert
|
||||||
|
[[Leitbild – Rituale & Systeme]].
|
||||||
|
|
||||||
|
### Anti-Pattern
|
||||||
|
★ **Aktionismus statt Priorität**
|
||||||
|
|
||||||
|
Weitere mögliche Anti-Pattern:
|
||||||
|
- Ausreden-Loop
|
||||||
|
- Selbstüberforderung
|
||||||
|
|
||||||
|
> [!edge] derived_from
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)#Disziplin]]
|
||||||
|
|
||||||
|
> [!edge] enforced_by
|
||||||
|
> [[Leitbild – Rituale & Systeme]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### P3a – Disziplin in der Familie
|
||||||
|
**Leitsatz:**
|
||||||
|
*Ich setze wenige Regeln ruhig durch, nachdem ich Bedürfnisse geprüft habe.*
|
||||||
|
|
||||||
|
Dieses Prinzip gilt **rollenspezifisch** für die Vater-Rolle
|
||||||
|
[[Leitbild – Rollen & Identität#Vater]].
|
||||||
|
|
||||||
|
**Signal:**
|
||||||
|
Angekündigte Konsequenzen werden verlässlich umgesetzt.
|
||||||
|
|
||||||
|
### Anti-Pattern
|
||||||
|
★ **Drohungen ohne Konsequenz**
|
||||||
|
|
||||||
|
Weitere mögliche Anti-Pattern:
|
||||||
|
- Impuls-Strafen
|
||||||
|
- Inkonsequente Ausnahmen
|
||||||
|
|
||||||
|
> [!edge] applies_to
|
||||||
|
> [[Leitbild – Rollen & Identität#Vater]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## P4 – Gerechtigkeit & Fairness
|
||||||
|
**Leitsatz:**
|
||||||
|
*Ich entscheide nach transparenten Maßstäben und höre beide Seiten (Steelman).*
|
||||||
|
|
||||||
|
Dieses Prinzip leitet sich ab aus
|
||||||
|
[[Leitbild – Kernwerte (Top 5)#Gerechtigkeit & Fairness]]
|
||||||
|
und ist entscheidend für Führungs- und Konfliktsituationen
|
||||||
|
[[Leitbild – Rollen & Identität]].
|
||||||
|
|
||||||
|
### Anti-Pattern
|
||||||
|
★ **Schnelles Urteilen**
|
||||||
|
|
||||||
|
Weitere mögliche Anti-Pattern:
|
||||||
|
- Sympathie-Bias
|
||||||
|
- Moralische Überlegenheit
|
||||||
|
|
||||||
|
> [!edge] derived_from
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)#Gerechtigkeit & Fairness]]
|
||||||
|
|
||||||
|
> [!edge] guides
|
||||||
|
> [[Leitbild – Rollen & Identität]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## P5 – Respekt
|
||||||
|
**Leitsatz:**
|
||||||
|
*Ich antworte erst, wenn ich verstanden habe.*
|
||||||
|
|
||||||
|
Dieses Prinzip basiert auf
|
||||||
|
[[Leitbild – Kernwerte (Top 5)#Respekt]]
|
||||||
|
und ist Grundlage jeder tragfähigen Beziehung.
|
||||||
|
|
||||||
|
### Anti-Pattern
|
||||||
|
★ **Antworten im Kopf während des Zuhörens**
|
||||||
|
|
||||||
|
Weitere mögliche Anti-Pattern:
|
||||||
|
- Belehren statt Verstehen
|
||||||
|
- Subtil abwertende Sprache
|
||||||
|
|
||||||
|
> [!edge] derived_from
|
||||||
|
> Abgeleitet von
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)#Respekt]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tier 2 – Mikro-Prinzipien (situativ)
|
||||||
|
|
||||||
|
Mikro-Prinzipien sind **kontextabhängige Verstärker**
|
||||||
|
und werden **nicht konfliktentscheidend** genutzt.
|
||||||
|
|
||||||
|
### MP1 – Fürsorge (Familie)
|
||||||
|
*Ich schenke tägliche Präsenz und schütze Familienzeit.*
|
||||||
|
|
||||||
|
|
||||||
|
> [!edge] enforced_by
|
||||||
|
> Umgesetzt über
|
||||||
|
> [[Leitbild – Rituale & Systeme#R6]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### MP2 – Klarheit (Struktur)
|
||||||
|
*Wer macht was bis wann.*
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### MP3 – Lernorientierung
|
||||||
|
*Ich wähle ein Deep-Dive-Thema und teile Wissen.*
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### MP4 – Großzügigkeit
|
||||||
|
*Ich teile Zeit und Wissen ohne Bilanzdenken.*
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### MP5 – Mut
|
||||||
|
*Ich spreche Unangenehmes früh an.*
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Anwendung & Durchsetzung
|
||||||
|
> [!edge] uses
|
||||||
|
> Prinzipien werden **angewendet, nicht diskutiert**. Abweichungen werden bewusst dokumentiert über
|
||||||
|
> [[Leitbild – Review-System]]
|
||||||
|
|
||||||
|
> [!edge] part_of
|
||||||
|
> Dieses Dokument ist Teil des zentralen Identitätskerns
|
||||||
|
> [[Leitbild – Identity Core (MOC)]]
|
||||||
|
|
||||||
|
> [!edge] derived_from
|
||||||
|
> Diese Prinzipien sind **konkrete Handlungsleitlinien**.
|
||||||
|
> Sie sind **direkt abgeleitet** aus den verbindlichen Werten
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)]]
|
||||||
|
|
||||||
|
> [!edge] guides
|
||||||
|
> Diese Handlungsprinzipien steuern mein Verhalten in all meinen Rollen, gemäß:
|
||||||
|
> [[Leitbild – Rollen & Identität]]
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-moc-2025
|
||||||
|
title: Leitbild – Identity Core (MOC)
|
||||||
|
type: concept
|
||||||
|
status: active
|
||||||
|
created: 2025-12-17
|
||||||
|
updated: 2025-12-17
|
||||||
|
tags: [identity, ego-core, leitbild, moc]
|
||||||
|
lang: de
|
||||||
|
retriever_weight: 1.4
|
||||||
|
chunking_profile: structured_smart_edges
|
||||||
|
---
|
||||||
|
|
||||||
|
# Leitbild – Identity Core (Entry Point)
|
||||||
|
|
||||||
|
Dies ist der **Single Point of Truth** für Identität, Werte, Ziele und Steuerung (Leitbild 2025–2029).
|
||||||
|
|
||||||
|
## 1) Narrative Identität
|
||||||
|
- [[Leitbild 2025–2029 – Persönliche Identität]]
|
||||||
|
|
||||||
|
|
||||||
|
## 2) Normativer Kern
|
||||||
|
- Werte: [[Leitbild – Kernwerte (Top 5)]]
|
||||||
|
- Prinzipien: [[Leitbild – Handlungsprinzipien]]
|
||||||
|
- Ziele: [[Leitbild – Nordsterne & Ziele]]
|
||||||
|
|
||||||
|
## 3) Kontext & Differenzierung
|
||||||
|
- Wertekompass: [[Leitbild – Wertekompass (vollständig)]]
|
||||||
|
- Rollen: [[Leitbild – Rollen & Identität]]
|
||||||
|
- Scope: [[Leitbild – Scope (Session 0)]]
|
||||||
|
|
||||||
|
## 4) Umsetzung & Betrieb
|
||||||
|
- Rituale: [[Leitbild – Rituale & Systeme]]
|
||||||
|
- Review: [[Leitbild – Review-System]]
|
||||||
|
- Ops: [[Leitbild – Operations Guide (v2025-refactored)]]
|
||||||
|
|
||||||
|
## 5) Historie
|
||||||
|
- [[Leitbild 2012 – Persönliche Ausrichtung]]
|
||||||
|
|
||||||
|
# Kantendefinitionen
|
||||||
|
|
||||||
|
> [!edge] references
|
||||||
|
> [[Leitbild 2025–2029 – Persönliche Identität]]
|
||||||
|
|
||||||
|
> [!edge] defines
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)]]
|
||||||
|
> [[Leitbild – Handlungsprinzipien]]
|
||||||
|
> [[Leitbild – Nordsterne & Ziele]]
|
||||||
|
> [[Leitbild – Rollen & Identität]]
|
||||||
|
|
||||||
|
> [!edge] contextualized_by
|
||||||
|
> [[Leitbild – Wertekompass (vollständig)]]
|
||||||
|
> [[Leitbild – Scope (Session 0)]]
|
||||||
|
|
||||||
|
> [!edge] implemented_by
|
||||||
|
> [[Leitbild – Rituale & Systeme]]
|
||||||
|
|
||||||
|
> [!edge] measured_by
|
||||||
|
> [[Leitbild – Review-System]]
|
||||||
|
|
||||||
|
> [!edge] succeeds
|
||||||
|
> [[Leitbild 2012 – Persönliche Ausrichtung]]
|
||||||
|
|
||||||
|
> [!edge] guided_by
|
||||||
|
> [[Leitbild – Operations Guide (v2025-refactored)]]
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-werte
|
||||||
|
title: Leitbild – Kernwerte (Top 5)
|
||||||
|
type: value
|
||||||
|
status: active
|
||||||
|
created: 2025-10-30
|
||||||
|
updated: 2025-12-17
|
||||||
|
tags: [leitbild, werte, core-values, decision-engine]
|
||||||
|
lang: de
|
||||||
|
retriever_weight: 1.0
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
---
|
||||||
|
|
||||||
|
# Werte – Top 5 (Priorität für 12 Monate)
|
||||||
|
> [!edge] leads_to
|
||||||
|
> Diese Werte haben **Priorität 1**.
|
||||||
|
> Bei Ziel-, Rollen- oder Interessenkonflikten **schlagen sie alle anderen Erwägungen**.
|
||||||
|
> Sie sind das normative Fundament für
|
||||||
|
> [[Leitbild – Handlungsprinzipien]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1) Integrität
|
||||||
|
**Definition:**
|
||||||
|
Ich handle **vorhersagbar principled**; **mein Wort gilt**.
|
||||||
|
|
||||||
|
**Anker:**
|
||||||
|
Jede relevante Entscheidung wird am Werte-Modell gespiegelt.
|
||||||
|
|
||||||
|
**Anti-Pattern:**
|
||||||
|
Rigidität oder moralische Selbstrechtfertigung.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2) Vertrauenswürdigkeit & Ehrlichkeit
|
||||||
|
**Definition:**
|
||||||
|
Zusagen sind verbindlich. Abweichungen werden **offen und frühzeitig** kommuniziert.
|
||||||
|
|
||||||
|
**Anker:**
|
||||||
|
Reparatur innerhalb von 24 Stunden bei Regelverstößen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3) Disziplin
|
||||||
|
**Definition:**
|
||||||
|
Ich halte zugesagte Standards und Regeln **verlässlich** ein.
|
||||||
|
|
||||||
|
**Anker:**
|
||||||
|
Wenige, klare Regeln – ruhig und konsequent umgesetzt.
|
||||||
|
|
||||||
|
**Bezug:**
|
||||||
|
Ermöglicht das System
|
||||||
|
[[Leitbild – Rituale & Systeme]].
|
||||||
|
|
||||||
|
> [!edge] enables
|
||||||
|
> [[Leitbild – Rituale & Systeme]]
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4) Gerechtigkeit & Fairness
|
||||||
|
**Definition:**
|
||||||
|
Entscheidungen erfolgen nach **transparenten Maßstäben**, die für alle gelten.
|
||||||
|
|
||||||
|
**Anker:**
|
||||||
|
Keine Impuls-Strafen; bewusste Steelman-Perspektive vor Urteilen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5) Respekt
|
||||||
|
**Definition:**
|
||||||
|
Ich erkenne jeden Menschen als **gleichwürdig** an.
|
||||||
|
|
||||||
|
**Anker:**
|
||||||
|
Sprache ohne Abwertung; erst verstehen, dann antworten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Konfliktregeln
|
||||||
|
* **Tier-1-Werte** schlagen alle Tier-2-Werte.
|
||||||
|
* Abweichungen sind **bewusst zu dokumentieren** über
|
||||||
|
> [[Leitbild – Review-System]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Abgrenzung
|
||||||
|
Dieses Dokument definiert **verbindliche Kernwerte**.
|
||||||
|
Nuancen und Kontextwerte sind im
|
||||||
|
[[Leitbild – Wertekompass (vollständig)]] dokumentiert.
|
||||||
|
|
||||||
|
# Kantenbeziehungen
|
||||||
|
> [!edge] uses
|
||||||
|
> [[Leitbild – Review-System]]
|
||||||
|
|
||||||
|
> [!edge] contextualized_by
|
||||||
|
> [[Leitbild – Wertekompass (vollständig)]]
|
||||||
|
|
||||||
|
> [!edge] part_of
|
||||||
|
> Dieses Dokument ist Teil des Identitätskerns
|
||||||
|
> [[Leitbild – Identity Core (MOC)]]
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-ziele
|
||||||
|
title: Leitbild – Nordsterne & Ziele
|
||||||
|
type: goal
|
||||||
|
status: active
|
||||||
|
created: 2025-10-30
|
||||||
|
updated: 2025-12-17
|
||||||
|
tags: [leitbild, ziele, nordsterne, strategie]
|
||||||
|
aliases: [Nordsterne, Ziele, Langfristziele]
|
||||||
|
lang: de
|
||||||
|
retriever_weight: 0.95
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
---
|
||||||
|
|
||||||
|
# Nordsterne & Ziele (2025–2029)
|
||||||
|
|
||||||
|
Dieses Dokument definiert meine **strategischen Langfristziele (Nordsterne)**. Sie leiten sich **direkt** aus meiner Identität ab [[Leitbild – Identity Core (MOC)]] und werden **wertebasiert gesteuert** [[Leitbild – Kernwerte (Top 5)]].
|
||||||
|
|
||||||
|
Die Umsetzung erfolgt rollenbasiert [[Leitbild – Rollen & Identität]] und wird über Systeme abgesichert [[Leitbild – Rituale & Systeme]].
|
||||||
|
|
||||||
|
> [edge] derived_from
|
||||||
|
> [[Leitbild – Identity Core (MOC)]]
|
||||||
|
|
||||||
|
> [!edge] governed_by
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)]]
|
||||||
|
|
||||||
|
> [edge!] pursued_by
|
||||||
|
> [[Leitbild – Rollen & Identität]]
|
||||||
|
|
||||||
|
> [!edge] enforced_by
|
||||||
|
> [[Leitbild – Rituale & Systeme]]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Nordstern 1 – Vater
|
||||||
|
**Zielbild:**
|
||||||
|
Eine starke, sichere Bindung und klare Standards im Alltag.
|
||||||
|
|
||||||
|
**Erfolgsindikatoren (qualitativ):**
|
||||||
|
- Regelmäßige 1:1-Zeit.
|
||||||
|
- Klare, ruhige Konsequenzen.
|
||||||
|
- Vertrauen in Konfliktsituationen.
|
||||||
|
|
||||||
|
> [!edge] pursued_by
|
||||||
|
> **Rollenbezug:**
|
||||||
|
> Primär verfolgt in der Rolle
|
||||||
|
> [[Leitbild – Rollen & Identität#Vater]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Nordstern 2 – Partner
|
||||||
|
**Zielbild:**
|
||||||
|
Partnerschaft als tragfähiges Team im Alltag.
|
||||||
|
|
||||||
|
**Erfolgsindikatoren:**
|
||||||
|
- Gemeinsame Planung.
|
||||||
|
- Offene Kommunikation.
|
||||||
|
- Geteilte Verantwortung.
|
||||||
|
|
||||||
|
> [!edge] pursued_by
|
||||||
|
> **Rollenbezug:**
|
||||||
|
> Primär verfolgt in der Rolle
|
||||||
|
> [[Leitbild – Rollen & Identität#Partner]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Nordstern 3 – Ich-Pflege
|
||||||
|
**Zielbild:**
|
||||||
|
Körperliche, mentale und emotionale Stabilität.
|
||||||
|
|
||||||
|
**Erfolgsindikatoren:**
|
||||||
|
- Regelmäßige Bewegung.
|
||||||
|
- Bewusste Regeneration.
|
||||||
|
- Stressarme Routinen.
|
||||||
|
|
||||||
|
**Guardrails:**
|
||||||
|
Kein Training durch Schmerz, Regeneration vor Leistungssteigerung.
|
||||||
|
|
||||||
|
> [!edge] pursued_by
|
||||||
|
> **Rollenbezug:**
|
||||||
|
> Primär verfolgt in der Rolle
|
||||||
|
> [[Leitbild – Rollen & Identität#Ich-Pflege]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Nordstern 4 – Karate & Gewaltschutz
|
||||||
|
**Zielbild:**
|
||||||
|
Ein sicheres, wirksames Lernökosystem für Kinder, Jugendliche und Trainer.
|
||||||
|
|
||||||
|
**Erfolgsindikatoren:**
|
||||||
|
- Klare Reifegradmodelle.
|
||||||
|
- Geschützte Lernräume.
|
||||||
|
- Nachhaltige Trainerausbildung.
|
||||||
|
|
||||||
|
> [!edge] pursued_by
|
||||||
|
> **Rollenbezug:**
|
||||||
|
> Primär verfolgt in der Rolle
|
||||||
|
> [[Leitbild – Rollen & Identität#Karate- & Gewaltschutztrainer]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Nordstern 5 – Berufsrolle
|
||||||
|
**Zielbild:**
|
||||||
|
Nachhaltige Wirkung durch evidenzbasierte, wiederverwendbare Arbeit.
|
||||||
|
|
||||||
|
**Erfolgsindikatoren:**
|
||||||
|
- Nachweisbare Wirkung.
|
||||||
|
- Strukturierte Wissensprodukte.
|
||||||
|
- Multiplikation durch Ausbildung.
|
||||||
|
|
||||||
|
> [!edge] pursued_by
|
||||||
|
> **Rollenbezug:**
|
||||||
|
> Primär verfolgt in der Rolle
|
||||||
|
> [[Leitbild – Rollen & Identität#Berufsrolle]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Zielkonflikte & Priorisierung
|
||||||
|
- Nordsterne stehen **nicht gleichrangig**, sondern im **Ausgleich**.
|
||||||
|
- Konflikte werden anhand der Kernwerte priorisiert
|
||||||
|
[[Leitbild – Kernwerte (Top 5)]].
|
||||||
|
- Bewusste Abweichungen werden dokumentiert
|
||||||
|
[[Leitbild – Review-System]].
|
||||||
|
|
||||||
|
> [!edge] governed_by
|
||||||
|
>[[Leitbild – Kernwerte (Top 5)]]
|
||||||
|
|
||||||
|
> [!edge] uses
|
||||||
|
> [[Leitbild – Review-System]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Abgrenzung
|
||||||
|
|
||||||
|
Dieses Dokument definiert **Zielbilder**, keine Maßnahmen.
|
||||||
|
Konkrete Umsetzung erfolgt über:
|
||||||
|
- Rollen: [[Leitbild – Rollen & Identität]]
|
||||||
|
- Systeme: [[Leitbild – Rituale & Systeme]]
|
||||||
|
|
||||||
|
|
||||||
|
> [!edge] pursued_by
|
||||||
|
> [[Leitbild – Rollen & Identität]]
|
||||||
|
|
||||||
|
> [!edge] enforced_by
|
||||||
|
> [[Leitbild – Rituale & Systeme]]
|
||||||
|
|
||||||
|
> [!edge] part_of
|
||||||
|
> Dieses Dokument ist Teil des Identitätskerns
|
||||||
|
> [[Leitbild – Identity Core (MOC)]]
|
||||||
|
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-ops-guide-2025
|
||||||
|
title: Leitbild – Operations Guide (2025, refactored)
|
||||||
|
type: system
|
||||||
|
status: active
|
||||||
|
created: 2025-12-17
|
||||||
|
tags: [leitbild, operations, betrieb, governance, refactored]
|
||||||
|
aliases: [Ops Guide 2025, Betriebsleitfaden Leitbild]
|
||||||
|
lang: de
|
||||||
|
retriever_weight: 0.85
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
---
|
||||||
|
|
||||||
|
# Operations Guide (refactored)
|
||||||
|
|
||||||
|
Dieser Guide beschreibt, **wie das Leitbild 2025 im Alltag betrieben wird**.
|
||||||
|
|
||||||
|
Der Guide leitet sich ab aus den normativen Grundlagen [[Leitbild – Kernwerte (Top 5)]], [[Leitbild – Handlungsprinzipien]] und operationalisiert die Zielverfolgung aus [[Leitbild – Nordsterne & Ziele]].
|
||||||
|
|
||||||
|
|
||||||
|
> [!edge] derived_from
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)]]
|
||||||
|
> [[Leitbild – Handlungsprinzipien]]
|
||||||
|
|
||||||
|
> [!edge] enables
|
||||||
|
> [[Leitbild – Nordsterne & Ziele]]
|
||||||
|
|
||||||
|
> [!edge] part_of
|
||||||
|
> Er ist Teil des Identitätskerns
|
||||||
|
> [[Leitbild – Identity Core (MOC)]]
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Geltungsbereich
|
||||||
|
- Gilt für **alle Rollen**
|
||||||
|
[[Leitbild – Rollen & Identität]].
|
||||||
|
- Gilt für **alle Systeme und Rituale**
|
||||||
|
[[Leitbild – Rituale & Systeme]].
|
||||||
|
- Gilt für **alle bewussten Entscheidungen und Abweichungen**.
|
||||||
|
|
||||||
|
> [!edge] applies_to
|
||||||
|
> [[Leitbild – Rollen & Identität]]
|
||||||
|
> [[Leitbild – Rituale & Systeme]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Entscheidungslogik (operativ)
|
||||||
|
|
||||||
|
### Schritt 1 – Werte-Check
|
||||||
|
- Entspricht die geplante Handlung den Kernwerten?
|
||||||
|
[[Leitbild – Kernwerte (Top 5)]]
|
||||||
|
|
||||||
|
### Schritt 2 – Prinzipien-Check
|
||||||
|
- Ist das Vorgehen konsistent mit den Handlungsprinzipien?
|
||||||
|
[[Leitbild – Handlungsprinzipien]]
|
||||||
|
|
||||||
|
### Schritt 3 – Zielabgleich
|
||||||
|
- Unterstützt die Handlung die Nordsterne?
|
||||||
|
[[Leitbild – Nordsterne & Ziele]]
|
||||||
|
|
||||||
|
### Schritt 4 – Systemverträglichkeit
|
||||||
|
- Ist die Handlung mit bestehenden Systemen kompatibel?
|
||||||
|
[[Leitbild – Rituale & Systeme]]
|
||||||
|
|
||||||
|
> [!edge] checked_against
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)]]
|
||||||
|
> [[Leitbild – Handlungsprinzipien]]
|
||||||
|
> [[Leitbild – Nordsterne & Ziele]]
|
||||||
|
> [[Leitbild – Rituale & Systeme]]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Umgang mit Abweichungen
|
||||||
|
Abweichungen sind **erlaubt**, wenn sie **bewusst** erfolgen.
|
||||||
|
|
||||||
|
**Pflicht bei Abweichung:**
|
||||||
|
- Dokumentation als `type: deviation`
|
||||||
|
- Kurzbegründung
|
||||||
|
- Review-Termin festlegen
|
||||||
|
|
||||||
|
Die Bewertung erfolgt über
|
||||||
|
[[Leitbild – Review-System]].
|
||||||
|
|
||||||
|
> [!edge] uses
|
||||||
|
> [[Leitbild – Review-System]]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Änderung des Leitbilds
|
||||||
|
Änderungen am Leitbild selbst sind **selten** und **bewusst**.
|
||||||
|
|
||||||
|
**Vorgehen:**
|
||||||
|
1. Anlass klar benennen
|
||||||
|
2. Auswirkungen auf Werte, Prinzipien, Ziele prüfen
|
||||||
|
3. Entscheidung dokumentieren (`type: decision`)
|
||||||
|
4. Review nach definierter Zeit
|
||||||
|
|
||||||
|
Reflexion erfolgt über
|
||||||
|
[[Leitbild – Review-System]]
|
||||||
|
und wird konsolidiert im
|
||||||
|
[[Leitbild – Identity Core (MOC)]].
|
||||||
|
|
||||||
|
> [!edge] uses
|
||||||
|
> [[Leitbild – Review-System]]
|
||||||
|
|
||||||
|
> [!edge] part_of
|
||||||
|
> [[Leitbild – Identity Core (MOC)]]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Notfallmodus
|
||||||
|
In Ausnahmesituationen (Überlast, Krise):
|
||||||
|
|
||||||
|
- Fokus auf **Stabilisierung**
|
||||||
|
- Reduktion auf **Kernrituale**
|
||||||
|
- Temporäre Zielanpassung erlaubt
|
||||||
|
|
||||||
|
Der Notfallmodus wird **zeitlich begrenzt**
|
||||||
|
und im Review explizit aufgehoben
|
||||||
|
[[Leitbild – Review-System]].
|
||||||
|
|
||||||
|
> [!edge] uses
|
||||||
|
> [[Leitbild – Review-System]]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Abgrenzung
|
||||||
|
Dieser Guide ist **kein neues Regelwerk**,
|
||||||
|
sondern ein **Betriebsmanual** für das Leitbild 2025.
|
||||||
|
|
||||||
|
Normative Quelle bleiben:
|
||||||
|
> [!edge] derived_from
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)]]
|
||||||
|
> [Leitbild – Handlungsprinzipien]]
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-review-system
|
||||||
|
title: Leitbild – Review-System
|
||||||
|
type: system
|
||||||
|
status: active
|
||||||
|
created: 2025-10-30
|
||||||
|
updated: 2025-12-17
|
||||||
|
tags: [leitbild, review, feedback, reflexion, governance]
|
||||||
|
aliases: [Review, Reviewsystem, Reflexion]
|
||||||
|
lang: de
|
||||||
|
retriever_weight: 0.9
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
---
|
||||||
|
|
||||||
|
# Review-System
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt das **verbindliche Review- und Feedbacksystem**.
|
||||||
|
|
||||||
|
Das Review-System überprüft die Einhaltung der
|
||||||
|
[[rel:checks_compliance_of Leitbild – Handlungsprinzipien]]
|
||||||
|
und misst die Zielausrichtung an
|
||||||
|
[[rel:measured_against Leitbild – Nordsterne & Ziele]].
|
||||||
|
|
||||||
|
Es ist Teil der operativen Steuerung des Identitätskerns
|
||||||
|
[[rel:part_of Leitbild – Identity Core (MOC)]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Grundprinzipien des Reviews
|
||||||
|
- **Beobachten statt bewerten**
|
||||||
|
- **Lernen statt rechtfertigen**
|
||||||
|
- **Kurskorrektur statt Perfektion**
|
||||||
|
|
||||||
|
Reviews dienen **nicht** der Selbstoptimierung um jeden Preis,
|
||||||
|
sondern der **Stabilisierung von Haltung und Wirkung**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Review-Ebenen
|
||||||
|
|
||||||
|
### 1) Micro-Review (täglich)
|
||||||
|
**Zweck:**
|
||||||
|
Frühe Wahrnehmung von Abweichungen.
|
||||||
|
|
||||||
|
**Format:**
|
||||||
|
Kurzreflexion (z. B. im Tagesjournal).
|
||||||
|
|
||||||
|
**Leitfragen:**
|
||||||
|
- Wo habe ich heute meinen Prinzipien entsprochen?
|
||||||
|
- Wo bin ich abgewichen – und warum?
|
||||||
|
|
||||||
|
**Anbindung:**
|
||||||
|
Abweichungen werden markiert für das
|
||||||
|
[[rel:uses Leitbild – Rituale & Systeme#R3]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2) Rollen-Review (wöchentlich / monatlich)
|
||||||
|
**Zweck:**
|
||||||
|
Qualität der Rollenausübung prüfen.
|
||||||
|
|
||||||
|
**Gegenstand:**
|
||||||
|
Rollen aus
|
||||||
|
[[rel:measured_by Leitbild – Rollen & Identität]].
|
||||||
|
|
||||||
|
**Leitfragen:**
|
||||||
|
- Welche Rolle war diese Woche dominant?
|
||||||
|
- Wo gab es Ziel- oder Wertekonflikte?
|
||||||
|
- Welche Anpassung ist nötig?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3) System-Review (monatlich / quartalsweise)
|
||||||
|
**Zweck:**
|
||||||
|
Wirksamkeit von Ritualen und Systemen überprüfen.
|
||||||
|
|
||||||
|
**Gegenstand:**
|
||||||
|
Systeme aus
|
||||||
|
[[rel:measured_by Leitbild – Rituale & Systeme]].
|
||||||
|
|
||||||
|
**Leitfragen:**
|
||||||
|
- Welche Rituale tragen aktuell?
|
||||||
|
- Wo entsteht Reibung?
|
||||||
|
- Was darf vereinfacht oder angepasst werden?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4) Strategisches Review (quartalsweise / jährlich)
|
||||||
|
**Zweck:**
|
||||||
|
Langfristige Ausrichtung überprüfen.
|
||||||
|
|
||||||
|
**Gegenstand:**
|
||||||
|
Nordsterne und Zielbilder aus
|
||||||
|
[[rel:measured_against Leitbild – Nordsterne & Ziele]].
|
||||||
|
|
||||||
|
**Leitfragen:**
|
||||||
|
- Stimmen Richtung und Realität überein?
|
||||||
|
- Gibt es neue Prioritäten?
|
||||||
|
- Ist eine bewusste Abweichung nötig?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Umgang mit Abweichungen
|
||||||
|
- Abweichungen werden **explizit benannt**
|
||||||
|
- Keine Rechtfertigung, nur **Ursachenklärung**
|
||||||
|
- Entscheidungen werden dokumentiert als:
|
||||||
|
- `type: decision`
|
||||||
|
- `type: deviation`
|
||||||
|
|
||||||
|
Diese Dokumentation schützt die Integrität der Werte
|
||||||
|
[[rel:protects Leitbild – Kernwerte (Top 5)]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dokumentationsregeln
|
||||||
|
- Jede relevante Abweichung erzeugt eine Note.
|
||||||
|
- Noten sind **kurz, ehrlich, zeitnah**.
|
||||||
|
- Keine nachträgliche Schönfärbung.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Abgrenzung
|
||||||
|
Dieses Dokument definiert **Review-Logik**, keine Werte, Ziele oder Systeme.
|
||||||
|
Normative Grundlage bleiben:
|
||||||
|
- [[rel:derived_from Leitbild – Kernwerte (Top 5)]]
|
||||||
|
- [[rel:derived_from Leitbild – Handlungsprinzipien]]
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-rituale-systeme
|
||||||
|
title: Leitbild – Rituale & Systeme
|
||||||
|
type: system
|
||||||
|
status: active
|
||||||
|
created: 2025-10-30
|
||||||
|
updated: 2025-12-17
|
||||||
|
tags: [leitbild, rituale, systeme, umsetzung, execution]
|
||||||
|
aliases: [Rituale, Systeme, Gewohnheiten]
|
||||||
|
lang: de
|
||||||
|
retriever_weight: 0.9
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
---
|
||||||
|
|
||||||
|
# Rituale & Systeme
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt die **operativen Systeme**, mit denen Werte, Prinzipien und Ziele **verlässlich umgesetzt** werden.
|
||||||
|
Rituale ersetzen Willenskraft durch **Struktur**.
|
||||||
|
|
||||||
|
Die Systeme sind abgeleitet aus
|
||||||
|
[[rel:derived_from Leitbild – Handlungsprinzipien]]
|
||||||
|
und dienen der Zielverfolgung aus
|
||||||
|
[[rel:enables Leitbild – Nordsterne & Ziele]].
|
||||||
|
|
||||||
|
Sie gelten rollenübergreifend
|
||||||
|
[[rel:applies_to Leitbild – Rollen & Identität]]
|
||||||
|
und sind Teil des Identitätskerns
|
||||||
|
[[rel:part_of Leitbild – Identity Core (MOC)]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Systemlogik
|
||||||
|
- **Wenig, aber stabil**
|
||||||
|
- **Regelmäßig statt intensiv**
|
||||||
|
- **Reviewbar statt perfekt**
|
||||||
|
|
||||||
|
Abweichungen werden **nicht moralisiert**, sondern überprüft über
|
||||||
|
[[rel:measured_by Leitbild – Review-System]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tägliche Rituale
|
||||||
|
|
||||||
|
### R1 – Morgenfokus
|
||||||
|
**Zweck:**
|
||||||
|
Klarer Start in den Tag.
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
- 5–10 Minuten Stille / Meditation
|
||||||
|
- Tagespriorität festlegen (1 Sache)
|
||||||
|
|
||||||
|
**Ableitung:**
|
||||||
|
Unterstützt die Prinzipien aus
|
||||||
|
[[rel:derived_from Leitbild – Handlungsprinzipien#P3 – Disziplin (Selbstführung)]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### R2 – Präsenz-Check
|
||||||
|
**Zweck:**
|
||||||
|
Bewusste Präsenz in Familie und Beruf.
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
- Kurz innehalten vor Rollenwechseln
|
||||||
|
- Aufmerksamkeit bewusst ausrichten
|
||||||
|
|
||||||
|
**Rollenbezug:**
|
||||||
|
Relevant für
|
||||||
|
[[rel:applies_to Leitbild – Rollen & Identität#Vater]],
|
||||||
|
[[rel:applies_to Leitbild – Rollen & Identität#Partner]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### R3 – Tagesjournal
|
||||||
|
**Zweck:**
|
||||||
|
Reflexion und Lerntransfer.
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
- 3 Stichpunkte:
|
||||||
|
- Was lief gut?
|
||||||
|
- Wo bin ich abgewichen?
|
||||||
|
- Was lerne ich?
|
||||||
|
|
||||||
|
**Durchsetzung:**
|
||||||
|
Abweichungen werden markiert für
|
||||||
|
[[rel:uses Leitbild – Review-System]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Wöchentliche Rituale
|
||||||
|
|
||||||
|
### R4 – Wochenplanung
|
||||||
|
**Zweck:**
|
||||||
|
Prioritäten setzen, Überlast vermeiden.
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
- Kalender-Review
|
||||||
|
- Eine Sache bewusst streichen
|
||||||
|
|
||||||
|
**Zielbezug:**
|
||||||
|
Unterstützt
|
||||||
|
[[rel:enables Leitbild – Nordsterne & Ziele]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### R5 – Partnerschafts-Check
|
||||||
|
**Zweck:**
|
||||||
|
Lasten fair verteilen, Nähe pflegen.
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
- Kurzer Abgleich:
|
||||||
|
- Was war schwer?
|
||||||
|
- Was brauchen wir?
|
||||||
|
|
||||||
|
**Rollenbezug:**
|
||||||
|
Gilt für
|
||||||
|
[[rel:applies_to Leitbild – Rollen & Identität#Partner]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### R6 – Familienrat (light)
|
||||||
|
**Zweck:**
|
||||||
|
Struktur und Fairness im Familienalltag.
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
- Kurze Runde
|
||||||
|
- Eine Regel, eine Entscheidung
|
||||||
|
|
||||||
|
**Rollenbezug:**
|
||||||
|
Gilt für
|
||||||
|
[[rel:applies_to Leitbild – Rollen & Identität#Vater]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Monatliche / Quartalsrituale
|
||||||
|
|
||||||
|
### R7 – Review & Kurskorrektur
|
||||||
|
**Zweck:**
|
||||||
|
Abgleich von Anspruch und Wirklichkeit.
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
- Rollen-Review
|
||||||
|
- Werte- & Prinzipien-Check
|
||||||
|
- Zielausrichtung prüfen
|
||||||
|
|
||||||
|
**Durchführung:**
|
||||||
|
Strukturiert über
|
||||||
|
[[rel:uses Leitbild – Review-System]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Guardrails
|
||||||
|
- Rituale dürfen **angepasst**, aber nicht **still abgeschafft** werden.
|
||||||
|
- Jede Änderung wird bewusst entschieden und dokumentiert.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Abgrenzung
|
||||||
|
Dieses Dokument definiert **Umsetzungssysteme**, keine Ziele und keine Werte.
|
||||||
|
Normative Grundlage bleibt
|
||||||
|
[[rel:derived_from Leitbild – Kernwerte (Top 5)]]
|
||||||
|
und
|
||||||
|
[[rel:derived_from Leitbild – Handlungsprinzipien]].
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-rollen
|
||||||
|
title: Leitbild – Rollen & Identität
|
||||||
|
type: profile
|
||||||
|
status: active
|
||||||
|
created: 2025-10-30
|
||||||
|
updated: 2025-12-17
|
||||||
|
tags: [leitbild, rollen, identität, profile]
|
||||||
|
aliases: [Rollenlandkarte, Rollenprofil, Identitätsrollen]
|
||||||
|
lang: de
|
||||||
|
retriever_weight: 0.95
|
||||||
|
chunking_profile: structured_smart_edges_strict
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Rollen & Identität
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt meine **zentralen Lebensrollen** und ihre jeweilige Mission.
|
||||||
|
Die Rollen leiten sich **direkt** aus dem Identitätskern ab
|
||||||
|
[[rel:defined_by Leitbild – Identity Core (MOC)]]
|
||||||
|
und verfolgen die strategischen Ziele (Nordsterne) aus
|
||||||
|
[[rel:pursues Leitbild – Nordsterne & Ziele]].
|
||||||
|
|
||||||
|
Alle Rollen werden **wertebasiert** geführt
|
||||||
|
[[rel:guided_by Leitbild – Handlungsprinzipien]]
|
||||||
|
und sind in Konflikten an die Kernwerte gebunden
|
||||||
|
[[rel:governed_by Leitbild – Kernwerte (Top 5)]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Vater
|
||||||
|
**Mission:**
|
||||||
|
Verlässlich präsent sein, ruhig führen und die Selbstwirksamkeit meiner Kinder stärken.
|
||||||
|
|
||||||
|
**Zielbezug:**
|
||||||
|
Diese Rolle verfolgt den Nordstern
|
||||||
|
[[rel:pursues Leitbild – Nordsterne & Ziele#Nordstern: Vater]].
|
||||||
|
|
||||||
|
**Qualitätskriterien:**
|
||||||
|
- Nähe & Präsenz (täglich 1:1).
|
||||||
|
- Faire Führung (Bedürfnis-Check vor Konsequenz).
|
||||||
|
- Ordnung & Verlässlichkeit im Alltag.
|
||||||
|
|
||||||
|
**Operative Absicherung:**
|
||||||
|
Diese Rolle wird unterstützt durch
|
||||||
|
[[rel:enforced_by Leitbild – Rituale & Systeme#R6]]
|
||||||
|
und regelmäßig überprüft über
|
||||||
|
[[rel:measured_by Leitbild – Review-System]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Partner
|
||||||
|
**Mission:**
|
||||||
|
Alltag als Team gestalten, Lasten fair verteilen und Nähe aktiv pflegen.
|
||||||
|
|
||||||
|
**Zielbezug:**
|
||||||
|
Diese Rolle verfolgt den Nordstern
|
||||||
|
[[rel:pursues Leitbild – Nordsterne & Ziele#Nordstern: Partner]].
|
||||||
|
|
||||||
|
**Qualitätskriterien:**
|
||||||
|
- Weekly Load-Check.
|
||||||
|
- Schutz gemeinsamer Ruhefenster.
|
||||||
|
- Konflikte zeitnah klären (≤48 h).
|
||||||
|
|
||||||
|
**Operative Absicherung:**
|
||||||
|
Gestützt durch Rituale aus
|
||||||
|
[[rel:enforced_by Leitbild – Rituale & Systeme#R5]]
|
||||||
|
und reflektiert im
|
||||||
|
[[rel:measured_by Leitbild – Review-System]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Berufsrolle (Umbrella)
|
||||||
|
**Mission:**
|
||||||
|
Evidenzbasiert, wertorientiert und menschenzentriert wirken.
|
||||||
|
|
||||||
|
**Zielbezug:**
|
||||||
|
Diese Rolle verfolgt den Nordstern
|
||||||
|
[[rel:pursues Leitbild – Nordsterne & Ziele#Nordstern: Berufsrolle]].
|
||||||
|
|
||||||
|
**Qualitätskriterien (rollenübergreifend):**
|
||||||
|
- Wirkung vor Aktivität.
|
||||||
|
- Wiederverwendbare Ergebnisse.
|
||||||
|
- Klarer Wissenstransfer.
|
||||||
|
|
||||||
|
### Subrollen
|
||||||
|
|
||||||
|
#### A1 – Research Lead
|
||||||
|
**Fokus:**
|
||||||
|
Erkenntnisse generieren und verdichten.
|
||||||
|
|
||||||
|
**Qualitätsmarker:**
|
||||||
|
- ≥1 Insight/Monat.
|
||||||
|
- ≥1 Deep-Dive/Quartal.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### A2 – IT-Kosten & Optimierung
|
||||||
|
**Fokus:**
|
||||||
|
Nachhaltige Kostenreduktion durch Struktur, Transparenz und Automatisierung.
|
||||||
|
|
||||||
|
**Qualitätsmarker:**
|
||||||
|
- Playbooks statt Einzellösungen.
|
||||||
|
- Nachweisbare Savings-Pipeline.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### A3 – Ausbilder
|
||||||
|
**Fokus:**
|
||||||
|
Menschen befähigen und Lernkurven beschleunigen.
|
||||||
|
|
||||||
|
**Qualitätsmarker:**
|
||||||
|
- Strukturierte Lernpfade.
|
||||||
|
- Messbare Placement- oder Wirkungsquote.
|
||||||
|
|
||||||
|
**Operative Absicherung (Berufsrolle):**
|
||||||
|
Unterstützt durch Systeme aus
|
||||||
|
[[rel:enforced_by Leitbild – Rituale & Systeme]]
|
||||||
|
und überprüft über
|
||||||
|
[[rel:measured_by Leitbild – Review-System]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Karate- & Gewaltschutztrainer
|
||||||
|
**Mission:**
|
||||||
|
Budo-Werte vermitteln, sichere Lernräume schaffen und Trainer multiplizieren.
|
||||||
|
|
||||||
|
**Zielbezug:**
|
||||||
|
Diese Rolle verfolgt den Nordstern
|
||||||
|
[[rel:pursues Leitbild – Nordsterne & Ziele#Nordstern: Karate & Gewaltschutz]].
|
||||||
|
|
||||||
|
**Qualitätskriterien:**
|
||||||
|
- Sichere Progression (Reifegradpfade).
|
||||||
|
- Kinderschutz & klare Standards.
|
||||||
|
- Trainer-Pipeline (S1 Shadowing → S4 Lead).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Freund
|
||||||
|
**Mission:**
|
||||||
|
Verlässlich, loyal und auf Augenhöhe in Beziehungen bleiben.
|
||||||
|
|
||||||
|
**Einordnung:**
|
||||||
|
Diese Rolle ist **wertebasiert ausgerichtet**, aber nicht zieltreibend im Sinne eines eigenen Nordsterns.
|
||||||
|
Sie ist
|
||||||
|
[[rel:aligned_with Leitbild – Kernwerte (Top 5)]]
|
||||||
|
und wird reflektiert über
|
||||||
|
[[rel:measured_by Leitbild – Review-System]].
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ich-Pflege
|
||||||
|
**Mission:**
|
||||||
|
Körper, Geist und emotionale Stabilität gesund halten.
|
||||||
|
|
||||||
|
**Zielbezug:**
|
||||||
|
Diese Rolle verfolgt den Nordstern
|
||||||
|
[[rel:pursues Leitbild – Nordsterne & Ziele#Nordstern: Ich-Pflege]].
|
||||||
|
|
||||||
|
**Guardrails:**
|
||||||
|
- Kein Training durch Schmerz.
|
||||||
|
- Regeneration vor Leistungssteigerung.
|
||||||
|
|
||||||
|
**Operative Absicherung:**
|
||||||
|
Umgesetzt über tägliche und wöchentliche Rituale aus
|
||||||
|
[[rel:enforced_by Leitbild – Rituale & Systeme]]
|
||||||
|
und reflektiert im
|
||||||
|
[[rel:measured_by Leitbild – Review-System]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rollenübergreifende Regeln
|
||||||
|
- Rollen stehen **nicht in Konkurrenz**, sondern im Ausgleich.
|
||||||
|
- Konflikte werden anhand der Kernwerte priorisiert
|
||||||
|
[[rel:governed_by Leitbild – Kernwerte (Top 5)]].
|
||||||
|
- Abweichungen werden bewusst dokumentiert
|
||||||
|
[[rel:uses Leitbild – Review-System]].
|
||||||
|
|
||||||
|
Dieses Dokument ist integraler Bestandteil des Identitätskerns
|
||||||
|
[[rel:part_of Leitbild – Identity Core (MOC)]].
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-scope-session-0
|
||||||
|
title: Leitbild – Scope (Session 0)
|
||||||
|
type: concept
|
||||||
|
status: archived
|
||||||
|
created: 2025-09-15
|
||||||
|
updated: 2025-12-17
|
||||||
|
tags: [leitbild, scope, kontext, session-0, historie]
|
||||||
|
aliases: [Scope, Leitbild Scope, Session 0]
|
||||||
|
lang: de
|
||||||
|
retriever_weight: 0.6
|
||||||
|
chunking_profile: structured_smart_edges
|
||||||
|
---
|
||||||
|
|
||||||
|
# Scope & Kontext (Session 0)
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt den **Entstehungsrahmen** des Leitbilds.
|
||||||
|
|
||||||
|
Der Scope liefert den **konzeptionellen Kontext** für den Identitätskern
|
||||||
|
[[rel:contextualizes Leitbild – Identity Core (MOC)]]
|
||||||
|
und für die konsolidierte Identitätsbeschreibung
|
||||||
|
[[rel:contextualizes Leitbild 2025–2029 – Persönliche Identität]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Anlass & Ausgangslage
|
||||||
|
- Persönliche Neuorientierung nach prägenden Ereignissen
|
||||||
|
- Wunsch nach Klarheit, Priorisierung und Stabilität
|
||||||
|
- Bedarf an einem belastbaren Referenzrahmen für Entscheidungen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ziel der Session 0
|
||||||
|
- Definition des **Geltungsbereichs** des Leitbilds
|
||||||
|
- Klärung, **was bewusst nicht** Teil des Leitbilds ist
|
||||||
|
- Festlegung der **Systemlogik** (keine Vorsätze, sondern Struktur)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Explizite Abgrenzungen
|
||||||
|
Dieses Leitbild:
|
||||||
|
|
||||||
|
- ist **kein Jahreszielkatalog**
|
||||||
|
- ist **kein Selbstoptimierungsprogramm**
|
||||||
|
- ist **keine Sammlung guter Vorsätze**
|
||||||
|
- ist **kein Projektplan**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Annahmen
|
||||||
|
- Entscheidungen entstehen aus **Werten, nicht aus Stimmung**
|
||||||
|
- Systeme schlagen Willenskraft
|
||||||
|
- Wenige klare Regeln sind wirksamer als viele
|
||||||
|
|
||||||
|
Diese Annahmen wurden später operationalisiert in
|
||||||
|
[[rel:derived_into Leitbild – Handlungsprinzipien]]
|
||||||
|
und umgesetzt über
|
||||||
|
[[rel:implemented_by Leitbild – Rituale & Systeme]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ergebnis der Session
|
||||||
|
- Entscheidung für einen **Ego-Core** (Identity Core)
|
||||||
|
- Trennung von:
|
||||||
|
- normativen Elementen (Werte, Prinzipien, Ziele)
|
||||||
|
- operativen Elementen (Rituale, Reviews)
|
||||||
|
- Festlegung eines iterativen Review-Ansatzes
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Abgrenzung (heute)
|
||||||
|
Dieses Dokument ist **archiviert**.
|
||||||
|
Es dient ausschließlich der **historischen Einordnung**.
|
||||||
|
|
||||||
|
Aktiv gültig sind:
|
||||||
|
- [[rel:references Leitbild – Identity Core (MOC)]]
|
||||||
|
- [[rel:references Leitbild – Kernwerte (Top 5)]]
|
||||||
|
- [[rel:references Leitbild – Handlungsprinzipien]]
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
---
|
||||||
|
id: leitbild-wertekompass
|
||||||
|
title: Leitbild – Wertekompass (vollständig)
|
||||||
|
type: value
|
||||||
|
status: active
|
||||||
|
created: 2025-10-30
|
||||||
|
updated: 2025-10-30
|
||||||
|
tags: [leitbild, werte, values-inventory, kontext]
|
||||||
|
lang: de
|
||||||
|
retriever_weight: 0.6
|
||||||
|
chunking_profile: structured_smart_edges
|
||||||
|
---
|
||||||
|
|
||||||
|
# Wertekompass - Tier 1 Kernwerte
|
||||||
|
|
||||||
|
> [!edge] derived_from
|
||||||
|
> **Zweck dieses Dokuments**
|
||||||
|
> Dieses Dokument ist ein **Arbeitsinventar** meiner Werte.
|
||||||
|
> Es dient der **Reflexion, Differenzierung und Ableitung**.
|
||||||
|
> **Verbindliche Kernwerte (Tier 1)** sind definiert in
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Kernwerte
|
||||||
|
|
||||||
|
> Diese Werte haben **Priorität 1** und sind **normativ**.
|
||||||
|
> Details, Anker und Konfliktregeln sind im Kernwertedokument beschrieben.
|
||||||
|
|
||||||
|
1. **Integrität**
|
||||||
|
Vorhersagbar principled handeln; das eigene Wort gilt.
|
||||||
|
|
||||||
|
2. **Vertrauenswürdigkeit & Ehrlichkeit**
|
||||||
|
Zusagen sind verbindlich; Abweichungen werden offen kommuniziert.
|
||||||
|
|
||||||
|
3. **Disziplin**
|
||||||
|
Zugesagte Standards werden verlässlich eingehalten.
|
||||||
|
|
||||||
|
4. **Gerechtigkeit & Fairness**
|
||||||
|
Entscheidungen folgen transparenten Maßstäben.
|
||||||
|
|
||||||
|
5. **Respekt**
|
||||||
|
Anerkennung der Gleichwürdigkeit aller Menschen.
|
||||||
|
|
||||||
|
> [!edge] references
|
||||||
|
> **Zweck dieses Dokuments**
|
||||||
|
> Dieses Dokument ist ein **Arbeitsinventar** meiner Werte.
|
||||||
|
> Es dient der **Reflexion, Differenzierung und Ableitung**.
|
||||||
|
> **Verbindliche Kernwerte (Tier 1)** sind definiert in
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Tier 2 – Unterstützungswerte (on deck)
|
||||||
|
|
||||||
|
> Diese Werte sind **nicht konfliktentscheidend**,
|
||||||
|
> sondern dienen als **Nuancierung und Kontext** für Entscheidungen.
|
||||||
|
|
||||||
|
## Fürsorge & Familienbindung
|
||||||
|
**Kurz:** Präsenz zeigen und Bindung aktiv stärken.
|
||||||
|
**Anker:** Wöchentliche Qualitätszeit.
|
||||||
|
**Bezug:** Stützt die Rolle
|
||||||
|
|
||||||
|
> [!edge] supports
|
||||||
|
> [[Leitbild – Rollen & Identität#Vater]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Klarheit & Struktur
|
||||||
|
**Kurz:** Wenige Regeln, klare Zuständigkeiten.
|
||||||
|
**Anker:** „Wer macht was bis wann“.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Lernorientierung
|
||||||
|
**Kurz:** Neugierig bleiben, Lerngewinne teilen.
|
||||||
|
**Anker:** „Lernen durch Lehren“.
|
||||||
|
**Bezug:** Stützt die Rolle
|
||||||
|
|
||||||
|
> [!edge] supports
|
||||||
|
> [[Leitbild – Rollen & Identität#Berufsrolle]].
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Großzügigkeit
|
||||||
|
**Kurz:** Zeit und Wissen teilen, ohne sich selbst zu verbrennen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Mut
|
||||||
|
**Kurz:** Unangenehmes respektvoll ansprechen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Arbeitsregeln für den Wertekompass
|
||||||
|
|
||||||
|
* **Konflikte:**
|
||||||
|
Tier-1-Werte schlagen Tier-2-Werte.
|
||||||
|
|
||||||
|
* **Ausnahmen:**
|
||||||
|
Abweichungen von Tier-1-Werten sind **explizit zu dokumentieren**
|
||||||
|
über eine `type: decision`-Notiz
|
||||||
|
|
||||||
|
> [!edge] uses
|
||||||
|
> [[Leitbild – Review-System]]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Abgrenzung
|
||||||
|
Dieses Dokument **steuert keine Entscheidungen direkt**.
|
||||||
|
Es liefert **Kontext, Sprache und Differenzierung** für:
|
||||||
|
|
||||||
|
* Werte-Reflexion
|
||||||
|
* Ableitung von Prinzipien
|
||||||
|
* Retro- und Review-Gespräche
|
||||||
|
|
||||||
|
> [!edge] derived_from
|
||||||
|
> [[Leitbild – Kernwerte (Top 5)]]
|
||||||
|
|
||||||
|
|
||||||
|
> [!edge] supports
|
||||||
|
> [[Leitbild – Handlungsprinzipien]]
|
||||||
|
|
||||||
|
> [!edge] part_of
|
||||||
|
> [[Leitbild – Identity Core (MOC)]]
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
---
|
|
||||||
id: leitbild-ops-guide
|
|
||||||
title: Leitbild – Leitfaden (Betrieb & Rhythmus)
|
|
||||||
type: concept
|
|
||||||
status: active
|
|
||||||
created: 2025-10-31
|
|
||||||
tags: [leitbild, operating-guide, habits]
|
|
||||||
lang: de
|
|
||||||
---
|
|
||||||
# Leitbild – Operations Manual (TL;DR)
|
|
||||||
|
|
||||||
Dieses Dokument beschreibt die operative Nutzung des Systems.
|
|
||||||
Es steuert die Anwendung von [[rel:uses leitbild-rituale-system]] und [[rel:uses leitbild-review]].
|
|
||||||
|
|
||||||
## 1) Karte – „Welche Datei wofür?“
|
|
||||||
* **Kompass:** [[rel:references leitbild-text]] (Wofür stehe ich?)
|
|
||||||
* **System:** [[rel:references leitbild-rituale-system]] (Trigger & Fallbacks).
|
|
||||||
* **Steuerung:** [[rel:references leitbild-review]] (Weekly/Monthly).
|
|
||||||
* **Strategie:** [[rel:references leitbild-ziele-portfolio]] (Nordsterne).
|
|
||||||
* **Identität:** [[rel:references leitbild-rollen]] (Kontext).
|
|
||||||
* **Ethik:** [[rel:references leitbild-prinzipien]] (Wächterfragen).
|
|
||||||
|
|
||||||
## 2) Dein Tag (Mikro-Anker)
|
|
||||||
* **Morgens:** R1 (Meditation) + Nordstern-Fokus.
|
|
||||||
* **Mittags:** R2 (Mobility).
|
|
||||||
* **Abends:** R6 (Rohan) + R3 (Journal).
|
|
||||||
|
|
||||||
## 3) Weekly Review SOP
|
|
||||||
Der Prozess für [[rel:related_to leitbild-review#Weekly Review]].
|
|
||||||
1. Scoreboard füllen.
|
|
||||||
2. Reflexion (Wirksamkeit, Repair).
|
|
||||||
3. **Decision Note** erstellen.
|
|
||||||
|
|
||||||
## 6) Decision & Deviation
|
|
||||||
Wie man Entscheidungen dokumentiert (siehe [[rel:related_to leitbild-prinzipien#P1 Integrität]]):
|
|
||||||
* **Decision Note:** Für echte Wahlmöglichkeiten.
|
|
||||||
* **Deviation Note:** Für Abweichungen ("Schuldschein").
|
|
||||||
|
|
||||||
## 10) Emergency Mode
|
|
||||||
Wenn Energie knapp ist:
|
|
||||||
* **Weniger, dafür besser:** Fallbacks aus [[rel:uses leitbild-rituale-system]] nutzen.
|
|
||||||
* **Repair first:** Konflikte bereinigen.
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
---
|
|
||||||
id: leitbild-prinzipien
|
|
||||||
title: Leitbild – Prinzipien
|
|
||||||
type: principle
|
|
||||||
status: active
|
|
||||||
created: 2025-10-30
|
|
||||||
updated: 2025-10-30
|
|
||||||
tags: [topic/prinzipien, method/values-to-principles]
|
|
||||||
lang: de
|
|
||||||
---
|
|
||||||
# Handlungsprinzipien
|
|
||||||
|
|
||||||
> Diese Prinzipien sind abgeleitet aus [[rel:derived_from leitbild-wertekompass]].
|
|
||||||
> Sie steuern das Verhalten in allen Rollen ([[rel:guides leitbild-rollen]]).
|
|
||||||
|
|
||||||
## P1 – Integrität
|
|
||||||
**Satz:** *Ich spiegele jede wichtige Entscheidung am Werte-Modell und dokumentiere Abweichungen.*
|
|
||||||
**Verbindung:** Basiert auf Wert [[rel:derived_from leitbild-wertekompass#Integrität]].
|
|
||||||
**Signal:** Decision Note („Schuldschein“) binnen 24h erstellt.
|
|
||||||
|
|
||||||
## P2 – Vertrauenswürdigkeit & Ehrlichkeit
|
|
||||||
**Satz:** *Ich kündige drohende Abweichungen proaktiv an und verhandle Alternativen.*
|
|
||||||
**Verbindung:** Basiert auf Wert [[rel:derived_from leitbild-wertekompass#Vertrauenswürdigkeit]].
|
|
||||||
**Signal:** Info *vor* Fristende.
|
|
||||||
|
|
||||||
## P3 – Disziplin (Selbstführung)
|
|
||||||
**Satz:** *Ich bin mir selbst konsequent; Unangenehmes gehe ich rechtzeitig an.*
|
|
||||||
**Verbindung:** Basiert auf Wert [[rel:derived_from leitbild-wertekompass#Disziplin]].
|
|
||||||
|
|
||||||
### P3a – Disziplin in der Familie
|
|
||||||
**Satz:** *Ich setze wenige Regeln ruhig durch, nachdem ich Bedürfnisse geprüft habe.*
|
|
||||||
**Signal:** Angekündigte Konsequenzen werden umgesetzt.
|
|
||||||
|
|
||||||
## P4 – Gerechtigkeit & Fairness
|
|
||||||
**Satz:** *Ich entscheide nach transparenten Maßstäben und höre beide Seiten (Steelman).*
|
|
||||||
**Verbindung:** Basiert auf Wert [[rel:derived_from leitbild-wertekompass#Gerechtigkeit]].
|
|
||||||
|
|
||||||
## P5 – Respekt
|
|
||||||
**Satz:** *Ich antworte erst, wenn ich verstanden habe.*
|
|
||||||
**Verbindung:** Basiert auf Wert [[rel:derived_from leitbild-wertekompass#Respekt]].
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Tier 2 – Mikro-Prinzipien
|
|
||||||
|
|
||||||
### MP1 – Fürsorge (Familie)
|
|
||||||
*Ich schenke tägliche Präsenz und schütze Familienzeit.*
|
|
||||||
(Siehe Ritual [[rel:enforced_by leitbild-rituale-system#R6]]).
|
|
||||||
|
|
||||||
### MP2 – Klarheit (Struktur)
|
|
||||||
*Wer macht was bis wann.*
|
|
||||||
|
|
||||||
### MP3 – Lernorientierung
|
|
||||||
*Ich wähle ein Deep-Dive-Thema und teile Wissen.*
|
|
||||||
|
|
||||||
### MP4 – Großzügigkeit
|
|
||||||
*Ich teile Zeit/Wissen ohne Bilanzdenken.*
|
|
||||||
|
|
||||||
### MP5 – Mut
|
|
||||||
*Ich spreche Unangenehmes früh an.*
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
---
|
|
||||||
id: leitbild-review
|
|
||||||
title: Leitbild – Review-System (Weekly · Monthly · Quarterly)
|
|
||||||
type: concept
|
|
||||||
status: active
|
|
||||||
created: 2025-10-31
|
|
||||||
tags: [review, scoreboard, retro, process]
|
|
||||||
lang: de
|
|
||||||
---
|
|
||||||
# Zweck
|
|
||||||
Das Betriebssystem zur Steuerung der Nordsterne.
|
|
||||||
Es verarbeitet Daten aus [[rel:analyzes leitbild-rituale-system]] und prüft [[rel:analyzes leitbild-ziele-portfolio]].
|
|
||||||
|
|
||||||
## 0) Cadence
|
|
||||||
* **Weekly:** Scoreboard & Decision Note.
|
|
||||||
* **Monthly:** Strategie-Check.
|
|
||||||
* **Quarterly:** Meilensteine.
|
|
||||||
|
|
||||||
## 1) Weekly Review (SOP)
|
|
||||||
1. **Scoreboard:** Fakten eintragen.
|
|
||||||
2. **Reflexion:** Wirksamkeit prüfen.
|
|
||||||
3. **Output:** Erstellung einer **Decision Note** (`type: decision`).
|
|
||||||
|
|
||||||
## 2) Monthly & Quarterly
|
|
||||||
* **Monthly:** Roll-up der KPIs.
|
|
||||||
* **Quarterly:** Validierung der Ziele in [[rel:validates leitbild-ziele-portfolio]].
|
|
||||||
|
|
||||||
## Templates (Copy-Paste)
|
|
||||||
|
|
||||||
### Decision Note
|
|
||||||
Nutze dies für Richtungsentscheidungen. Erzeugt `type: decision`.
|
|
||||||
> Siehe [[rel:related_to leitbild-ops-guide]].
|
|
||||||
|
|
||||||
### Deviation Note (Schuldschein)
|
|
||||||
Nutze dies bei Abweichung von Werten.
|
|
||||||
> Referenziert [[rel:checks_compliance_of leitbild-werte]].
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
---
|
|
||||||
id: leitbild-rituale-system
|
|
||||||
title: Leitbild – Rituale & Systeme
|
|
||||||
type: concept
|
|
||||||
status: active
|
|
||||||
created: 2025-10-31
|
|
||||||
updated: 2025-10-31
|
|
||||||
tags: [rituale, habits, recovery, system-design]
|
|
||||||
lang: de
|
|
||||||
---
|
|
||||||
# Ziel
|
|
||||||
Das Betriebssystem für Recovery & Alltag.
|
|
||||||
Es operationalisiert die Ziele aus [[rel:solves leitbild-ziele-portfolio]] und sichert die Prinzipien aus [[rel:enforces leitbild-prinzipien]].
|
|
||||||
|
|
||||||
## DAILY RITUALE
|
|
||||||
|
|
||||||
### R1 – Meditation (Zazen) · 20 Minuten
|
|
||||||
* **Trigger:** Erster ruhiger 30′-Block.
|
|
||||||
* **Aktion:** Zazen (Atem zählen 1-10).
|
|
||||||
* **Zweck:** Dient dem Ziel [[rel:contributes_to leitbild-ziele-portfolio#Nordstern Ich-Pflege]].
|
|
||||||
|
|
||||||
### R2 – Flexibilität/Mobility · 10 Minuten
|
|
||||||
* **Trigger:** Mittagspause Start.
|
|
||||||
* **Aktion:** Mobility Flow.
|
|
||||||
|
|
||||||
### R3 – Abendliches Journal
|
|
||||||
* **Trigger:** Licht aus.
|
|
||||||
* **Aktion:** 3 Zeilen (Gut, Gelernt, Fokus).
|
|
||||||
* **Datenfluss:** Speist Daten in [[rel:feeds leitbild-review]].
|
|
||||||
|
|
||||||
### R6 – 1:1 mit Rohan
|
|
||||||
* **Trigger:** Nach Abendessen.
|
|
||||||
* **Aktion:** Bindungs-Check.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## PERIODISCHE RITUALE
|
|
||||||
|
|
||||||
### R5 – Paar-Ritual Tanzen (Weekly)
|
|
||||||
Stärkt die Rolle [[rel:related_to leitbild-rollen#Partner]].
|
|
||||||
|
|
||||||
### R7 – 1:1 mit Rouven (Weekly)
|
|
||||||
Walk & Talk.
|
|
||||||
|
|
||||||
### R4 – Familienrat light (14-tägig)
|
|
||||||
Klärt Regeln und Standards.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## MESSUNG & ZIELE
|
|
||||||
* **KPIs:** R1-R3 ≥6/7.
|
|
||||||
* **Relapse-Shield:** Mini-Reset ≤24 h.
|
|
||||||
* **Tracking:** Siehe [[rel:related_to leitbild-review]].
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
---
|
|
||||||
id: leitbild-rollen
|
|
||||||
title: Leitbild – Rollenlandkarte
|
|
||||||
type: profile
|
|
||||||
status: active
|
|
||||||
created: 2025-10-30
|
|
||||||
updated: 2025-10-31
|
|
||||||
tags: [topic/rollen, identity, persona]
|
|
||||||
lang: de
|
|
||||||
---
|
|
||||||
# Rollenlandkarte
|
|
||||||
|
|
||||||
Diese Rollen definieren meine Identität und verfolgen die Strategien in [[rel:pursues leitbild-ziele-portfolio]].
|
|
||||||
|
|
||||||
## Vater
|
|
||||||
**Mission:** Verlässlich präsent, ruhige Führung, Stärkung der Selbstwirksamkeit.
|
|
||||||
**Ziele:** Siehe [[rel:pursues leitbild-ziele-portfolio#Nordstern Vater]].
|
|
||||||
**Qualitätskriterien:**
|
|
||||||
* Nähe & Präsenz (Täglich 1:1).
|
|
||||||
* Faire Führung (Bedürfnis-Check vor Konsequenz).
|
|
||||||
* Ordnung (Küche morgens sauber).
|
|
||||||
|
|
||||||
## Partner
|
|
||||||
**Mission:** Team-Alltag, faire Lastverteilung, zärtliche Präsenz.
|
|
||||||
**Ziele:** Siehe [[rel:pursues leitbild-ziele-portfolio#Nordstern Partner]].
|
|
||||||
**Qualitätskriterien:**
|
|
||||||
* Weekly Load-Check.
|
|
||||||
* Energie schützen (Ruhefenster vor Terminen).
|
|
||||||
|
|
||||||
## Berufsrolle (Umbrella)
|
|
||||||
**Mission:** Evidenzbasiert, wertorientiert, menschenzentriert.
|
|
||||||
**Ziele:** Siehe [[rel:pursues leitbild-ziele-portfolio#Nordstern Beruf]].
|
|
||||||
**Sub-Rollen:**
|
|
||||||
1. **A1 Research Lead:** Insight/Monat, Deep-Dive/Quartal.
|
|
||||||
2. **A2 IT-Kosten:** Playbooks, Savings-Pipeline.
|
|
||||||
3. **A3 Ausbilder:** Lernkurven, Placement-Rate.
|
|
||||||
|
|
||||||
## Karate- & Gewaltschutztrainer
|
|
||||||
**Mission:** Budo-Werte, Kinderschutz, Trainer-Multiplikation.
|
|
||||||
**Ziele:** Siehe [[rel:pursues leitbild-ziele-portfolio#Nordstern Karate]].
|
|
||||||
**Qualitätskriterien:**
|
|
||||||
* Sichere Progression (Reifegradpfade).
|
|
||||||
* Trainer-Pipeline (S1 Shadowing → S4 Lead).
|
|
||||||
|
|
||||||
## Freund
|
|
||||||
**Mission:** Verlässlich, loyal, Kontakt auf Augenhöhe.
|
|
||||||
**Ziele:** Siehe [[rel:pursues leitbild-ziele-portfolio#Nordstern Freund]].
|
|
||||||
**Qualitätskriterien:**
|
|
||||||
* Kontakt-Cadence (1 Ping/Monat).
|
|
||||||
* Kein Gossip, keine Rettung ohne Kapazität.
|
|
||||||
|
|
||||||
## Ich-Pflege
|
|
||||||
**Mission:** Körper, Geist und Herz gesund halten.
|
|
||||||
**Ziele:** Siehe [[rel:pursues leitbild-ziele-portfolio#Nordstern Ich-Pflege]].
|
|
||||||
**Guardrails:** Kein Training durch Schmerz.
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
---
|
|
||||||
id: leitbild-scope
|
|
||||||
title: Leitbild – Scope (Session 0, final)
|
|
||||||
type: concept
|
|
||||||
status: active
|
|
||||||
created: 2025-10-30
|
|
||||||
tags: [topic/leitbild, history, scope]
|
|
||||||
lang: de
|
|
||||||
---
|
|
||||||
# Schlüsselpunkte (Session 0 – Konstitution)
|
|
||||||
|
|
||||||
Dieses Dokument definiert den Kontext für das Projekt [[rel:defines_scope_for leitbild-text]].
|
|
||||||
|
|
||||||
## 1. Auslöser & Kontext
|
|
||||||
Ursprung: Schicksalsschlag (Glioblastom). Dies führte zu einer Neuausrichtung der Prioritäten.
|
|
||||||
Neue Rollen: Research-Lead, IT-Cost, Ausbilder (siehe [[rel:related_to leitbild-rollen]]).
|
|
||||||
|
|
||||||
## 2. Familienphase
|
|
||||||
Fokus auf Bindung und Halt für die Söhne (18 & 15).
|
|
||||||
|
|
||||||
## 3. Zweck
|
|
||||||
Strategischer Kompass, keine operative Checkliste.
|
|
||||||
|
|
||||||
## 8. Wertekern
|
|
||||||
Fokus auf **Integrität** und **Vertrauen** (definiert in [[rel:related_to leitbild-wertekompass]]).
|
|
||||||
|
|
||||||
## 13. 90-Tage-Checks
|
|
||||||
Initiale Metriken für den Start (mittlerweile abgelöst durch [[rel:replaced_by leitbild-review]]).
|
|
||||||
|
|
||||||
### Kompass-Formel
|
|
||||||
„Ich spiegle jede wichtige Entscheidung am Werte-Modell.“
|
|
||||||
Dies ist die Basis für das Prinzip [[rel:leads_to leitbild-prinzipien#P1 Integrität]].
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
---
|
|
||||||
id: leitbild-text
|
|
||||||
title: Persönliches Leitbild (2025–2029)
|
|
||||||
type: concept
|
|
||||||
status: active
|
|
||||||
created: 2025-10-31
|
|
||||||
updated: 2025-10-31
|
|
||||||
tags: [leitbild, werte, prinzipien, rollen, nordsterne, ich-perspektive]
|
|
||||||
lang: de
|
|
||||||
---
|
|
||||||
# Wer ich bin
|
|
||||||
Ich bin Lars. Ich stehe für Verlässlichkeit, klare Haltung und freundliche Konsequenz.
|
|
||||||
Schicksalsschläge haben mich geerdet. Ich wähle bewusst: **präsent sein, fair handeln, vorleben statt fordern**.
|
|
||||||
Dieser Text ist die narrative Klammer um [[rel:summarizes leitbild-scope]].
|
|
||||||
|
|
||||||
# Wofür ich jeden Morgen aufstehe
|
|
||||||
Ich baue ein Zuhause für meine Kinder. Ich pflege meine Partnerschaft.
|
|
||||||
Ich diene als Trainer und Ausbilder: **ideenreich, integer, wirksam**.
|
|
||||||
Dies definiert meine Identität in [[rel:defined_by leitbild-rollen]].
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Meine Kernwerte (kompakt)
|
|
||||||
Das Fundament für alle Entscheidungen (siehe [[rel:based_on leitbild-werte]]):
|
|
||||||
|
|
||||||
* **Integrität** – Wort = Verpflichtung.
|
|
||||||
* **Disziplin (mit Menschlichkeit)** – Konsequent, aber fair.
|
|
||||||
* **Respekt** – Jeder Mensch ist gleichwürdig.
|
|
||||||
|
|
||||||
**Ergänzende Leitwerte:** Fürsorge, Klarheit, Lernorientierung (siehe [[rel:related_to leitbild-wertekompass]]).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Handlungsprinzipien (Auszug)
|
|
||||||
Konkrete Regeln aus [[rel:derived_from leitbild-prinzipien]]:
|
|
||||||
* **Vorbild vor Anspruch.**
|
|
||||||
* **Verstehen vor Antworten.**
|
|
||||||
* **Repair first.**
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Rollen & Missionen
|
|
||||||
Zusammenfassung der Profile aus [[rel:summarizes leitbild-rollen]]:
|
|
||||||
|
|
||||||
### Vater
|
|
||||||
Präsent, fair, verlässlich. Stärkt Bindung und Selbstwirksamkeit.
|
|
||||||
|
|
||||||
### Partner
|
|
||||||
Zugewandt, klar, Lasten teilend.
|
|
||||||
|
|
||||||
### Berufsrolle (AI-first)
|
|
||||||
Research-Tiefe, IT-Kostensenkung, Ausbildung.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Nordsterne (2025–2029)
|
|
||||||
Die strategischen Ziele aus [[rel:summarizes leitbild-ziele-portfolio]]:
|
|
||||||
1. **Vater:** Starke Bindung, klare Standards.
|
|
||||||
2. **Ich-Pflege:** Ruhe, Beweglichkeit.
|
|
||||||
3. **Karate:** Sicheres Lernökosystem.
|
|
||||||
4. **Partner:** Nähe als Team.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Rituale als Systeme
|
|
||||||
Umsetzung via [[rel:uses leitbild-rituale-system]]:
|
|
||||||
* **R1** Meditation
|
|
||||||
* **R3** Journal
|
|
||||||
* **R4** Familienrat light
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Standards & Grenzen
|
|
||||||
Abweichungen werden dokumentiert via [[rel:uses leitbild-review]] (Decision Notes).
|
|
||||||
* **Zuhause:** Ablagen frei, Küche sauber.
|
|
||||||
* **Nein-Liste:** Keine Verwässerung der Nordsterne.
|
|
||||||
|
|
||||||
> [!edge]
|
|
||||||
> derived_from: [[leitbild-werte]], [[leitbild-rollen]]
|
|
||||||
> guides: [[leitbild-ops-guide]]
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
---
|
|
||||||
id: leitbild-werte
|
|
||||||
title: Leitbild – Werte (Top-5)
|
|
||||||
type: value
|
|
||||||
status: active
|
|
||||||
created: 2025-10-30
|
|
||||||
updated: 2025-10-30
|
|
||||||
tags: [topic/werte, method/values-inventory, core-values]
|
|
||||||
lang: de
|
|
||||||
---
|
|
||||||
# Werte – Top-5 (Priorität für 12 Monate)
|
|
||||||
|
|
||||||
> **Decision Engine Hinweis:** Diese Werte haben Priorität 1. Bei Konflikten schlagen sie andere Erwägungen.
|
|
||||||
> Sie sind das Fundament für [[rel:leads_to leitbild-prinzipien]].
|
|
||||||
|
|
||||||
## 1) Integrität
|
|
||||||
**Definition:** Ich handle **vorhersagbar principled**; **mein Wort gilt**.
|
|
||||||
**Anker:** Entscheidungen am Werte-Modell spiegeln.
|
|
||||||
**Anti-Pattern:** Rigidität.
|
|
||||||
|
|
||||||
## 2) Vertrauenswürdigkeit & Ehrlichkeit
|
|
||||||
**Definition:** **Wort gilt**; Abweichungen offen ansprechen.
|
|
||||||
**Anker:** 24h-Reparatur bei Verstößen.
|
|
||||||
|
|
||||||
## 3) Disziplin
|
|
||||||
**Definition:** Ich halte zugesagte Standards und Regeln verlässlich ein.
|
|
||||||
**Anker:** Wenige klare Regeln, ruhig durchgesetzt.
|
|
||||||
**Bezug:** Ermöglicht das System [[rel:enables leitbild-rituale-system]].
|
|
||||||
|
|
||||||
## 4) Gerechtigkeit & Fairness
|
|
||||||
**Definition:** Transparente Maßstäbe für alle.
|
|
||||||
**Anker:** Keine Impuls-Strafen; Steelman-Argumentation.
|
|
||||||
|
|
||||||
## 5) Respekt
|
|
||||||
**Definition:** Ich erkenne jeden Menschen als gleichwertig an.
|
|
||||||
**Anker:** Sprache ohne Abwertung; erst verstehen, dann antworten.
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
---
|
|
||||||
id: leitbild-wertekompass
|
|
||||||
title: Leitbild – Wertekompass (vollständig)
|
|
||||||
type: value
|
|
||||||
status: active
|
|
||||||
created: 2025-10-30
|
|
||||||
updated: 2025-10-30
|
|
||||||
tags: [topic/werte, method/values-inventory]
|
|
||||||
lang: de
|
|
||||||
---
|
|
||||||
# Wertekompass – vollständige Übersicht
|
|
||||||
|
|
||||||
> Zweck: Arbeitsinventar aller relevanten Werte.
|
|
||||||
> Dieser Kompass definiert die Basis für [[rel:derived_from leitbild-werte]] (Top-5) und stützt die Prinzipien in [[rel:supports leitbild-prinzipien]].
|
|
||||||
|
|
||||||
## Tier 1 – Kernwerte (Top-5, verbindlich)
|
|
||||||
1. **Integrität** – Ich handle vorhersagbar principled; mein Wort gilt.
|
|
||||||
2. **Vertrauenswürdigkeit & Ehrlichkeit** – Zusagen sind verlässlich.
|
|
||||||
3. **Disziplin** – Ich halte zugesagte Standards.
|
|
||||||
4. **Gerechtigkeit & Fairness** – Klare Maßstäbe für alle.
|
|
||||||
5. **Respekt** – Würdigung von Mensch und Prozess.
|
|
||||||
|
|
||||||
> Details und Verhaltensanker findest du im verkürzten Dokument [[rel:related_to leitbild-werte]].
|
|
||||||
|
|
||||||
## Tier 2 – Unterstützungswerte **on deck** (12 Monate)
|
|
||||||
Diese Werte dienen als Reserve und Nuance für Entscheidungen.
|
|
||||||
|
|
||||||
### Fürsorge & Familienbindung
|
|
||||||
* **Kurz:** Ich bin ansprechbar und stärke Bindung aktiv.
|
|
||||||
* **Anker:** Wöchentliche Qualitätszeit.
|
|
||||||
* **Bezug:** Stützt die Rolle [[rel:supports leitbild-rollen#Vater]].
|
|
||||||
|
|
||||||
### Klarheit & Struktur
|
|
||||||
* **Kurz:** Wenige Regeln, klare Zuständigkeiten.
|
|
||||||
* **Anker:** „Wer macht was bis wann“.
|
|
||||||
|
|
||||||
### Lernorientierung
|
|
||||||
* **Kurz:** Neugierig bleiben, Lerngewinne teilen.
|
|
||||||
* **Anker:** „Teach-back“ als Standard.
|
|
||||||
* **Bezug:** Stützt die Rolle [[rel:supports leitbild-rollen#Berufsrolle]].
|
|
||||||
|
|
||||||
### Großzügigkeit
|
|
||||||
* **Kurz:** Zeit/Wissen teilen, ohne sich zu verbrennen.
|
|
||||||
|
|
||||||
### Mut
|
|
||||||
* **Kurz:** Unangenehmes respektvoll ansprechen.
|
|
||||||
|
|
||||||
## Arbeitsregeln
|
|
||||||
* **Konflikte:** Tier 1 schlägt Tier 2.
|
|
||||||
* **Ausnahmen:** Dokumentation via `type: decision` (Schuldschein).
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
---
|
|
||||||
id: leitbild-ziele-portfolio
|
|
||||||
title: Leitbild – Ziele-Portfolio (Nordsterne komplett)
|
|
||||||
type: goal
|
|
||||||
status: active
|
|
||||||
created: 2025-10-30
|
|
||||||
updated: 2025-10-31
|
|
||||||
tags: [topic/ziele, method/objectives, scope/nordsterne]
|
|
||||||
lang: de
|
|
||||||
---
|
|
||||||
# Ziele-Portfolio (Nordsterne)
|
|
||||||
|
|
||||||
Diese Datei definiert die strategischen Outcomes 2026–2029.
|
|
||||||
Der Fortschritt wird überwacht durch [[rel:measured_by leitbild-review]].
|
|
||||||
|
|
||||||
## Nordstern: Vater
|
|
||||||
**Ziel:** Verlässlich präsent, ruhig und gerecht.
|
|
||||||
**Strategie:** Tägliche Nähe, faire Führung.
|
|
||||||
**Bezug:** Definiert Erfolg für [[rel:defines_success_for leitbild-rollen#Vater]].
|
|
||||||
**KPIs:** 1:1 ≥5 Tage/W; Konsequenzen-Quote ≥90%.
|
|
||||||
|
|
||||||
## Nordstern: Ich-Pflege
|
|
||||||
**Ziel:** Belastbar, schmerzfrei trainierbar.
|
|
||||||
**Strategie:** Reha-Bridge, Zazen, Ernährung.
|
|
||||||
**KPIs:** Kraft ≥2×/W; Mobility ≥4×/W.
|
|
||||||
|
|
||||||
## Nordstern: Karate & Gewaltschutz
|
|
||||||
**Ziel:** Sicheres Lernökosystem & Traineraufbau.
|
|
||||||
**Bezug:** Definiert Erfolg für [[rel:defines_success_for leitbild-rollen#Karate-Trainer]].
|
|
||||||
**KPIs:** ≥2 neue Leads/Jahr.
|
|
||||||
|
|
||||||
## Nordstern: Partner
|
|
||||||
**Ziel:** Alltag als Team, faire Lastverteilung.
|
|
||||||
**Strategie:** Weekly Load-Check, Paar-Ritual.
|
|
||||||
**KPIs:** Konflikte ≤48h geklärt.
|
|
||||||
|
|
||||||
## Nordstern: Freund (Neuaufbau)
|
|
||||||
**Ziel:** Neuer Kreis auf Augenhöhe.
|
|
||||||
**Strategie:** Mikro-Events, 90-Tage-Pipeline.
|
|
||||||
|
|
||||||
## Nordstern: Berufsrolle (AI-first)
|
|
||||||
**Ziel:** Evidenzbasiert, IT-Kostensenkung, Assetisierung.
|
|
||||||
**Bezug:** Definiert Erfolg für [[rel:defines_success_for leitbild-rollen#Berufsrolle]].
|
|
||||||
**Strategie:** AI-OS v1, Reuse-Quote ≥50%.
|
|
||||||
Reference in new issue
Block a user